# How we test a diskless runtime

> When a bucket holds the only copy of your state, unit tests are not enough. How Cairnflow layers protocol models, deterministic simulation, failpoints and chaos — and the bugs they caught.

Author: Phuong Pham | Date: 2026-12-05 | Source: https://cairnflow.dev/blog/how-we-test

In the [previous post](/blog/no-disks), we explained Cairnflow's core bet: every journal, state
entry, timer, queue and lease lives in one S3-compatible bucket, and runtime nodes keep nothing
they cannot lose.

That design removes a stateful cluster from your infrastructure, and pushes the whole burden of
correctness onto the protocol. A diskless engine has no replica to fall back on. One wrong delete,
one stale leader sneaking a write past a lease, or one acknowledgement sent before a batch is
durable in the bucket, and the only copy of a customer's state is gone.

Ordinary unit and integration tests exercise the common paths. The failures that matter live in
rare interleavings: a node frozen across a lease expiry, a crash between uploading an SST and
writing a manifest, or an S3 retry returning `PreconditionFailed` for a write that already landed.

To catch those before they reach a real bucket, Cairnflow layers five kinds of testing — from
exhaustive state-space search over the protocols down to 24-hour `kill -9` soaks on a real
object store.

```text
  Protocol models (M1–M4)    exhaustive BFS over every interleaving (Stateright)
            │
  Deterministic simulation   3-node cluster, 1 thread, 1 seed, fault swarm + shrinker
            │
  Failpoints & ambiguity     160 named boundaries + every conditional PUT made ambiguous once
            │
  Verify & safety mutants    cairn-ctl verify on every test drop + 15 targeted safety mutants
            │
  Chaos on a real store      real processes, real S3 store, kill -9 every 10s, splits & failpoints
```

Each layer catches bugs the layers above and below it miss. Here is how they work, what they have
actually caught, and what they still do not prove.

## 1. Four protocol models, and three bugs in the shared WAL

The hardest bugs in Cairnflow are not local coding mistakes. They are sequences of ten or twelve
steps across two nodes, a background garbage collector and an object store.

`crates/cairn-model` models the four distributed protocols with
[Stateright](https://github.com/stateright/stateright):

- **M1** — node sessions, owner-record compare-and-swap, SlateDB's `writer_epoch` fence, delegated
  renewal, and the quiesce fences of range splits and merges.
- **M2** — online range splits, merges, retired-database GC and forks. Its transition function
  runs the production decision core (`cairn_split::step`) against a modelled bucket.
- **M3** — the per-node shared write-ahead log: sealing, takeover, the GC floor, dead-log
  sweeping, stripe rotation and follower exposure.
- **M4** — the invocation lifecycle. Its transition function is the production core
  (`cairn_lifecycle::step_mutated`), driven by a modelled shell and environment.

Every acceptance test in `crates/cairn-model` is two-sided. With every fence turned on,
breadth-first search must exhaust the entire state space with zero invariant violations. With any
single historical fix switched off via a `Fences` or `Bugs` flag, the checker must find a
counterexample again. A fixed distributed bug cannot be silently refactored away later without
turning the model suite red.

To make that concrete, here are three real failure modes pinned in
[`crates/cairn-model/tests/m3.rs`](https://github.com/cairnflowdev/cairnflow/blob/main/crates/cairn-model/tests/m3.rs):

### NW-7: trusting an in-memory flush mark

When SlateDB flushes a memtable, it uploads the SST and advances its in-memory
`replay_after_wal_id` mark *before* writing the updated manifest to the bucket. Early shared-WAL
GC trusted that in-memory mark and deleted WAL objects that the stored manifest did not cover yet.
If the node crashed in the gap between the SST upload and the manifest PUT, acknowledged rows
disappeared.

The fix is one line in the GC floor calculation: cut at `in_memory.min(stored)`, where `stored`
is read from the durable manifest in the bucket. Flipping `gc_durable_mark: false` in M3
reproduces the data-loss trace immediately.

### C2: sealing a slot GC just freed

When a node takes over a range from a dead leader, it seals the old incarnation's shared log by
reading the log's GC floor and probing forward for the first empty sequence slot. In C2, the taker
reads the floor, the old leader — still alive as a zombie — runs a GC pass that advances the floor
and deletes the first WAL object, and the taker probes from its stale floor. It lands the seal on
the slot GC just freed, *below* the new floor, sees no objects ahead of it, and drops the old WAL
segment with acknowledged writes still in it.

This breaks even when clocks are healthy: the acknowledged write happened before the old session
died; the zombie only ran GC. The fix is to reread the floor after writing the seal and retry if
it moved past the seal's slot.

### The forgotten seal (found by M3 itself)

When a dead incarnation's shared log was completely flushed and no owner record listed it anymore,
`LogStore::forget` cleaned up the whole log — including the seal object. Under healthy clocks that
was safe, because the dead leader's lease grant had already expired.

When we ran M3 with the clock assumption disabled (`Fences::NO_CLOCK`), the checker found a short
counterexample: a zombie whose clock stopped or ran slowly, and whose stream had not written since
being sealed, woke up *after* `LogStore::forget` removed the seal. It executed a create-only PUT
into the exact slot where the seal used to sit, succeeded, and acknowledged a write into a log the
cluster had already forgotten.

The fix was to keep the seal object and write a `forgotten` marker next to it — two tiny objects
left behind per dead log — so the fence lives in the bucket instead of depending on node clocks.

A model is still only a hypothesis about the code. If someone changes the event order in the server
without updating the model, the two drift apart. `M2` and `M4` narrow that gap by calling the real
Rust decision cores (`cairn-split` and `cairn-lifecycle`), which are pure functions with no I/O,
and a source lint rejects status transitions or range-table CASes outside their shells.

## 2. Deterministic simulation, enforced by clippy

Protocol models abstract away serialization, Tokio task scheduling, SlateDB's background tasks,
flow control and HTTP plumbing. To test the real cluster code together,
`crates/cairn-server/tests/sim_cluster.rs` runs a three-node cluster against a shared in-memory
bucket inside a **single thread**:

- a `current_thread` Tokio runtime with paused time (`start_paused`);
- every range engine running inline on that runtime's `LocalSet`;
- SlateDB's compaction and GC spawned onto the same runtime through a spawn hook in our fork;
- node-to-node and node-to-SDK HTTP routed straight into each receiver's router through
  `netfilter::LocalNet`, with no sockets.

One `splitmix64` generator drives the whole universe: wall clock, process IDs, random bytes,
network outcomes (deliver, drop, delay, hold and release), store latency and errors, workload
shapes, and a fault **swarm** that turns individual failure classes on or off per seed. One swarm
dimension injects a crash right inside the SlateDB library gap — after an SST lands in the bucket
and before the manifest is written.

Determinism breaks the moment any crate calls `SystemTime::now()` or iterates over a standard
`HashMap` with a random seed. Rather than relying on code review,
[`clippy.toml`](https://github.com/cairnflowdev/cairnflow/blob/main/clippy.toml) rejects
nondeterminism sources across the workspace:

```toml
disallowed-methods = [
  { path = "std::time::SystemTime::now", reason = "wall-clock time goes through `cairn_store::entropy::now`/`now_ms` (the simulation installs virtual time)" },
  { path = "std::time::Instant::now", reason = "the monotonic clock is `tokio::time::Instant` (the simulation runs tokio's virtual clock)" },
  { path = "std::process::id", reason = "the pid goes through `cairn_store::entropy::process_id`" },
  { path = "getrandom::fill", reason = "random bytes go through `cairn_store::entropy::fill`" },
  { path = "reqwest::RequestBuilder::send", reason = "outbound HTTP requests go through `egress::send` (the simulation routes them through `netfilter::LocalNet`)" },
  # …
]

disallowed-types = [
  { path = "std::time::Instant", reason = "the monotonic clock is `tokio::time::Instant` (the simulation runs tokio's virtual clock)" },
  { path = "std::collections::HashMap", reason = "random hasher per process: use `cairn_store::entropy::HashMap` (fixed keys under the simulation) or `BTreeMap`" },
  { path = "std::collections::HashSet", reason = "random hasher per process: use `cairn_store::entropy::HashSet` (fixed keys under the simulation) or `BTreeSet`" },
  { path = "std::hash::RandomState", reason = "random keys per process: use `cairn_store::entropy::HashState`" },
  # …
]
```

`scripts/lint-sources.sh` adds the checks Clippy cannot express, such as bare `sleep(…).await` in
background loops and SlateDB builders that are not seeded from `cairn_store::entropy`.

Every simulation seed runs four phases:

1. **Fault phase:** cross-range invocations and flaky handlers run under injected store errors,
   dropped messages, node kills, ambiguous conditional writes and flow-control limits.
2. **Healing phase:** faults stop and killed nodes can revive.
3. **Liveness phase:** the clock advances until no work is pending — every invocation settled,
   every range led, no split/merge intent left behind — and every `Flaky` invocation that paused
   at `maxAttempts` actually delivered all `maxAttempts` turns to the SDK.
4. **Verification:** the cluster shuts down and runs a full `cairn-ctl verify` over the bucket.

When a seed fails, the harness automatically **shrinks** it along the swarm dimensions to find the
smallest set of faults that still breaks, and prints a ready-to-paste `#[test]`. Under
`RUSTFLAGS="--cfg tokio_unstable"`, the same seed produces the exact same event trace hash, byte
for byte — including Tokio's `select!` scheduling.

```sh
CAIRN_SIM_SEEDS=64 cargo test -p cairn-server --features testkit --test sim_cluster
```

## 3. 160 named failpoints and ambiguous S3 writes

Simulation finds unexpected interleavings. When we already know a dangerous boundary — the gap
between a winning range-table CAS and writing its history entry, or between flushing a commit and
marking it durable — we want a deterministic test that stops the thread *right there*, every time.

`crates/cairn-store/src/failpoint.rs` registers **160 named failpoints** using the `fail` crate
(compiled out completely unless `--features failpoints` is enabled, so release binaries carry
nothing). Tests pause one specific node at a boundary, let another node race past it, and resume
it using channels rather than `sleep`.

Branches that must never execute carry **tripwires** — failpoints placed directly on the forbidden
path so tests and chaos runs can arm them with `panic`:

- `flow::second_live_permit` — granting a concurrency permit to an invocation that already holds
  one;
- `flow::lock_released_by_non_holder` — releasing a virtual-object lock held by another
  invocation;
- `coordinator::ack_after_expire` — acknowledging a session heartbeat after issuing an `expired`
  CAS for that session.

On top of failpoints, we test one S3 quirk across the entire cluster test suite: **ambiguous
conditional writes**.

The object-store client retries `5xx` responses automatically, including on conditional PUTs. If
the first attempt actually landed on S3 before a proxy timed out, the retry returns
`PreconditionFailed` or `AlreadyExists`. A node that takes that error at face value concludes it
lost a lease or a table update that it actually won.

Cairnflow resolves every ambiguous conditional write by reading the object back and comparing it
with what it meant to write. To make sure no caller forgets, running any cluster test with
`CAIRNFLOW_TEST_FAULTS=each-once` makes the first write or delete of every `(operation, path)` pair
succeed on the store and then returns the client retry's misleading error to the caller:

```sh
CAIRNFLOW_TEST_FAULTS=each-once cargo test -p cairn-server --test split
CAIRNFLOW_TEST_FAULTS=each-once+nodewal cargo test -p cairn-server --test split
```

The second command applies the same ambiguity injection to shared-WAL objects as well. Every new
conditional write added to the codebase must pass under it.

## 4. Testing the tests: verify-on-drop, contracts and safety mutants

Three smaller mechanisms catch blind spots in the test suite itself:

**Verify on drop.** Cluster tests never create a bare in-memory bucket; they call
`common::bucket()`. When the test finishes and the bucket drops, it automatically runs
`cairn-ctl verify` and fails the test on any finding that no background loop heals — a leaked
range database, a dangling ancestor reference, a range table with a gap, or an orphan owner
record. Any test that deliberately leaves debris has to declare `bucket.allow(check, reason)`.
The same checks run read-only in production as the background scrubber (`--scrub-every-s`).

**Library and store contracts.** Cairnflow's safety rests on specific guarantees from SlateDB,
`object_store` and the S3 backend. Each assumption is pinned by a contract test:

- `library_contracts.rs` pins SlateDB and `object_store` semantics — for instance, that
  `flush_with_options(MemTable)` only returns *after* the manifest PUT lands, that a clone writes
  the child manifest before creating ancestor checkpoints, and that prefix `LIST` matches whole
  path segments (so deleting `ranges/1` can never match `ranges/10/…`).
- `s3_store_contract.rs` runs against a real bucket and checks read-after-write, list-after-write,
  conditional PUTs under versioning, and atomic PUTs under `kill -9`. Checks like these are how we
  caught Garage v1.0.1 overwriting on conditional create and a local erasure-coded MinIO tearing a
  lease object mid-update — and why a node probes its store at startup and refuses to run on one
  that fails (detailed on the [object stores page](/docs/self-hosting/storage)).

**Mutation testing of safety checks.** `scripts/mutants.py` holds 15 targeted one-line mutations
that each disable a specific safety check in the real codebase — changing `in_memory.min(stored)`
back to `in_memory`, skipping the range-table version re-check right before deleting a retired
database, skipping the lease validity check before acknowledging a commit, or letting `trash.rs`
delete a still-live range. The script applies one mutant at a time, runs the tests expected to
catch it, restores the file, and exits non-zero if any non-equivalent mutant survives.

## 5. Chaos on a real object store

Models and simulations run in memory. The final layer runs real `cairnflow` processes against a
real S3-compatible store.

`harness/chaos/chaos.ts` starts a multi-node cluster on SeaweedFS, drives steady load — including
cross-range call trees, sagas, fan-outs, artifacts, logs and a payment-style `--workload billing`
that checks its own ledger against a mock gateway — and kills nodes with `kill -9` on a timer.
Optional flags interleave continuous range splits and merges (`CHAOS_SPLIT_EVERY_S`), arm random
failpoints on live nodes over `POST /admin/failpoints`, restart the SDK endpoint to drop its
replay cache, and enable the SST disk cache across restarts.

In our longest soak so far:

- **24 hours**, three `cairnflow` nodes, real single-process SeaweedFS with injected request
  faults and latency;
- **5,231 `kill -9`s** — one node killed every 10 seconds — plus backups and restores every 15
  minutes and a full consistency check every 5 minutes;
- **701,034 acknowledged results** checked afterwards: **0 lost, 0 wrong**, and the range table
  returned cleanly to rest once faults stopped.

You can run the same harness locally against Docker SeaweedFS:

```sh
scripts/dev-store/up.sh                      # SeaweedFS on localhost:18333 (Docker)
cargo build --bin cairnflow
CHAOS_STORE_URI=s3://walbench/chaos-$RANDOM CHAOS_DURATION_S=600 \
  node harness/chaos/chaos.ts
```

## What this still does not prove

Listing five testing layers can make a beta runtime sound finished. It is not. Here are the edges
we have not closed yet:

- **The 24-hour soak ran on a single-process SeaweedFS.** We injected request faults and latency,
  but we have not yet run equivalent 24-hour soaks on distributed SeaweedFS, AWS S3 under real
  regional degradations, or S3 Express One Zone.
- **Models still depend on their environment.** Even where `M2` and `M4` run production Rust
  decision cores, the async shells around them are still abstracted. A bug in the shell outside
  the modelled steps will not be seen by Stateright — which is why simulation, failpoints and
  chaos sit beneath it.
- **Simulation is bounded by seeds and budgets.** Exhaustive model checks bound the number of
  ranges, incarnations and writes; deterministic simulation only checks the seeds we actually run;
  the 15 safety mutants only guard the checks we explicitly listed.
- **Synthetic workloads are not production workloads.** Real applications combine tenant limits,
  strange payloads, slow providers, proxy timeouts and operational mistakes in ways a test harness
  rarely invents first.

That is why Cairnflow is `v0.1.0-beta.0` and why we recommend turning on bucket versioning on any
cluster you care about.

Every layer described here lives in the public repository, and
[`docs/testing.md`](https://github.com/cairnflowdev/cairnflow/blob/main/docs/testing.md) has the
exact commands to run them yourself. If you want to try the runtime on your own machine, the
[quickstart](/docs/quickstart) takes two minutes — or [join the Cairnflow Cloud waitlist](/#pricing)
if you would rather let us run the nodes.
