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

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:
swaitsandClaude Fable 5.2 committed 2026-11-22 22:29:02 -07:00
commit 2fc1fe9c2d
223 files changed
+22163

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
---
id: check-tiering
title: Fast checks on every change, deep checks before release or on a schedule, with the freshness recorded
answers: Which checks must run now, which run later, and how old is the evidence from the deep ones?
rung: 3
section: completeness
languages: any
kinds: general
cost: medium
detect: just --version
ran_here: no
verified: docs
---
Note: modelled on a reference project, which keeps a table of each
technique, its command, its cost, how often it runs and the date and result of the
last run, and has CI run the heavy ones weekly. Not run here.
## Use when
- Some checks (mutation testing, long proofs, fuzzing, full end to end) take minutes or hours and cannot run on every edit.
- You want "done" for a small change to be fast and "release" to be thorough, with no confusion over which is which.
- Deep evidence goes stale after code changes and you need to see that.
## Do not use when
- All checks finish in under a minute. Put them in one gate (`single-gate-command`).
## Set up
Two commands: `check` (fast, every change) and `deep` (slow, release or schedule).
Keep a table `docs/verification-status.md`: technique, command, cost, cadence,
last run date, commit, result.
## Minimal example
`docs/verification-status.md`:
| technique | command | cost | cadence | last run | commit | result |
| clippy, tests | just check | 2 min | every change | CI | HEAD | pass |
| cargo-mutants | just mutants | 2 h | weekly | 2026-11-14 | a1b2c3d | 312 caught, 4 equivalent (see findings-log) |
| kani proofs | just prove | 20 min | before release | 2026-11-20 | e4f5a6b | pass |
A scheduled workflow (`on: schedule: - cron: "0 3 * * 1"`) runs `just deep`.
## Run
git rev-list --count a1b2c3d..HEAD -- src/ # commits since the deep evidence
Passing looks like: the fast set passes on this change, and for each deep
technique the recorded commit is the current one for the code it covers, or the count
of commits since touching that code is zero. If not zero, the deep result is stale:
say "last run at <commit>, N commits behind", never "passes".
## As a contract check
{"id": "deep-evidence-fresh", "claim": "Deep verification was run on the current code, or its age is reported", "kind": "general", "rung": 3, "cmd": "python3 tools/evidence_age.py docs/verification-status.md --max-commits 0", "expect": {"exit": 0}, "timeout_s": 60}
## What a pass does not prove
That the deep run itself was strong. A date with no commit hash is
unusable, and one hand-edited without running is false evidence: have CI write
the table. Splitting into tiers is only safe if release runs the deep tier; see
`release-gate`.
+57
View File
@@ -0,0 +1,57 @@
---
id: findings-log
title: A log of every defect found, rejected mutant and false alarm
answers: What has already been found, tried and ruled out, so I do not repeat or reopen it?
rung: 3
section: completeness
languages: any
kinds: general
cost: low
detect:
ran_here: no
verified: docs
---
Note: no tool. Modelled on a reference project, which records what
each proof and mutation run found, and which survivors were equivalent. Not run here.
## Use when
- A verification effort spans more than one session, and the next agent must know what the last one covered.
- A tool reports things that are not bugs (an equivalent mutant, a lint you decided to accept, a flaky test cause). Say so once, with the reason.
- You found a real defect: record its id, what caught it, and the regression test.
## Do not use when
- A single quick check with nothing to carry forward.
## Set up
Create `docs/findings.md` with a table or dated list. One line per finding.
Fields: date, what, how found (technique id), verdict, evidence, follow-up.
## Minimal example
| 2026-11-09 | Negative amounts accepted by the engine | kani | defect, fixed | test `rejects_negative_line` | none |
| 2026-11-09 | Mutant `a < b` to `a <= b` in `fees.rs:42` survived | cargo-mutants | equivalent: both branches return the same value when equal | read of lines 40-44 | none |
| 2026-11-10 | `test_sync` fails 1 in 50 | stress-repeat | defect: shared temp dir; fixed | passes 500 runs | none |
Every "equivalent" or "false alarm" verdict needs the reason, or it is just a
dismissal. Every defect names its regression test.
## Run
python3 - <<'PY'
import re,sys
rows=[l for l in open("docs/findings.md") if l.startswith("|") and "---" not in l]
bad=[l for l in rows if re.search(r"equivalent|false alarm",l) and len(l.split("|"))<7]
print("rows:",len(rows)); sys.exit(1 if bad else 0)
PY
Passing looks like: every row is complete and each defect row names a test that
exists (`grep -rn "rejects_negative_line" tests/`). Before starting, read the log for
the area; do not re-triage a recorded equivalent mutant.
## As a contract check
{"id": "findings-recorded", "claim": "Every defect found has a regression test and every dismissal has a reason", "kind": "general", "rung": 3, "cmd": "python3 tools/findings_lint.py docs/findings.md", "expect": {"exit": 0}, "timeout_s": 30}
## What a pass does not prove
That the log is complete: only what someone wrote. Keep the real record in the
repository, not the chat. A dismissal can be wrong; give it a date and re-open on a code
change to the area. The log is for the next agent, so write for someone who
saw none of this session.
+54
View File
@@ -0,0 +1,54 @@
---
id: no-stubs-scan
title: Scanning for stubs, skipped tests, commented-out assertions and placeholder data
answers: Is anything still a placeholder, skipped, or switched off in what I am calling finished?
rung: 3
section: completeness
languages: any
kinds: general
cost: low
detect: git --version
ran_here: yes
verified: ran
---
## Use when
- Always before saying "done". An unfinished function that compiles is the most common false finish.
- Tests were added or changed: skipped and `#[ignore]`d tests count as missing.
- You edited tests to get a green run (deleting or commenting an assertion is how a failing test gets quieted).
## Do not use when
- It is the only check. It finds markers, not missing work with no marker.
## Set up
Commit `scripts/stubscan.sh`. Tune the pattern to the languages in use. Where a
marker is legitimate (a documented known gap), list the file in the script's
exclusions with a reason, not a blanket `|| true`.
## Minimal example
`scripts/stubscan.sh`:
#!/usr/bin/env bash
pat='todo!\(|unimplemented!\(|NotImplementedError|^\s*sorry\b|#\[ignore|@pytest\.mark\.(skip|xfail)|\.skip\(|\bxit\(|t\.Skip\(|^\s*//\s*(assert|expect)|^\s*#\s*assert|lorem ipsum'
if git grep -n -I -E -i -e "$pat" -- . ':!scripts/stubscan.sh' ':!docs'; then exit 1; fi
`git grep` exits 0 when it finds a match, so a match fails the script. Also look in the diff:
`git diff BASE | grep -E '^-.*(assert|expect)'` lists assertions you removed.
For `unwrap()`/`panic!("not yet")` and `pass`-only bodies, add patterns to taste.
## Run
bash scripts/stubscan.sh
Passing looks like: no output, exit 0. Failure (run here) prints file:line for each
`todo!()`, `#[ignore]` and commented assertion, and exits 1. Then also ask: is
there placeholder data (names like `foo`, `test@example.com`, `12345`) in
shipped files, not tests? Grep for it by hand.
## As a contract check
{"id": "no-stubs", "claim": "No stub markers, skipped tests or commented-out assertions in the tree", "kind": "general", "rung": 3, "cmd": "bash scripts/stubscan.sh", "expect": {"exit": 0}, "timeout_s": 60}
## What a pass does not prove
A stub written without a marker (`return 0`, an empty `else`) passes. A test that
asserts nothing passes (see `vacuity-check`, `assertion-strength-review`). The
scan checks tracked and untracked files but not ignored ones. Do not weaken the
pattern to get a pass; add a justified exclusion instead.
+58
View File
@@ -0,0 +1,58 @@
---
id: release-gate
title: One command or workflow that must pass before release
answers: Is this exact build safe to publish, with the right version, notices, full tests and package contents?
rung: 3
section: completeness
languages: any
kinds: general
cost: medium
detect: just --version
ran_here: no
verified: docs
---
Note: modelled on a release workflow in a reference project (tag must
equal the program's version; notices current; packages built on the oldest supported
system; each package inspected for its contents; the release left as a draft).
Not run here.
## Use when
- You are about to tag, publish a package, push an image or hand over a build.
- A release process has more than two manual steps and one has been missed before.
## Do not use when
- Nothing is being released. For everyday work use `single-gate-command`.
## Set up
A script `scripts/release-gate.sh` that the release workflow calls first and fails
fast. Keep publishing a separate step that runs only after the gate. Leave the
release a draft until the owner has tried the package.
## Minimal example
#!/usr/bin/env bash
set -euo pipefail
ver=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
[ "${GITHUB_REF_NAME:-v$ver}" = "v$ver" ] || { echo "tag != version $ver" >&2; exit 1; }
scripts/notices.sh --check
just check
cargo package --list | grep -q '^LICENSE' || { echo "LICENSE missing from package" >&2; exit 1; }
cargo package --locked --allow-dirty >/dev/null
git diff --exit-code # nothing the gate regenerated is uncommitted
## Run
scripts/release-gate.sh
Passing looks like: exit 0 and each step's own success line. Failure names the step
(`tag != version`, `notices out of date`). Then install the built package on a clean
machine and run it (`packaging-install-upgrade`, `clean-clone-build`); the gate
alone does not do that. Include the changelog entry and the deep tier (`check-tiering`).
## As a contract check
{"id": "release-gate", "claim": "The release gate passes for the version being released", "kind": "general", "rung": 3, "cmd": "scripts/release-gate.sh", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 3600}
## What a pass does not prove
That the release works for users. A gate on a developer machine proves little
about a clean one; run it in CI from a fresh clone. A gate someone can skip by
tagging by hand is not a gate: have the workflow trigger on the tag and refuse
to publish unless the gate job passed.
@@ -0,0 +1,62 @@
---
id: requirement-to-check-map
title: Mapping each sentence of the request to a contract check, and listing what has none
answers: Does every thing the human asked for have a check, and which asks have none?
rung: 3
section: completeness
languages: any
kinds: general
cost: low
detect: python3 --version
ran_here: no
verified: docs
---
Note: no tool; the map is a small file and a script. The script was not run
here as written, only the traceability idea behind it (`spec-traceability`).
## Use when
- You start non-trivial work from a request in prose and are drafting `.sisi/contract.json` (core rule 1).
- The request is long, or has "and also" clauses that are easy to drop.
- You are about to say "done" and need to show nothing asked for was left out.
## Do not use when
- The request is a one-line change; just run its check.
- A numbered spec already exists; use `spec-traceability`.
## Set up
Copy the request into `.sisi/request.md`, one sentence or clause per line, each
tagged `Q1`, `Q2`, and so on. Number them in the order the human wrote them.
## Minimal example
`.sisi/request.md`:
Q1 Import the bank CSV into the books.
Q2 Skip rows that are already there.
Q3 Show me what was skipped.
Q4 Keep the old import working.
In the contract, add `"asks": ["Q1"]` to the check that proves each, or list a
sentence under `"unchecked": {"Q3": "needs the human; screen output"}` with the reason.
## Run
python3 - <<'PY'
import json,re,sys
q=set(re.findall(r"^(Q\d+)",open(".sisi/request.md").read(),re.M))
c=json.load(open(".sisi/contract.json"))
have={a for k in c["checks"] for a in k.get("asks",[])}|set(c.get("unchecked",{}))
miss=sorted(q-have); print("no check:",miss or "none"); sys.exit(1 if miss else 0)
PY
Passing looks like: `no check: none`, exit 0. Failure prints the sentences with no
check, exit 1. Report every `unchecked` entry in the final answer as not verified.
## As a contract check
{"id": "request-mapped", "claim": "Every sentence of the request maps to a check or a stated reason it has none", "kind": "general", "rung": 3, "cmd": "python3 tools/request_map.py", "expect": {"exit": 0, "stdout_contains": "no check: none"}, "timeout_s": 30}
## What a pass does not prove
That the check is strong; a Q mapped to a weak check passes. Read the map for
the sentences where the check is only "the command runs". Implicit asks (the
human did not write "do not break the old import") are missing: Q4 above must
be added by you, from the invariants in core rule 3. An `unchecked` list is
honest only if it is reported.
@@ -0,0 +1,59 @@
---
id: single-gate-command
title: One project command that runs everything required, so done has one definition
answers: Is there exactly one command whose success means the project's required checks all pass?
rung: 3
section: completeness
languages: any
kinds: general
cost: low
detect: just --version
ran_here: yes
verified: ran
---
Ran here: a two-step `justfile` recipe, failing and then passing. Make works the
same way with a `verify` target.
## Use when
- A project has several checks (format, lint, tests, dependency audit, notices) and people or agents run a different subset each time.
- You want the contract's required checks, CI and a developer's "am I done" to be the same thing.
- Starting a project: create the gate on day one, while it is small.
## Do not use when
- Some checks take hours. Put those in the deep tier (`check-tiering`); the gate is the fast set.
## Set up
# justfile
set shell := ["bash", "-euo", "pipefail", "-c"]
check:
cargo fmt --all --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
scripts/stubscan.sh
cargo deny check
CI must run `just check` and nothing else for the pull-request job, or the two definitions diverge.
## Minimal example
check:
test "$(cat flag.txt)" = ok
echo "gate passed"
`just check` with `flag.txt` containing `bad` stops at the first failing line, prints
the line `error: recipe check failed on line 3 with exit code 1` and exits 1; with `ok` it prints `gate passed`, exit 0.
## Run
just check
Passing looks like: exit 0, with each step's output visible. just stops at the first failing line. In Make, each line is its own shell and
also stops the recipe, but a multi-line `if` or loop needs `&&` chaining or `.ONESHELL` with `set -e`. Never write `command || true` in the gate.
## As a contract check
{"id": "gate", "claim": "The project gate command passes", "kind": "general", "rung": 3, "cmd": "just check", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800}
## What a pass does not prove
Only what the gate contains. The usual rot is a check removed from the recipe, or a
step that exits 0 on failure. Review diffs to the gate file as closely as code, and
ensure a deliberately broken input fails it (check the check). A gate
that is too slow gets skipped; keep the fast set fast.
@@ -0,0 +1,65 @@
---
id: spec-traceability
title: Requirement ids cited by code and tests, with a test that fails on an unknown, uncited or untested id
answers: Is every requirement implemented and tested, and does every cited id exist?
rung: 3
section: completeness
languages: any
kinds: general, state-machine, money
cost: medium
detect: python3 --version
ran_here: yes
verified: ran
---
Modelled on a reference project, where each rule has an id, tests live
under a `spec/` folder keyed by those ids, and a loader test fails when a
claim has no test. The script below was run here on a scratch repository.
## Use when
- There is a written specification (rules, requirements, invariants) and "all of it is done" must be checkable.
- The request has many separate rules and one is easy to forget.
- A reviewer asks "where is rule R-17 implemented, and what tests it?"
## Do not use when
- The task is small or has no written requirements. Use `requirement-to-check-map` for the request's sentences.
- Ids would be cited without being exercised. The citation proves a link, not that the test is strong; see `assertion-strength-review`.
## Set up
Give every requirement a stable id in one file (`spec/requirements.md`, lines
`- R-001: text`). Code cites `implements: R-001` in a comment; each test cites
`covers: R-001`. Never renumber; retire an id with a note.
## Minimal example
`scripts/spec_trace.py` (standard library, run from the repository root):
import re, subprocess, sys
ids = set(re.findall(r"^- (R-\d+):", open("spec/requirements.md").read(), re.M))
files = subprocess.run(["git","ls-files","-co","--exclude-standard","src","tests"],
capture_output=True, text=True, check=True).stdout.split()
impl, cov = set(), set()
for f in files:
t = open(f, errors="ignore").read()
impl |= set(re.findall(r"implements:\s*(R-\d+)", t))
cov |= set(re.findall(r"covers:\s*(R-\d+)", t))
bad = [f"unknown id cited: {i}" for i in sorted((impl|cov)-ids)]
bad += [f"{i}: no code cites it" for i in sorted(ids-impl)]
bad += [f"{i}: no test covers it" for i in sorted(ids-cov)]
print("\n".join(bad) or f"ok: {len(ids)} requirements traced")
sys.exit(1 if bad else 0)
## Run
python3 scripts/spec_trace.py
Passing looks like: `ok: N requirements traced`, exit 0. Failure lists each problem
(`R-002: no test covers it`, `unknown id cited: R-009`) and exits 1 (run here).
## As a contract check
{"id": "spec-traced", "claim": "Every requirement id is cited by code and by a test, and every cited id exists", "kind": "general", "rung": 3, "cmd": "python3 scripts/spec_trace.py", "expect": {"exit": 0, "stdout_contains": "requirements traced"}, "timeout_s": 60}
## What a pass does not prove
That a test citing `covers: R-001` actually checks R-001, or even passes. A
comment is cheap. Strengthen it: the test run must also pass, and the cited test
should fail when the requirement's code is broken (`mutation-on-diff`). Also
count the ids: a spec that was quietly shortened passes, so compare the id count to the
agreed spec in review.
@@ -0,0 +1,55 @@
---
id: address-and-ub-sanitizers
title: Memory-error and undefined-behaviour detection with ASan, UBSan and MSan
answers: Does my C, C++ or unsafe Rust code read or write bad memory, overflow, or use uninitialised data while the tests run?
rung: 2
section: concurrency
languages: c, cpp, rust
kinds: general, concurrency
cost: low
detect: cc --version
ran_here: yes
verified: ran
---
## Use when
- You changed C, C++ or `unsafe` Rust, FFI, buffers, pointer arithmetic or parsing of untrusted bytes.
- A test crashes only sometimes, or output differs by build mode, which hints at undefined behaviour.
- You want a fast memory-safety check that works on code too heavy for Miri.
## Do not use when
- The code is safe Rust with no FFI; the compiler already prevents these.
- You need data-race detection; use `thread-sanitizer`. ASan and TSan cannot be combined in one binary.
- MSan on Linux needs clang and an instrumented standard library; skip it if you cannot rebuild dependencies.
## Set up
- ASan (heap and stack overflow, use-after-free, leaks): `-fsanitize=address -g`.
- UBSan (signed overflow, bad shifts, null deref): `-fsanitize=undefined -fno-sanitize-recover=undefined`, so a finding stops the run with a non-zero exit.
- MSan (uninitialised reads, clang only): `-fsanitize=memory -g`.
- Rust nightly: `RUSTFLAGS="-Zsanitizer=address"` (or `memory`) with `--target <host triple>`. `memory` also needs `-Zbuild-std`.
## Minimal example
`a.c`, a heap overflow:
#include <stdlib.h>
int main(int argc, char **argv) { int *a = malloc(4 * sizeof(int)); a[argc + 3] = 1; free(a); return 0; }
Rust, a read one past a vector:
pub fn read_past_end() -> u8 { let v = vec![1u8, 2, 3]; unsafe { *v.as_ptr().add(3) } }
#[test] fn t() { let _ = read_past_end(); }
## Run
gcc -fsanitize=address -g a.c -o a && ./a
RUSTFLAGS="-Zsanitizer=address" cargo +nightly test --target x86_64-unknown-linux-gnu --lib
Passing looks like: exit 0 and no `ERROR: AddressSanitizer` text. Failure prints `ERROR: AddressSanitizer: heap-buffer-overflow ... SUMMARY: ...` and exits 1; UBSan prints `runtime error: signed integer overflow` and, with `-fno-sanitize-recover`, exits 1. MSan prints `use-of-uninitialized-value` and exits 1.
## As a contract check
{"id": "asan-tests", "claim": "No memory errors under AddressSanitizer in the unit tests", "kind": "general", "rung": 2, "cmd": "RUSTFLAGS=\"-Zsanitizer=address\" cargo +nightly test --target x86_64-unknown-linux-gnu --lib", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
## What a pass does not prove
- It only watches code paths the tests execute. Rung 2 at best; pair with fuzzing to reach more paths.
- ASan misses uninitialised reads; MSan misses overflows; neither covers everything UBSan checks. Run the ones that fit.
- Only instrumented code is checked. A prebuilt library is not.
- Check the check: keep a deliberately bad test (the overflow above) and confirm each sanitizer build fails on it. The sanitizer runtime must be installed, or the build fails to link; a build failure is not a pass.
@@ -0,0 +1,65 @@
---
id: async-cancellation-safety
title: Cancellation-safety tests that drop a future at every await point
answers: If this async function is cancelled at any await, does shared state stay consistent?
rung: 2
section: concurrency
languages: rust, any
kinds: concurrency, state-machine, money
cost: medium
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- An async function mutates shared state, holds a lock, sends a message or writes a file across more than one `.await`.
- The future may be dropped: `select!`, `timeout`, task abort, client disconnect, request cancellation.
- You changed the order of effects around an await, or added an await in the middle of an update.
## Do not use when
- The function has no await between related effects; plain tests are enough.
- You need races between tasks, not cancellation of one. Use `shuttle` or `loom`.
## Set up
No dependency is needed. Drive the future by hand with `Waker::noop()` (stable since Rust 1.85): poll it `k` times, drop it, then assert the invariant. Loop `k` from 1 until the future completes. Each `k` is one await point. In Tokio code, put the same loop on a current-thread runtime with `tokio::time::pause`.
## Minimal example
`src/lib.rs`. `transfer` debits, awaits, then credits; the test finds the lost money.
pub async fn transfer(a: &Account, amt: i64) {
*a.from.borrow_mut() -= amt;
yield_now().await; // cancelled here: money vanishes
*a.to.borrow_mut() += amt;
}
fn run_until_dropped<F: Future<Output = ()>>(fut: F, k: usize) -> bool {
let mut fut = std::pin::pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
for _ in 0..k { if fut.as_mut().poll(&mut cx).is_ready() { return true; } }
false // dropped on return
}
#[test] fn conserved_when_dropped_at_every_await() {
for k in 1..=10 {
let a = Account { from: RefCell::new(100), to: RefCell::new(0) };
let done = run_until_dropped(transfer(&a, 30), k);
assert_eq!(*a.from.borrow() + *a.to.borrow(), 100, "after {k} polls");
if done { return; }
}
panic!("never finished");
}
`yield_now` is a hand-written future that returns `Pending` once and calls `wake_by_ref`. Fix the bug by crediting and debiting together, or with a drop guard that restores state.
## Run
cargo test conserved_when_dropped_at_every_await
Passing looks like: `test result: ok. 1 passed`. Failure shows `assertion failed: ... after 1 polls`, exit 101.
## As a contract check
{"id": "cancel-safe", "claim": "Invariants hold when transfer is dropped at every await", "kind": "concurrency", "rung": 2, "cmd": "cargo test conserved_when_dropped_at_every_await", "expect": {"exit": 0, "stdout_contains": "1 passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- It cancels at poll boundaries of one future in isolation, not with other tasks running between polls. Combine with `shuttle` for that.
- Real I/O futures complete or fail on their own timing; this only tests your own await points with stubbed dependencies.
- The bound on `k` must exceed the real await count, which is why the test panics if it never finishes.
- Check the check: reintroduce the bug and confirm the failure message.
@@ -0,0 +1,69 @@
---
id: deterministic-simulation
title: Deterministic simulation of async and distributed systems (turmoil, madsim)
answers: Does my networked or async system keep working under reordering, delays, partitions and crashes, reproducibly from a seed?
rung: 2
section: concurrency
languages: rust, any
kinds: concurrency, state-machine
cost: high
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- The system has several nodes or tasks talking over a network, uses timeouts, retries, leases or elections.
- You need fault tests (partition, delay, restart) that are repeatable, not flaky.
- A bug appeared once in the field and you want to replay it from a seed.
## Do not use when
- The code is one thread with no I/O; use plain tests.
- You must exercise the real kernel, real sockets or real disks. Simulation replaces them.
- Code under test calls the wall clock or OS randomness directly and cannot be routed through the simulator; it will not be deterministic.
## Set up
The pattern: all time, network, disk and randomness go through a simulated layer driven by one seed; the same seed gives the same run. Rust options:
- `turmoil` (Tokio hosts, simulated TCP and UDP, partitions): `cargo add turmoil` plus `tokio` with `rt,macros,time`.
- `madsim` (also simulates disk and RPC; swap in `madsim-tokio`; build with `RUSTFLAGS="--cfg madsim"`). Its seed environment variables were not confirmed here; check docs.rs/madsim.
In other languages, copy the pattern: inject a clock, a network and a random source, then run many seeds.
## Minimal example
`src/main.rs` with turmoil 0.7:
use std::time::Duration;
use turmoil::{net::{TcpListener, TcpStream}, Builder};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
fn run(seed: u64) -> turmoil::Result {
let mut sim = Builder::new().rng_seed(seed).simulation_duration(Duration::from_secs(60)).build();
sim.host("server", || async {
let l = TcpListener::bind("0.0.0.0:9000").await?;
loop { let (mut s, _) = l.accept().await?; let mut b = [0u8; 4]; s.read_exact(&mut b).await?; s.write_all(&b).await?; }
});
sim.client("client", async {
let mut s = TcpStream::connect("server:9000").await?;
s.write_all(b"ping").await?; let mut b = [0u8; 4]; s.read_exact(&mut b).await?;
assert_eq!(&b, b"ping");
turmoil::partition("client", "server");
let r = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect("server:9000")).await;
assert!(!matches!(r, Ok(Ok(_))), "connect must fail across a partition");
turmoil::repair("client", "server");
Ok(())
});
sim.run()
}
fn main() { for seed in 0..20 { run(seed).unwrap_or_else(|e| panic!("seed {seed}: {e}")); } println!("20 seeds ok"); }
## Run
cargo run
Passing looks like: `20 seeds ok`, exit 0. Failure panics with the failing seed, exit 101. Re-run just that seed to debug.
## As a contract check
{"id": "sim-seeds", "claim": "Protocol invariants hold across 20 simulated seeds with a partition", "kind": "concurrency", "rung": 2, "cmd": "cargo run", "expect": {"exit": 0, "stdout_contains": "seeds ok"}, "tier": "deep", "timeout_s": 600}
## What a pass does not prove
- It samples seeds and faults; rung 2. More seeds and more fault types find more.
- It tests your logic against the simulator's model of the network, not the real one. Simulator gaps (partial writes, clock drift) hide bugs.
- Anything outside the simulated layer is not controlled. If the same seed gives different outcomes, determinism is broken; run one seed twice and compare.
- Check the check: inject a known bug (drop the retry) and confirm some seed fails.
+58
View File
@@ -0,0 +1,58 @@
---
id: go-race-detector
title: Data-race detection in Go with go test -race
answers: Do my goroutines read and write the same variable without synchronisation?
rung: 2
section: concurrency
languages: go
kinds: concurrency
cost: low
detect: go version
ran_here: no
verified: docs
---
## Use when
- You touched goroutines, channels, shared maps or slices, `sync` types or closures that capture loop variables.
- You want a cheap, always-on check in CI for any Go package with concurrency.
- A Go test is flaky and you suspect a race.
## Do not use when
- You want proof of no races. It sees only races that actually happen in the run.
- Cgo is disabled or no C compiler is installed; the race detector needs both.
- The race is a logic race over properly locked data; it only reports unsynchronised access.
## Set up
Nothing to install beyond the Go toolchain (and a C compiler on non-macOS). Supported on linux/amd64, arm64, and several other platforms listed in Go's race detector doc. Not checked on this machine: Go is not installed here, so commands come from go.dev/doc/articles/race_detector.
## Minimal example
`race_test.go`:
package race
import ("sync"; "testing")
func TestCounter(t *testing.T) {
n := 0
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Add(1)
go func() { defer wg.Done(); n++ }() // race: use sync/atomic or a mutex
}
wg.Wait()
}
## Run
go test -race ./...
GORACE="halt_on_error=1 history_size=2" go test -race -count=5 ./...
Passing looks like: `ok <pkg>` lines, exit 0. Failure prints `WARNING: DATA RACE` with the conflicting reads and writes and goroutine creation stacks, and the test fails (`testing.go: race detected during execution of test`); the binary exit status after a race is 66 by default. Add `-count=N` to repeat; the detector is per-run.
## As a contract check
{"id": "go-race", "claim": "No data race detected across the Go test suite", "kind": "concurrency", "rung": 2, "cmd": "go test -race -count=3 ./...", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
## What a pass does not prove
- Races only on code paths that ran. Execution is 2x to 20x slower and uses 5x to 10x more memory, so some teams run only part of the suite; say which.
- It finds data races, not deadlocks, goroutine leaks, or ordering bugs on synchronised data.
- Build-tagged `//go:build !race` tests are skipped under `-race`; check none hide the test you care about.
- Check the check: introduce the unsynchronised write above and confirm `go test -race` fails. If you add `-run` or a package filter, confirm tests actually ran (`go test -race -v` lists them; `no tests to run` means vacuous).
@@ -0,0 +1,57 @@
---
id: linearizability-checking
title: Linearizability checking of recorded histories (Porcupine, Knossos)
answers: Can the operations my concurrent or distributed store returned be explained by some one-at-a-time order?
rung: 2
section: concurrency
languages: go, any
kinds: concurrency, state-machine
cost: high
detect: go version
ran_here: no
verified: docs
---
## Use when
- You built a concurrent map, queue, register, lock service or replicated store and claim "it behaves as if operations happen one at a time".
- Individual tests pass but you doubt results seen by concurrent clients.
- You can record, per operation, the call time, the return time, the input and the output.
## Do not use when
- The claim is a weaker consistency level; model that instead (Jepsen's Elle checks serializability and snapshot isolation).
- You only need to detect data races; use a race detector.
- Operations cannot be timestamped by a single clock source or logical order.
## Set up
Go: Porcupine, `go get github.com/anishathalye/porcupine`. Clojure: Knossos, used by Jepsen. Not run here: Go is not installed; the API below is from Porcupine's README and pkg.go.dev. Steps: (1) run many concurrent clients against the system with random operations, recording each as an `Operation`; (2) write a sequential model of the object; (3) check the history.
## Minimal example
A register (put/get) in Go:
type in struct{ put bool; v int }
model := porcupine.Model{
Init: func() interface{} { return 0 },
Step: func(state, input, output interface{}) (bool, interface{}) {
i := input.(in)
if i.put { return true, i.v }
return output.(int) == state.(int), state
},
}
// history []porcupine.Operation{ {ClientId, Input, Call, Output, Return}, ... }
if !porcupine.CheckOperations(model, history) { t.Fatal("history is not linearizable") }
`CheckOperationsTimeout(model, history, d)` returns `Ok`, `Illegal` or `Unknown` (timeout). Use `porcupine.Visualize` for an HTML picture of a failure.
## Run
go test -run TestLinearizable -count=1 ./...
Passing looks like: the test passes, exit 0, with a non-trivial history (many overlapping operations). Failure is `history is not linearizable` plus the visualisation file.
## As a contract check
{"id": "linearizable", "claim": "Recorded concurrent histories are linearizable against the register model", "kind": "concurrency", "rung": 2, "cmd": "go test -run TestLinearizable -count=1 ./...", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
## What a pass does not prove
- It checks the histories you generated. Different timing or faults may produce a bad one; run with fault injection and many seeds. Rung 2.
- A model that is too permissive passes anything. Check the check: edit the system to return a stale read and see the history be rejected.
- Weak workloads (one client, few keys, no overlap) pass trivially; assert that operations actually overlap.
- Checking can time out on long histories; `Unknown` is not a pass. Treat it as failure or shorten and partition by key.
@@ -0,0 +1,58 @@
---
id: lock-order-and-deadlock
title: Deadlock detection and lock-order checking (parking_lot, Go, Clang)
answers: Can my code deadlock by taking locks in conflicting orders?
rung: 2
section: concurrency
languages: rust, go, c, cpp
kinds: concurrency
cost: low
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- Code takes more than one lock, or calls out to user code while holding one.
- A test or service hangs and you suspect a deadlock.
- You changed lock acquisition order, or added a new lock to a module.
## Do not use when
- A single lock and no callbacks; there is nothing to order.
- You need a guarantee. These tools report deadlocks that happen or conflicts that were seen, not all possible ones; `loom` or `shuttle` explore more orderings.
## Set up
- Rust: `cargo add parking_lot --features deadlock_detection`, use `parking_lot::Mutex`, and run a checker thread.
- Go: the runtime prints `fatal error: all goroutines are asleep - deadlock!` and exits 2 when every goroutine blocks. Partial deadlocks are not detected; add a test timeout (`go test -timeout 60s`).
- C/C++: ThreadSanitizer reports `lock-order-inversion` (potential deadlock) even if no hang occurred; build with `-fsanitize=thread`.
## Minimal example
Rust checker thread, started at program or test start:
std::thread::spawn(|| loop {
std::thread::sleep(std::time::Duration::from_secs(1));
let d = parking_lot::deadlock::check_deadlock();
if d.is_empty() { continue; }
for (i, ts) in d.iter().enumerate() {
eprintln!("deadlock #{i}");
for t in ts { eprintln!("thread {:?}\n{:?}", t.thread_id(), t.backtrace()); }
}
std::process::exit(101);
});
A program where two threads lock `a` then `b` and `b` then `a` (with a short sleep between) prints `deadlock #0` with backtraces and exits 101. Without the checker it hangs forever.
## Run
cargo test # with the checker thread started in the test setup
timeout 120 cargo test
Passing looks like: tests finish, exit 0. Failure is the `deadlock #N` report and exit 101, or a timeout (exit 124 from `timeout`).
## As a contract check
{"id": "no-deadlock", "claim": "Test suite finishes with no parking_lot deadlock reported", "kind": "concurrency", "rung": 2, "cmd": "timeout 300 cargo test --features deadlock_detection", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 330}
## What a pass does not prove
- It detects a deadlock only if the test actually drove the threads into it. Rung 2. A hang with no checker is the failure signal, so always run under a timeout.
- `parking_lot` detection covers its own locks, not `std::sync::Mutex`, channels or async mutexes.
- Go's detector misses deadlocks while any other goroutine is alive (such as an HTTP server).
- Check the check: keep a two-lock inversion test and confirm it fails with the checker on.
+71
View File
@@ -0,0 +1,71 @@
---
id: loom
title: Exhaustive interleaving tests for Rust concurrency with loom
answers: Is there any thread interleaving of this lock-free or shared-state code that breaks my assertion?
rung: 1
section: concurrency
languages: rust
kinds: concurrency, state-machine
cost: medium
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- You wrote or changed a small concurrent core: an atomic counter, a lock-free queue, a channel, a mutex-protected state machine, a once-cell.
- A test passes "most of the time" and you need every ordering, not a sample of them.
- The claim is about memory ordering (`Relaxed`, `Acquire`, `Release`) and a stress test cannot show it.
## Do not use when
- The code is large or does I/O, sleeps, or uses `tokio`; loom's state space explodes. Use `shuttle` for those.
- The code is single-threaded. Use ordinary tests.
- You need to check real `unsafe` memory behaviour; use `miri` as well.
## Set up
Loom replaces `std::sync`, `std::thread` and atomics with model-checked versions. Gate it behind `--cfg loom` so normal builds are untouched.
[target.'cfg(loom)'.dependencies]
loom = "0.7"
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(loom)'] }
In the code, import atomics and threads from `loom::` under `#[cfg(loom)]`, from `std::` otherwise.
## Minimal example
`src/lib.rs`. The counter below has a lost-update bug; loom finds it. Replace load+store with `fetch_add` and it passes.
#[cfg(loom)] use loom::sync::atomic::{AtomicUsize, Ordering};
#[cfg(not(loom))] use std::sync::atomic::{AtomicUsize, Ordering};
pub struct Counter(AtomicUsize);
impl Counter {
pub fn new() -> Self { Counter(AtomicUsize::new(0)) }
pub fn incr(&self) { self.0.fetch_add(1, Ordering::SeqCst); }
pub fn get(&self) -> usize { self.0.load(Ordering::SeqCst) }
}
#[cfg(loom)]
mod loom_tests {
use super::*; use loom::{sync::Arc, thread};
#[test] fn both_increments_counted() {
loom::model(|| {
let c = Arc::new(Counter::new()); let c2 = c.clone();
let t = thread::spawn(move || c2.incr());
c.incr(); t.join().unwrap();
assert_eq!(c.get(), 2);
});
}
}
## Run
RUSTFLAGS="--cfg loom" cargo test --release --lib loom_tests
Passing looks like: `test result: ok. 1 passed`, exit 0. Failure shows as a panic inside `loom::model` (for the buggy version: `left: 1, right: 2`), exit 101. Set `LOOM_MAX_PREEMPTIONS=3` to bound a slow model.
## As a contract check
{"id": "loom-counter", "claim": "No interleaving of two incr calls loses an update", "kind": "concurrency", "rung": 1, "cmd": "RUSTFLAGS=\"--cfg loom\" cargo test --release --lib loom_tests", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
## What a pass does not prove
- It covers only the threads, operations and inputs inside the `loom::model` closure. Rung 1 holds within those bounds only.
- With `LOOM_MAX_PREEMPTIONS` set, it is bounded, not exhaustive.
- Code that still uses `std::sync` types is invisible to it. Check every concurrency import is swapped under `cfg(loom)`.
- Check the check: put the bug back (load then store). The test must fail. Also confirm the test ran: a filter that matches nothing prints `0 passed` and exits 0.
+62
View File
@@ -0,0 +1,62 @@
---
id: miri
title: Undefined behaviour and data-race detection for Rust with Miri
answers: Does my unsafe Rust code, or my threaded test, perform undefined behaviour or a data race?
rung: 2
section: concurrency
languages: rust
kinds: concurrency, general
cost: medium
detect: cargo +nightly miri --version
ran_here: yes
verified: ran
---
## Use when
- You wrote or changed `unsafe` code, raw pointers, `transmute`, FFI-free pointer arithmetic or custom `Send`/`Sync` impls.
- A test uses threads and you want data races on non-atomic memory detected.
- You want out-of-bounds, use-after-free, uninitialised reads and aliasing violations reported as errors.
## Do not use when
- The code does heavy I/O, FFI, or runs long. Miri is 10x to 100x slower and cannot run most foreign code.
- You need to find logic-level races on atomics or locks. Use `loom` or `shuttle`.
## Set up
rustup toolchain install nightly --component miri
cargo +nightly miri setup
Pin the nightly in CI so results are reproducible.
## Minimal example
Two threads write one `u32` without synchronisation:
use std::thread;
pub struct Racy(*mut u32);
unsafe impl Send for Racy {}
pub fn racy_count() -> u32 {
let mut n = 0u32;
let p = Racy(&mut n);
let h = thread::spawn(move || { let p = p; unsafe { *p.0 += 1 }; });
unsafe { *(&raw mut n) += 1 };
h.join().unwrap();
n
}
#[test] fn counts() { assert_eq!(racy_count(), 2); }
Plain `cargo test` passes. Miri fails it. Using `AtomicU32` instead makes Miri pass.
## Run
cargo +nightly miri test
MIRIFLAGS="-Zmiri-many-seeds=0..16" cargo +nightly miri test # vary the thread schedule
MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri test # allow clock and file access
Passing looks like: normal test output, exit 0. Failure shows `error: Undefined Behavior: Data race detected between ...` (or the UB kind), exit 1.
## As a contract check
{"id": "miri-ub", "claim": "No undefined behaviour or data race in the unit tests under Miri", "kind": "concurrency", "rung": 2, "cmd": "cargo +nightly miri test --lib", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800}
## What a pass does not prove
- Miri checks only executions the tests perform, on one schedule per seed. Use `-Zmiri-many-seeds` to sample more; it is still sampling, rung 2.
- It checks the Rust abstract machine, not hardware memory models in full.
- Tests that cannot run under Miri (FFI, some syscalls) are skipped or fail; do not mark them `#[cfg_attr(miri, ignore)]` without saying so.
- Check the check: introduce a known UB (read past a `Vec`'s end) and confirm Miri errors. Reduce proptest or loop counts under Miri (for example `PROPTEST_CASES=4`) so it finishes; say you did.
+61
View File
@@ -0,0 +1,61 @@
---
id: shuttle
title: Randomised schedule testing for Rust concurrency with shuttle
answers: Does my concurrent or async Rust code hold its invariants across many different thread schedules?
rung: 2
section: concurrency
languages: rust
kinds: concurrency, state-machine
cost: medium
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- The concurrent code is too large for `loom` to explore exhaustively, but you want schedule control and replay.
- You need a failing schedule you can replay exactly, which a plain stress test cannot give.
- You want to test code built on `std::sync`, `std::thread` or futures with a controlled scheduler.
## Do not use when
- The component is small enough for `loom`; exhaustive is stronger.
- The bug is in memory ordering. Shuttle models sequentially consistent execution, not weak memory.
- The code uses real I/O or wall-clock time; shuttle cannot control them.
## Set up
Add `shuttle` as a dev-dependency and have the code under test use `shuttle::sync` and `shuttle::thread` (via a `cfg` switch or a small facade module).
cargo add --dev shuttle
## Minimal example
A lost-update bug; shuttle finds it within a few schedules.
#[cfg(test)]
mod tests {
use shuttle::sync::{atomic::{AtomicUsize, Ordering}, Arc};
use shuttle::thread;
fn body() {
let n = Arc::new(AtomicUsize::new(0)); let n2 = n.clone();
let t = thread::spawn(move || { let v = n2.load(Ordering::SeqCst); n2.store(v + 1, Ordering::SeqCst); });
let v = n.load(Ordering::SeqCst); n.store(v + 1, Ordering::SeqCst);
t.join().unwrap();
assert_eq!(n.load(Ordering::SeqCst), 2);
}
#[test] fn random_schedules() { shuttle::check_random(body, 1000); }
}
Use `fetch_add` to fix it. Other entry points: `shuttle::check_pct(body, iters, depth)` and `shuttle::check_dfs(body, Some(max_iters))`.
## Run
cargo test random_schedules
Passing looks like: `test result: ok. 1 passed`, exit 0. Failure prints `failing schedule:` followed by a string, then the panic; exit 101. Replay it with `shuttle::replay(body, "<schedule string>")` to debug deterministically.
## As a contract check
{"id": "shuttle-schedules", "claim": "Invariant holds across 1000 random schedules", "kind": "concurrency", "rung": 2, "cmd": "cargo test random_schedules", "expect": {"exit": 0, "stdout_contains": "1 passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- It samples schedules. Rung 2 at best; a rare interleaving can be missed. Raise the iteration count and use `check_pct` for deeper bugs.
- It models sequential consistency only, so weak-memory bugs pass.
- Only code using shuttle's types is controlled. A stray `std::sync::Mutex` is not.
- Check the check: reinstate the bug and see `failing schedule`. Confirm the test name matched (`1 passed`, not `0 passed`).
+49
View File
@@ -0,0 +1,49 @@
---
id: stress-repeat
title: Repeated and randomised-timing runs of concurrent tests
answers: Does this concurrent test keep passing when I run it many times under different timing?
rung: 3
section: concurrency
languages: any
kinds: concurrency
cost: low
detect:
ran_here: no
verified: docs
---
## Use when
- It is the only affordable check, and the code is too big for `loom`, `shuttle` or simulation.
- You are hunting a flaky failure and need to make it reproduce often enough to diagnose.
- As an extra layer beside a stronger check: run the same test with a race detector, sanitizer or Miri in a loop.
## Do not use when
- You can write an exhaustive or schedule-controlled test. Those find bugs repetition misses.
- You want to conclude the code is correct. Passing 1,000 runs only shows it did not fail in 1,000 runs.
## Set up
No special tooling. Tools that help:
- Rust: a shell loop around `cargo test`, and `cargo test -- --test-threads=1` versus the default to change contention.
- Go: `go test -count=N -race -cpu=1,2,4,8 -shuffle=on`.
- Any: a shell loop, `taskset -c 0` to confine to one CPU, a parallel CPU burner (`stress-ng --cpu 8`) to perturb timing, and random `sleep` or `yield` jitter injected in test hooks.
## Minimal example
for i in $(seq 1 200); do
cargo test --release my_concurrent_test || { echo "FAILED on run $i"; exit 1; }
done
Go: `go test -race -count=200 -cpu=1,4 -run TestQueue ./queue`.
## Run
Use the loop above, with stderr kept so a failing run's output is not lost.
Passing looks like: every run exits 0 and the loop ends silently. Failure is the first non-zero exit with the run number; keep its output.
## As a contract check
{"id": "stress-queue", "claim": "queue test passes 200 repeated runs under CPU contention", "kind": "concurrency", "rung": 3, "cmd": "for i in $(seq 1 200); do cargo test --release queue_concurrent || exit 1; done", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800}
## What a pass does not prove
- This is a weak check, rung 3. A rare schedule needs luck to occur, and a clean loop says little about it.
- Timing changes between machines. A bug that needs a particular core count or load may never appear on the test machine.
- A filtered name that matches no tests passes every iteration with `0 tests run`; assert that at least one test executed.
- Still worth having when: it can reproduce a known flaky failure, it runs alongside a race detector, or you have no better option and say so in the result. Check the check: it should fail when you add a known race and a short sleep.
+52
View File
@@ -0,0 +1,52 @@
---
id: thread-sanitizer
title: Data-race detection with ThreadSanitizer (C, C++, Rust, Go)
answers: Do any two threads touch the same memory without synchronisation while my tests run?
rung: 2
section: concurrency
languages: c, cpp, rust, go
kinds: concurrency
cost: medium
detect: cc --version
ran_here: yes
verified: ran
---
## Use when
- You have C, C++ or Rust code (including `unsafe` or FFI) running threads, and Miri cannot run it.
- You want a race check on a real, full-speed test run or integration test.
- You changed locking, atomics or shared buffers.
## Do not use when
- It is Go: `go test -race` is the same engine, see `go-race-detector`.
- You need exhaustive coverage of orderings. TSan reports races only on paths that actually ran.
- You also need ASan in the same binary; the two cannot be combined. Run them in separate builds.
## Set up
- C/C++: compile and link with `-fsanitize=thread -g` (gcc or clang), plus `-pthread`.
- Rust: needs nightly and the `rust-src` component, because the standard library must be rebuilt instrumented:
rustup toolchain install nightly --component rust-src
## Minimal example
`t.c`, two threads incrementing a global:
#include <pthread.h>
int n = 0;
void *w(void *a) { n++; return 0; }
int main(void) { pthread_t t; pthread_create(&t, 0, w, 0); n++; pthread_join(t, 0); return 0; }
## Run
clang -fsanitize=thread -g t.c -o t -pthread && ./t
RUSTFLAGS="-Zsanitizer=thread" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu
Passing looks like: no `WARNING: ThreadSanitizer` text and exit 0. Failure prints `WARNING: ThreadSanitizer: data race` with both stacks and exits 66. For Rust, the harness line can still say `test result: ok` while the process exits 66, so check the exit status, not the text. Pass `--target` explicitly or build scripts get instrumented too. Output may differ between runs; here gcc reported the race on some runs only, clang on the first, so repeat the run.
## As a contract check
{"id": "tsan-tests", "claim": "No data race reported by ThreadSanitizer in the test suite", "kind": "concurrency", "rung": 2, "cmd": "RUSTFLAGS=\"-Zsanitizer=thread\" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800}
## What a pass does not prove
- Only races on paths the run exercised, under the schedules that happened. Rung 2 at best. Run it several times.
- It flags data races, not logic races (a check-then-act bug using proper locks is invisible), and not deadlocks.
- Code not built with the flag (a prebuilt C library) is not watched.
- Check the check: keep the racy example in a test, build it the same way, and confirm exit 66.
+50
View File
@@ -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.
+56
View File
@@ -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.
+63
View File
@@ -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.
+77
View File
@@ -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.
+66
View File
@@ -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.
+57
View File
@@ -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.
+64
View File
@@ -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.
+60
View File
@@ -0,0 +1,60 @@
---
id: acceptance-examples
title: Acceptance examples agreed with the human up front and made executable
answers: Does the program give the exact results the human said they wanted for concrete cases?
rung: 3
section: intent
languages: any
kinds: general, money, parsing
cost: low
detect:
ran_here: no
verified: docs
---
Note: there is no tool. The example runner below is plain test code; it was
not run here as a separate artefact. `verified: docs` reflects that the method
is standard specification by example.
## Use when
- The request is a behaviour in words ("round fees to the nearest cent", "a late invoice gets a reminder"). Words are ambiguous; examples are not.
- The human will not review code but will read a table of inputs and outputs.
- You have to choose between readings of the request and want the human's choice fixed before you build.
## Do not use when
- The claim is "this holds for all inputs". Examples show cases only; use a property or proof (rung 1 or 2).
- The behaviour is visual or tasteful; see `pairwise-comparison`.
## Set up
Write `acceptance/examples.json` and show it to the human once (core rule 5: one
round of confirmation, with your default stated). Edge cases first: zero,
empty, the largest, a tie, a negative, an invalid input and what it must do.
## Minimal example
`acceptance/examples.json`:
[
{"name": "tie rounds to even", "in": {"amount": "2.675", "dp": 2}, "out": "2.68"},
{"name": "zero", "in": {"amount": "0", "dp": 2}, "out": "0.00"},
{"name": "negative", "in": {"amount": "-1.005", "dp": 2}, "out": "-1.00"},
{"name": "bad input", "in": {"amount": "abc", "dp": 2}, "error": "invalid amount"}
]
`acceptance/test_examples.py` loops over the file, calls the product through its
public entry point, and fails with the example's `name`.
## Run
python3 -m unittest discover -s acceptance -v
Passing looks like: one `ok` per example, exit 0. Failure names the example,
the expected and the actual. Never edit an expected value to make a run pass;
a changed expectation goes back to the human as a contract amendment.
## As a contract check
{"id": "acceptance-examples", "claim": "Every example the human agreed gives the stated result", "kind": "general", "rung": 3, "cmd": "python3 -m unittest discover -s acceptance", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
## What a pass does not prove
Only the cases listed. Check that the examples can fail: change the code on
purpose (swap round-half-even for round-half-up) and see at least one fails.
Examples you wrote and the human skimmed are weak; flag which the human
confirmed. Add a property test for the rule behind them where one exists.
@@ -0,0 +1,56 @@
---
id: domain-evidence-report
title: Printing the domain's own reports as evidence a behaviour change is right
answers: Do the numbers a domain expert would read (trial balance, P&L, balance sheet) come out right after my change?
rung: 3
section: intent
languages: any
kinds: money, general
cost: low
detect:
ran_here: no
verified: docs
---
Note: modelled on how a reference project (an accounting program)
shows its books after each change. Not run here.
## Use when
- You changed behaviour whose correctness a domain expert judges by a standard report: accounting (trial balance, P&L, balance sheet), inventory (stock on hand), billing (statement), scheduling (calendar).
- The human cannot read the diff but can read the report.
- A bug fix must be shown to correct the figure the user complained about.
## Do not use when
- The report is generated by the same code you changed and you have no independent expectation. Then it shows what the code does, not what it should do.
## Set up
Build a small, fixed scenario (a few entries or orders) whose correct report you
can compute by hand or already know. Keep the inputs in the repository.
## Minimal example
Scenario: a $100 sale and a $40 expense in the same period. Expected, by hand:
revenue 100.00, expense 40.00, net income 60.00, and a trial balance whose debit and
credit totals both equal 140.00.
$ product report trial-balance --period 2026-01 > out/tb.txt
$ grep -E "^(TOTAL|Net income)" out/tb.txt
TOTAL 140.00 140.00
Net income 60.00
## Run
product report trial-balance --period 2026-01 | diff -u expected/tb.txt -
product report profit-and-loss --period 2026-01 | diff -u expected/pl.txt -
Passing looks like: empty diff, exit 0. Failure is a diff showing which line
differs. Print the report in the final answer so the human can read it. The
expected file must come from hand calculation or an independent source, and the
check that the report foots (debits equal credits; assets equal liabilities plus equity) is a built-in test of itself.
## As a contract check
{"id": "tb-expected", "claim": "The trial balance for the fixed scenario matches the hand-computed report", "kind": "money", "rung": 3, "cmd": "product report trial-balance --period 2026-01 | diff -u expected/tb.txt -", "expect": {"exit": 0}, "timeout_s": 60}
## What a pass does not prove
Only the scenario. Include the cases that change the report: a reversal, a
period boundary, a rounding tie. An expected file generated by running the
product proves nothing; say how you derived it. For money cores, pair with a
property or proof that the invariants hold for all inputs.
+58
View File
@@ -0,0 +1,58 @@
---
id: feedback-as-amendment
title: Feedback restated as a one-line contract amendment, with a scope check on the diff
answers: Did I change only what the human's feedback asked for, and nothing else?
rung: 3
section: intent
languages: any
kinds: general
cost: low
detect: git --version
ran_here: yes
verified: ran
---
## Use when
- The human reacts to your work ("the button is too big", "round down not up", "the second paragraph is wrong"). Core rule 4: this is an amendment, not licence to rework.
- A previous change reached further than the request; you want to make that impossible.
- You are fixing a review comment and the diff must show only that fix.
## Do not use when
- The feedback truly spans the work ("start over"). Then write a new contract.
## Set up
Record the amendment in one line in `.sisi/contract.json` (as a new check or a
note) and name the paths it may touch. Note the commit you start from:
`git rev-parse HEAD`. Re-run the invariants from rule 3.
## Minimal example
Amendment: "Round fees down to the cent, only in `src/fees.py`." Scope script
`scope.sh` fails on any changed or new file outside the given paths:
#!/usr/bin/env bash
set -eu
base=$1; shift
changed=$( { git diff --name-only "$base"; git ls-files -o --exclude-standard; } | sort -u)
allowed=$(git ls-files -c -o --exclude-standard -- "$@" | sort -u)
outside=$(comm -23 <(printf '%s\n' "$changed") <(printf '%s\n' "$allowed") | sed '/^$/d')
[ -z "$outside" ] || { echo "outside the amendment:"; echo "$outside"; exit 1; }
echo "ok: all changes inside $*"
For regions inside one file, list the hunks: `git diff -U0 "$base" -- src/fees.py | grep '^@@'`
and check each range lies in the function the amendment names.
## Run
scope.sh "$BASE" src/fees.py tests/test_fees.py
Passing looks like: `ok: all changes inside ...` and exit 0 (run here on a scratch
repository). Failure prints `outside the amendment:` and the files, exit 1.
Formatting churn, renames and lockfile changes show up here; revert them.
## As a contract check
{"id": "amendment-scope", "claim": "Only the files named by the amendment changed since the base commit", "kind": "general", "rung": 3, "cmd": "bash scripts/scope.sh $(cat .sisi/base) src/fees.py tests/test_fees.py", "expect": {"exit": 0, "stdout_contains": "ok: all changes inside"}, "timeout_s": 60}
## What a pass does not prove
That the change inside the allowed file is correct, or that it did not damage
behaviour in a file that depends on it. Run the invariants for that. The
allowed list is a decision: keep it as small as the feedback. Staged and
unstaged changes are both covered by `git diff BASE`; commit history is not.
@@ -0,0 +1,59 @@
---
id: owner-acceptance-runbook
title: A scripted acceptance walked through using only the product's public surface
answers: Can the owner, or an agent acting as the owner, do the real job end to end using only what the product exposes?
rung: 6
section: intent
languages: any
kinds: general, ui
cost: medium
detect:
ran_here: no
verified: docs
---
Note: modelled on a runbook in a reference project (a re-audit done
through the product's tools alone, with a test mirroring it). Not run here.
## Use when
- The product is finished, or a large part is, and the question is "does it do what the owner wanted?" not "do the units pass?".
- Several features must work together, and unit tests passed each on its own.
- The human wants to run a short script and see for themselves.
## Do not use when
- The change is small or internal; a runbook costs more than it finds.
- Nobody, human or agent, can run the product in its real environment.
## Set up
Write `docs/runbooks/acceptance.md`. Each step: what to do, using only the CLI,
the UI, the API or the agent tools the product ships (never the database, a
debugger or a source file); what to expect; what to do on a mismatch. Say who
acts: the owner, or an agent with no access to the source.
## Minimal example
1. Start the product on an empty data directory: `product serve --data /tmp/acc`.
Expect: "listening on 127.0.0.1:8080", exit when stopped with code 0.
2. Create a customer via the public API (curl in the runbook). Expect: 201 and an id.
3. Issue an invoice for $100 and fetch the statement. Expect: balance 100.00.
4. Restart the product on the same directory. Expect: the same balance.
5. If any expectation fails, stop. The runbook or the product is wrong; say which.
## Run
An agent walks the runbook, copying each command and its real output into
`acceptance-report.md`. The owner reads the report, or walks it themselves.
Every step records pass, fail or not run.
Passing looks like: every step passed with real output pasted, nothing skipped,
and the report names who ran it and on what version. A runbook step that needed a
workaround is a failure of the product, even if the workaround worked.
## As a contract check
{"id": "acceptance-runbook", "claim": "The acceptance runbook passes end to end through the public surface", "kind": "general", "rung": 6, "cmd": "python3 tools/walk_runbook.py docs/runbooks/acceptance.md", "expect": {"exit": 0, "stdout_contains": "ALL STEPS PASSED"}, "tier": "deep", "timeout_s": 900}
`tools/walk_runbook.py` is yours to write; where steps are human-only, the contract
check is the owner's recorded verdict, not a command.
## What a pass does not prove
Only the journeys written down. An agent that can read the source may use it, so
state what it may not read. Steps that depend on data from a previous run give
false passes; start clean. The owner's own pass is the only one that counts as rung 6.
+58
View File
@@ -0,0 +1,58 @@
---
id: pairwise-comparison
title: Before and after shown side by side instead of scored in the absolute
answers: Is the new version better than the old one for the thing the human cares about?
rung: 5
section: intent
languages: any
kinds: general, ui
cost: low
detect:
ran_here: no
verified: docs
---
Note: no tool; the procedure is the technique. Not run here.
## Use when
- You changed something that already worked (a layout, a message, a report, a prompt) and the risk is that it got worse.
- "Is this good?" has no stable answer but "which is better?" does.
- You have a before capture from `baseline-before-change`.
## Do not use when
- There is an exact correct output; test it.
- There is no earlier version. Use `rubric-judge` or `acceptance-examples`.
## Set up
Capture the old output before your first edit and the new output after, from
identical inputs. Strip anything that gives away which is new (dates, version
strings, file names). Randomise which is shown as A and B.
## Minimal example
For a judge or the human, a two-column card:
Task: the invoice email, same data.
A: <output 1> B: <output 2>
Question: which is clearer for a customer who owes money? Answer A, B or tie, and quote the line that decided it.
Run each pair twice with the sides swapped. A verdict that changes with the
order is "tie".
## Run
python3 tools/pair.py --before out/before.txt --after out/after.txt --judge other-family --swap
Passing looks like: "after" wins or ties on both orders for every case, and no case
is a loss. Report wins, ties and losses, with the quote for each loss. For a
human, show images or text side by side and record the verdict with
`sisi learn` only if the human states a lasting preference.
## As a contract check
{"id": "pairwise-not-worse", "claim": "The new output is never judged worse than the old", "kind": "general", "rung": 5, "cmd": "python3 tools/pair.py --before out/before.txt --after out/after.txt --swap --fail-on-loss", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
`tools/pair.py` is yours to write; it must exit non-zero on a loss.
## What a pass does not prove
That the new version is good, only that it is not worse on the cases shown.
Small samples hide rare losses; include the cases that were hard. A judge that
shares the author's model family leans toward the author's style. Position bias
is why you swap. For anything the human cares about, they decide.
+58
View File
@@ -0,0 +1,58 @@
---
id: rubric-judge
title: A written rubric scored by an independent model judge
answers: Does the output meet qualities a command cannot measure, such as clarity, tone or fit to the brief?
rung: 5
section: intent
languages: any
kinds: general, ui
cost: medium
detect:
ran_here: no
verified: docs
---
Note: no tool is needed beyond a model CLI or API you already use. The honesty
measures below follow published LLM-as-judge practice; nothing here was run.
## Use when
- The claim is about quality that has no exact answer: a summary, an error message, a design, documentation, a tool description.
- Human review would be the only check otherwise and you want to narrow what the human must read.
- You can write what good looks like as a short list of yes-or-no criteria.
## Do not use when
- A command, test or proof can decide it. A judge is a sample of opinion; it is the weaker rung.
- You are the only model available. A model judging its own work agrees with itself.
## Set up
Write `rubric.md`: 4 to 8 criteria, each a question with a clear pass line and one
example of a pass and a fail. Gather a calibration set from `taste-baseline`.
## Minimal example
`rubric.md` excerpt:
C1 States what happened in the first sentence. Pass: "The import failed: row 12 has no date." Fail: "An error occurred."
C2 Says what to do next. C3 Contains no internal jargon. C4 Under 40 words.
Reply as JSON: {"C1": true|false, "C2": ..., "evidence": {"C1": "<quote>"}}
## Run
Keep the judge honest:
- Blind: give it the output and the rubric only, never the request history, your reasoning or which version is "new".
- A different model family from the one that wrote the work, with temperature 0, and require a quoted line as evidence for every verdict.
- Calibrate first: run the judge on 10 or more outputs the human already judged; require at least 90% agreement. If lower, fix the rubric, not the threshold.
- Run it 3 times and take the majority; a criterion that flips is a vague criterion.
- Treat any false as a failed check, and report the quotes.
Passing looks like: every criterion true in the majority of runs, with quotes
that actually appear in the output, and calibration agreement recorded.
## As a contract check
{"id": "rubric-judge", "claim": "Independent judge passes all rubric criteria", "kind": "general", "rung": 5, "cmd": "python3 tools/judge.py --rubric rubric.md --input out/summary.txt --min-agree 0.9", "expect": {"exit": 0, "stdout_contains": "ALL PASS"}, "tier": "deep", "timeout_s": 300}
`tools/judge.py` is yours to write; it must exit non-zero on any failed criterion.
## What a pass does not prove
That the human would agree. Judges favour long, confident, polished text and
their own style. Quotes can be checked mechanically (is the quote in the
output?); do that. Check the judge can fail: feed it a deliberately bad output.
A pass at rung 5 does not replace a human check for anything the human cares about.
+60
View File
@@ -0,0 +1,60 @@
---
id: taste-baseline
title: Recording the human's past verdicts on before and after pairs
answers: Does this work match what this human has said they prefer, in cases they already judged?
rung: 6
section: intent
languages: any
kinds: general, ui
cost: low
detect:
ran_here: no
verified: docs
---
Note: no tool. The store is plain files; not run here.
## Use when
- The human's judgement is the real test (layout, wording, density, tone) and they have already given verdicts you can reuse.
- You run `rubric-judge` and need cases to calibrate it against.
- The same kind of complaint comes back repeatedly.
## Do not use when
- You have no recorded verdicts. Do not invent them; ask once, or use `pairwise-comparison` with the human.
- A preference was a one-off about a different context.
## Set up
Create `docs/taste/` with one small file per verdict. Record a verdict only when
the human states it (core rule 7: `sisi learn "<their words>"` for lasting
preferences, quoted, never your inference).
## Minimal example
`docs/taste/0007-invoice-email.md`:
date: 2026-11-09
pair: before/invoice-email.txt vs after/invoice-email.txt
verdict: after
their words: "Better. But keep the amount in the subject line."
rule it implies: the amount stays in the subject.
## Run
List the verdicts that apply to the area you changed, then re-run the pairs
through the judge or show the human only the cases that differ from past verdicts:
ls docs/taste/ | head
python3 tools/taste_check.py --judge-config judge.json --taste docs/taste/
Passing looks like: for every recorded pair in scope, the judge's verdict equals
the human's (agreement at or above the threshold), and no implied rule is violated
(for the example, the subject still has the amount: `grep -q '\$' out/subject.txt`).
## As a contract check
{"id": "taste-rules", "claim": "Rules implied by the human's past verdicts still hold", "kind": "general", "rung": 6, "cmd": "python3 tools/taste_check.py --taste docs/taste/", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
`tools/taste_check.py` is yours to write; turn each implied rule into a command
where you can, and list the rest as "needs the human".
## What a pass does not prove
Verdicts are about the pairs shown; a new context may need a new verdict. Old
verdicts can be stale: date them and let the human retire them. Your summary of
their words is not their words; keep the quote.
+73
View File
@@ -0,0 +1,73 @@
---
id: afl-plus-plus
title: Fuzzing C, C++ and Rust with AFL++
answers: Can any input make this native program or library crash, hang or trip a sanitizer?
rung: 2
section: many-inputs
languages: c, cpp, rust
kinds: parsing, general
cost: medium
detect: afl-fuzz -h
ran_here: no
verified: docs
---
## Use when
- The target is C or C++ (or Rust via `cargo-afl`) that reads a file or stdin, and you want a mature fuzzer with many mutation strategies.
- A program has a command-line entry point and cannot easily be turned into a libFuzzer function.
- You want to run several fuzzer processes for long periods on a server.
## Do not use when
- A libFuzzer-style function is easy to write: `cargo-fuzz`, `go-fuzz` or `jazzer` are less work.
- You only need a few minutes of sanity fuzzing of a Rust crate: `cargo-fuzz` is simpler.
## Set up
C and C++: build the target with an AFL compiler (`afl-clang-fast` or `afl-cc`):
CC=afl-clang-fast CXX=afl-clang-fast++ ./configure --disable-shared && make
Rust: `cargo install cargo-afl`, add `afl = "*"` to `Cargo.toml`, then `cargo afl build`.
Put a few small valid inputs in `in/`.
## Minimal example (Rust, `src/main.rs`)
#[macro_use]
extern crate afl;
fn main() {
fuzz!(|data: &[u8]| {
if let Ok(s) = std::str::from_utf8(data) {
let _ = mycrate::parse_pair(s);
}
});
}
C and C++: `afl-fuzz -i in -o out -- ./target @@` (`@@` is replaced by the input
file name; leave it out to feed stdin).
## Run
cargo afl build
cargo afl fuzz -i in -o out target/debug/<binary>
AFL runs until stopped; for a time budget use the time-limit option that
`afl-fuzz -h` lists (I believe `-V <seconds>`; not confirmed against the docs here).
Passing looks like: the run ends with "saved crashes: 0" in the status screen. Failure
leaves crashing inputs in `out/default/crashes/`. Reproduce one with
`cargo afl run <binary> < out/default/crashes/<file>`.
## As a contract check
{"id": "afl-parse-pair", "claim": "AFL++ finds no crash in parse_pair in 60 seconds", "kind": "parsing", "rung": 2, "cmd": "sh scripts/afl-budget.sh 60 && test -z \"$(ls out/default/crashes 2>/dev/null | grep -v README)\"", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
`scripts/afl-budget.sh` is yours: it must run `cargo afl fuzz` with the time limit
and exit. AFL itself exits non-zero or hangs in ways that need that wrapper.
## What a pass does not prove
- A run with no crashes means none found in the time given; a short run in a CI machine without core-pattern or CPU-governor tuning may fail to start (AFL prints the fix).
- It finds crashes, not wrong outputs. Add assertions in the harness.
- Not run here (AFL++ and `cargo-afl` are not installed). Compile and run commands for C and Rust are from the AFL++ and Rust fuzz book pages; the time-limit flag is unconfirmed. Check the check: plant a crash behind a recognisable input.
+74
View File
@@ -0,0 +1,74 @@
---
id: algebraic-laws
title: Domain laws as properties (conservation, idempotence, commutativity, monotonicity)
answers: Do the rules my domain guarantees, such as debits equal credits, hold after any generated sequence of operations?
rung: 2
section: many-inputs
languages: any
kinds: money, state-machine, general
cost: low
detect:
ran_here: yes
verified: ran
---
## Use when
- The domain has laws that must always hold: debits equal credits, totals are conserved by transfers, applying an operation twice equals once, order of independent operations does not matter, a counter never goes down.
- Money, inventory, permissions, scheduling, any ledger-like state.
- You can name each law in one sentence. Each becomes one test, named for the law.
## Do not use when
- The law is only true for a subset of states you cannot generate; generate valid states first.
- You want to compare with another implementation: `differential-reference`.
## Set up
Write a generator for operations (or for valid starting states), apply them with
the real code, then check the law on the result. Keep money in integer cents.
## Minimal example (Python; a transfer ledger)
from hypothesis import given, strategies as st
def apply(balances, a, b, cents): # under test
out = dict(balances)
if cents <= 0 or out.get(a, 0) < cents:
return out # refused: nothing changes
out[a] -= cents
out[b] = out.get(b, 0) + cents
return out
names = st.sampled_from("abc")
state = st.dictionaries(names, st.integers(0, 10**6))
transfers = st.lists(st.tuples(names, names, st.integers(-5, 10**6)), max_size=30)
@given(state, transfers)
def test_conservation(s, ts):
total = sum(s.values())
for a, b, c in ts:
s = apply(s, a, b, c)
assert sum(s.values()) == total # nothing created or destroyed
assert all(v >= 0 for v in s.values()) # nobody goes negative
@given(state, names, names, st.integers(1, 10**6))
def test_refused_transfer_is_idempotent_noop(s, a, b, c):
once = apply(s, a, b, c)
assert apply(once, a, b, 10**9) == once # an impossible transfer changes nothing
## Run
python3 -m pytest -q test_laws.py
Passing looks like: `2 passed`, exit 0. Failure shows the shortest violating sequence.
## As a contract check
{"id": "law-conservation", "claim": "transfers conserve the total and never overdraw", "kind": "money", "rung": 2, "cmd": "python3 -m pytest -q test_laws.py", "expect": {"exit": 0, "stdout_contains": "2 passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- Laws that hold are necessary, not sufficient: an implementation that does nothing conserves the total. Pair with `stateful-model-test` for what should have happened.
- The check holds only for generated states. If the generator never makes an overdrawn account or `a == b`, those cases are untested.
- Check the check: break the code (skip the debit, or credit twice) and see the right law fail.
+76
View File
@@ -0,0 +1,76 @@
---
id: atheris
title: Coverage-guided fuzzing of Python with Atheris
answers: Can any input make this Python code raise an exception it should not, hang, or crash the interpreter?
rung: 2
section: many-inputs
languages: python
kinds: parsing, general
cost: medium
detect: python3 -c "import atheris"
ran_here: yes
verified: ran
---
## Use when
- Python code parses or transforms untrusted input and should raise only its documented exceptions.
- You want libFuzzer's coverage guidance, corpus handling and time budget for Python code, including C extensions.
- Property tests with `hypothesis` have not found anything and you want a search guided by coverage.
## Do not use when
- You need shrinking to a readable counterexample and structured values: `hypothesis`.
- The code is pure and fast to reason about; a property test is less work.
## Set up
python3 -m venv .venv && .venv/bin/pip install atheris
Atheris builds against clang; wheels exist for common platforms. Use
`@atheris.instrument_func` on your functions or `atheris.instrument_imports()`
around the import of the code under test. Without instrumentation there is no
coverage feedback and the fuzzer finds almost nothing.
## Minimal example (`fuzz_parse.py`)
import sys
import atheris
@atheris.instrument_func
def parse_pair(s: str):
a, _, b = s.partition(",")
x, y = int(a), int(b) # ValueError is the documented error
if s.startswith("42,") and y == 7:
raise RuntimeError("seeded bug") # anything else is a finding
return x, y
def test_one_input(data: bytes):
fdp = atheris.FuzzedDataProvider(data)
s = fdp.ConsumeUnicodeNoSurrogates(16)
try:
parse_pair(s)
except ValueError:
pass
atheris.Setup(sys.argv, test_one_input)
atheris.Fuzz()
## Run
mkdir -p corpus && .venv/bin/python fuzz_parse.py corpus -max_total_time=60 -timeout=10
Passing looks like: `Done N runs in 60 second(s)`, exit 0.
Failure prints the traceback, writes `crash-<hash>` in the current directory
(`artifact_prefix='./'`) and exits 77. Replay with `.venv/bin/python fuzz_parse.py crash-<hash>`;
commit the file as a regression case.
## As a contract check
{"id": "fuzz-parse-pair-py", "claim": "parse_pair raises only ValueError on 60 seconds of fuzzed input", "kind": "parsing", "rung": 2, "cmd": ".venv/bin/python fuzz_parse.py corpus -max_total_time=60 -timeout=10", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- Only what was found in the time given; the bug in the example took under 60 seconds with instrumentation and was never found in 30 seconds without it.
- Uninstrumented code and code in another process are invisible to the fuzzer.
- Check the check: confirm a planted bug is found, and that the `except` clause only catches the documented error.
+69
View File
@@ -0,0 +1,69 @@
---
id: cargo-fuzz
title: Coverage-guided fuzzing of Rust with cargo-fuzz (libFuzzer)
answers: Can any input I did not think of make this Rust code panic, overflow, hang or break an assertion?
rung: 2
section: many-inputs
languages: rust
kinds: parsing, general, state-machine
cost: medium
detect: cargo fuzz --version
ran_here: yes
verified: ran
---
## Use when
- Rust code takes untrusted or complex input: parsers, decoders, importers, journal and file readers, request handlers.
- You want a run with a time budget and a saved reproducer for any crash.
- You have a few valid example inputs to seed the search.
## Do not use when
- The input must satisfy a grammar that raw bytes rarely meet; use `structure-aware-fuzzing`.
- You need a law checked on structured values with shrinking: `proptest`.
- You cannot run nightly Rust. cargo-fuzz needs a nightly toolchain.
## Set up
cargo install cargo-fuzz # once; needs rustup nightly
cargo fuzz init # creates fuzz/ with fuzz_target_1
mkdir -p fuzz/corpus/fuzz_target_1 fuzz/seeds/fuzz_target_1
Put small valid inputs in `fuzz/seeds/<target>/` and commit them. The `corpus/`
directory grows during runs and is normally git-ignored. Crash files appear in
`fuzz/artifacts/<target>/`.
## Minimal example (`fuzz/fuzz_targets/fuzz_target_1.rs`)
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
if let Ok(s) = std::str::from_utf8(data) {
let _ = mycrate::parse_pair(s); // must never panic, only return None/Err
}
});
## Run
cd <crate> && RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 \
fuzz/corpus/fuzz_target_1 fuzz/seeds/fuzz_target_1 -- -max_total_time=60 -timeout=10
The first directory after the target is where new inputs are written; later ones
are read-only seeds. The directory must already exist (the run refuses with
"The required directory ... does not exist" otherwise).
Passing looks like: `Done N runs in 60 second(s)`, exit 0.
Failure shows the panic message, `Test unit written to fuzz/artifacts/fuzz_target_1/crash-<hash>`,
and exit 1. Replay one crash with `cargo fuzz run fuzz_target_1 fuzz/artifacts/fuzz_target_1/crash-<hash>`;
after the fix, copy it into `fuzz/seeds/fuzz_target_1/` as a regression case.
## As a contract check
{"id": "fuzz-parse-pair", "claim": "parse_pair neither panics nor hangs on 60 seconds of fuzzed input", "kind": "parsing", "rung": 2, "cmd": "cd fuzz-host && RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 fuzz/seeds/fuzz_target_1 -- -max_total_time=60 -timeout=10", "expect": {"exit": 0, "stdout_contains": "Done"}, "tier": "deep", "timeout_s": 600}
## What a pass does not prove
- A clean run only means nothing was found in that time. The bug seeded in the example needs a specific prefix; a 30-second run on a numeric comparison deeper in the code did not find an equivalent one. Longer runs and good seeds matter.
- It finds crashes, not wrong answers. Add assertions inside the target (round trip, agreement with a reference) to catch those.
- Check the check: plant a panic behind a recognisable input and see the fuzzer find it, then remove it. Also check the target actually reaches the code (`cargo fuzz coverage`).
@@ -0,0 +1,72 @@
---
id: derived-view-agreement
title: Every displayed figure recomputed from the core and compared
answers: Does every number a screen, report or export shows equal what the core computes from the same data?
rung: 2
section: many-inputs
languages: any
kinds: ui, money
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- A UI, report, CSV export or API response shows figures that a core library also computes (balances, totals, percentages).
- Formatting, rounding or caching in the display layer could change a value the core got right.
- Two surfaces show the same fact (a dashboard and an exported statement).
## Do not use when
- The view has no figures, only layout: use `ui-screenshot-compare`.
- The view is the only place the figure is computed; compare against an independent reference (`differential-reference`).
## Set up
Give the display layer a seam that returns what it will show as data (not pixels):
a view model, a rendered text, a parsed export. Generate random data, load it
through the core, and for each displayed figure recompute from the core
and compare after normalising only the formatting.
## Minimal example (Python)
from decimal import Decimal
from hypothesis import given, strategies as st
def core_total(entries): # the core: integer cents
return sum(entries)
def render_report(entries): # the display layer under test
lines = [f"{c / 100:.2f}" for c in entries] # a float in a money path
return {"lines": lines, "total": f"{core_total(entries) / 100:.2f}"}
def parse(text): return int(Decimal(text) * 100)
@given(st.lists(st.integers(-10**9, 10**9), max_size=30))
def test_every_figure_matches_core(entries):
view = render_report(entries)
assert [parse(x) for x in view["lines"]] == entries # each line
assert parse(view["total"]) == core_total(entries) # the total
assert sum(parse(x) for x in view["lines"]) == parse(view["total"]) # the page adds up
## Run
python3 -m pytest -q test_view.py
Passing looks like: `1 passed`, exit 0 (the float formatting is right for these sizes).
With amounts above about 2**53 cents the float version fails and Hypothesis shrinks
to the smallest such figure. Widen the range to see it; a display path that must
handle big amounts should use `Decimal`, not `float`.
## As a contract check
{"id": "view-matches-core", "claim": "every figure the report displays equals the core's value, and the report adds up", "kind": "money", "rung": 2, "cmd": "python3 -m pytest -q test_view.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- It checks the figures you list. Enumerate every displayed number (tests that walk the whole view model help) and add new ones as screens are added.
- Equal to the core only shows the view is faithful; the core can still be wrong (see `algebraic-laws`, `differential-reference`).
- A reference project also scans display source for rounding calls outside the one shared function; a source scan is a cheap extra guard.
- Check the check: change the rounding in the view by one cent and see it fail.
@@ -0,0 +1,75 @@
---
id: differential-executable-spec
title: Differential testing against an executable formal model
answers: Does the implementation agree, on random cases, with the formal model that was proved, run as a program?
rung: 2
section: many-inputs
languages: any
kinds: state-machine, money, parsing
cost: high
detect:
ran_here: yes
verified: ran
---
## Use when
- The design has a formal model that can be run: a Lean checker binary, a TLA+ trace checker, an Alloy or Dafny program.
- You want the implementation compared to the model itself, not to a hand transcription of it.
- A mismatch must name which side is wrong, so each case carries both answers.
## Do not use when
- The model cannot be executed. Use `model-test-from-spec` with a hand transcription.
- A checker run is slow per case: batch many cases into one call, or the test will be too slow to run in CI.
## Set up
Build the checker once and pin its revision. Write the glue: run each random
case through the implementation, write the case and the implementation's answer
as a file in the checker's input format, run the checker once for the whole
batch, and fail if it reports any mismatch. Fail loudly if the checker is missing
(never skip silently): one reference project makes the test fail when `lake` is absent.
## Minimal example (Python; `checker.py` stands in for the formal model's binary)
# test_vs_checker.py
import json, subprocess, sys
from hypothesis import given, settings, strategies as st
def impl_total(prices): # implementation under test
return sum(prices)
CASES = st.lists(st.integers(0, 10**6), max_size=20)
@settings(max_examples=50, deadline=None)
@given(st.lists(CASES, min_size=1, max_size=20))
def test_against_checker(batch):
cases = [{"input": c, "got": impl_total(c)} for c in batch]
out = subprocess.run([sys.executable, "checker.py"], input=json.dumps(cases),
capture_output=True, text=True, check=True).stdout
mismatches = json.loads(out)
assert mismatches == [], mismatches
# checker.py (the "executable spec": here a trivial model)
import json, sys
cases = json.load(sys.stdin)
print(json.dumps([c for c in cases if sum(c["input"]) != c["got"]]))
## Run
python3 -m pytest -q test_vs_checker.py
Passing looks like: `1 passed`, exit 0.
Failure shows the batch and the mismatch list from the checker, exit 1.
## As a contract check
{"id": "diff-formal-model", "claim": "the implementation agrees with the formal model's checker on generated cases", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_vs_checker.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 900}
## What a pass does not prove
- Only the cases generated, and only the commands the checker's input format can express. List what it cannot say.
- The checker may skip outcomes it does not know (one reference project's checker ignores refusal words it does not list); count skipped cases and fail if too many.
- The model may not match the intended behaviour. This shows code and model agree, not that either is right.
- Check the check: change the implementation by one rule and see the checker report a mismatch.
@@ -0,0 +1,66 @@
---
id: differential-old-vs-new
title: Differential testing of new code against the previous version
answers: Did my refactor or rewrite keep the behaviour of the old code on inputs I did not think of?
rung: 2
section: many-inputs
languages: any
kinds: general, parsing, money, migration
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- You are refactoring, optimising or rewriting code whose behaviour must not change.
- The old version is trusted by its users, even if not proved.
- You can keep both versions side by side for the length of the change (old copy in the test tree, a tagged release, or a git worktree of the old commit).
## Do not use when
- The behaviour is meant to change. Then compare only the parts that must not change, or use `metamorphic`.
- The old version has known bugs you do not want to keep; agreement would preserve them. Record the known differences explicitly.
## Set up
Freeze the old implementation as a module the test can import (copy it as
`old_impl.py`, or build the old commit in a worktree and call it as a program).
Delete the copy when the change is merged and its job is done.
## Minimal example (Python; a faster word counter against the original)
from collections import Counter
from hypothesis import given, strategies as st
def old_count(text): # frozen original
counts = {}
for w in text.split():
counts[w] = counts.get(w, 0) + 1
return counts
def new_count(text): # rewrite under test
return dict(Counter(text.split()))
@given(st.text(alphabet=" \n\tab é", max_size=200))
def test_new_matches_old(text):
assert new_count(text) == old_count(text)
## Run
python3 -m pytest -q test_old_vs_new.py
Passing looks like: `1 passed`, exit 0.
Failure prints the shrunk input and both outputs, exit 1.
## As a contract check
{"id": "refactor-same-behaviour", "claim": "new_count returns what the old implementation returned on generated text", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_old_vs_new.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- It compares outputs on generated inputs only. Side effects (files, logs, timing) are not compared unless you read them back.
- The alphabet decides what is tried: include the awkward characters, empty input and very large ones. In the example, a non-breaking space is the kind of case that separates `split()` rewrites.
- Errors count too: compare raised exceptions and messages, not only returned values.
- Check the check: change the new code by one character and confirm the test fails.
@@ -0,0 +1,70 @@
---
id: differential-reference
title: Differential testing against an independent reference implementation
answers: Does my implementation give the same answer as an independent, trusted one on random inputs?
rung: 2
section: many-inputs
languages: any
kinds: general, parsing, money
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- Another library, tool or program already computes the same thing (a standard library, a database, a reference tool run in a container).
- The result is hard to state as a law but easy to compare.
- You wrote a faster or custom version of something with a trusted slow version.
## Do not use when
- The reference shares code or an algorithm with your implementation; agreement then proves little. Prefer one written independently.
- Both may legitimately differ (rounding rules, ordering of ties). Decide first what counts as equal.
- A prior version of your own code is the reference: use `differential-old-vs-new`.
## Set up
Choose the reference and pin its version. A program in a container is fine:
call it through a function that takes an input and returns a normalised answer.
Generate inputs with `hypothesis`, `proptest` or `fast-check`.
## Minimal example (Python: a custom decimal rounder against `decimal`)
from decimal import Decimal, ROUND_HALF_EVEN
from hypothesis import given, strategies as st
def my_round_cents(units: int, scale: int) -> int:
"""units / 10**scale, rounded half to even, in cents (integers only)."""
q, r = divmod(units * 100, 10**scale)
twice = 2 * r
if twice > 10**scale or (twice == 10**scale and q % 2 == 1):
q += 1
return q
def reference(units: int, scale: int) -> int:
d = Decimal(units).scaleb(-scale).quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN)
return int(d.scaleb(2))
@given(st.integers(-10**12, 10**12), st.integers(0, 9))
def test_matches_reference(units, scale):
assert my_round_cents(units, scale) == reference(units, scale)
## Run
python3 -m pytest -q test_diff.py
Passing looks like: `1 passed`, exit 0.
Failure prints the shrunk input and both answers, exit 1.
## As a contract check
{"id": "diff-rounding", "claim": "my rounding equals Python's decimal on generated amounts", "kind": "money", "rung": 2, "cmd": "python3 -m pytest -q test_diff.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- It shows agreement, not correctness: if the reference has the same bug or misreads the spec, both pass.
- Generated inputs that the reference rejects or that both treat identically make the pass thin; check the distribution (include edge scales, negatives, ties).
- Pin the reference version and record it; a drifting reference changes the answer.
- Check the check: introduce an off-by-one in the tie rule and see it fail.
+67
View File
@@ -0,0 +1,67 @@
---
id: fast-check
title: Property testing in TypeScript and JavaScript with fast-check
answers: Does this JavaScript or TypeScript function hold its law for generated inputs, and what is the smallest counterexample?
rung: 2
section: many-inputs
languages: typescript, javascript
kinds: general, parsing, money, state-machine
cost: low
detect: node --version
ran_here: yes
verified: ran
---
## Use when
- A function or module has a law (round trip, idempotence, order, agreement with a simple version) and you use Node, Jest, Vitest or the built-in `node:test`.
- You want shrinking and a replayable seed.
- You want to test a sequence of operations against a model (see `stateful-model-test`).
## Do not use when
- The code is browser-only and cannot run under Node; run the same property in the browser test runner instead.
- You need coverage-guided search. Use `jazzer`.
## Set up
npm install --save-dev fast-check
fast-check runs inside any runner. The example uses `node --test`, which needs
no extra install.
## Minimal example (`props.test.mjs`)
import test from 'node:test';
import fc from 'fast-check';
const encode = (b) => Buffer.from(b).toString('hex');
const decode = (s) => Uint8Array.from(Buffer.from(s, 'hex'));
test('round trip', () => {
fc.assert(
fc.property(fc.uint8Array({ maxLength: 256 }), (bytes) =>
Buffer.compare(Buffer.from(decode(encode(bytes))), Buffer.from(bytes)) === 0),
{ numRuns: 1000 },
);
});
## Run
node --test props.test.mjs
Passing looks like: `ℹ pass 1` and `ℹ fail 0`, exit 0.
Failure shows `Counterexample: [...]`, `Shrunk N time(s)` and a line
`{ seed: -2075209501, path: "..." }`, exit non-zero. Replay it by passing the
same values: `fc.assert(prop, { seed: -2075209501, path: "8:4:..." })`. Pin
important cases permanently with `{ examples: [[...]] }`.
## As a contract check
{"id": "prop-round-trip-js", "claim": "decode(encode(x)) equals x for generated byte arrays", "kind": "parsing", "rung": 2, "cmd": "node --test props.test.mjs", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- It samples (100 runs by default; `numRuns` raises it). The arbitrary decides what is ever tried, so check its bounds against real inputs.
- A property that returns `true` for any input is vacuous. Test the test: break the code on purpose, confirm a counterexample appears, restore it.
- Number generators include `NaN`, `-0` and huge values only if you ask; `fc.integer()` is not `fc.double()`.
@@ -0,0 +1,83 @@
---
id: fault-injection-storage
title: Fault injection for storage (power loss, disk full, short writes)
answers: If the machine dies or the disk fills in the middle of a write, do the data reopen correctly with nothing lost that was acknowledged?
rung: 2
section: many-inputs
languages: any
kinds: state-machine, general
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- Code writes its own files (journal, snapshot, backup) and claims to be crash-safe or atomic.
## Do not use when
- A database makes the guarantee and you only use its API: test your use of transactions instead.
- You need real kernel or hardware faults (reordered writes, lost fsync); this simulates file contents only.
## Set up
Make the last write observable: record the file bytes before and after it. Then
simulate each fault by building the damaged file yourself and reopening it:
- power loss: for every cut `k` in `1..len(last_write)`, the file is `before + last[:k]`;
- disk full or short write: a write function that raises `OSError` after N bytes.
## Minimal example (Python; a checksummed append-only log)
import os, tempfile, zlib
class Log:
def __init__(self, path):
self.path, self.items = path, []
if os.path.exists(path):
raw = open(path, "rb").read()
good = 0
for line in raw.splitlines(keepends=True):
body, _, crc = line.rstrip(b"\n").rpartition(b" ")
if not line.endswith(b"\n") or not crc.isdigit() or zlib.crc32(body) != int(crc):
break # torn tail: drop it
self.items.append(body.decode()); good += len(line)
if good < len(raw):
open(path, "r+b").truncate(good) # heal
def append(self, text):
line = text.encode() + b" " + str(zlib.crc32(text.encode())).encode() + b"\n"
with open(self.path, "ab") as f:
f.write(line); f.flush(); os.fsync(f.fileno())
self.items.append(text)
def test_power_loss_at_every_byte_of_the_last_append():
p = os.path.join(tempfile.mkdtemp(), "log")
log = Log(p); log.append("one"); log.append("two")
before = open(p, "rb").read()
log.append("three")
last = open(p, "rb").read()[len(before):]
for k in range(1, len(last)): # every cut short of the whole line
open(p, "wb").write(before + last[:k])
assert Log(p).items == ["one", "two"], f"cut at {k}"
assert open(p, "rb").read() == before, f"not healed at {k}"
open(p, "wb").write(before + last)
assert Log(p).items == ["one", "two", "three"]
## Run
python3 -m pytest -q test_faults.py
Passing looks like: `1 passed`, exit 0. Failure names the byte cut (`cut at 7`).
One reference project's store also checks that reports after reopening equal those from before.
## As a contract check
{"id": "torn-write-recovery", "claim": "a power cut at any byte of the last append reopens to the state before it", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_faults.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- It covers truncation of the last write only. Torn writes that leave garbage in the middle, reordered writes, a lost `fsync` and media errors need other tests or a real crash rig.
- Also check an acknowledged write is never lost, not only that the file opens.
- Check the check: remove the CRC check or the truncate and see it fail.
@@ -0,0 +1,65 @@
---
id: generator-coverage
title: Checking that random tests actually reach interesting cases
answers: Is my property or model test really exercising edge cases and rare commands, or is it passing because it never gets there?
rung: 2
section: many-inputs
languages: any
kinds: general, state-machine
cost: low
detect: python3 -c "import hypothesis"
ran_here: yes
verified: ran
---
## Use when
- You wrote a property, model or fuzz test and it passes on the first try.
- The generator filters, rejects or chooses by weights, so most cases may be boring or discarded.
- A model test might never post, reverse or close anything.
## Do not use when
- The test is a fixed example.
## Set up
Count what happens. In Hypothesis use `event()` and `target()` and read
`--hypothesis-show-statistics`; in proptest print a count per accepted command and per
refusal (one reference project's model test does this under `MODEL_STATS=1`); in fast-check use
`fc.statistics`; in a fuzzer use `cargo fuzz coverage` or the coverage output.
## Minimal example (Python)
from hypothesis import given, event, strategies as st
@given(st.integers(-5, 150), st.integers(0, 100))
def test_withdraw_cases_all_occur(amount, balance):
if amount <= 0:
event("bad amount")
elif amount > balance:
event("insufficient")
else:
event("success")
# ... the real assertions about withdraw(amount, balance) go here
## Run
python3 -m pytest -q test_cov.py --hypothesis-show-statistics
Passing looks like: `1 passed` and, in the statistics block, each event
(`bad amount`, `insufficient`, `success`) with a share well above zero. Failure here is
a reading task: any event at 0 percent or under about 1 percent means that branch is
effectively untested, and the generator needs fixing. To make this automatic, assert
on counts with a collected dictionary in a small harness, or fail on health-check
warnings (`HealthCheck.filter_too_much`, `too_slow`) by not suppressing them.
## As a contract check
{"id": "generators-reach-cases", "claim": "the withdraw property test exercises bad, insufficient and successful cases", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_cov.py --hypothesis-show-statistics", "expect": {"exit": 0, "stdout_contains": "success"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- Events show that a case occurred, not that the assertion beside it is strong.
- A generator that reaches every named case can still miss ones you did not name; add boundary values by hand (`@example`).
- Check the check: narrow the generator (balance always 0) and confirm "success" disappears from the statistics.
+67
View File
@@ -0,0 +1,67 @@
---
id: go-fuzz
title: Native Go fuzzing with go test -fuzz
answers: Can any input make this Go function panic, hang or break an invariant?
rung: 2
section: many-inputs
languages: go
kinds: parsing, general
cost: low
detect: go version
ran_here: no
verified: docs
---
## Use when
- A Go function parses or processes input from outside: decoders, importers, request handlers.
- You want the standard toolchain only, with saved failing inputs that become regression tests automatically.
## Do not use when
- The input must be structured values and you want shrinking: `go-rapid`.
- The target needs more than one second a call; the engine treats that as a hang.
## Set up
Nothing to install beyond Go. Write a `FuzzXxx` function in a `*_test.go` file with
seeds via `f.Add`. Supported argument types: `string`, `[]byte`, the integer and
float types, and `bool`.
## Minimal example (`parse_test.go`)
package pair
import "testing"
func FuzzParsePair(f *testing.F) {
f.Add("1,2")
f.Add("")
f.Fuzz(func(t *testing.T, s string) {
a, b, err := ParsePair(s)
if err == nil && (a < 0 || b < 0) {
t.Fatalf("accepted a negative value from %q", s)
}
})
}
## Run
go test -run=FuzzParsePair ./... # replays seeds and saved failures only
go test -fuzz=FuzzParsePair -fuzztime=30s # fuzzes for 30 seconds
`-fuzz` takes a regex that must match exactly one fuzz test in the package.
Passing looks like: the fuzz run ends at the time limit with exit 0 and no `--- FAIL`.
Failure writes a minimised input to `testdata/fuzz/FuzzParsePair/<hash>`, prints
`FAIL`, and exits 1. Commit that file: from then on plain `go test` replays it as a
unit test. Re-run just that case with `go test -run=FuzzParsePair/<hash>`.
## As a contract check
{"id": "fuzz-parse-pair-go", "claim": "ParsePair survives 30 seconds of fuzzing and every saved failing input", "kind": "parsing", "rung": 2, "cmd": "go test -run=FuzzParsePair ./... && go test -fuzz=FuzzParsePair -fuzztime=30s", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- A clean run means nothing was found in that time. Coverage guidance works best on AMD64 and ARM64.
- Only the failures that panic, call `t.Fatal`, or run over time are caught; wrong answers need assertions in the target.
- Not run here (Go is not installed on this machine). Flags, directory layout and types are from the official Go fuzzing documentation. Check the check: add a deliberate panic behind a seed-adjacent input and see it found.
+72
View File
@@ -0,0 +1,72 @@
---
id: go-rapid
title: Property testing in Go with rapid
answers: Does this Go code hold its law for generated inputs, and what is the smallest failing case?
rung: 2
section: many-inputs
languages: go
kinds: general, parsing, money, state-machine
cost: low
detect: go version
ran_here: no
verified: docs
---
## Use when
- Go code has a law (round trip, sorted output, idempotence, agreement with a model) and you want shrinking.
- You want a stateful model test using `T.Repeat` (see `stateful-model-test`).
## Do not use when
- You want coverage-guided search: use `go-fuzz`. rapid can be wired into it with `rapid.MakeFuzz`, but the fuzzing engine then does the guiding, not rapid.
- A table of examples already covers the cases that matter (see the `test-quality` section).
## Set up
go get pgregory.net/rapid
# in a *_test.go file: import "pgregory.net/rapid"
## Minimal example
package hexcodec
import (
"bytes"
"encoding/hex"
"testing"
"pgregory.net/rapid"
)
func TestRoundTrip(t *testing.T) {
rapid.Check(t, func(t *rapid.T) {
data := rapid.SliceOf(rapid.Byte()).Draw(t, "data")
got, err := hex.DecodeString(hex.EncodeToString(data))
if err != nil || !bytes.Equal(got, data) {
t.Fatalf("round trip failed for %v: %v, %v", data, got, err)
}
})
}
## Run
go test -run TestRoundTrip ./...
go test -rapid.checks=10000 -run TestRoundTrip ./...
Passing looks like: `ok <package>` and exit 0.
Failure shows the minimal failing draw (`data = []byte{...}`) and `FAIL`, exit 1.
rapid saves minimised failing cases and re-runs them automatically; the
directory was not confirmed against the docs here, so look for a new
`testdata/` subdirectory after a failure and commit it. Each flag also has a
`RAPID_` environment variable (for example `RAPID_CHECKS`).
## As a contract check
{"id": "prop-round-trip-go", "claim": "hex decode of encode returns the input for generated byte slices", "kind": "parsing", "rung": 2, "cmd": "go test -run TestRoundTrip ./...", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- 100 checks by default; it samples. Raise `-rapid.checks` for important laws.
- `t.Skip` in a property discards the case; if most cases skip, the pass is nearly empty.
- Not run here (Go is not installed on this machine). The example, `-rapid.checks`, the `RAPID_` variables, `T.Repeat` and `MakeFuzz` come from the package documentation; the failure-file location and `-rapid.seed` could not be confirmed. Break the code on purpose to see the check fail.
@@ -0,0 +1,76 @@
---
id: hostile-input-from-schema
title: Hostile arguments generated from an API or tool schema
answers: Does every call my API or tool accepts survive wrong, missing, huge and strange arguments with a clean error and no crash?
rung: 2
section: many-inputs
languages: any
kinds: parsing, general
cost: medium
detect: python3 -c "import hypothesis_jsonschema"
ran_here: yes
verified: ran
---
## Use when
- A server, CLI or agent tool publishes a schema (JSON Schema, OpenAPI, MCP `tools/list`) for its inputs.
- A panic or internal error reachable by one request is a denial of service or loses data.
- You need to show that after hostile calls the server still serves and its data still reopens.
## Do not use when
- There is no schema; write one, or fuzz the raw handler with `cargo-fuzz` or `atheris`.
- You only care about valid calls: use ordinary tests.
## Set up
pip install hypothesis hypothesis-jsonschema pytest
For each operation, generate valid arguments from its schema, then make them
hostile: wrong types, missing and extra fields, empty and huge strings, negative,
fractional and maximum numbers, control characters, absurd dates.
## Minimal example
from hypothesis import given, settings, strategies as st
from hypothesis_jsonschema import from_schema
SCHEMA = {"type": "object", "required": ["cents", "memo"], "properties": {
"cents": {"type": "integer", "minimum": 0}, "memo": {"type": "string"}}}
def handle(args): # the thing under test: result or clean refusal
if not isinstance(args, dict) or not isinstance(args.get("cents"), int) \
or isinstance(args.get("cents"), bool) or args["cents"] < 0:
return {"error": "invalid_arguments"}
return {"ok": len(str(args.get("memo", "")))}
hostile = st.one_of(
from_schema(SCHEMA),
st.recursive(st.none() | st.booleans() | st.integers() | st.floats() | st.text(),
lambda c: st.lists(c, max_size=3) | st.dictionaries(st.text(max_size=5), c, max_size=3)))
@settings(max_examples=300)
@given(hostile)
def test_no_crash_clean_error(args):
out = handle(args) # any exception here is a failure
assert "ok" in out or out.get("error")
assert handle({"cents": 1, "memo": "x"}) == {"ok": 1} # still serving afterwards
## Run
python3 -m pytest -q test_hostile.py
Passing looks like: `1 passed`, exit 0. Failure shows the shrunk argument that raised or
got no clean answer.
## As a contract check
{"id": "hostile-args", "claim": "no generated or mangled argument crashes the handler; each gets a result or a clean error", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q test_hostile.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 600}
## What a pass does not prove
- Only the shapes generated. A server whose crash needs a particular combination across fields or calls needs a stateful sequence (`stateful-model-test`).
- "Clean error" is whatever your assert accepts; define it (error code, no stack trace, no data change).
- Check after the hostile calls that the server still answers and the stored data reopens. One reference project's suite does both: every tool is called with hostile arguments, then a restarted server must still read the books.
- Check the check: add a deliberate crash on one input class (`cents` above 2**63) and see it found.
+71
View File
@@ -0,0 +1,71 @@
---
id: hypothesis
title: Property testing in Python with Hypothesis
answers: Does this Python function keep its promise for every input Hypothesis can generate, and what is the smallest input that breaks it?
rung: 2
section: many-inputs
languages: python
kinds: general, parsing, money, state-machine
cost: low
detect: python3 -c "import hypothesis"
ran_here: yes
verified: ran
---
## Use when
- A function has a law that must hold for all inputs and one example test shows only one case.
- You want shrinking to a minimal failing input and automatic replay of earlier failures.
- Money in integer cents, parsers, serialisers, sort or search code.
## Do not use when
- No packages may be installed. Use `python-stdlib-property`.
- The function is slow (over about 50 ms a call): Hypothesis will run it hundreds of times. Lower `max_examples` or test a smaller unit.
- The input space is a coverage problem for a native parser. Use `atheris`.
## Set up
python3 -m venv .venv && .venv/bin/pip install hypothesis pytest
Put tests in `tests/test_props.py`. Hypothesis stores failures in `.hypothesis/`
(local, normally git-ignored); pin important ones with `@example(...)`.
## Minimal example
from hypothesis import given, settings, strategies as st
def encode(b: bytes) -> str:
return b.hex()
def decode(s: str) -> bytes:
return bytes.fromhex(s)
@settings(max_examples=500)
@given(st.binary(max_size=256))
def test_round_trip(data):
assert decode(encode(data)) == data
# money: integer cents, never floats
@given(st.integers(0, 10**9), st.integers(0, 10**9))
def test_add_commutes(a, b):
assert a + b == b + a
## Run
python3 -m pytest -q tests/test_props.py
Passing looks like: `2 passed` and exit 0.
Failure shows `Falsifying example: test_round_trip(data=b'\x00')` (shrunk) and
exit 1. Add `--hypothesis-seed=0` to make a run reproducible in CI, and
`--hypothesis-show-statistics` to see how many examples were valid.
## As a contract check
{"id": "prop-round-trip-py", "claim": "decode(encode(x)) == x for generated byte strings", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q tests/test_props.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- It samples; the default is 100 examples. Raise `max_examples` for important laws and keep strategies as wide as real input.
- Overusing `assume()` or `.filter()` makes most examples discarded; Hypothesis warns with a health-check failure. Fix the strategy, do not suppress the check.
- To check the test can fail, break the code on purpose and see a shrunk `Falsifying example`. A fixed seed (`derandomize=True`) repeats the same sample forever, so run it with a random seed too.
+73
View File
@@ -0,0 +1,73 @@
---
id: jazzer
title: Fuzzing the JVM and JavaScript with Jazzer and Jazzer.js
answers: Can any input make this Java, Kotlin or Node code throw an unexpected exception, hang or hit a known bug pattern?
rung: 2
section: many-inputs
languages: java, kotlin, javascript, typescript
kinds: parsing, general
cost: medium
detect: jazzer --help
ran_here: no
verified: docs
---
## Use when
- JVM or Node code parses or processes untrusted input and should throw only documented errors.
- You want fuzz tests that run as ordinary unit tests (replaying saved crashes) in CI and as a long fuzz job on demand.
- You want built-in detectors for common problems (injection sinks, unsafe deserialisation).
## Do not use when
- You want shrinking and structured values: `jqwik` or `fast-check`.
- The code is Python (`atheris`) or Go (`go-fuzz`).
## Set up
JVM (JUnit 5): add `com.code-intelligence:jazzer-junit` as a test dependency
(Maven Central; use the current version). A standalone `jazzer` binary is on the
project's GitHub releases page.
Node: `npm install --save-dev @jazzer.js/core` (and `@jazzer.js/jest-runner` for Jest).
## Minimal example (JVM, `ParserFuzzTest.java`)
import com.code_intelligence.jazzer.junit.FuzzTest;
class ParserFuzzTest {
@FuzzTest
void parsePairNeverCrashes(String input) {
try {
Parser.parsePair(input);
} catch (IllegalArgumentException expected) {
// the documented error; any other exception is a finding
}
}
}
Node equivalent (`fuzz.js`): `module.exports.fuzz = function (data /* Buffer */) { parsePair(data.toString()); };`
## Run
JAZZER_FUZZ=1 mvn test -Dtest=ParserFuzzTest # fuzzing mode
mvn test # regression mode: replays saved crashes only
npx jazzer fuzz # Node; see `npx jazzer --help` for corpus and time flags
Without `JAZZER_FUZZ=1` the JUnit tests only replay saved inputs, so a plain test run
is quick and never fuzzes. Passing looks like: tests pass, exit 0. Failure reports the
stack trace and writes the crashing input under
`src/test/resources/<package>/<Class>Inputs/<method>/`; commit it so regression
mode replays it. A time budget for the JVM and Node jobs is a libFuzzer flag
(`-max_total_time=60`); I could not confirm from the docs how each wrapper passes it.
## As a contract check
{"id": "fuzz-parser-jvm", "claim": "parsePair throws only IllegalArgumentException and all saved crashing inputs still pass", "kind": "parsing", "rung": 2, "cmd": "mvn -q test -Dtest=ParserFuzzTest", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
This replays the saved inputs; a fuzzing-mode job is a separate scheduled run.
## What a pass does not prove
- In regression mode it only re-checks saved inputs; it does not search.
- A fuzzing run finding nothing is not a proof; budget and seed corpus matter.
- Not run here (no JDK is set on this machine). `@FuzzTest`, `JAZZER_FUZZ`, the artifact location and the Node install and signature are from the project READMEs; Node corpus and time flags were not confirmed. Check the check: plant a crash and see it found.
+70
View File
@@ -0,0 +1,70 @@
---
id: jqwik
title: Property testing on the JVM with jqwik
answers: Does this Java or Kotlin code hold its law for generated inputs, and what is the smallest failing sample?
rung: 2
section: many-inputs
languages: java, kotlin
kinds: general, parsing, money, state-machine
cost: medium
detect: java -version
ran_here: no
verified: docs
---
## Use when
- JVM code has a law that must hold for all inputs and you run tests with Gradle or Maven.
- You want shrinking, replayable seeds and generators built from annotations.
## Do not use when
- The author asks agents not to use it: since version 1.10 the jqwik user guide has an "Anti-AI Usage Clause" saying "This project is not meant to be used by any “AI” coding agents at all" and adding that the test engine prints a line to stdout on every run telling agents not to use the library; the main JVM alternative is Kotest's property testing (`io.kotest:kotest-property`, Kotlin API, actively released), and for plain Java `junit-quickcheck` exists but has had no commits since 2024.
- You need coverage-guided search for a parser. Use `jazzer`.
- The project is locked to JUnit 4 only; jqwik runs as its own JUnit Platform engine.
## Set up
Gradle (versions as in the jqwik user guide at the time of writing; check for newer):
testImplementation "net.jqwik:jqwik:1.10.2"
test { useJUnitPlatform { includeEngines 'jqwik' } }
Maven: dependency `net.jqwik:jqwik:1.10.2`, scope `test`. Add `-parameters` to
the Java compiler flags so failure reports show argument names.
## Minimal example
import net.jqwik.api.*;
class RoundTripProperties {
static String encode(byte[] b) { return java.util.HexFormat.of().formatHex(b); }
static byte[] decode(String s) { return java.util.HexFormat.of().parseHex(s); }
@Property(tries = 1000)
boolean roundTrips(@ForAll byte[] data) {
return java.util.Arrays.equals(decode(encode(data)), data);
}
}
## Run
./gradlew test # or: mvn test
Passing looks like: the build succeeds, exit 0, the test report shows the property
with `tries = 1000` and no failures.
Failure shows `Shrunk Sample (N steps)` and `Original Sample` plus a `seed`; the
build exits non-zero. By default the next run tries the failing sample first
(`afterFailure = SAMPLE_FIRST`); jqwik keeps this in a local database file, so check
whether your build wipes it. Reproduce explicitly with `@Property(seed = "...")`.
## As a contract check
{"id": "prop-round-trip-jvm", "claim": "decode(encode(x)) equals x for generated byte arrays", "kind": "parsing", "rung": 2, "cmd": "./gradlew test --tests 'RoundTripProperties'", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"}
## What a pass does not prove
- It samples 1000 tries by default; edge cases (empty, extremes) are favoured but not exhaustive.
- A fixed `seed` left in committed code freezes the sample; use `whenFixedSeed = FAIL` to forbid it.
- If the engine is not on the test classpath the property is silently never run: confirm the report lists it. Break the code once and see it fail.
- Not run here (no JDK version is set on this machine). Coordinates, annotations and the shrinking output are from the user guide; the failure-database location was not confirmed.
+70
View File
@@ -0,0 +1,70 @@
---
id: metamorphic
title: Metamorphic testing when there is no oracle
answers: Even though I cannot say what the right answer is, does changing the input in a known way change the output in the way it must?
rung: 2
section: many-inputs
languages: any
kinds: general, parsing, money
cost: low
detect:
ran_here: yes
verified: ran
---
## Use when
- You cannot compute the expected output independently (search ranking, compilers, numeric code, image or report generation) but you know how the output must relate across two related inputs.
- Typical relations: reordering the input does not change the result; scaling inputs scales outputs; adding an irrelevant item does not change the answer; a query with a stricter filter returns a subset.
## Do not use when
- An oracle or reference exists. Use `differential-reference`.
- The relation is only "decode undoes encode". That is `round-trip`.
## Set up
Pick relations from the domain, write each as a function of (input, transformed
input), and run them on generated inputs with `hypothesis`, `proptest` or
`fast-check`. One relation per test so a failure names it.
## Minimal example (Python; a median function)
from statistics import median
from hypothesis import given, strategies as st
def my_median(xs): # under test
s = sorted(xs)
n = len(s)
return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2
nums = st.lists(st.integers(-10**6, 10**6), min_size=1, max_size=50)
@given(nums, st.randoms())
def test_order_does_not_matter(xs, rnd):
ys = xs[:]; rnd.shuffle(ys)
assert my_median(ys) == my_median(xs)
@given(nums, st.integers(-1000, 1000))
def test_shift_shifts_median(xs, k):
assert my_median([x + k for x in xs]) == my_median(xs) + k
@given(nums, st.integers(1, 1000))
def test_scale_scales_median(xs, k):
assert my_median([x * k for x in xs]) == my_median(xs) * k
## Run
python3 -m pytest -q test_metamorphic.py
Passing looks like: `3 passed`, exit 0. Failure names the relation and shrinks the input.
## As a contract check
{"id": "meta-median", "claim": "median is order-independent and shifts and scales with its inputs", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_metamorphic.py", "expect": {"exit": 0, "stdout_contains": "3 passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- A relation only constrains the output, so a wrong function can satisfy one. Use several relations that together pin the behaviour down.
- It never proves the output is the right value, only that it is consistent.
- Check the check: replace the function with a plausible wrong one (the mean, the first element) and see at least one relation fail.
@@ -0,0 +1,79 @@
---
id: model-test-from-spec
title: Model test transcribed from a formal spec (TLA+ or Lean)
answers: Does the implementation behave like the formally specified design, step by step, including what it must refuse?
rung: 2
section: many-inputs
languages: any
kinds: state-machine, money
cost: high
detect: python3 -c "import hypothesis"
ran_here: yes
verified: ran
---
## Use when
- A TLA+, Lean or similar model of the design exists (or is being written) and its properties are proved or model-checked.
- You need the proof to reach the code: the proved design is only worth something if the implementation does what it says.
- Refusal rules matter (what must be rejected, and why), not just happy paths.
## Do not use when
- There is no formal model. Write a plain `stateful-model-test` instead.
- The model can be run directly as a program; then use `differential-executable-spec`, which needs no transcription.
## Set up
Write the model as a small pure function in the implementation's language, one
branch per spec action, from the spec text and not from the implementation.
Name each branch after the spec rule it transcribes. Then use the tooling from
`stateful-model-test` to drive both with random command sequences.
## Minimal example (Python; the spec fragment is a TLA+ `Withdraw` action)
from hypothesis import strategies as st
from hypothesis.stateful import RuleBasedStateMachine, rule
# Spec: Withdraw(n) == n > 0 /\ n <= balance /\ balance' = balance - n
def spec_withdraw(balance, n): # returns (new_balance, refusal)
if n <= 0: return balance, "bad_amount"
if n > balance: return balance, "insufficient"
return balance - n, None
class Account: # implementation under test
def __init__(self): self.balance = 100
def withdraw(self, n):
if n <= 0: return "bad_amount"
if n > self.balance: return "insufficient"
self.balance -= n
class AgainstSpec(RuleBasedStateMachine):
def __init__(self):
super().__init__(); self.impl, self.balance = Account(), 100
@rule(n=st.integers(-5, 150))
def withdraw(self, n):
self.balance, want = spec_withdraw(self.balance, n)
assert self.impl.withdraw(n) == want # same decision, same reason
assert self.impl.balance == self.balance
TestAgainstSpec = AgainstSpec.TestCase
## Run
python3 -m pytest -q test_against_spec.py
Passing looks like: `1 passed`, exit 0. Failure names the command that diverged, with
the shrunk sequence. Keep the spec's rule ids in comments so a mismatch points at a rule.
## As a contract check
{"id": "model-vs-spec", "claim": "the implementation accepts and refuses commands as the TLA+ Withdraw action does", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_against_spec.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- The transcription is by hand. If it drifts from the spec, you test your reading of the spec; have it reviewed against the spec text.
- It samples sequences. The proof covers all of them; this only shows no counterexample was found.
- Commands the generator cannot express are not compared. List them. (One reference project's Lean differential test lists the model commands its input format cannot reach and leaves those to review.)
- Make the test fail on purpose: change one comparison in the implementation, or let the model allow something the spec forbids.
@@ -0,0 +1,84 @@
---
id: old-data-compatibility
title: Compatibility with data written by older and newer versions
answers: Do files written by earlier versions still open to their recorded figures, and is data from a newer version reported as newer rather than corrupt?
rung: 3
section: many-inputs
languages: any
kinds: migration, state-machine, money
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- The program reads files, databases or journals that users keep across upgrades.
- You change a format, a schema or the rules for computing a stored figure.
- An old version may meet newer data (downgrade, shared folder, restored backup).
## Do not use when
- You want sampled inputs: use `round-trip`; this uses fixed fixtures.
## Set up
1. When a format version ships, write real data with that version and commit it
as `tests/fixtures/<version>/` together with `expected.json`, the figures the
version itself computed. Never regenerate old fixtures with new code.
2. Keep a newer-format fixture (or fake one with a bumped format field).
## Minimal example (Python)
import json, pathlib, tempfile
CURRENT = 2
def open_book(path):
data = json.loads(pathlib.Path(path).read_text()) # raises on garbage
v = data.get("format")
if v is None or not isinstance(v, int):
raise ValueError("corrupt: no format")
if v > CURRENT:
raise RuntimeError(f"newer: written by format {v}, this reader knows {CURRENT}")
return {"total": sum(data["cents"])} # v1 and v2 both store `cents`
def test_old_fixture_reopens_to_recorded_figures():
got = open_book("fixtures/v1/book.json")
assert got == json.load(open("fixtures/v1/expected.json"))
def test_newer_is_reported_as_newer_and_left_untouched():
p = pathlib.Path(tempfile.mkdtemp()) / "b.json"
p.write_text(json.dumps({"format": 3, "cents": [1]}))
before = p.read_bytes()
try:
open_book(p); assert False
except RuntimeError as e:
assert str(e).startswith("newer")
assert p.read_bytes() == before # never repaired or rewritten
def test_damage_is_still_corrupt():
p = pathlib.Path(tempfile.mkdtemp()) / "b.json"
p.write_text("{not json")
try:
open_book(p); assert False
except ValueError: pass
## Run
python3 -m pytest -q test_compat.py
Passing looks like: `3 passed`, exit 0. Failure shows which fixture gave other figures,
or a newer file reported as corrupt (or the reverse).
## As a contract check
{"id": "old-data-compat", "claim": "v1 fixtures reopen to recorded figures; newer data is reported newer and untouched; damage stays corrupt", "kind": "migration", "rung": 3, "cmd": "python3 -m pytest -q test_compat.py", "expect": {"exit": 0, "stdout_contains": "3 passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- Only the fixtures you have: keep one per released format.
- Expected figures come from the old version; never regenerate them to make a test pass.
- It does not show an upgrade is safe on real data: test the upgrade step on a copy.
- Check the check: edit a fixture's figure and see the test fail; bump a format number and see "newer" appear.
+73
View File
@@ -0,0 +1,73 @@
---
id: proptest
title: Property testing in Rust with proptest
answers: Does this Rust function keep its promise for every input I can generate, not just the few I thought of?
rung: 2
section: many-inputs
languages: rust
kinds: general, parsing, money, state-machine
cost: low
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- A pure function or data structure has a law that must hold for all inputs: round trip, idempotence, agreement with a slow reference, "never panics".
- You want a failure reduced to a small input (shrinking) and replayed on every later run.
- Money, parsing or index arithmetic, where the dangerous inputs are ones nobody writes by hand.
## Do not use when
- The law cannot be stated without re-implementing the function. Use `metamorphic` or `differential-reference`.
- The property needs coverage-guided search of a deep parser. Use `cargo-fuzz`.
- A proof is affordable and a sample is not enough. See the `prove` section.
## Set up
cargo add --dev proptest
Put the test in `#[cfg(test)]` in the crate or in `tests/props.rs`. Commit the
`proptest-regressions` files that proptest writes (see `regression-seed-hygiene`).
## Minimal example
pub fn encode(x: &[u8]) -> String { x.iter().map(|b| format!("{:02x}", b)).collect() }
pub fn decode(s: &str) -> Option<Vec<u8>> {
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
proptest! {
#![proptest_config(ProptestConfig::with_cases(1000))]
#[test]
fn round_trip(bytes in proptest::collection::vec(any::<u8>(), 0..256)) {
prop_assert_eq!(decode(&encode(&bytes)), Some(bytes));
}
}
}
## Run
cargo test round_trip
PROPTEST_CASES=10000 cargo test round_trip # more cases, same test
Passing looks like: `test tests::round_trip ... ok` and exit 0.
Failure shows `minimal failing input: bytes = [0]` after shrinking, exit 101, and
a line saying the seed was saved to a `proptest-regressions/...` file. Later runs
replay that seed first. To make a test cheap for mutation testing or a slow
host, `PROPTEST_MAX_SHRINK_ITERS=0` turns shrinking off.
## As a contract check
{"id": "prop-round-trip", "claim": "decode(encode(x)) == x for generated byte strings", "kind": "parsing", "rung": 2, "cmd": "cargo test round_trip", "expect": {"exit": 0, "stdout_contains": "1 passed"}, "tier": "deep", "timeout_s": 600}
## What a pass does not prove
- It samples. 1000 cases of small inputs say nothing about the huge or odd ones the strategy never produces: check the ranges (`0..256`) against real input sizes.
- A filter such as `prop_assume!` that rejects most cases makes a pass nearly empty. proptest aborts with "too many local rejects" when that happens; do not raise the limit to silence it.
- To check the test can fail, break the code on purpose (change `{:02x}` to `{:x}` in `encode`) and see it fail with a shrunk input, then restore it. `cargo-mutants` does this at scale.
@@ -0,0 +1,69 @@
---
id: python-stdlib-property
title: Property-style tests with only the Python standard library
answers: Can I check a law over many generated inputs when I may not install any package?
rung: 2
section: many-inputs
languages: python
kinds: general, parsing, money
cost: low
detect: python3 --version
ran_here: yes
verified: ran
---
## Use when
- No third-party packages are allowed or available.
- The law is simple (round trip, ordering, agreement with a reference) and a bounded, seeded random loop is enough.
- You need a quick sample before deciding whether to bring in `hypothesis`.
## Do not use when
- Packages are allowed: `hypothesis` shrinks failures and remembers them; this does not.
- The input has structure that blind random bytes rarely satisfy (valid JSON, balanced entries). Write a structured generator or use `structure-aware-fuzzing`.
## Set up
Nothing to install. Put the test in `tests/test_props.py` and run it with `unittest`.
## Minimal example
import os, random, unittest
def encode(b): return b.hex()
def decode(s): return bytes.fromhex(s)
class Props(unittest.TestCase):
def test_round_trip(self):
fixed = [0, 1, 2] # always run: reproducible
fresh = [random.randrange(2**32) for _ in range(3)] # new ground each run
extra = [int(s) for s in os.environ.get("SEEDS", "").split(",") if s]
for seed in fixed + fresh + extra:
rng = random.Random(seed)
for _ in range(500):
data = bytes(rng.randrange(256) for _ in range(rng.randrange(64)))
with self.subTest(seed=seed, data=data):
self.assertEqual(decode(encode(data)), data)
if __name__ == "__main__":
unittest.main()
## Run
python3 -m unittest discover -s tests
Passing looks like: `Ran 1 test` then `OK`, exit 0.
Failure shows `FAIL: test_round_trip (seed=..., data=...)` with the seed and input
in the subTest label, exit 1. Reproduce a failing fresh seed with
`SEEDS=<seed> python3 -m unittest discover -s tests`, then copy it into `fixed`.
## As a contract check
{"id": "prop-round-trip-stdlib", "claim": "decode(encode(x)) == x over seeded random inputs", "kind": "parsing", "rung": 2, "cmd": "python3 -m unittest discover -s tests", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
## What a pass does not prove
- There is no shrinking: the failing input may be large. Print it, then reduce by hand.
- Uniform random bytes seldom hit edge cases (empty, maximum, boundary values). Add them to the generator explicitly.
- The checker only sees what the generator makes. Test the check by breaking the code on purpose and seeing it fail.
@@ -0,0 +1,70 @@
---
id: regression-seed-hygiene
title: Keeping failing seeds checked in, replayed and never orphaned
answers: Once a random test or fuzzer found a bug, is that exact input still replayed on every run so the bug cannot return?
rung: 2
section: many-inputs
languages: any
kinds: general, parsing, state-machine
cost: low
detect:
ran_here: yes
verified: ran
---
## Use when
- You use proptest, Hypothesis, fast-check, a fuzzer or rapid, and a failure has been found, or will be.
- A random test went red once and green on re-run, and nobody recorded why.
- You are finishing a bug fix found by a random or fuzz test.
## Do not use when
- The suite has only fixed example tests; those already replay.
## Set up
Know where each tool keeps failures, and commit those:
- proptest: `proptest-regressions/*.txt` (or `*.proptest-regressions` beside the test file); the path is printed on failure.
- cargo-fuzz: `fuzz/artifacts/<target>/crash-*`; copy fixed cases to `fuzz/seeds/<target>/`.
- Go native fuzzing: `testdata/fuzz/FuzzName/<hash>`; plain `go test` replays them.
- Hypothesis: `.hypothesis/` is local; pin the minimal case with `@example(...)` in the test.
- fast-check: pass `{ seed, path }` to reproduce, or add `examples: [[...]]` to keep it.
## Minimal example (Hypothesis: pin the shrunk failure)
from hypothesis import given, example, strategies as st
def parse_amount(s):
return int(s.replace(",", "")) # fixed: used to reject "1,000"
@given(st.integers(0, 10**9).map(lambda n: f"{n:,}"))
@example("1,000") # the case the fuzzer found; stays forever
def test_parse_amount(text):
assert parse_amount(text) == int(text.replace(",", ""))
A cheap guard that none are orphaned (a deleted test leaves its seed file behind):
# check_seeds.sh: every seed file maps to an existing test file
for f in proptest-regressions/*.txt; do
t=$(basename "$f" .txt); [ -e "src/$t.rs" ] || [ -e "tests/$t.rs" ] || { echo "orphaned: $f"; exit 1; }
done
## Run
python3 -m pytest -q test_amount.py
sh check_seeds.sh
Passing looks like: `1 passed`, exit 0, and no `orphaned:` line. A removed pin makes
the pinned case vanish silently, so review diffs of `@example` and seed files.
## As a contract check
{"id": "seeds-replayed", "claim": "every saved failing input is replayed and no seed file is orphaned", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_amount.py && sh check_seeds.sh", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- Replay proves the old bug is not back, not that the area is clean.
- A seed recorded for an old test shape may no longer reach the same code after a refactor (proptest seeds depend on the strategy); for important bugs also add a plain named example test.
- Check the check: revert the fix and confirm the pinned or saved case fails by itself, with random generation turned off (`derandomize=True`, or a replay of only the seed file).
@@ -0,0 +1,78 @@
---
id: replay-equivalence
title: Replay equivalence for event-sourced and journalled state
answers: Is the live state exactly what you get by replaying the log from scratch, and does a refused command leave no trace?
rung: 2
section: many-inputs
languages: any
kinds: state-machine, money
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- State is built from a log of events or journal lines (event sourcing, write-ahead logs, ledgers, undo stacks).
- Restart, backup restore and replication rebuild state by replay, so any drift between live and replayed state is data loss waiting to happen.
- Commands can be refused (validation, closed period, limits).
## Do not use when
- State is stored directly and no log exists. Use `fault-injection-storage` and `round-trip`.
## Set up
Expose two things: a way to apply a command (which may append to the log and
change live state) and a way to build state from the log alone. Drive both with
random command sequences, including commands that must be refused.
## Minimal example (Python)
from hypothesis import given, strategies as st
class Store:
def __init__(self): self.log, self.balance = [], 0
@staticmethod
def fold(log): # state from the log alone
b = 0
for kind, n in log:
b += n if kind == "dep" else -n
return b
def command(self, kind, n):
if n <= 0 or (kind == "wd" and n > self.balance):
return "refused"
self.log.append((kind, n))
self.balance += n if kind == "dep" else -n
return "ok"
cmds = st.lists(st.tuples(st.sampled_from(["dep", "wd"]), st.integers(-3, 50)), max_size=40)
@given(cmds)
def test_live_equals_replay_and_refusals_leave_no_trace(commands):
s = Store()
for kind, n in commands:
log_before, state_before = list(s.log), s.balance
if s.command(kind, n) == "refused":
assert s.log == log_before # nothing written
assert s.balance == state_before # nothing changed
assert s.balance == Store.fold(s.log) # live == replay, after every command
## Run
python3 -m pytest -q test_replay.py
Passing looks like: `1 passed`, exit 0. Failure shows the shortest command list where live
and replayed state differ, or where a refusal wrote something.
## As a contract check
{"id": "replay-equivalence", "claim": "live state equals state replayed from the log after any command sequence, and refused commands change nothing", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_replay.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- Replay may use the same code as the live path, and then agrees trivially. Make replay a separate, simpler fold, or replay through the persisted bytes (write the log, reopen, compare).
- Compare everything observable (balances, indexes, derived reports), not one number; a field left out hides drift.
- Include refused commands in the generator, or the "no trace" half is never tested. Count how many were refused.
- Check the check: make a refused command append to the log, or make replay skip one event type, and see it fail.
+68
View File
@@ -0,0 +1,68 @@
---
id: round-trip
title: Round-trip properties for encode/decode, serialise/parse and do/undo
answers: Does undoing an operation always return exactly what I started with, for every input I can generate?
rung: 2
section: many-inputs
languages: any
kinds: parsing, general, money
cost: low
detect:
ran_here: yes
verified: ran
---
## Use when
- A serialiser and a parser, an encoder and a decoder, a compressor and decompressor, or a do and an undo operation exist.
- Data is saved and reloaded (files, wire formats, journal lines, backups).
- You want a cheap check that loses no information, with no oracle needed.
## Do not use when
- The encoding is lossy by design; test the part that must survive instead.
- Only one direction exists; use `metamorphic` or `algebraic-laws`.
## Set up
Generate values of the in-memory type (not strings of the encoded form), encode,
decode, compare. Also test the other direction where it matters: for any text
the parser accepts, encoding the parsed value gives the canonical text again.
## Minimal example (Python; JSON of integer cents)
import json
from hypothesis import given, strategies as st
entry = st.fixed_dictionaries({
"memo": st.text(max_size=40),
"cents": st.integers(-2**63, 2**63 - 1),
"tags": st.lists(st.text(max_size=8), max_size=5),
})
@given(entry)
def test_value_round_trip(e):
assert json.loads(json.dumps(e)) == e
@given(entry)
def test_text_is_stable(e):
text = json.dumps(e, sort_keys=True)
assert json.dumps(json.loads(text), sort_keys=True) == text
## Run
python3 -m pytest -q test_round_trip.py
Passing looks like: `2 passed`, exit 0.
Failure shows the shrunk value that came back changed, exit 1.
## As a contract check
{"id": "round-trip-entry", "claim": "entries survive serialise then parse unchanged", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q test_round_trip.py", "expect": {"exit": 0, "stdout_contains": "2 passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- It shows no loss, not that the encoding is right: a format that stores the wrong thing round-trips perfectly. Add a golden file or reference parser for the format itself.
- It only covers values the generator makes. Give it the awkward ones: empty, maximum, negative, non-ASCII, a trailing newline, NaN if floats are allowed.
- Equal after the round trip can hide equality that is too loose (`1 == 1.0`, `0 == -0.0`); compare types and canonical text too.
- Check the check: drop a field from the encoder and see the test fail.
@@ -0,0 +1,80 @@
---
id: stateful-model-test
title: Stateful model testing against a simple in-memory model
answers: After any sequence of operations, does the real system agree with a trivially simple model of what it should do?
rung: 2
section: many-inputs
languages: rust, python, typescript, go
kinds: state-machine, general, money
cost: medium
detect: python3 -c "import hypothesis"
ran_here: yes
verified: ran
---
## Use when
- The system has state and commands (a store, ledger, cache, queue, editor buffer) and bugs appear only after particular sequences.
- You can write a model in a few dozen lines using lists and dictionaries, with no performance tricks.
- You need to show that refused commands change nothing and that accepted ones do what the model says.
## Do not use when
- The model would be as complex as the system. Then the two share bugs; use `model-test-from-spec` or `differential-reference` instead.
- The behaviour is stateless: use `proptest`, `hypothesis` or `fast-check` directly.
- The commands race each other. See the `concurrency` section.
## Set up
Python: `pip install hypothesis`. Rust: `cargo add --dev proptest proptest-state-machine`.
TypeScript: `npm i -D fast-check` (`fc.commands`, `fc.modelRun`). Go: `rapid`'s `T.Repeat`.
## Minimal example (Python, Hypothesis `RuleBasedStateMachine`)
from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
from hypothesis import strategies as st
class Stack: # the system under test
def __init__(self): self.items = []
def push(self, x): self.items.append(x)
def pop(self): return self.items.pop()
class StackMachine(RuleBasedStateMachine):
def __init__(self):
super().__init__()
self.sut, self.model = Stack(), []
@rule(x=st.integers())
def push(self, x):
self.sut.push(x); self.model.append(x)
@rule()
def pop(self):
if self.model: # only when the model allows it
assert self.sut.pop() == self.model.pop()
@invariant()
def same_contents(self):
assert self.sut.items == self.model
TestStack = StackMachine.TestCase
## Run
python3 -m pytest -q test_stack.py
Passing looks like: `1 passed`, exit 0.
Failure prints the shortest failing sequence as `state.push(x=0)`, `state.push(x=1)`,
`state.pop()`, exit 1. Rust prints `minimal failing input` with the transition list;
fast-check prints `Counterexample: [push(0),push(1),pop()]`.
## As a contract check
{"id": "model-stack", "claim": "the stack agrees with a list model after any command sequence", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_stack.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
- Sequences are short and random; a bug needing a rare long sequence can hide. Weight the generator toward commands that interact (post then reverse, close then add).
- A model that never reaches interesting states passes vacuously. Count how often each accepted command and each refusal occurs (one reference project's ledger test prints these under `MODEL_STATS=1`; its first version never posted an entry and agreed with the model for the wrong reason).
- Check the check: make the model wrong on purpose (for example allow a second reversal) and see the test fail quickly.
- It compares only what you read back. Compare every observable: results, refusals, and a full read of the state.
@@ -0,0 +1,79 @@
---
id: structure-aware-fuzzing
title: Structure-aware fuzzing with `arbitrary` and grammar-based inputs
answers: Can sequences of valid-looking operations, not just random bytes, break the code or its invariants?
rung: 2
section: many-inputs
languages: rust
kinds: state-machine, parsing, money
cost: medium
detect: cargo fuzz --version
ran_here: yes
verified: ran
---
## Use when
- Raw bytes almost never form valid input (JSON, command lists, balanced entries), so a plain fuzzer wastes its time on rejections.
- You want the fuzzer to drive a sequence of operations on a state machine and check invariants after each.
- The fuzz target should check more than "no panic": a model, a round trip, "a refused command changes nothing".
## Do not use when
- The input really is arbitrary bytes (a file format parser): use `cargo-fuzz` with `&[u8]`.
- You want shrinking and readable counterexamples: `proptest` is better at that.
## Set up
cargo add arbitrary --features derive # in the fuzz crate (cargo fuzz init already adds it)
Derive `Arbitrary` on the input types. For grammar-style input (valid SQL,
JSON), write a small generator that turns the fuzzer's bytes into a valid
document with `Unstructured`, or use a grammar-based fuzzer such as `Grammarinator`.
## Minimal example (`fuzz/fuzz_targets/fuzz_target_1.rs`)
#![no_main]
use libfuzzer_sys::fuzz_target;
// in the library crate:
// #[derive(Debug, arbitrary::Arbitrary)]
// pub enum Op { Deposit(u32), Withdraw(u32) }
// Account::apply(&mut self, &Op) -> Result<(), &'static str>
fuzz_target!(|ops: Vec<mycrate::Op>| {
let mut acct = mycrate::Account::default();
let mut model: u64 = 0;
for op in &ops {
let before = acct.cents;
if acct.apply(op).is_ok() {
match op {
mycrate::Op::Deposit(n) => model += *n as u64,
mycrate::Op::Withdraw(n) => model -= *n as u64,
}
} else {
assert_eq!(acct.cents, before, "refused op changed state");
}
assert_eq!(acct.cents as u64, model, "balance diverged from model");
}
});
## Run
RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 -- -max_total_time=60
Passing looks like: `Done N runs in 60 second(s)`, exit 0.
Failure prints the panic or assertion and the input as the `Debug` of the Rust
value (`[Withdraw(...)]`), then exits 1 with a crash file in `fuzz/artifacts/`.
Print an old crash as Rust values with `cargo fuzz fmt fuzz_target_1 <crash-file>`.
## As a contract check
{"id": "fuzz-account-ops", "claim": "no fuzzed operation sequence breaks the account model or changes state on refusal", "kind": "state-machine", "rung": 2, "cmd": "cd fuzz-host && RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 -- -max_total_time=60", "expect": {"exit": 0, "stdout_contains": "Done"}, "tier": "deep", "timeout_s": 600}
## What a pass does not prove
- Only what the run reached in its time budget; a clean run is not a proof.
- A derived `Arbitrary` makes uniform-looking values. If the interesting values (zero, maximum, the same account twice) are rare, bias the generator by hand.
- The invariants are only as good as the asserts. One reference project's operation-sequence target checks that the trial balance balances after any sequence; without that assert the same run would only look for panics.
- Check the check: seed a bug (the example subtracts one extra cent on withdrawal) and see the fuzzer find it within seconds.
+54
View File
@@ -0,0 +1,54 @@
---
id: aeneas-rust-to-lean
title: Translating Rust to Lean with Charon and Aeneas to prove real code
answers: Can I prove a property of my actual Rust function, not of a hand-written model of it?
rung: 1
section: prove
languages: rust
kinds: general, parsing, money
cost: high
detect: aeneas --help
ran_here: no
verified: docs
---
## Use when
- The Rust is safe, mostly functional code (no heavy trait objects, little unsafe) and you want an unbounded proof about it.
- You need the proof to be about the compiled-from source, so `proof-bridging` is not enough.
## Do not use when
- A bounded proof will do. `kani` is far cheaper.
- The code uses features Charon cannot translate (many closures, async, `dyn` traits). Check what it supports first.
## Set up
Both tools are built from source; there is no package install. From the Aeneas and Charon READMEs (github.com/AeneasVerif/aeneas, .../charon): you need `rustup` (Charon pins its own nightly), OCaml 5 with opam (`opam switch create 5.3.0`, then `opam install src --deps-only --with-test` in the Aeneas checkout), and Lean. In the Aeneas checkout `make setup-charon` builds Charon at the commit in `charon-pin`, and `make` builds `bin/aeneas`. Put `charon` and `aeneas` on PATH. Not installed here, so nothing below was run.
Translate, from inside the crate:
```
charon cargo --preset=aeneas # writes <crate_name>.llbc
aeneas -backend lean my_crate.llbc -dest lean/
```
`-backend` also takes `fstar`, `coq` and `hol4`. Generated Lean files import the `Aeneas` package, so the Lean project needs it: `lake new`, copy `lean-toolchain` from `backends/lean` in the Aeneas repo, and require it in the lakefile with `[[require]] name = "aeneas" path = "PATH_TO_AENEAS_REPO/backends/lean"` (or `require aeneas from "PATH..."` in a `lakefile.lean`). Aeneas emits definitions in a `Result` monad for panics and overflow. Flags change between releases (both projects publish nightly releases); check `charon --help` and `aeneas --help`.
## Minimal example
A Rust function to prove things about:
```rust
pub fn add_cents(a: u32, b: u32) -> Option<u32> { a.checked_add(b) }
```
Aeneas emits a Lean `add_cents` returning a `Result`. You then write a theorem in a separate Lean file that says: if the result is `ok (some c)` then `c.val = a.val + b.val`, and prove it with the Aeneas tactics `step` (older releases called it `progress`; `step*` repeats it) and `scalar_tac` (arithmetic on bounded integers). The exact names and goal shapes depend on the generated code and library version, so copy the pattern from the Aeneas repository's `tests/lean/Tutorial/` (`Solutions.lean` uses `step as ⟨ ... ⟩` and `scalar_tac`). Not confirmed by running here.
## Run
`lake build --wfail` in the Lean project, after regenerating the Lean files from the current Rust.
Passing looks like: exit 0, and the audit of `lean-axiom-audit` is clean. Failure: Lean errors on the open goal.
## As a contract check
```json
{"id": "prove-add-cents-aeneas", "claim": "add_cents is exact or None, proved on the Lean translation of the Rust", "kind": "money", "rung": 1, "cmd": "bash -c 'charon cargo --preset=aeneas && aeneas -backend lean my_crate.llbc -dest lean/ && cd lean && lake build --wfail'", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"}
```
## What a pass does not prove
- The translation must be regenerated on every Rust change; a stale `lean/` dir proves the old code. The command above regenerates first.
- Aeneas's own semantics are trusted, and the proof assumes the Rust compiler follows them.
- Unsafe code and unsupported features are excluded or axiomatised; read the generated file for `axiom` and `opaque`.
- Not run here: the charon and aeneas invocations, `-dest`, and the tactic names were checked against the READMEs, the Aeneas command-line source and its Lean tutorial, but the example theorem was not compiled.
+67
View File
@@ -0,0 +1,67 @@
---
id: cbmc
title: CBMC bounded model checking for C
answers: Can this C code overflow, read out of bounds or break an assert for any input within a loop bound?
rung: 1
section: prove
languages: c
kinds: general, parsing
cost: medium
detect: cbmc --version
ran_here: yes
verified: ran
---
## Use when
- C code with buffers, indexes and integer arithmetic needs a check over all inputs up to a loop bound.
- You want memory-safety and overflow checks without writing a contract language.
## Do not use when
- You need unbounded proofs. Use `frama-c-wp`.
- The code is Rust. Use `kani`, which is built on CBMC.
## Set up
Install `cbmc` from your package manager or releases (github.com/diffblue/cbmc). Tried with 6.11.0, the binary that Kani bundles (`~/.kani/kani-*/bin/cbmc`). A C compiler is not needed for checking.
## Minimal example
`a.c`:
```c
#include <assert.h>
#include <stdint.h>
int clamp(int lo, int hi, int x) { return x < lo ? lo : (x > hi ? hi : x); }
uint32_t sum(const uint8_t *a, unsigned n) {
uint32_t s = 0;
for (unsigned i = 0; i < n; i++) s += a[i];
return s;
}
int main(void) {
int lo, hi, x; /* uninitialised = any value */
__CPROVER_assume(lo <= hi);
int r = clamp(lo, hi, x);
assert(lo <= r && r <= hi);
uint8_t buf[4];
unsigned n;
__CPROVER_assume(n <= 4);
assert(sum(buf, n) <= 4 * 255);
return 0;
}
```
## Run
`cbmc a.c --bounds-check --pointer-check --signed-overflow-check --unwind 5 --unwinding-assertions`
Passing looks like: `VERIFICATION SUCCESSFUL`, exit 0, and `** 0 of N failed`. Failure: `VERIFICATION FAILED` and exit 10 (seen after changing the assert to `lo < r`). `--unwinding-assertions` makes a loop that needs more iterations than `--unwind` fail instead of passing silently.
## As a contract check
```json
{"id": "prove-clamp-cbmc", "claim": "clamp stays in [lo, hi] and sum has no memory errors for n <= 4", "kind": "general", "rung": 1, "cmd": "cbmc a.c --bounds-check --pointer-check --signed-overflow-check --unwind 5 --unwinding-assertions", "expect": {"exit": 0, "stdout_contains": "VERIFICATION SUCCESSFUL"}, "tier": "deep", "timeout_s": 900}
```
## What a pass does not prove
- Only paths within the unwind bound and the `assume`s. Omit `--unwinding-assertions` and the bound is not even checked.
- An unsatisfiable `__CPROVER_assume` makes everything pass; add a reachability assertion such as `__CPROVER_assert(0, "reached")` expecting failure, or use `--cover location`, to see the point is reached.
- Library calls without a model are treated as returning any value, which may cause false alarms but not false passes.
+56
View File
@@ -0,0 +1,56 @@
---
id: creusot
title: Creusot deductive verification for Rust
answers: Does this Rust code satisfy its contracts for all inputs, proved through Why3?
rung: 1
section: prove
languages: rust
kinds: general
cost: high
detect: cargo creusot --help
ran_here: no
verified: docs
---
## Use when
- You want proofs for safe Rust including ownership-heavy code (it models borrows prophetically) and are comfortable with the Why3 ecosystem.
- Contracts as attributes (`#[requires]`, `#[ensures]`, `#[logic]`) suit you better than a separate macro block.
## Do not use when
- You need low set-up cost. Use `kani`. Creusot needs opam, Why3 and SMT solvers.
- Unsafe or heavily dynamic code is involved.
## Set up
From the Creusot README and guide ("Installation"): there is no `cargo install`. Needs `rustup`, `opam` (for Why3 and `why3find`) and `curl` (to download the provers alt-ergo, z3, cvc4 and cvc5). Then:
git clone https://github.com/creusot-rs/creusot
cd creusot
./INSTALL # a few minutes; makes a private opam switch under ~/.local/share/creusot/_opam
cargo creusot --help # check the install
Create a project with `cargo creusot new project-name`, or add the contracts crate to an existing one (the crate is now `creusot-std`, imported as `creusot_std`; if the compiler says its items are missing, the guide's troubleshooting section shows a `[patch.crates-io]` entry pointing at the checkout). Not installed here, so the example was not run.
## Minimal example
```rust
use creusot_std::prelude::*;
#[requires(a@ + b@ <= u32::MAX@)]
#[ensures(result@ == a@ + b@)]
pub fn add(a: u32, b: u32) -> u32 { a + b }
```
`x@` is the logical (mathematical) value of `x`. Spec language details change by release; follow the guide's current examples.
## Run
`cargo creusot` compiles the crate to Coma (into `verif/`) and then runs the provers through Why3find. The two steps can be run separately: `cargo creusot --only=coma` and `cargo creusot --only=prove`. A Coma file can be named to prove just that one; `-i` opens the Why3 IDE when a proof fails; `--replay` only re-checks existing proofs (`proof.json`). There is no `cargo creusot prove` subcommand in the current guide.
Passing looks like: the guide says a successful run "gives us the certainty that functions defined in this package satisfy their contracts". It does not state what the output or exit status looks like for unproved goals; check on a deliberately wrong contract that `cargo creusot` exits non-zero before relying on exit alone. Only libraries and binaries are compiled, not tests or examples.
## As a contract check
```json
{"id": "prove-add-creusot", "claim": "add returns the exact sum when it fits in u32", "kind": "general", "rung": 1, "cmd": "cargo creusot", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only the contracts written; functions marked `#[trusted]` are assumed. Grep for `trusted`.
- Proofs by SMT solvers can time out; whether an unproved goal makes `cargo creusot` exit non-zero is not documented, so test it.
- Not run here; commands come from the Creusot README, guide and command-line reference. `#[trusted]` (also in the guide) skips checking of the function body, and the `x@` notation for the logical value is as in the guide's quick start.
+56
View File
@@ -0,0 +1,56 @@
---
id: crosshair
title: CrossHair symbolic checking of Python contracts
answers: Can I find any inputs that break this Python function's contract or type annotations?
rung: 2
section: prove
languages: python
kinds: general, parsing
cost: low
detect: crosshair --version
ran_here: yes
verified: ran
---
## Use when
- Pure Python functions with a docstring contract (`pre:` / `post:`) or PEP 316 / icontract / deal contracts.
- You want a solver to hunt for counterexamples before writing property tests.
- You want it to replay found inputs as ordinary tests.
## Do not use when
- The function does I/O, uses C extensions heavily or hashing-dependent logic: the solver gives up.
- You need a proof. Silence from CrossHair means "none found in the time given", so this is rung 2 here. Use `dafny`, `z3-smt` or `lean4-proofs` for rung 1.
## Set up
`pip install crosshair-tool` (5.4.1 observed; use a virtualenv). Contracts live in docstrings.
## Minimal example
`cc.py`:
```python
def clamp(lo: int, hi: int, x: int) -> int:
"""
pre: lo <= hi
post: lo <= __return__ <= hi
"""
if x < lo:
return lo
if x > hi:
return hi
return x
```
Add a function with a false postcondition to see failure, for example `post: __return__ >= 0` on `return x - 1 if x > 0 else x`.
## Run
`crosshair check cc.py --per_condition_timeout=30`
Passing looks like: no output and exit 0. Failure: a line like `cc.py:14: error: false when calling bad(-1) (which returns -1)` and exit 1 (observed). `--per_condition_timeout` bounds the search per function.
## As a contract check
```json
{"id": "prove-clamp-crosshair", "claim": "clamp satisfies its postcondition for all inputs CrossHair can find in 30 seconds", "kind": "general", "rung": 2, "cmd": "crosshair check cc.py --per_condition_timeout=30", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- A time-limited search that found nothing; it does not say it covered all paths. Raise the timeout once and see whether a failure appears.
- It checks only the contract you wrote. A weak or missing `post:` passes everything.
- Add a failing function as a canary to confirm the run really analyses your file.
+65
View File
@@ -0,0 +1,65 @@
---
id: dafny
title: Dafny verified algorithms that compile to a target language
answers: Does this algorithm meet its specification for all inputs, and can I run the verified code?
rung: 1
section: prove
languages: dafny
kinds: general, state-machine
cost: medium
detect: dafny --version
ran_here: yes
verified: ran
---
## Use when
- You are writing an algorithm or data structure from scratch and can write it in Dafny, then compile to Python, Go, Java, C# or JavaScript.
- You want pre/postconditions and loop invariants checked by an SMT solver for all inputs.
- A spec-first workflow fits: `requires`/`ensures` first, body second.
## Do not use when
- The code already exists in Rust, C or Python and must be verified as is. Use `verus`, `kani`, `frama-c-wp` or `crosshair`.
- The compiled output must meet tight performance or integration needs the target backend cannot.
## Set up
Download the release zip from github.com/dafny-lang/dafny/releases (4.11.0 tried; it includes its own runtime, Z3 included) and unzip. No global install needed: call `./dafny/dafny`.
## Minimal example
`a.dfy`:
```dafny
method Abs(x: int) returns (y: int)
ensures y >= 0 && (y == x || y == -x)
{
if x < 0 { y := -x; } else { y := x; }
}
method SumTo(n: nat) returns (s: nat)
ensures s == n * (n + 1) / 2
{
s := 0;
var i := 0;
while i < n
invariant i <= n && s == i * (i + 1) / 2
{
i := i + 1;
s := s + i;
}
}
method Main() { var r := Abs(-3); print r, "\n"; }
```
## Run
`dafny verify a.dfy`, then `dafny run --target:py a.dfy` to compile and run on Python.
Passing looks like: exit 0 and `Dafny program verifier finished with 4 verified, 0 errors`. Failure: an error with the failing line and `finished with 3 verified, 1 error`, exit 4 (observed after changing `s + i` to `s + i + 1`). Use `--verification-time-limit <seconds>` (default 30) to bound each assertion batch; a timeout is reported as an error.
## As a contract check
```json
{"id": "prove-sumto-dafny", "claim": "SumTo and Abs satisfy their postconditions for all inputs", "kind": "general", "rung": 1, "cmd": "dafny verify a.dfy", "expect": {"exit": 0, "stdout_contains": "0 errors"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Only the written `ensures`. A weak postcondition (say `ensures true`) verifies trivially; review the specs.
- `assume` statements, `{:axiom}` and `{:verify false}` skip proof; grep for them. Termination is checked unless `decreases *` is used.
- The compiled program is trusted to match: the compiler and runtime are not verified. Target-language integers and I/O are outside the proof.
@@ -0,0 +1,65 @@
---
id: exhaustive-small-domain
title: Brute-forcing every input when the domain is small enough
answers: Does this function give the right answer for every possible input, because I tried them all?
rung: 1
section: prove
languages: any
kinds: general, money, parsing
cost: low
detect:
ran_here: yes
verified: ran
---
## Use when
- The input domain is small: every `u8`, every `u16`, every pair of `u8` (65,536), every string up to length 3 over a small alphabet.
- You have a reference you trust (a wider type, a formula, a slow obvious version) to compare against.
- A proof tool would be heavier than a loop that finishes in seconds.
## Do not use when
- The domain is `u32` pairs or larger (about 1.8e19 cases). Use `kani`, `z3-smt` or a property test (rung 2).
- You would need to sample. Sampling is a property test, not this.
## Set up
Nothing. Count the cases first: `domain_size = product of each input's range`. Keep it under roughly 1e9 for fast code and write the number in the test.
## Minimal example
```rust
#[test]
fn every_u8_is_accepted_or_refused_correctly() {
for v in 0..=u8::MAX {
assert_eq!(Percent::new(v).is_some(), v <= 100);
}
}
#[test]
fn every_u16_checked_add_matches_the_wide_sum() {
let mut n = 0u64;
for a in 0..=u16::MAX {
for b in 0..=u16::MAX {
let w = a as u32 + b as u32;
assert_eq!(a.checked_add(b).map(u32::from), (w <= 65535).then_some(w));
n += 1;
}
}
assert_eq!(n, 65_536 * 65_536); // proves the loop ran over the whole domain
}
```
In Python use `itertools.product(range(256), repeat=2)` and assert the count.
## Run
`cargo test --release every_`
Passing looks like: exit 0 and `test result: ok. 2 passed`. The full pair loop takes a few seconds in release mode. Failure: the first failing input is in the panic message.
## As a contract check
```json
{"id": "many-inputs-u16-add", "claim": "checked_add on u16 matches the exact sum for every pair of u16 values", "kind": "general", "rung": 1, "cmd": "cargo test --release every_", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- It proves the claim only on that domain. A function on `u64` tested over `u16` is a sample of it, so call it rung 2 then.
- The reference answer can itself be wrong; derive it independently.
- Assert the loop count (as above) so that an edited range or an early `continue` cannot shrink the domain silently.
- If the domain is too large to finish, do not cut it down and still call it exhaustive.
+60
View File
@@ -0,0 +1,60 @@
---
id: flux-refinement-types
title: Flux refinement types for Rust
answers: Can my Rust signatures carry value constraints (positive, in range, indexes in bounds) that the compiler checks?
rung: 1
section: prove
languages: rust
kinds: general
cost: medium
detect: command -v cargo-flux
ran_here: no
verified: docs
---
## Use when
- The properties are small value constraints on arguments and results: an index below a length, a non-zero divisor, a sum within a bound.
- You want checking close to type checking, with little proof effort, and mostly automatic inference of loop invariants.
## Do not use when
- The property is relational or complex (sorted, permutation, money laws). Use `verus`, `lean4-proofs` or `kani`.
- You cannot use Flux's pinned nightly toolchain.
## Set up
From the Flux book ("Installing and Running Flux"): the only way to use Flux is to build it from source. Requirements: `rustup`, `liquid-fixpoint` (nightly binaries on its GitHub releases) and `z3` 4.15 or later, both on PATH. Then either `curl -fsSL https://raw.githubusercontent.com/flux-rs/flux/main/install.sh | bash`, or:
git clone https://github.com/flux-rs/flux && cd flux
cargo xtask install # installs `flux` and `cargo-flux`, and the sysroot in ~/.flux/sysroot
The repository's `rust-toolchain.toml` pins the nightly. To use it in a Cargo package, add to `Cargo.toml`:
[package.metadata.flux]
enabled = true
[dependencies]
flux-rs = { git = "https://github.com/flux-rs/flux.git" }
Not installed here, so the example was not run.
## Minimal example
```rust
use flux_rs::attrs::*;
#[spec(fn(x: i32{x > 0}) -> i32{v: v > x})]
fn bump(x: i32) -> i32 { x + 1 }
```
On a single file run with the standalone `flux` binary, write the attribute as `#[flux::spec(...)]` instead. Overflow of `x + 1` is checked only if you switch on `check-overflow` in the `[package.metadata.flux]` section (default `none`; see the book's "Checking Overflows"); this example passes without it.
## Run
`cargo flux` (a package), or `flux --crate-type=lib path/to/file.rs` (one file; it accepts the same flags as `rustc`).
Passing looks like: no errors reported. Failure: the book's example shows `error[FLUX]: postcondition might not hold` with the source location (a wrong body such as `x - 1`). The book does not state the exit status; the driver is a rustc wrapper and should exit non-zero on errors, but confirm with a deliberately wrong body.
## As a contract check
```json
{"id": "prove-bump-flux", "claim": "bump returns a value greater than its positive argument", "kind": "general", "rung": 1, "cmd": "cargo flux", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- Only the refinements stated in signatures; unannotated code gets default (weak) types. `#[flux_rs::trusted]` (`#[flux::trusted]` on a single file) skips checking.
- Annotations are written by you; a trivially true refinement verifies trivially.
- Not run here; commands and messages come from the Flux book. Check the check: change the body to `x - 1` and confirm `cargo flux` fails.
+51
View File
@@ -0,0 +1,51 @@
---
id: frama-c-wp
title: Frama-C WP for C with ACSL contracts
answers: Does this C function meet its contract and avoid undefined behaviour for all inputs?
rung: 1
section: prove
languages: c
kinds: general, parsing
cost: high
detect: frama-c -version
ran_here: no
verified: docs
---
## Use when
- Small, critical C functions (parsers, buffers, arithmetic, drivers) need a proof that holds for all inputs, with no unwinding bounds.
- You can write ACSL contracts (`requires`, `ensures`, `assigns`, loop invariants) in comments.
## Do not use when
- You only need a bounded check with minimal effort. Use `cbmc`.
- The code relies on heavy pointer aliasing, floating point, or concurrency without a plan.
## Set up
Install with opam (the Frama-C site's recipe: `opam init --compiler 4.14.1`, `eval $(opam env)`, `opam install frama-c`). Per the WP manual (written for Frama-C 33.0 "Arsenic", July 2026), the WP plug-in ships with Frama-C, needs the Why3 platform and at least one external prover, and opam installs Alt-Ergo and Why3 automatically; WP finds provers on `$PATH` and in the Why3 configuration. Not installed here, so nothing below was run.
## Minimal example
`abs.c`:
```c
#include <limits.h>
/*@ requires x > INT_MIN;
assigns \nothing;
ensures \result >= 0 && (\result == x || \result == -x);
*/
int my_abs(int x) { return x < 0 ? -x : x; }
```
## Run
`frama-c -wp -wp-rte -wp-timeout 20 abs.c`
Passing looks like: a line `[wp] Proved goals: N / N` (the manual shows `[wp] Proved goals: 4 / 4`; a run with a failure shows `Proved goals: 6 / 7` and an `Unknown:` count). `-wp-rte` adds the no-undefined-behaviour obligations (overflow, bounds) and `-wp-timeout` is the per-goal prover timeout in seconds (default 2). The manual does not document an exit status for unproved goals, and Frama-C is commonly seen exiting 0 with unproved goals, so the contract tests the text. Real output may pad the numbers with extra spaces, so the pattern allows them:
`frama-c ... | grep -E 'Proved goals: +([0-9]+) / \1$'` (the backreference is GNU grep).
## As a contract check
```json
{"id": "prove-abs-framac", "claim": "my_abs meets its contract and has no runtime errors when x > INT_MIN", "kind": "general", "rung": 1, "cmd": "bash -c \"frama-c -wp -wp-rte -wp-timeout 20 abs.c | tee /dev/stderr | grep -E 'Proved goals: +([0-9]+) / \\\\1$'\"", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- Only the written contract, under a memory model that assumes no aliasing the contract does not allow. `assigns` clauses must be right.
- All goals proved means none were skipped by `-wp-timeout`; a timeout counts as unproved, which the `N / N` test catches.
- Not run here; the output format is from the WP manual's examples. Confirm the exit status and spacing of the `Proved goals` line on your version, and check the check by weakening the `ensures` so a goal fails.
@@ -0,0 +1,66 @@
---
id: illegal-states-unrepresentable
title: Making illegal states unrepresentable with types, checked by a compile-fail test
answers: Is it impossible, not just unlikely, for callers to build an invalid value or call an operation in the wrong state?
rung: 1
section: prove
languages: rust, typescript
kinds: general, state-machine, money
cost: low
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- A value has a validity rule (a percentage 0 to 100, a non-empty list, a validated email) that is currently checked in many places.
- An object has phases (closed then open, draft then posted) and calls are only legal in some of them.
- You want the compiler to reject misuse, and a test that proves it does.
## Do not use when
- The rule depends on runtime data the type cannot hold (a balance across accounts). Use a runtime check plus `kani` or tests.
- A quick enum or `Option` already forces the case. Do not add types for show.
## Set up
Rust: nothing extra. Make fields private and expose a constructor that validates (parse, don't validate: return `Option`/`Result` once at the edge, then pass the type everywhere). Use enums and exhaustive `match` with no `_` arm; use the typestate pattern with a type parameter for phases. For compile-fail tests use `compile_fail` doctests, or the `trybuild` crate (add under `[dev-dependencies]`) to compare compiler output.
TypeScript: see `typescript-type-level`.
## Minimal example
```rust
pub struct Percent(u8); // private field
impl Percent {
pub fn new(v: u8) -> Option<Percent> { (v <= 100).then_some(Percent(v)) }
pub fn get(self) -> u8 { self.0 }
}
pub struct Conn<S>(std::marker::PhantomData<S>);
pub struct Open; pub struct Closed;
impl Conn<Closed> { pub fn open(self) -> Conn<Open> { Conn(std::marker::PhantomData) } }
impl Conn<Open> { pub fn send(&self, _b: &[u8]) {} }
/// ```compile_fail
/// use ise::Percent;
/// let p = Percent(250); // private field: must not compile
/// ```
///
/// ```compile_fail
/// use ise::Conn;
/// Conn::new().send(b"x"); // a closed connection has no `send`
/// ```
pub struct CompileFailTests;
```
(Add `Conn::new() -> Conn<Closed>`.) The crate is named `ise` in the doctests.
## Run
`cargo test --doc`
Passing looks like: exit 0 and `test src/lib.rs - CompileFailTests (line N) - compile fail ... ok`. Failure: a `compile_fail` test whose code does compile shows `Test compiled successfully, but it's marked 'compile_fail'.` and exits 101. With `trybuild`, `cargo test` compares the real compiler message with a stored `.stderr` file.
## As a contract check
```json
{"id": "prove-percent-unrepresentable", "claim": "A Percent above 100 and a send on a closed connection cannot be written: both fail to compile", "kind": "general", "rung": 1, "cmd": "cargo test --doc", "expect": {"exit": 0, "stdout_contains": "compile fail"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- A `compile_fail` test passes on any compile error, including a typo. Observed: adding an error code like `compile_fail,E0451` is not enforced on stable (a wrong code still passed). Use `trybuild`, which pins the message, for tests that must fail for the right reason.
- Rules the type cannot express remain open; construction inside the defining module bypasses private-field checks. Keep the smart constructor the only way in, and review `unsafe` and `Default`/`Deserialize` impls that could build invalid values.
+54
View File
@@ -0,0 +1,54 @@
---
id: isabelle
title: Isabelle/HOL proofs with Sledgehammer
answers: Is this property proved by machine, with automatic proof search to help?
rung: 1
section: prove
languages: any
kinds: general, state-machine
cost: high
detect: isabelle version
ran_here: no
verified: docs
---
## Use when
- Your team already uses Isabelle, or you build on the Archive of Formal Proofs.
- You want strong automation: Sledgehammer calls external provers and returns a proof line to paste in.
- The claim is about algorithms or specifications over lists, sets and numbers.
## Do not use when
- You have no existing Isabelle investment. `lean4-proofs` has better command-line tooling for agents.
- A bounded check is enough (`kani`, `cbmc`).
## Set up
Download the bundle for your platform from isabelle.in.tum.de (current release: Isabelle2026, October 2026; it includes its own Java, ML system and provers). On Linux, unpack it and put its `bin/` on PATH (the install page shows `Isabelle2026/bin/isabelle`). Not installed here, so the example was not run. A session is a directory with a `ROOT` file:
```
session Demo = HOL +
theories Demo
```
## Minimal example
`Demo.thy`:
```isabelle
theory Demo imports Main begin
theorem rev_rev: "rev (rev xs) = xs"
by simp
end
```
When a goal resists, write `sledgehammer` in the interactive editor, take the proof it prints (`by (metis ...)`), and replace the call. Do not leave `sledgehammer` or `sorry` in committed files.
## Run
`isabelle build -D .` (`-D DIR` includes a session directory and selects its sessions; `-d DIR` only makes sessions known; `-j N` runs N jobs in parallel; `-v` is verbose).
Passing looks like: exit 0, with the build log reporting the session `Demo` as finished (exact wording is not in the system manual). The manual says the overall return code is the status of the set of selected sessions, so a session that fails to build gives a non-zero exit (conventionally 1) and the log names the failing theory and step. The manuals read here do not say whether a plain `isabelle build` rejects `sorry` or `oops` (or what the `quick_and_dirty` option changes), so do not rely on the build alone: grep the sources for both, as in the contract below.
## As a contract check
```json
{"id": "prove-demo-isabelle", "claim": "The Isabelle session builds and contains no sorry", "kind": "general", "rung": 1, "cmd": "bash -c 'isabelle build -D . && ! grep -R -E \"\\\\b(sorry|oops)\\\\b\" --include=*.thy .'", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"}
```
## What a pass does not prove
- Only the stated theorem about the Isabelle definitions.
- Not run here. `isabelle build -D`, the `ROOT` syntax and the exit-status rule come from the Isabelle system manual; whether the build itself rejects `sorry` is unconfirmed (see Run).
- The grep also flags the word inside comments, which is the safe direction. Check the check: put a `sorry` in a scratch lemma and confirm the contract fails.
+56
View File
@@ -0,0 +1,56 @@
---
id: kani-proof-hygiene
title: Keeping Kani proofs honest: covers, bounds, canary, harness list, time caps
answers: Are my Kani proofs vacuous, silently skipped, or cut off, so that "verified" means less than it says?
rung: 1
section: prove
languages: rust
kinds: general, money
cost: medium
detect: cargo kani --version
ran_here: yes
verified: ran
---
## Use when
- You have Kani harnesses and a CI check that says "all verified".
- Harnesses use `kani::assume`, `unwind`, or restricted inputs, where an over-tight bound makes a proof pass for no reason.
- The suite is slow, or you split it into fast and slow sets.
## Do not use when
- There are no Kani harnesses yet. See `kani`.
## Set up
A Rust and Lean 4 project does all of this in `justfile` with a shell wrapper around `cargo kani`. Copy the ideas, not its domain code.
## Minimal example
1. Cover every interesting case. `kani::cover!(cond, "message")` fails the check if `cond` is unreachable under the harness's assumptions:
```rust
#[kani::proof]
fn vacuous() {
let x: u8 = kani::any();
kani::assume(x > 10 && x < 5); // impossible: nothing is checked
assert!(x == 99);
kani::cover!(x > 0, "never reached");
}
```
2. A canary for a known tool bug: keep a harness marked `#[kani::should_panic]` that exercises the buggy construct; when a Kani upgrade fixes the bug it starts failing and tells you to drop the workaround.
3. A harness list check: enumerate harnesses (`grep` for `#[kani::proof]`), then fail on duplicate names and on a name in the slow list that no harness has.
4. Time caps: `cargo kani -j "$(nproc)" -Z unstable-options --harness-timeout 900s`, and wrap the run in `timeout 1800`.
## Run
`cargo kani --output-format terse | tee kani.log` then
`grep -E '\*\* [0-9]+ of [0-9]+ cover properties satisfied' kani.log | awk '$2 != $4 {bad=1} END {exit bad}'`
Passing looks like: for the vacuous harness above, Kani itself prints `** 0 of 1 cover properties satisfied (1 unreachable)` yet `VERIFICATION:- SUCCESSFUL` and exits 0 (observed, 0.68.0). The awk line then exits 1; that is how the check catches it. Also require the line `Complete - N successfully verified harnesses, 0 failures, N total` with N equal to the number of harnesses you listed. A timed-out harness is reported, not silently passed; a missing line means the run was cut off.
## As a contract check
```json
{"id": "prove-kani-honest", "claim": "All Kani harnesses verify, the expected number ran, and every cover! is satisfiable", "kind": "general", "rung": 1, "cmd": "bash scripts/kani-check.sh", "expect": {"exit": 0, "stdout_contains": "successfully verified harnesses"}, "tier": "deep", "timeout_s": 3600}
```
`scripts/kani-check.sh` runs steps 3 and 4 and the awk test above.
## What a pass does not prove
- `cover!` shows each marked case is reachable, not that your marks cover all the cases that matter. Add one for each branch a reviewer would ask about.
- A harness proved on a smaller representation (e.g. `i64`) says nothing about the real type; see `proof-bridging`.
- The canary only watches the one bug you thought of. `--harness-timeout` needs `-Z unstable-options` and may change; check `cargo kani --help` after upgrades.
+67
View File
@@ -0,0 +1,67 @@
---
id: kani
title: Kani bounded model checking for Rust
answers: Can this Rust function panic, overflow or break an assertion for any input within a bound?
rung: 1
section: prove
languages: rust
kinds: general, money, parsing
cost: medium
detect: cargo kani --version
ran_here: yes
verified: ran
---
## Use when
- A small, mostly pure function (money arithmetic, index maths, bounded parsers, state transitions) must hold for all inputs, not a sample.
- You want "cannot panic or overflow" for every value of the input types, such as every `u32`.
- A property test would be the next best thing but you want a proof within the bound.
## Do not use when
- The claim needs unbounded sizes or heavy loops over big data; use `lean4-proofs` or `verus`.
- The function does I/O, threads or unsupported FFI.
- You have not read `kani-proof-hygiene`. A Kani pass can be vacuous.
## Set up
`cargo install --locked kani-verifier && cargo kani setup` (once; downloads a nightly toolchain and CBMC). Put harnesses under `#[cfg(kani)]` so normal builds ignore them.
## Minimal example
`src/lib.rs`:
```rust
pub fn add_cents(a: u32, b: u32) -> Option<u32> { a.checked_add(b) }
#[cfg(kani)]
mod proofs {
use super::*;
#[kani::proof]
fn add_cents_is_exact_or_none() {
let a: u32 = kani::any();
let b: u32 = kani::any();
let wide = a as u64 + b as u64;
match add_cents(a, b) {
Some(s) => assert_eq!(s as u64, wide),
None => assert!(wide > u32::MAX as u64),
}
kani::cover!(add_cents(a, b).is_none(), "overflow case reachable");
kani::cover!(add_cents(a, b).is_some(), "ok case reachable");
}
}
```
Loops need `#[kani::unwind(N)]`; restrict inputs with `kani::assume(...)`, sparingly.
## Run
`cargo kani --output-format terse`
Passing looks like: exit 0, `2 of 2 cover properties satisfied`, `VERIFICATION:- SUCCESSFUL` and `Complete - 1 successfully verified harnesses, 0 failures, 1 total.` (Kani 0.68.0). Failure: `VERIFICATION:- FAILED` with the failing check and a nonzero exit. To select one harness use `--harness <fully::qualified::name> --exact`; an unqualified name with `--exact` is refused.
## As a contract check
```json
{"id": "prove-add-cents-kani", "claim": "add_cents never wraps: Some(sum) is exact and None only when the sum exceeds u32::MAX", "kind": "money", "rung": 1, "cmd": "cargo kani --output-format terse", "expect": {"exit": 0, "stdout_contains": "successfully verified harnesses, 0 failures"}, "tier": "deep", "timeout_s": 1800}
```
## What a pass does not prove
- Only inputs within the harness: `unwind` bounds, array lengths, `kani::assume`. Beyond them nothing is claimed.
- An over-tight `assume` or unreachable code makes the pass vacuous. See `kani-proof-hygiene`.
- Harness code can be wrong. Confirm each harness can fail: flip an assertion and see `FAILED`.
- Its model of the standard library has gaps (e.g. known bugs on bulk copies of symbolic length); a pass is not a statement about the real binary.
+72
View File
@@ -0,0 +1,72 @@
---
id: klee
title: KLEE symbolic execution of C programs
answers: Which inputs make this C program crash, overflow or break an assert, found by exploring its paths?
rung: 1
section: prove
languages: c, c++
kinds: general, parsing
cost: high
detect: klee --version
ran_here: no
verified: docs
---
## Use when
- C programs or functions with many branches where you want generated inputs that reach each path and trigger errors.
- You want concrete test cases for each path as a by-product.
## Do not use when
- You want a simpler tool: `cbmc` is easier to run and gives a proof within a bound.
- The code does a lot of I/O, threads, floating point or deep loops over symbolic sizes.
## Set up
Easiest is the Docker image (from the KLEE Docker page; 3.0 is the current tag there):
docker pull klee/klee:3.0
docker run --rm -ti --ulimit='stack=-1:-1' klee/klee:3.0 # then `klee --version` inside
The `--ulimit` avoids stack overflows inside KLEE. Building from source needs LLVM (the site recommends LLVM 18), clang and an SMT solver; see klee-se.org. Programs include `klee/klee.h`; compile with `-I` pointing at KLEE's `include` directory. Not installed here, so the example was not run.
## Minimal example
`a.c`:
```c
#include <klee/klee.h>
int clamp(int lo, int hi, int x) { return x < lo ? lo : (x > hi ? hi : x); }
int main(void) {
int lo, hi, x;
klee_make_symbolic(&lo, sizeof lo, "lo");
klee_make_symbolic(&hi, sizeof hi, "hi");
klee_make_symbolic(&x, sizeof x, "x");
klee_assume(lo <= hi);
int r = clamp(lo, hi, x);
klee_assert(lo <= r && r <= hi);
return 0;
}
```
## Run
```
clang -I /path/to/klee/include -emit-llvm -c -g -O0 -Xclang -disable-O0-optnone a.c -o a.bc
klee a.bc
```
The tutorial says `-O0 -Xclang -disable-O0-optnone` is preferred over plain `-O0` on LLVM newer than 5.0. Output goes to `klee-out-N/` (lowest unused N) with a `klee-last` symlink to the newest.
Passing looks like (from the tutorial):
KLEE: done: total instructions = 33
KLEE: done: completed paths = 3
KLEE: done: partially completed paths = 0
KLEE: done: generated tests = 3
with no `KLEE: ERROR` lines and no `test*.err` files in `klee-last/`. Failure: `KLEE: ERROR: ... ASSERTION FAIL` and a file `test000001.assert.err` next to the `.ktest` that reproduces it (the file docs give the pattern `test<N>.<error-type>.err`; `ktest-tool` prints a `.ktest`). The KLEE docs fetched do not state the exit status; KLEE is generally reported to exit 0 even when it found errors, so test for the `.err` files rather than the exit code, and confirm that on your version.
## As a contract check
```json
{"id": "prove-clamp-klee", "claim": "KLEE finds no assertion failure or memory error in clamp", "kind": "general", "rung": 1, "cmd": "bash -c 'klee a.bc && ! ls klee-last/*.err 2>/dev/null'", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only completes if exploration ends before limits (`--max-time`, `--max-memory`); if it stops early the pass is partial. Look for "partially completed paths = 0".
- Symbolic sizes and the modelled environment (`--posix-runtime`, `--libc=uclibc`) bound what is covered.
- Commands and output come from the KLEE tutorial and docs, not from a run here.
+53
View File
@@ -0,0 +1,53 @@
---
id: lean-axiom-audit
title: Making a Lean proof trustworthy: no sorry, only the standard axioms
answers: Does my Lean proof really prove the theorem, or does it rely on sorry or an extra axiom?
rung: 1
section: prove
languages: any
kinds: general
cost: low
detect: lake --version
ran_here: yes
verified: ran
---
## Use when
- A Lean project is the evidence for a claim and a green `lake build` must mean the proof is complete.
- An agent wrote or edited proofs; `sorry`, `axiom` and `native_decide` are easy to slip in.
- You want a CI step that fails on anything but the standard axioms.
## Do not use when
- There is no Lean proof. See `lean4-proofs`.
## Set up
List the theorems that carry the claim in one file, `Audit.lean`, so the list is reviewed in one place:
```lean
import Demo
#print axioms clamp_le
#print axioms add_zero'
```
## Minimal example
```
lake build --wfail
lake env lean Audit.lean | tee audit.txt
! grep -v -E "depends on axioms: \[(propext|Quot.sound|Classical.choice)(, (propext|Quot.sound|Classical.choice))*\]$|does not depend on any axioms" audit.txt
```
The third line fails if any output line is not one of the allowed forms. The three allowed axioms are `propext`, `Classical.choice`, `Quot.sound`. This is the filter a Rust and Lean 4 project uses in its `prove` recipe.
## Run
Put the three lines in a script, `audit-lean.sh`, with `set -euo pipefail`.
Passing looks like: exit 0 and output such as `'clamp_le' depends on axioms: [propext, Classical.choice, Quot.sound]`. Failure shows `depends on axioms: [sorryAx]` for a theorem that uses `sorry` (observed: `lake build` itself exited 0 and only warned; `--wfail` made it exit 1). `native_decide` shows `Lean.ofReduceBool`, and a custom `axiom` appears by name; both fail the filter.
## As a contract check
```json
{"id": "prove-lean-axioms", "claim": "The Lean theorems depend on no sorry and only the three standard axioms", "kind": "general", "rung": 1, "cmd": "bash audit-lean.sh", "expect": {"exit": 0, "stdout_contains": "depends on axioms"}, "tier": "deep", "timeout_s": 1800}
```
## What a pass does not prove
- That the theorem statements say what you meant. Axiom-clean proofs of the wrong statement pass.
- Only theorems listed in `Audit.lean` are audited; a new theorem not listed is not. Compare the list against the project's theorems in review, or generate it.
- A trailing `sorry` in a file `Audit.lean` does not import is not seen; build the whole library.
- If `Audit.lean` prints nothing (a typo in a name raises an error, which is good) make sure the script checks that the output is non-empty.
+56
View File
@@ -0,0 +1,56 @@
---
id: lean4-proofs
title: Proving properties in Lean 4 with a lake project and lake build
answers: Is this property true for all inputs, with a machine-checked proof rather than tests?
rung: 1
section: prove
languages: any
kinds: general, money, state-machine
cost: high
detect: lake --version
ran_here: yes
verified: ran
---
## Use when
- The claim is a law over all inputs of a function you can write in Lean (or a model of your code): sums are conserved, a rounding step is within half a unit, an operation is its own inverse.
- Tests and Kani only cover bounded cases and you need the law at any size.
- You can state the law as a `theorem` and let `lake build` be the judge.
## Do not use when
- The code under test is Rust or C and you need the proof about that code. Use `aeneas-rust-to-lean`, `kani` or `verus`.
- The property is a quick bounded check. `kani` or `exhaustive-small-domain` cost far less.
## Set up
```
lake new demo # then in lakefile.toml set defaultTargets = ["Demo"] and delete the lean_exe stanza and Main.lean
cd demo
```
`lean-toolchain` pins the Lean version; commit it and `lake-manifest.json`. Mathlib is optional: add `[[require]] name = "mathlib" scope = "leanprover-community"` to `lakefile.toml` only when you need it (a first build downloads a large cache; run `lake exe cache get`). Without Mathlib, the tactics `simp`, `omega` and `decide` already handle most arithmetic.
## Minimal example
`Demo/Basic.lean`:
```lean
def clamp (lo hi x : Nat) : Nat := if x < lo then lo else if hi < x then hi else x
theorem clamp_le (lo hi x : Nat) (h : lo ≤ hi) :
lo ≤ clamp lo hi x ∧ clamp lo hi x ≤ hi := by
unfold clamp
split <;> (try split) <;> omega
```
The agent loop: edit, run `lake build`, read the error (it shows the unsolved goal), adjust. Put `sorry` in one place at a time to see the goal, then replace it. `lake env lean Demo/Basic.lean` checks one file faster.
## Run
`lake build --wfail`
Passing looks like: exit 0 with lines like `✔ Built Demo.Basic`. A wrong proof gives `error:` with the goal and exit 1 (observed). Plain `lake build` exits 0 even when a proof contains `sorry` (it only warns), so use `--wfail` and the audit in `lean-axiom-audit`.
## As a contract check
```json
{"id": "prove-clamp-lean", "claim": "clamp stays within [lo, hi] for all Nat inputs, proved in Lean 4", "kind": "general", "rung": 1, "cmd": "lake build --wfail", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800}
```
## What a pass does not prove
- It proves the theorem about the Lean definition. If the definition is not the real code, add a bridge (`proof-bridging`, `aeneas-rust-to-lean`).
- A theorem that is easier than the claim (wrong statement, hypotheses that cannot hold) builds fine. Read the statement, and prove a non-trivial instance with `example`.
- `sorry` and extra axioms pass the build; see `lean-axiom-audit`.
+57
View File
@@ -0,0 +1,57 @@
---
id: liquid-haskell
title: LiquidHaskell refinement types for Haskell
answers: Do my Haskell functions respect value constraints (non-zero divisors, in-range indexes, length-preserving) for all inputs?
rung: 1
section: prove
languages: haskell
kinds: general
cost: medium
detect: ghc --version
ran_here: no
verified: docs
---
## Use when
- Haskell code where totality and value constraints matter: safe division, bounds, sorted or length-indexed lists.
- You want checks written as comments next to the types, so the code still compiles with plain GHC.
## Do not use when
- The code is not Haskell. See the entries for your language.
- The GHC version you need is newer than the LiquidHaskell release supports: only one GHC version is supported at a time (currently 9.14.1).
## Set up
From the LiquidHaskell README: install Z3 4.15.1 or newer on PATH, then in the project directory
cabal install --lib liquidhaskell liquid-prelude liquid-vector --package-env . --force-reinstalls
(`--package-env .` writes a `.ghc.environment*` file so only GHC runs started from this directory see the plugin). Put `{-# OPTIONS_GHC -fplugin=LiquidHaskell #-}` at the top of each checked module. LiquidHaskell supports exactly one GHC version at a time: the latest release (v0.9.14.1, May 2026) builds with GHC 9.14.1, and the previous release (v0.9.12.2) is the last one for GHC 9.12.2. Use the LiquidHaskell release that matches your GHC. Not installed here (no Haskell toolchain), so the example was not run.
## Minimal example
```haskell
{-# OPTIONS_GHC -fplugin=LiquidHaskell #-}
module Safe where
{-@ safeDiv :: Int -> {v:Int | v /= 0} -> Int @-}
safeDiv :: Int -> Int -> Int
safeDiv x y = x `div` y
ok :: Int
ok = safeDiv 10 2
-- bad = safeDiv 10 0 -- uncomment: rejected at compile time
```
## Run
`ghc -fplugin=LiquidHaskell Safe.hs` (the README's command), or in a Cabal project add `-fplugin=LiquidHaskell` to `ghc-options` with `liquidhaskell` and `liquid-prelude` in `build-depends` and run `cabal build`. GHC does not rerun the plugin on modules it considers up to date, so after a first pass force a rebuild (`-fforce-recomp`, or touch the file) before trusting a pass.
Passing looks like: the compile succeeds. Failure: a refinement type error from the plugin at the offending call, and a failed compile (non-zero exit as for any GHC error). The exact error wording (older versions printed `Liquid Type Mismatch`; the older `liquid Safe.hs` printed `LIQUID: SAFE`) was not confirmed here.
## As a contract check
```json
{"id": "prove-safediv-liquid", "claim": "safeDiv is never called with a zero divisor", "kind": "general", "rung": 1, "cmd": "ghc -fforce-recomp -fplugin=LiquidHaskell Safe.hs", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only annotated specs; `{-@ lazy @-}`, `assume` and `{-@ LIQUID "--no-termination" @-}` weaken or skip checking. Grep for them.
- Modules without the plugin line are not checked at all; make sure the plugin line is on every module that matters.
- Not run here; commands come from the LiquidHaskell README. Check the check: uncomment `bad = safeDiv 10 0` and confirm the compile fails.
+57
View File
@@ -0,0 +1,57 @@
---
id: proof-bridging
title: Bridging a proof on a simplified type to the real type with a differential test
answers: My proof was done on a simpler representation (like i64); does the real code (like Decimal) behave the same?
rung: 2
section: prove
languages: any
kinds: money, general
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- A proof tool handles only a simple model (Kani on `i64`, Lean on `Nat`, Dafny on `int`) and the production code uses another type (`Decimal`, `BigInt`, floating point, a struct).
- You want to say the proof carries over to the real code, with evidence you can run.
## Do not use when
- You can prove the real type directly (`aeneas-rust-to-lean`, `verus`). Do that instead.
- The two types differ in the property you proved (rounding, overflow, ordering): then the bridge must show where they agree, and the claim shrinks to that region.
## Set up
Write the model function and the real function with the same shape. In the test, generate inputs, run both, convert the model result to the real type, and assert equal. Include an independent exact reference (a big-integer or rational one) as a third voice when the model is lossy. Use `proptest` in Rust or `hypothesis` in Python for random inputs, plus a fixed list of edge cases (zero, minimum, maximum, ties, negatives).
## Minimal example
```rust
fn halve_model(x: i64) -> i64 { x / 2 } // what the proof covers
fn halve_real(x: i128) -> i128 { x / 2 } // what production runs (wider type)
#[test]
fn bridge_agrees() {
let mut s: u64 = 0x9E37_79B9_7F4A_7C15; // fixed seed: reproducible
for _ in 0..100_000 {
s ^= s << 13; s ^= s >> 7; s ^= s << 17; // xorshift
let x = s as i64;
assert_eq!(halve_model(x) as i128, halve_real(x as i128));
}
}
```
State in the test's doc comment which proof it carries (`kani proof halve_is_floor`), over which inputs, and what is assumed equal.
## Run
`cargo test bridge`
Passing looks like: exit 0 and `test tests::bridge_agrees ... ok`. Failure: the first disagreeing input in the panic message.
## As a contract check
```json
{"id": "prove-bridge-i64-to-wide", "claim": "The real halve agrees with the proved i64 model on 100000 seeded inputs and the edge cases", "kind": "money", "rung": 2, "cmd": "cargo test bridge", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- It samples, so the bridge is rung 2, and the proved claim for the real type is only as strong as the bridge. Say so in the contract claim.
- The bridge must show: same results where both are defined; both refuse (error or `None`) on the same inputs; behaviour at the model's bounds; and every wrapper between the proof and the real call. A wrapper that is not in the bridge is unproved.
- Compare against an independent exact reference where the model truncates (for example integer division drops fractions that `Decimal` keeps), or you test two things that share a flaw.
- Generators that rarely hit edges miss them; list ties, zero, min and max explicitly.
+48
View File
@@ -0,0 +1,48 @@
---
id: prusti
title: Prusti verification for Rust
answers: Does this Rust function satisfy its pre- and postconditions for all inputs?
rung: 1
section: prove
languages: rust
kinds: general
cost: high
detect: cargo prusti --version
ran_here: no
verified: docs
---
## Use when
- You are already on a Rust toolchain Prusti supports and want Viper-based proofs with contract attributes.
- The code is safe Rust with moderate complexity, and unbounded proofs are needed.
## Do not use when
- Status, checked on the repository: Prusti is not abandoned. It moved from `viperproject/prusti-dev` to `prusti/prusti`, has commits almost daily in November 2026 and publishes nightly pre-release builds. But its last non-pre-release was in February 2024 (`v-2024-02-28-1817`), and the user guide warns that some syntax it describes exists only in the "LatestDev" build. Expect the stable binary to be old; on current Rust prefer `verus`, `creusot` or `kani`, and check which Rust toolchain your Prusti build pins (the repository's `rust-toolchain` pins a nightly, `nightly-2026-08-15` at the time of writing).
- Your Rust is recent and you want the old stable build: it supports only the nightly it was built against, so it often cannot compile modern crates.
## Set up
Download a precompiled build from github.com/prusti/prusti/releases (Ubuntu, Windows, macOS; "Pre-release" builds are the current ones), or use the VS Code extension "Prusti Assistant", or build from source (`rustup`, `./x.py setup`, `./x.py build --release`). Every option provides `prusti-rustc` and `cargo-prusti`. Add the contracts crate to the project with `cargo add prusti-contracts` and put `use prusti_contracts::*;` in the file. Not installed here, so the example was not run.
## Minimal example
```rust
use prusti_contracts::*;
#[requires(a >= 0 && a < i32::MAX)]
#[ensures(result == a + 1)]
fn inc(a: i32) -> i32 { a + 1 }
```
## Run
`cargo prusti` from the crate root (Prusti on a single file: `prusti-rustc --edition=2018 path/to/file.rs`). By default Prusti also verifies absence of integer overflow and of reachable `panic!`/`unreachable!`; a `Prusti.toml` can switch overflow checks off.
Passing looks like: the guide says "Prusti should report that verification succeeded" (exact message not quoted there). Failure is reported like a compiler error with the prefix `Prusti: verification error`, for example `error: [Prusti: verification error] statement might panic`. The guide does not state the exit status; as a rustc wrapper it should exit non-zero on errors, but confirm with a wrong postcondition.
## As a contract check
```json
{"id": "prove-inc-prusti", "claim": "inc returns a + 1 for every a below i32::MAX", "kind": "general", "rung": 1, "cmd": "cargo prusti", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only annotated functions; `#[trusted]` ones are assumed. Grep for it.
- Quantifiers and loops need invariants that the tool may fail to use, giving false alarms rather than false passes.
- Not run here; commands come from the Prusti README and user guide. The guide itself notes some syntax needs the LatestDev build, so the snippet may differ by version.
+56
View File
@@ -0,0 +1,56 @@
---
id: rocq
title: Rocq (formerly Coq) proofs, and when to pick it over Lean
answers: Is this property proved by machine, in a prover with a large existing library of verified programs?
rung: 1
section: prove
languages: any
kinds: general, state-machine
cost: high
detect: rocq --version
ran_here: no
verified: docs
---
## Use when
- You depend on an existing Rocq development (CompCert, Iris, VST, Fiat Crypto, MathComp) or the team already knows it.
- You need extraction of verified code to OCaml or Haskell.
- The proof is about C via VST, or concurrent separation logic via Iris.
## Do not use when
- You are starting fresh and have no reason to prefer it. Prefer `lean4-proofs`: faster builds, better agent tooling, and `lake build` as one oracle.
- A bounded check will do (`kani`, `cbmc`).
## Set up
Install through opam (version 2.1 or newer). Rocq packages are not in the default opam repository, so add theirs first:
opam repo add rocq-released https://rocq-prover.org/opam/released
opam install rocq-prover
rocq -v
The package is `rocq-prover` (the old name was `coq`); the binary is `rocq`, and the batch compiler is `rocq compile` (alias `rocq c`). The current reference manual documents only `rocq`-prefixed commands and does not mention `coqc`, so on a modern install use `rocq compile`; an older `coq` install has `coqc`. Not installed here, so nothing was run.
For a Dune build (the manual calls Dune support experimental), `dune-project` has a `(lang dune 3.x)` line and `(using rocq 0.14)` (Dune docs, Dune 3.25; the Rocq language version is not the Rocq version), and a `dune` file has `(rocq.theory (name Demo))`. Without Dune: `rocq makefile -f _CoqProject -o CoqMakefile`, then `make -f CoqMakefile`.
## Minimal example
`Demo.v`:
```coq
Theorem add_zero_r : forall n : nat, n + 0 = n.
Proof. intros n. induction n; simpl; auto. Qed.
Print Assumptions add_zero_r.
```
## Run
`dune build` (or `rocq compile Demo.v` for one file; name the logical path with `-Q . Demo` when needed; the file name must be a valid identifier, so `to-to.v` fails).
Passing looks like: exit 0 (the manual does not document `rocq compile` exit codes; a Rocq error such as an unsolved goal fails the compile and Dune reports it). `Print Assumptions add_zero_r.` prints `Closed under the global context` when no axioms are used; any listed axiom, or `Admitted.` in the source, means the proof is incomplete. Dune normally hides the output of successful rules, so to see the `Print Assumptions` line compile the file directly with `rocq compile`, and grep the sources as well.
## As a contract check
```json
{"id": "prove-demo-rocq", "claim": "The Rocq development builds with no Admitted lemmas", "kind": "general", "rung": 1, "cmd": "bash -c 'dune build && ! grep -R -E \"Admitted|admit\\.\" --include=*.v .'", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"}
```
## What a pass does not prove
- Only the stated theorem about the Rocq definitions; the link to real code is a separate problem (`proof-bridging`).
- `Admitted` and `Axiom` pass the build; the grep and `Print Assumptions` catch them.
- Not run here. The opam commands, `rocq compile` and the Dune stanzas come from the Rocq install page, refman and Dune docs; the exit status of `rocq compile` is not documented in them.
+70
View File
@@ -0,0 +1,70 @@
---
id: spark-ada
title: SPARK (Ada) proofs with GNATprove
answers: Is this Ada code free of runtime errors and does it meet its contracts, proved?
rung: 1
section: prove
languages: ada
kinds: general
cost: medium
detect: gnatprove --version
ran_here: no
verified: docs
---
## Use when
- The project is in Ada and needs absence of runtime errors (overflow, range, index) or functional contracts proved.
- Safety standards ask for proof evidence.
## Do not use when
- The code is not Ada. Choose the entry for its language.
## Set up
Get GNATprove from Alire (`alr with gnatprove` in an Alire project, then `eval $(alr printenv)`), or install a GNAT toolchain plus GNATprove from AdaCore (see the SPARK user guide, "Installation of GNATprove"). Put `SPARK_Mode` on the code to prove (`pragma SPARK_Mode (On);` in a package spec and body, or `with SPARK_Mode` on declarations) and have a project file. Not installed here, so the example was not run.
`proj.gpr`:
project Proj is
for Source_Dirs use (".");
for Object_Dir use "obj";
end Proj;
## Minimal example
`bounds.ads`:
package Bounds with SPARK_Mode is
function Clamp (Lo, Hi, X : Integer) return Integer
with Pre => Lo <= Hi,
Post => Clamp'Result in Lo .. Hi;
end Bounds;
`bounds.adb`:
package body Bounds with SPARK_Mode is
function Clamp (Lo, Hi, X : Integer) return Integer is
begin
if X < Lo then return Lo;
elsif X > Hi then return Hi;
else return X;
end if;
end Clamp;
end Bounds;
GNATprove checks the postcondition and every runtime check in the body.
## Run
`gnatprove -P proj.gpr --level=2 --checks-as-errors=on`
`--level` runs from 0 (fast) to 4 (most powerful); level 2 is cvc5, z3 and Alt-Ergo with a 5 second timeout and counterexamples on. Raise the level or `--timeout` when a prover cannot decide.
Passing looks like: exit 0 and a summary table in which every check is "Proved". Failure shows messages such as `medium: postcondition might fail` and, only with `--checks-as-errors=on`, exits non-zero. The SPARK user guide states that GNATprove otherwise "returns with an exit status of zero, even when unproved check messages and warnings are issued". Use `--warnings=error` as well if warnings should fail the run.
## As a contract check
```json
{"id": "prove-clamp-spark", "claim": "Clamp has no runtime errors and satisfies its postcondition", "kind": "general", "rung": 1, "cmd": "gnatprove -P proj.gpr --level=2 --checks-as-errors=on", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only code in `SPARK_Mode`; code outside it (`SPARK_Mode => Off`) is assumed. Search for `pragma Assume` and `Annotate`.
- Only contracts as written.
- Without `--checks-as-errors=on` a run with unproved checks still exits 0, so a contract on the exit code alone would pass vacuously. Commands and exit-status behaviour come from the SPARK user guide, not from a run here.
+68
View File
@@ -0,0 +1,68 @@
---
id: typescript-type-level
title: TypeScript strict mode, branded types, exhaustive never checks, type tests
answers: Does the TypeScript compiler reject misuse of this API: wrong units, unhandled cases, invalid states?
rung: 1
section: prove
languages: typescript
kinds: general, money, state-machine
cost: low
detect: npx --no-install tsc --version
ran_here: yes
verified: ran
---
## Use when
- Values are easy to mix up (cents vs dollars, user id vs order id) and you want the compiler to stop it.
- A union grows over time and every `switch` over it must handle new members.
- You want type-level behaviour tested, so a refactor cannot silently weaken a type.
## Do not use when
- The rule is about runtime values only. A brand does not validate; it needs a smart constructor that does.
- You wrote `as any` or `// @ts-ignore` to get it to compile; the check is then worthless.
## Set up
`npm i -D typescript` (7.0.2 tried; `tsd` 0.33 for dedicated type tests). `tsconfig.json`: `{"compilerOptions": {"strict": true, "noEmit": true, "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "types": []}, "include": ["src"]}`.
## Minimal example
`src/brand.ts`:
```ts
declare const brand: unique symbol;
export type Cents = number & { readonly [brand]: "Cents" };
export function cents(n: number): Cents {
if (!Number.isInteger(n)) throw new RangeError("cents must be an integer");
return n as Cents;
}
export type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };
export function area(sh: Shape): number {
switch (sh.kind) {
case "circle": return 3 * sh.r * sh.r;
case "square": return sh.s * sh.s;
default: { const _x: never = sh; return _x; } // fails if a case is missing
}
}
export function pay(_c: Cents): void {}
```
`src/brand.test-d.ts` (type test, type-checked only, never run):
```ts
import { pay, cents } from "./brand";
pay(cents(5));
// @ts-expect-error a plain number is not Cents
pay(5);
```
`@ts-expect-error` itself fails the build if the next line has no error, so the test cannot rot.
## Run
`npx tsc -p .`
Passing looks like: no output, exit 0. Failure: `error TS2345: Argument of type 'number' is not assignable to parameter of type 'Cents'` (removing the `@ts-expect-error` line), or `Type '{ kind: "square"; ... }' is not assignable to type 'never'` after deleting the `square` case; exit 2 or 1 (nonzero). With `tsd`, run `npx tsd` and use `expectError` and `expectType`.
## As a contract check
```json
{"id": "prove-cents-brand", "claim": "A plain number cannot be passed where Cents is required, and area handles every Shape", "kind": "general", "rung": 1, "cmd": "npx tsc -p .", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Types are erased at runtime; data arriving from JSON or the network is unchecked unless parsed by a validator (zod and similar) that returns the branded type.
- `any`, `as` casts, `@ts-ignore` and `@ts-expect-error` placed on the wrong line defeat it. Grep for them and add `noImplicitAny` (part of `strict`).
- TypeScript's type system is intentionally unsound in places (array covariance, index access without `noUncheckedIndexedAccess`).
+64
View File
@@ -0,0 +1,64 @@
---
id: verus
title: Verus deductive verification for Rust
answers: Does this Rust code meet its requires/ensures specification for all inputs, with no size bound?
rung: 1
section: prove
languages: rust
kinds: general, state-machine
cost: high
detect: verus --version
ran_here: no
verified: docs
---
## Use when
- You write new Rust (or a core module) that needs unbounded proofs: data structures, allocators, protocols, algorithms with loops.
- You can accept writing specs and loop invariants inline in the Rust file, and ghost code.
- `kani` bounds are too small and a separate Lean model would drift from the code.
## Do not use when
- You need to verify existing unmodified Rust with traits and iterators everywhere: Verus supports a subset.
- A bounded proof is enough. `kani` takes minutes to set up.
## Set up
Download a release binary from github.com/verus-lang/verus/releases (the weekly point releases are recommended), unzip it, and run `./verus`. It tells you which `rustup` toolchain it pins (for example `rustup install 1.86.0-x86_64-unknown-linux-gnu`) and how to install it; repeat until `./verus` stops complaining. For a Cargo project the release also ships `cargo-verus`; put both on PATH, then `cargo verus new --bin my_project`, or in an existing crate `cargo add vstd` and add `[package.metadata.verus]` with `verify = true` to `Cargo.toml` (details in the guide chapter "Using Verus via Cargo"). Not installed here, so the example was not run.
## Minimal example
`max.rs`:
```rust
use vstd::prelude::*;
verus! {
fn max(a: u32, b: u32) -> (r: u32)
ensures r >= a, r >= b, r == a || r == b
{
if a > b { a } else { b }
}
} // verus!
fn main() {}
```
Loops need `invariant` and `decreases` clauses; arithmetic overflow is a proof obligation unless the type is `int`.
## Run
`verus max.rs`, or in a Cargo project `cargo verus verify` (not `cargo verus focus`, which skips the proofs of dependencies).
Passing looks like (from the guide):
note: verifying root module
verification results:: 1 verified, 0 errors
Failure prints `error: assertion failed` (or a failed `ensures`) with the source location, then `error: aborting due to previous error` and `verification results:: 0 verified, 1 errors`. The guide does not state the process exit status; Verus is a rustc-based driver and should exit non-zero on errors, but confirm it with a deliberately wrong spec before relying on exit alone. The contract below also checks the text. `verus file.rs --compile` additionally builds a binary.
## As a contract check
```json
{"id": "prove-max-verus", "claim": "max returns one of its arguments and is at least both", "kind": "general", "rung": 1, "cmd": "verus max.rs", "expect": {"exit": 0, "stdout_contains": "verified, 0 errors"}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- Only the `ensures` you wrote and only functions inside `verus!`; code outside it is trusted. Search for `#[verifier::external]`, `assume(`, `admit(` and `external_body`, which skip proof.
- Verus and its trusted specs of `vstd` are part of what you trust.
- Check the check can fail: weaken the body and confirm an error appears, and that the exit status is non-zero.
- Commands and output format were read from the Verus guide and INSTALL.md, not run here.
+55
View File
@@ -0,0 +1,55 @@
---
id: z3-smt
title: Encoding a property directly for Z3 (Python or SMT-LIB)
answers: Does a counterexample to this property exist, found by a solver, when no verifier fits my language?
rung: 1
section: prove
languages: any
kinds: general, money, parsing
cost: medium
detect: python3 -c "import z3"
ran_here: yes
verified: ran
---
## Use when
- The property is a bit-level or arithmetic fact (overflow tests, rounding, bit tricks, small state-transition rules) you can restate as formulas.
- No verifier covers your language, or you want a quick independent check of a formula.
## Do not use when
- You can verify the real code (`kani`, `cbmc`, `dafny`). Re-encoding invites mistakes.
- The claim has unbounded loops, heap structures or floating-point subtleties.
## Set up
In a throwaway virtualenv: `python3 -m venv .venv && .venv/bin/pip install z3-solver`. The package also provides the `z3` command-line program for SMT-LIB files.
## Minimal example
`z.py`. Claim: for 32-bit unsigned `a`, `b`, `(a + b) < a` holds exactly when the addition overflowed.
```python
from z3 import BitVec, Solver, ULT, UGE, ZeroExt, sat, unsat
a, b = BitVec("a", 32), BitVec("b", 32)
wrapped_smaller = ULT(a + b, a)
really_overflowed = UGE(ZeroExt(32, a) + ZeroExt(32, b), 2**32)
s = Solver()
s.add(wrapped_smaller != really_overflowed) # ask for a counterexample
r = s.check()
assert r == unsat, f"counterexample: {s.model()}" if r == sat else f"solver said {r}"
print("proved: overflow test is exact for all 32-bit a, b")
```
The same in SMT-LIB (`a.smt2`): declare `a`, `b` as `(_ BitVec 32)`, assert the negated claim, `(check-sat)`; expect `unsat`.
## Run
`python3 z.py` or `z3 a.smt2`
Passing looks like: `proved: ...` with exit 0; for SMT-LIB the single word `unsat`. Failure: `sat` (a model is a counterexample). Changing `>=` to `>` in `really_overflowed` gave the counterexample `a = 3489660928, b = 805306368` (their sum is exactly 2^32) and exit 1. The result `unknown` (timeout) is not a pass; the script asserts `unsat`.
## As a contract check
```json
{"id": "prove-overflow-test-z3", "claim": "(a + b) < a is equivalent to unsigned 32-bit overflow", "kind": "general", "rung": 1, "cmd": "python3 z.py", "expect": {"exit": 0, "stdout_contains": "proved"}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Only the formulas, not your code. A wrong translation proves something else; test the encoding against concrete values with `s.add(a == 3, ...)` expecting `sat`.
- You proved the negation is unsatisfiable. Check the formulas are not trivially unsat: assert that the model without the final constraint is `sat`.
- `z3-solver` versions differ in `unknown` behaviour; set `s.set("timeout", ms)` and treat `unknown` as failure.
+54
View File
@@ -0,0 +1,54 @@
---
id: accessibility-axe
title: Automated accessibility checks with axe-core
answers: Does this page have any detectable accessibility violations (contrast, labels, roles)?
rung: 3
section: real-world
languages: javascript, typescript, python
kinds: ui
cost: low
detect: npx playwright --version
ran_here: no
verified: docs
---
## Use when
- You build or change pages and the user said accessibility matters, or you add forms, buttons, images or colours.
- You want a cheap guard against missing labels, low contrast, wrong ARIA roles and bad heading order.
## Do not use when
- You want to claim "accessible". Automated rules catch only a portion of problems; say "no detectable violations".
## Set up
```sh
npm i -D @playwright/test @axe-core/playwright && npx playwright install chromium
```
## Minimal example
```ts
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test('home has no detectable a11y violations', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations).toEqual([]); // prints each violation with the offending element
});
```
Run it on every state that changes the DOM: after opening the menu, the dialog, the error state. Use `.withTags(['wcag2a', 'wcag2aa'])` to pick a standard. Do not disable rules to get green; if a rule must be excluded, `.disableRules([...])` it with a comment saying why and mention it in the report. Take the violation list before your change and show it has not grown.
## Run
`npx playwright test`
Passing looks like: `N passed`. Failure prints the `violations` array: rule id (`color-contrast`), impact, and the HTML node, exit 1.
## As a contract check
```json
{"id": "a11y-axe", "claim": "No axe violations on the covered pages", "kind": "ui", "rung": 3,
"cmd": "npx playwright test tests/a11y.spec.ts", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Roughly a third to a half of accessibility problems can be found by machine; keyboard flow, screen reader wording and sense of the page need a human or a real assistive tool.
- Only pages and states visited. Pixel-level contrast on images is not checked.
- Not run here; the `AxeBuilder({ page }).analyze()` call is from the package README.
- Check the check: add an `<img>` without `alt` and confirm `image-alt` appears.
@@ -0,0 +1,58 @@
---
id: agent-surface-evals
title: Scripted agent transcripts played against the real tool server
answers: Can an agent finish the job by following only what the tool itself tells it to do next?
rung: 3
section: real-world
languages: any
kinds: general, state-machine
cost: high
detect:
ran_here: no
verified: docs
---
## Use when
- You build or change a tool that AI agents call: an MCP server, a CLI an agent drives, an API with guidance in its responses.
- The tool's responses carry guidance ("next steps", error hints) and you want it proved to be enough, with no model involved.
## Do not use when
- The tool is only used by humans. Use `cli-transcript-tests`.
- You want to measure a particular model's skill; this check uses no model and proves only that a path exists.
## Set up
Write transcripts as data files (JSON), one per journey. A transcript is `{ "description", "settings", "setup": [...], "steps": [...] }`. `setup` calls are made directly (the chart and the books an agent finds on arrival; they are not the agent's moves) and may save values with `"save": {"x": "/pointer"}`. Write a small runner that starts the real server (a temporary data directory, a real socket or stdio), plays the steps, and fails when a step's tool is not in the previous result's next steps. The reference project does exactly this in `crates/app-cli/tests/agent_evals.rs`, with six transcripts in `crates/app-cli/tests/agent_evals/*.json`; the test asserts the exact list of transcript names, so a deleted transcript fails.
## Minimal example
Trimmed from the reference project's `onboarding_to_first_post.json`:
```json
{ "description": "A new book: onboarding to the first account, following only next_steps.",
"steps": [
{ "call": "books.start", "args": { "agent": { "model": "scripted", "reasoning_effort": "none", "harness": "agent_evals" } } },
{ "expect": { "/state": "needs_onboarding" } },
{ "expect_next_steps_contains": "books.set_setting" },
{ "follow": "books.set_setting", "with": { "changes": [{ "key": "company.name", "value": "Eval Co" }], "decided_by": "Avery Quill" } },
{ "expect_next_steps_contains": "books.add_account" },
{ "follow": "books.add_account", "with": { "code": "1000", "name": "Cash", "account_type": "asset" } } ] }
```
The step forms in the reference runner: `call` (first step only, and only `books.start`), `follow` (the previous result's `next_steps` must name that tool; its `args` are used with `with` laid over them, so `with` supplies only what an agent decides: an amount, a date), `follow_prompt` (the previous result must name that prompt), `expect_next_steps_contains` and `expect` (JSON-pointer equality on the previous result). The runner panics on any other step. The tool names above belong to that project's server; use your own server's.
Add the cases agents get wrong: a refused call must say what to do instead, and the transcript then follows that advice.
## Run
Your test command; the reference project's is `cargo test -p app-cli --test agent_evals`. The test function plays every file, and asserts that each transcript called at least one tool after the start.
Passing looks like: `test result: ok` for `agent_evals_follow_only_next_steps`. Failure names the step, for example `"onboarding step 3: books.add_account is not in the previous result's next_steps: [...]"`, or `was refused` when the call itself errored.
## As a contract check
```json
{"id": "agent-evals", "claim": "An agent can complete each journey by following the tool's own next steps", "kind": "general", "rung": 3,
"cmd": "cargo test -p app-cli --test agent_evals", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- That a model will actually choose those steps; it proves they exist and are enough.
- Only the journeys scripted. Add one for each reported agent failure.
- Not run here. `verified: docs` means checked against the reference project's runner source and transcripts (this entry describes that pattern; the runner is specific to its server).
- The reference runner has no explicit "end state" step: a transcript ends where its last `expect` lines say, so give every transcript a final `expect` on the result that proves the journey finished.
- A transcript with no `expect` lines proves only that calls did not error. Assert on content.
- Check the check: edit the server's next steps to name a wrong tool and see a transcript fail.
@@ -0,0 +1,56 @@
---
id: annotation-behaviour-check
title: Verifying that declared properties (read-only, idempotent) hold in behaviour
answers: Does every tool marked read-only or idempotent really behave that way?
rung: 3
section: real-world
languages: any
kinds: general, state-machine
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- A tool, API method or command declares a property an agent will rely on: MCP `readOnlyHint`, `idempotentHint`, `destructiveHint`, an HTTP `GET` that must be safe, a "dry run" flag.
- You add or change such a tool. A false `readOnlyHint` makes an agent call a destructive tool freely.
## Do not use when
- Nothing relies on the declaration.
## Set up
Build a fixture with data in every table or file the tools can touch. Write a snapshot function for the whole data area (paths, sizes, hashes; see `read-only-guarantee`). Get the tool list and its annotations from the running server (`tools/list` in MCP), and iterate over it so new tools are covered by default.
## Minimal example
```python
# pseudo-code for a test loop; a reference project does this for every tool in tools/list
for tool in server.list_tools():
for args in sample_arguments(tool): # valid calls plus refused ones
before = snapshot(data_dir)
result = server.call(tool.name, args)
after = snapshot(data_dir)
if tool.annotations.get("readOnlyHint"):
assert before == after, f"{tool.name} {args} changed data" # success or refusal
if tool.annotations.get("idempotentHint") and not result.is_error:
server.call(tool.name, args)
assert snapshot(data_dir) == after, f"{tool.name} is not idempotent"
```
Check both outcomes: a refused call must also leave data unchanged. Exclude only files that legitimately change (SQLite `-wal` and `-shm` files change on read; compare database contents by a digest instead). A second assertion belongs here: a tool that does change data must not be marked read-only, so also assert that at least one tool carries `readOnlyHint: false` and that each such tool's sample call changes something; otherwise the loop may be testing nothing.
## Run
Your test command, for example `cargo test --test spec_mcp`.
Passing looks like: all tools pass and the log says how many read-only calls ran and that each changed nothing. Failure names the tool, the arguments and the changed file.
## As a contract check
```json
{"id": "annotations-true", "claim": "Every tool marked read-only leaves data unchanged, success or refusal", "kind": "general", "rung": 3,
"cmd": "cargo test --test spec_mcp readonly", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
```
## What a pass does not prove
- Only the argument samples used. A tool that writes on a rare path (a cache miss, a quota reset) passes unless the samples reach it.
- A declared property outside the data you snapshot (network calls, email) is not checked. Say which areas are covered.
- The check ran here only in miniature (the snapshot comparison from `read-only-guarantee`); the loop above is the pattern from the reference project, not a tool you can install.
- Check the check: make one read-only tool touch a file and confirm the loop catches it.
+50
View File
@@ -0,0 +1,50 @@
---
id: clean-clone-build
title: Build and test from a fresh clone in a clean container
answers: Does this work from a fresh checkout, or only on my working tree?
rung: 3
section: real-world
languages: any
kinds: general
cost: medium
detect: docker --version
ran_here: yes
verified: ran
---
## Use when
- You are about to say "done" on something that builds, packages or deploys.
- You added a file, a generated asset, an environment variable or a tool that your tree may have and the repository does not.
- A path that only exists on your machine (an ignored file, a global tool) could be hiding a break.
## Do not use when
- The change is a comment or documentation only.
- A full build takes hours; then use CI as the clean room and wait for it.
## Set up
Commit (or stage) everything first: a clone sees only committed files. You need `git` and, for a clean machine, Docker or Podman and an image of the target OS.
## Minimal example
```sh
git clone --no-local . /tmp/fresh # only committed files come along
docker run --rm -v /tmp/fresh:/work:ro -w /work debian:trixie-slim \
sh -c 'apt-get update -qq && apt-get install -y -qq make >/dev/null && make test'
```
Without Docker the fresh clone alone catches most problems: `cd /tmp/fresh && make test`. Run the project's real build and test command, with no cache mounts, and on the clean machine install tools only as the README says. If the README's steps are not enough, the README is a bug.
Here a repository with an ignored `generated.txt` passed `make test` in its own directory and failed (`Error 1`) in the fresh clone.
## Run
The commands above. Passing looks like: the same exit 0 and test summary you got on your tree. Failure: missing file, missing tool or failing test in the clean place only, which means the claim "works" was about your tree.
## As a contract check
```json
{"id": "clean-clone", "claim": "A fresh clone builds and passes tests", "kind": "general", "rung": 3,
"cmd": "rm -rf /tmp/fresh && git clone --no-local . /tmp/fresh && cd /tmp/fresh && make test", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800}
```
## What a pass does not prove
- Only the commit you cloned. Uncommitted edits are not tested; commit first.
- A clone on the same machine still inherits your global tools and `~/.cargo`; use a container for the OS and toolchain claim.
- A pinned base image can go stale. Note the image tag.
- Network-fetched dependencies can change between runs; use lockfiles (`--locked`, `npm ci`) so the clean build is repeatable.
- Check the check: delete an ignored-but-needed file and confirm the clone fails.
@@ -0,0 +1,56 @@
---
id: cli-transcript-tests
title: Recorded CLI sessions with trycmd, cram or scrut
answers: Does the command-line tool still print exactly what its documented examples show?
rung: 4
section: real-world
languages: any
kinds: general, parsing
cost: low
detect: scrut --version
ran_here: no
verified: docs
---
## Use when
- You build or change a command-line tool and want its documented usage checked like tests.
- Output, exit codes and error messages are part of the product.
## Do not use when
- The output includes times or absolute paths and you cannot normalise them; use patterns or a different assertion.
- The tool is a library; use ordinary unit tests.
## Set up
- Rust: `cargo add --dev trycmd`, and `tests/cli.rs` containing `#[test] fn cli() { trycmd::TestCases::new().case("tests/cmd/*.toml").case("README.md"); }`.
- Any language: `scrut` (Markdown or `.t` files, `scrut test file.md`) or Python `cram` (`pip install cram`, `cram tests/*.t`).
## Minimal example
A cram or scrut file (`tests/basic.t`): commands indented with `$ `, expected output below, and `(re)` for a regex line.
```
$ mytool --version
mytool 1.2.3
$ mytool add 2 3
5
$ mytool add x 3
error: 'x' is not a number
[2]
```
`[2]` is the expected exit status. Record the file by running the tool BEFORE changing it and reading the output yourself. Write error cases too: what the user sees when it fails is part of the contract. trycmd writes new expectations when run with `TRYCMD=overwrite`; use that only to accept an intended change.
## Run
`scrut test tests/basic.t` or `cram tests/basic.t` or `cargo test --test cli`
Passing looks like: a summary of passed tests and exit 0. Failure prints a diff of expected against actual output and exits 1.
## As a contract check
```json
{"id": "cli-transcripts", "claim": "CLI behaviour matches the recorded transcripts", "kind": "general", "rung": 4,
"cmd": "cargo test --test cli", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Only the invocations recorded. A flag nobody wrote a case for is not covered.
- Transcripts record what the program printed, not what it should have printed. Review expected output as you would a spec.
- Overwrite modes pass anything; look at the `git diff` of the transcript files.
- Not run here (none of these tools is installed). The trycmd and scrut forms are from their READMEs; the `cram` syntax and the `[2]` exit-status line are from memory; test them on a trivial file first.
- Check the check: change an output string in the tool and confirm a diff.
@@ -0,0 +1,80 @@
---
id: contract-testing-pact
title: Consumer-driven contract tests between services (Pact)
answers: Does the service I changed still satisfy what each of its consumers expects?
rung: 3
section: real-world
languages: javascript, typescript, python, java, go, rust
kinds: general
cost: high
detect:
ran_here: no
verified: docs
---
## Use when
- Two services talk over HTTP or messages, owned by different people, and integration tests are slow or flaky.
- You change a provider's response, or a consumer's request, and need to know who breaks.
## Do not use when
- One codebase owns both sides and a type checker covers the interface. A shared schema check (`api-breaking-schema`) is cheaper.
- You only need one end-to-end flow; use `e2e-playwright` or `smoke-after-deploy`.
## Set up
JavaScript/TypeScript (pact-js, current release 17.x; needs Node 16 or newer): `npm install --save-dev @pact-foundation/pact`. Other languages: `pip install pact-python` (4.x), and the Pact libraries for Java, Go and Rust (see docs.pact.io). The Python, Go and Rust APIs differ from the JavaScript one below; use the library's own README. Decide where contracts are stored: a Pact Broker, or a committed `pacts/` directory.
## Minimal example
Consumer side: describe one interaction in a test, run it against Pact's mock server, which writes a contract file to `pacts/` when the test passes. Provider side: replay every consumer's contract against the real provider. From the pact-js README (the `PactV3` and `MatchersV3` classes are the current consumer API):
```ts
import { PactV3, MatchersV3 } from '@pact-foundation/pact';
import path from 'path';
const provider = new PactV3({
dir: path.resolve(process.cwd(), 'pacts'),
consumer: 'MyConsumer',
provider: 'MyProvider',
});
it('returns user 1', () => {
provider
.given('user 1 exists')
.uponReceiving('a request for user 1')
.withRequest({ method: 'GET', path: '/users/1' })
.willRespondWith({
status: 200,
headers: { 'Content-Type': 'application/json' },
body: { id: MatchersV3.integer(1), name: MatchersV3.like('Ada') },
});
return provider.executeTest(async (mockserver) => {
const res = await fetch(`${mockserver.url}/users/1`); // replace with your real client
expect((await res.json()).name).toBe('Ada');
});
});
```
Provider verification (also from the README; `Verifier` is the provider interface):
```ts
import { Verifier } from '@pact-foundation/pact';
await new Verifier({
providerBaseUrl: 'http://localhost:8081', // your provider, already running
pactUrls: [path.resolve(process.cwd(), 'pacts/MyConsumer-MyProvider.json')],
stateHandlers: { 'user 1 exists': async () => { /* insert user 1 */ } },
}).verifyProvider();
```
Use `like()`-style matchers instead of exact values so only the structure is pinned. Run verification on the provider before merging a provider change.
## Run
Consumer: your normal test command (it writes the contract). Provider: the test file above, run by your test runner (`npm run test:pact:provider`, a script you define). Passing looks like: every interaction verified and the test passes (exit 0). Failure: `verifyProvider()` rejects, so the test fails with the interaction and mismatched field in the output. A state name missing from `stateHandlers` is a provider setup gap to fix, not a pass. With a Broker, `publishVerificationResult` should be on only in CI.
## As a contract check
```json
{"id": "pact-provider", "claim": "The provider satisfies all consumer contracts", "kind": "general", "rung": 3,
"cmd": "npm run test:pact:provider", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- Only interactions consumers wrote down. A consumer using a field it never put in a contract is not protected.
- Matching structure is not matching meaning.
- Not run here (no Pact libraries installed); the snippets follow the pact-js README and docs (docs/consumer.md, docs/provider.md). The API changes between major versions, so confirm names against the installed version.
- Pending pacts (`enablePending: true`) make a new contract not fail the provider build; do not enable them in a gating check.
- Provider states that set up fake data can hide real-data issues.
- Check the check: remove a field from the provider response in a scratch copy and see the verification fail.
@@ -0,0 +1,60 @@
---
id: cross-platform-matrix
title: Running build and tests on the other operating systems in CI
answers: Does this also work on Windows and macOS, not just on the Linux machine I tested on?
rung: 3
section: real-world
languages: any
kinds: general
cost: medium
detect: gh --version
ran_here: no
verified: docs
---
## Use when
- The software ships for more than one OS, or touches paths, file permissions, line endings, case sensitivity, processes, sockets or the clock.
- You changed anything that reads or writes files, spawns processes or draws a UI.
## Do not use when
- The product is Linux-server-only and says so. Then a matrix is cost without benefit.
- You cannot reach CI. Say so; a Linux pass does not support a claim about other systems.
## Set up
Use the CI provider's hosted runners. For GitHub Actions the labels are `ubuntu-latest` (or a pinned `ubuntu-24.04`), `windows-latest` and `macos-latest`. Pin versions where results must not drift.
## Minimal example
`.github/workflows/matrix.yml`
```yaml
name: matrix
on: [push, pull_request]
jobs:
test:
strategy:
fail-fast: false # one OS failing must not hide the others
matrix:
os: [ubuntu-24.04, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- run: cargo test --locked
shell: bash
```
Write the platform code with the differences in mind and test them: `#[cfg(unix)]` for permission bits (a read-only folder cannot be made on Windows; use the read-only attribute), path separators, `\r\n`. A test that cannot run on one OS must be skipped explicitly with a reason, never silently.
After pushing, read the result: `gh run list --branch "$(git branch --show-current)"` and `gh run view <id> --log-failed`.
## Run
Push and wait for the workflow. Passing looks like: every matrix job green (`gh run view` shows `✓` for each OS). Failure: a red job named after the OS; read its log, do not rerun until green.
## As a contract check
```json
{"id": "ci-matrix", "claim": "Tests pass on Linux, Windows and macOS in CI for this commit", "kind": "general", "rung": 3,
"cmd": "gh run list --commit $(git rev-parse HEAD) --workflow matrix.yml --json conclusion --jq '.[0].conclusion' | grep -x success", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
```
## What a pass does not prove
- Only the OS versions of the hosted runners, with their tools. Real desktops differ (graphics, locale, antivirus).
- Skipped tests are invisible in a green run. Count them in the log.
- GUI pixel comparisons differ across OS renderers; compare structure or shapes there (`visual-regression-native-gui`).
- Not run here: no CI access in this session; the workflow syntax is standard GitHub Actions, the `gh` commands were not executed.
- Check the check: confirm the workflow file actually lists the OSes, and that `gh run list` returns a run for this commit rather than nothing.
@@ -0,0 +1,61 @@
---
id: doc-tests-and-links
title: Doctests, compiled examples and link checking
answers: Do the examples in the docs and comments still run, and do the links still resolve?
rung: 3
section: real-world
languages: rust, python, any
kinds: general
cost: low
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- You wrote or changed documentation, a README, or a doc comment that contains code or links.
- You change a public function: the examples that show it must still compile and give the stated result.
## Do not use when
- The examples need unavailable services. Mark them (`no_run` in Rust) so they at least compile, and say so.
## Set up
- Rust: `cargo test --doc` compiles and runs each fenced example in doc comments and in the crate's README when included with `#![doc = include_str!("../README.md")]`.
- Python: `python3 -m doctest -v file.py` or `pytest --doctest-modules`.
- Links: `lychee` (https://github.com/lycheeverse/lychee) checks Markdown and HTML links; `lychee --offline` checks local file links only.
## Minimal example
```rust
/// Adds two numbers.
///
/// ```
/// assert_eq!(mycrate::add(2, 2), 4);
/// ```
pub fn add(a: i32, b: i32) -> i32 { a + b }
```
```python
def f(x):
"""
>>> f(2)
4
"""
return x * 2
```
Make the example the real documentation of behaviour: assert results, not just calls. Check docs build without broken intra-doc links: `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps` (see `zero-warnings`).
## Run
`cargo test --doc`, `python3 -m doctest file.py`, `lychee --offline README.md docs/`
Passing looks like: `test result: ok` (Rust), no output and exit 0 (Python doctest), `0 errors` (lychee). Failure: Rust marks `test src/lib.rs - add (line 3) ... FAILED`; Python prints `***Test Failed*** 1 failure` and exits 1. Both ran here; lychee was not usable here, so its output is from its README.
## As a contract check
```json
{"id": "doctests", "claim": "All documentation examples compile and pass", "kind": "general", "rung": 3,
"cmd": "cargo test --doc", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Examples with no assertion pass when they only run. `0 passed` also appears when there are no doctests at all; require a count above zero.
- An external link that answers 200 can still point to the wrong page. Network link checks are flaky; run them separately from the main gate.
- Prose can still be wrong. Only code and links are tested.
- Check the check: change an expected value and see the failure (done here with Rust and Python).
+56
View File
@@ -0,0 +1,56 @@
---
id: e2e-playwright
title: End-to-end browser tests against the running app (Playwright)
answers: Can a user actually do this task in the real running app in a real browser?
rung: 3
section: real-world
languages: javascript, typescript, python
kinds: ui, general
cost: medium
detect: npx playwright --version
ran_here: yes
verified: ran
---
## Use when
- A claim is about a user flow: sign in, add to cart, save a form, see the result.
- Unit tests pass but you have not seen the pieces work together through the real UI.
## Do not use when
- The claim is about a calculation or a rule; a unit or property test is faster and more precise.
- The flow depends on third-party services you cannot fake; stub them at the network layer (`page.route`) and say you did.
## Set up
```sh
npm i -D @playwright/test && npx playwright install chromium
```
Let Playwright start the app so the test never runs against a stale server: in `playwright.config.ts` set `webServer: { command: 'npm run start', url: 'http://localhost:3000', reuseExistingServer: false }` and `use: { baseURL: 'http://localhost:3000' }`. Use a fresh test database or fixture each run.
## Minimal example
```ts
import { test, expect } from '@playwright/test';
test('a visitor can add a note', async ({ page }) => {
await page.goto('/');
await page.getByRole('textbox', { name: 'Note' }).fill('buy milk');
await page.getByRole('button', { name: 'Add' }).click();
await expect(page.getByRole('listitem')).toHaveText('buy milk'); // asserts the result, not just that the click worked
});
```
Locate by role and accessible name, not CSS classes, so the test survives restyling. Assert on what the user sees after the action. For a bug fix, write the test so it fails on the old code first.
## Run
`npx playwright test`
Passing looks like: `N passed`, exit 0. Failure shows the failing step, a trace (`--trace on` then `npx playwright show-trace`), and exit 1. A web server that fails to start makes the run fail, not pass. (Run here against a static page served by `python3 -m http.server`.)
## As a contract check
```json
{"id": "e2e", "claim": "The add-note flow works in a real browser", "kind": "ui", "rung": 3,
"cmd": "npx playwright test", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Only the paths you scripted, in one browser. Add projects for Firefox and WebKit when it matters.
- Flaky tests tempt retries. A test that passes only on retry is failing sometimes; fix the wait (assert on a visible state) instead of adding `retries`.
- `expect(...).toBeVisible()` alone proves little; assert the content or effect.
- Check the check: break the feature (remove the handler) and confirm the test fails.
+63
View File
@@ -0,0 +1,63 @@
---
id: lighthouse-budget
title: Lighthouse CI budgets and score assertions
answers: Is this page still within its performance, accessibility and best-practice budgets?
rung: 4
section: real-world
languages: javascript, any
kinds: ui
cost: medium
detect: npx lhci --version
ran_here: no
verified: docs
---
## Use when
- Page weight, load time or Lighthouse scores matter and you changed scripts, images, fonts or markup.
- You want a number with a limit, checked on every change.
## Do not use when
- The page needs a login you cannot script around; Lighthouse measures a single loaded page.
- You want a verdict on user experience. Scores are a proxy.
## Set up
```sh
npm i -D @lhci/cli
```
Create `lighthouserc.json`. Run it in an environment you can repeat (a CI container); local laptops give different timings.
## Minimal example
`lighthouserc.json`
```json
{
"ci": {
"collect": { "url": ["http://localhost:3000/"], "numberOfRuns": 3, "startServerCommand": "npm run start" },
"assert": {
"assertions": {
"categories:performance": ["error", { "minScore": 0.9 }],
"categories:accessibility": ["error", { "minScore": 1 }],
"total-byte-weight": ["error", { "maxNumericValue": 500000 }]
}
}
}
}
```
Several runs and the median handle noise. Prefer hard resource budgets (bytes, request counts), which do not wobble, over timing metrics. Record the current scores BEFORE you edit so you know the margin. `lhci assert --preset=lighthouse:recommended` is available as a starting set and individual assertions can be switched off (`--assertions.uses-webp-images=off`).
## Run
`npx lhci autorun` (collect, assert, upload), or `npx lhci collect && npx lhci assert`.
Passing looks like: all assertions pass and exit 0. Failure prints each failed assertion with expected and actual values and exits nonzero.
## As a contract check
```json
{"id": "lighthouse", "claim": "The home page meets its Lighthouse budgets", "kind": "ui", "rung": 4,
"cmd": "npx lhci autorun", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Lab results on one URL and one machine, not real users' devices and networks.
- Timing scores vary between runs; a pass on three runs is not a guarantee.
- Lowering a threshold to pass is a change to review, as in `ratchet-floor`.
- Not run here (`lhci` is not installed). `lhci assert`, `--preset` and `--assertions` appear in the Lighthouse CI configuration docs; the JSON shape follows those docs.
- Check the check: set `minScore` to 1 on performance and confirm it can fail.
+61
View File
@@ -0,0 +1,61 @@
---
id: load-test-k6
title: Load tests with pass/fail thresholds (k6)
answers: Does the service stay fast and correct under the load it must handle?
rung: 3
section: real-world
languages: any
kinds: general
cost: medium
detect: k6 version
ran_here: no
verified: docs
---
## Use when
- You changed a query, cache, index, lock or request path and need to show it holds under concurrency.
- A latency or error-rate promise exists (a service level objective).
## Do not use when
- The service has no stated target; invent none. Ask for one, or compare before and after instead.
- You would point it at a production system or one you do not own. Test a copy.
## Set up
Install k6 (https://grafana.com/docs/k6/latest/set-up/install-k6/). Run the system under test locally or in a staging copy with realistic data volume.
## Minimal example
`load.js`
```js
import http from 'k6/http';
import { check } from 'k6';
export const options = {
vus: 20, duration: '30s',
thresholds: {
http_req_failed: ['rate<0.01'], // under 1 % errors
http_req_duration: ['p(95)<300'], // 95 % of requests under 300 ms
},
};
export default function () {
const res = http.get('http://localhost:3000/api/items');
check(res, { 'status is 200': (r) => r.status === 200, 'has items': (r) => r.json().length > 0 });
}
```
Thresholds are what make this a check: if any is crossed, k6 exits nonzero. Checks (`check`) alone only count and do not fail the run, so also put `checks: ['rate>0.99']` in `thresholds`. Run once against the unchanged system first and record the numbers.
## Run
`k6 run load.js`
Passing looks like: every threshold line marked with a tick (`✓`) and exit 0. Failure marks the threshold `✗` and exits with code 99.
## As a contract check
```json
{"id": "load", "claim": "p95 latency under 300 ms and under 1% errors at 20 users", "kind": "general", "rung": 3,
"cmd": "k6 run load.js", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Only the traffic mix you scripted. Real users behave differently.
- The load generator and the system share a machine in a local test; results are optimistic. Record where it ran.
- Not run here (`k6` is not installed). Thresholds and their behaviour come from the k6 documentation; the exit code 99 is from memory.
- Passing latency does not show the responses were right; keep the `check` calls and a threshold on them.
- Check the check: set `p(95)<1` and confirm the run fails.
@@ -0,0 +1,60 @@
---
id: multi-user-isolation
title: Proving one account cannot read another's data
answers: Can user B see, change or guess user A's data through any door the product offers?
rung: 3
section: real-world
languages: any
kinds: general
cost: medium
detect:
ran_here: no
verified: docs
---
## Use when
- The product has accounts, tenants, workspaces or roles, and a leak between them would be serious.
- You added an endpoint, a query, an export, a search index, a cache or a background job that touches stored data.
## Do not use when
- A single-user tool with no sharing. Use `read-only-guarantee` if the concern is accidental writes.
## Set up
Two layers, as a Rust project did them in a CI workflow (`two-user.yml`) and an integration test (`two_user.rs`):
1. Operating-system layer. A system account `appsvc` runs the server and owns the data root; the root is created mode `0700` (`sudo install -d -o appsvc -g appsvc -m 0700 /srv/appdata`). The test runs as a different account (the CI runner) and must be refused.
2. Network layer. The server listens only on loopback (`--http 127.0.0.1:PORT`) with `--isolation enforced`; each book has its own bearer token, minted by the server (`token create --book acme --name ci`, stored in a 0600 file under the root). The test reaches the data only through that door, with the token.
For a product with accounts rather than OS users, the same idea: create accounts A and B with distinctive data (`ALPHA-SECRET-1`) and make every request as B using only B's credentials.
## Minimal example
What the reference test asserts as the agent account, in Rust: `std::fs::read_dir(tenant_root)` and `File::open(tenant_root/books/<book>/journal.jsonl)` must both fail with `ErrorKind::PermissionDenied` (the test checks the error kind, so a missing path does not pass as "refused"); then `books.start` over HTTP with the token must report `isolation` equal to `service_user (enforced)`, and a read, a write, an upload and an export must still work through that door (the account is shut out of the files, not out of the product). Separate tests check that `--http` rejects non-loopback addresses and that books moved to the server keep their head hash.
A generic web-API version of the cross-account cases (not from the reference project):
```sh
# As user B, ask for A's record by every route: direct id, list, search, export, attachment URL.
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $TOKEN_B" "$BASE/api/records/$A_RECORD_ID" # expect 403 or 404
curl -s -H "Authorization: Bearer $TOKEN_B" "$BASE/api/records?q=ALPHA-SECRET" | grep -c ALPHA-SECRET || true # expect 0
```
Also test: no credentials at all (401), a tampered or expired token, writing to A's record as B (must change nothing; check A's record afterwards), and listing endpoints returning only B's rows. Write every case with a distinctive value and assert its absence from every response body, not only the status code.
## Run
The reference job builds the server, creates the accounts and directories, starts two servers, then runs, as the agent account, with the deployment given in `TWO_USER_TEST=1`, `APP_TENANT_ROOT`, `APP_SERVER_URL`, `APP_BOOK`, `APP_TOKEN` and related variables:
cargo test -p app-cli --test two_user -- --nocapture --test-threads=1
Passing looks like: both tests ran and passed. Without `TWO_USER_TEST` each test prints `SKIPPED ...` and returns, which cargo counts as a pass, so a laptop run proves nothing: require that the output contains no `SKIPPED`. Failure: a panic such as "this account can read the tenant root". For a web API, your own script: every forbidden access returns 403, 404 or 401, the secret strings appear in no response, and A's data is byte-identical afterwards.
## As a contract check
```json
{"id": "isolation", "claim": "Account B cannot read or modify account A's data through the API", "kind": "general", "rung": 3,
"cmd": "sh tests/isolation.sh", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"}
```
For the reference-style OS check, make the script fail on a `SKIPPED` line in the cargo output.
## What a pass does not prove
- Only the doors you tried. Enumerate every endpoint from the route list or the tool list, and test each as B.
- Insecure direct object references hide in ids that are guessable; also try other users' ids from a list you did not get from the API.
- Not run here. `verified: docs` means this entry was checked against the reference project's workflow file and test source, which it describes accurately; the generic curl cases are not taken from it, and the project's two-user test does not try one account's token against another account's book.
- A shared cache or search index can leak even when the database is separate. Include them.
- Check the check: temporarily remove the authorisation check and confirm the test fails.
@@ -0,0 +1,54 @@
---
id: packaging-install-upgrade
title: Install and upgrade real packages in containers across distributions
answers: Can a user install this package, open their data, upgrade, and still have their data intact?
rung: 3
section: real-world
languages: any
kinds: general, migration
cost: high
detect: docker --version
ran_here: no
verified: docs
---
## Use when
- You ship `.deb`, `.rpm`, Arch packages, installers or a self-update path.
- Version N+1 changes a file format or a data directory, and users have data from version N.
## Do not use when
- You ship only a container image or a library; test the image directly or use `clean-clone-build`.
## Set up
Build the old and the new package. For each target distribution, start a clean container (Debian, Fedora, Arch images are enough) with the package directory mounted read-only. Create an ordinary user in the container: installs run as root, data belongs to a user.
## Minimal example
The pattern, as used in a reference project (`deploy/packaging/test-linux-packages.sh`), per distribution:
```sh
docker run --rm -v "$PWD/target/packages:/packages:ro" debian:trixie-slim bash -c '
set -euo pipefail
useradd -m tester
apt-get install -y /packages/mytool_0.1.0_amd64.deb
su tester -c "mytool setup && mytool create demo"
before=$(su tester -c "mytool list")
apt-get install -y /packages/mytool_0.1.1_amd64.deb # the upgrade
after=$(su tester -c "mytool list")
[ "$before" = "$after" ]'
```
Check things that break in practice: the data's head or checksum is unchanged, a long-running process restarts onto the new binary (`readlink /proc/$pid/exe` must not say `(deleted)`), the self-updater refuses when a package manager owns the install, and uninstall leaves user data alone. Repeat with `fedora:latest` (`dnf install`) and `archlinux:latest` (`pacman -U`).
## Run
Your script, once per distribution. Passing looks like: exit 0 in every container and the same data summary before and after. Failure: a nonzero exit with the failed assertion; keep the container logs.
## As a contract check
```json
{"id": "pkg-upgrade", "claim": "Install, open data, upgrade: data is unchanged on Debian, Fedora and Arch", "kind": "general", "rung": 3,
"cmd": "sh deploy/test-packages.sh", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 3600}
```
## What a pass does not prove
- Only the distributions and versions tested. Other package managers and init systems differ.
- Real user data is richer than your demo data; use an anonymised copy from an old version when you can.
- Docker's default seccomp and missing systemd can change behaviour; services that need them need `--privileged` or a VM, which weakens isolation.
- Not run here (no packages to build). The shape comes from the reference project's script; Docker and the base images are installed on this machine.
- Check the check: corrupt the data in the new package's migration and see the comparison fail.
@@ -0,0 +1,53 @@
---
id: runtime-self-check
title: Give the product its own verify or doctor command and run it as a check
answers: Does the product's own data pass its own integrity checks (hash chain, control totals, invariants)?
rung: 3
section: real-world
languages: any
kinds: money, state-machine, general
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- The product holds data whose consistency can be checked from the data alone: a journal with a hash chain, ledgers whose debits equal credits, counters that must add up to a stored total, foreign keys that must resolve.
- You want the same check to run in tests, after a migration, after a restore, in CI and in production.
## Do not use when
- There is no invariant to check. A `verify` command that always prints OK is worse than none.
## Set up
Add a command, for example `mytool verify [--data DIR]`, that reads the data and checks invariants without writing anything (see `read-only-guarantee`). Make it exit 0 when all hold and nonzero with a specific message for each broken one. Typical checks: each record's hash includes the previous hash; sum of debits equals sum of credits; row counts match a stored control total; no orphan references; every file referenced exists.
## Minimal example
A hash-chained log, with `verify` as a few lines of shell:
```sh
# each line: <prev-hash> <payload>; the next line's prev-hash must be sha256 of the whole previous line
prev=GENESIS
while IFS= read -r line; do
[ "${line%% *}" = "$prev" ] || { echo "chain broken at: $line"; exit 1; }
prev=$(printf '%s' "$line" | sha256sum | cut -d' ' -f1)
done < journal.log
echo "chain ok"
```
Run it on good data, then edit one payload byte in a copy and confirm it fails (done here: a tampered line printed `chain broken at:` and exited 1). Then use it as a check wherever data changes: after a migration (`db-migration-safety`), after an upgrade (`packaging-install-upgrade`), after a restore. The owner's reference project exposes this as a `verify` tool and runs it in migration and hostile-input tests, asserting the books still verify afterwards.
## Run
`mytool verify --data data/` or the script above.
Passing looks like: `chain ok` (or the product's own summary) and exit 0. Failure: a message naming the first broken record, exit 1.
## As a contract check
```json
{"id": "self-verify", "claim": "The data directory passes the product's own integrity check", "kind": "general", "rung": 3,
"cmd": "mytool verify --data tests/fixtures/books", "expect": {"exit": 0, "stdout_contains": "ok"}, "tier": "deep", "timeout_s": 120}
```
## What a pass does not prove
- Only the invariants coded into `verify`. If a bug writes data that satisfies the checker, the checker passes. Keep the invariants independent from the write path.
- A hash chain shows tampering or corruption after the fact; it does not show the entries were correct.
- A verify that runs on an empty fixture proves nothing; use data with every kind of record.
- Check the check: corrupt one record in a copy and confirm failure.
@@ -0,0 +1,50 @@
---
id: smoke-after-deploy
title: Post-deploy smoke checks and health endpoints
answers: Is the thing I just deployed actually up and serving correct responses?
rung: 3
section: real-world
languages: any
kinds: general
cost: low
detect: curl --version
ran_here: yes
verified: ran
---
## Use when
- You deployed, released or restarted a service and are about to say it is live.
- You want a small set of fast checks that run after every deploy and after rollback.
## Do not use when
- You need deep correctness; smoke checks only show it is alive and wired.
- You cannot reach the deployed URL; then say what you could not check.
## Set up
Have a health endpoint (for example `/healthz`) that checks real dependencies (database reachable, migrations applied), not just that the process is up. Know the version string the deploy should now report, so you can tell the new build from the old one.
## Minimal example
```sh
BASE=https://app.example.com
expected=$(git rev-parse --short HEAD)
curl -fsS --max-time 10 --retry 5 --retry-delay 3 --retry-connrefused "$BASE/healthz" | tee /tmp/health.json
curl -fsS "$BASE/version" | grep -q "$expected" # the new build is the one answering
curl -fsS -o /dev/null -w '%{http_code}\n' "$BASE/" | grep -qx 200
curl -fsS "$BASE/api/items?limit=1" | python3 -c 'import json,sys; json.load(sys.stdin)' # one real read that parses
```
`-f` makes curl fail on HTTP errors (4xx, 5xx), which is what turns the check into an exit code. `--retry` gives a starting service time. Add one write-and-read round trip against a test account if the service has state. Keep the smoke set under a minute.
## Run
The commands above, as a script with `set -e`. Passing looks like: exit 0, the health JSON shows each dependency `ok`, and the version matches. Failure: curl exits 22 (HTTP error), 28 (timeout) or 7 (connection refused); `grep` exits 1 when the version is old.
## As a contract check
```json
{"id": "smoke", "claim": "The deployed service is healthy and serving the new build", "kind": "general", "rung": 3,
"cmd": "sh scripts/smoke.sh https://app.example.com", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
```
## What a pass does not prove
- Only the endpoints probed. A healthy `/healthz` can sit in front of a broken checkout page.
- A load balancer may send you to one healthy instance while another is bad; probe more than once.
- A cached or CDN-served response can mask a failed deploy. The version check is what shows the new build is live.
- Check the check: point it at a wrong path (`/nope`) and confirm `curl -f` exits 22 (run here against a local server: 22 for the missing path, 7 for a refused connection; the full script was not run against a real deployment).
@@ -0,0 +1,60 @@
---
id: tool-description-lint
title: Linting tool descriptions and help text for misleading instructions
answers: Do this tool's descriptions and help text tell an agent anything false, missing or contradictory?
rung: 3
section: real-world
languages: any
kinds: general
cost: low
detect: python3 --version
ran_here: yes
verified: ran
---
## Use when
- You write or change tool descriptions for an MCP server, `--help` text, error messages or prompts that an agent reads and acts on.
- You rename or remove a tool and need every mention of it found.
## Do not use when
- You want to judge whether the text is persuasive or clear to a model. A lint finds mechanical errors only; use a rubric review or `agent-surface-evals`.
## Set up
Dump the tool list as JSON (for MCP, the result of `tools/list`; for a CLI, the output of each `--help`). Write the rules as a small script and keep it in the repo. Useful rules: every tool named in a description exists; a tool marked read-only does not say it creates, saves or deletes; every required parameter has a description; no description is empty or over a stated length; examples in descriptions parse against the input schema.
## Minimal example
`tests/lint_tools.py` (ran here against a two-tool list)
```python
import json, re, sys
tools = json.load(open(sys.argv[1]))["tools"]
names = {t["name"] for t in tools}
bad = []
for t in tools:
d = t.get("description", "")
for ref in re.findall(r"\b[a-z_]+\.[a-z_]+\b", d):
if ref not in names and ref.split(".")[0] in {n.split(".")[0] for n in names}:
bad.append(f"{t['name']}: description names unknown tool {ref}")
if t.get("annotations", {}).get("readOnlyHint") and re.search(r"\b(creates?|deletes?|saves?|writes?|updates?)\b", d, re.I):
bad.append(f"{t['name']}: readOnlyHint tool description talks about writing")
for p in t["inputSchema"].get("required", []):
if not t["inputSchema"]["properties"].get(p, {}).get("description"):
bad.append(f"{t['name']}: required parameter {p} has no description")
print("\n".join(bad) or "tool text ok"); sys.exit(1 if bad else 0)
```
## Run
`python3 tests/lint_tools.py tools.json`
Passing looks like: `tool text ok` and exit 0. Failure lists each problem, one per line, and exits 1, for example `books.show: description names unknown tool books.post_entry`.
## As a contract check
```json
{"id": "tool-text-lint", "claim": "Tool descriptions name only existing tools and match their annotations", "kind": "general", "rung": 3,
"cmd": "python3 tests/lint_tools.py tests/tools.json", "expect": {"exit": 0, "stdout_contains": "tool text ok"}, "timeout_s": 60}
```
## What a pass does not prove
- Only the rules you wrote. A description can be mechanically clean and still send an agent the wrong way.
- The regex for write words has false positives and misses synonyms; treat each hit as a question to a human.
- A stale `tools.json` passes against an old tool list. Regenerate it from the running server in the same check.
- Check the check: add a reference to a tool that does not exist and confirm failure (done here).
@@ -0,0 +1,53 @@
---
id: api-breaking-schema
title: Breaking-change checks for protobuf, OpenAPI and GraphQL schemas
answers: Did my schema change break existing clients of this API?
rung: 4
section: regression
languages: any
kinds: general, migration
cost: low
detect: buf --version
ran_here: no
verified: docs
---
## Use when
- You edited a `.proto` file, an OpenAPI document or a GraphQL schema that other code or other teams consume.
- You must show a change is additive, not breaking.
## Do not use when
- The schema is internal and changes with all its users in one commit; a compile is enough.
- You need runtime behaviour: see `contract-testing-pact` in `real-world/`.
## Set up
- Protobuf: install `buf` (https://buf.build/docs/installation) and keep a `buf.yaml` at the module root.
- OpenAPI: install `oasdiff` (Go binary or Docker image).
- GraphQL: `npm i -D @graphql-inspector/cli graphql`.
Each tool compares the working tree to a known-good base: a git ref or a saved copy of the old schema.
## Minimal example
```sh
buf breaking --against '.git#branch=main' # protobuf, against the main branch
oasdiff breaking --fail-on ERR base/openapi.yaml openapi.yaml # OpenAPI; first arg is the old spec
graphql-inspector diff base/schema.graphql schema.graphql # GraphQL; reports breaking, dangerous, safe
```
Get the base BEFORE editing: `git show main:api/openapi.yaml > /tmp/base-openapi.yaml`. Use `--fail-on WARN` with oasdiff to also fail on risky changes. `buf` has rule sets (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`) set under `breaking:` in `buf.yaml`; pick the one that matches how clients are built.
## Run
Any of the commands above.
Passing looks like: no output and exit 0 from `buf breaking`; oasdiff exits 0 with no `error` lines; graphql-inspector says no breaking changes. Failure: buf prints `file:line:col:message` for each break and exits 100; oasdiff with `--fail-on ERR` exits 1 and lists each change with an id; graphql-inspector exits 1 on breaking changes.
## As a contract check
```json
{"id": "api-schema-compat", "claim": "The OpenAPI spec has no breaking changes against main", "kind": "general", "rung": 4,
"cmd": "git show main:api/openapi.yaml > /tmp/base.yaml && oasdiff breaking --fail-on ERR /tmp/base.yaml api/openapi.yaml", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
```
## What a pass does not prove
- Only the schema, not the server. A server can stop matching its own spec; test that separately (`contract-testing-pact`, schema-validating end-to-end tests).
- Semantics are invisible: renaming meaning without renaming a field passes.
- Not run here (the tools are not installed). `buf breaking --against` and `oasdiff breaking --fail-on ERR` are from their READMEs; the graphql-inspector command and buf's exit code 100 are from memory and should be checked with `--help`.
- Comparing to the wrong base (your own branch) always passes. Check the base is the released one.
- Check the check: remove a field in a scratch copy and confirm it reports a break.
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff. Show more