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

@@ -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.