A validator can run for weeks before two ordinary operations land in one extraordinary order.
Certificate insertion starts. Garbage collection removes related state. Block sync checks an index halfway through the update. Each operation is valid on its own, yet their interleaving leaves storage describing a state that never should have existed.
Running the same test 10,000 times may find that race. Usually it does not. The operating system chooses the schedule, and operating systems are rather fond of repeating schedules that are fast and unsurprising.
snarkOS PR #4793 takes a better approach. It puts BFT storage under Shuttle, a randomized concurrency-testing library that controls when threads advance. PR #4795 pushes the same model into async BFT code by replacing Tokio with Shuttle's compatible implementation under a test-only configuration.
I like this direction a lot. Aleo does not need louder stress tests. It needs authority over the schedule.
Stress tests rent the scheduler
A normal concurrent test starts workers, feeds them operations, waits, then checks the result. The test controls the inputs. The host controls almost everything interesting between those inputs.
Suppose storage maintains certificate data across separate maps. One map indexes certificates by round. Another stores the certificate objects. Other structures track batch IDs and transmissions. An insertion may touch each structure in sequence while garbage collection removes old entries through another path.
A useful invariant might be:
Every certificate ID reachable through the round index
must resolve to a stored certificate.
The bad schedule is short:
insert: add certificate ID to round index
<context switch>
sync: read ID from round index
sync: look up certificate object and fail
<context switch>
insert: add certificate object
No unsafe Rust is required. Every map can be protected by a correct lock. The bug lives above those locks because the logical transaction spans several independently protected structures.
A stress test asks the kernel to interrupt insertion inside that narrow window. More CPU load may even make discovery less likely if one worker keeps a core long enough to finish the whole operation. Adding sleeps widens one guessed window, but sleep-based tests encode a theory about the race before the team knows which race exists. They are also slow and flaky.
Shuttle changes who makes the scheduling decision. Code runs through instrumented concurrency primitives, and Shuttle picks which runnable thread or task proceeds at each scheduling point. A test can execute the same scenario thousands of times under different choices rather than hoping Linux happens to be mischievous today.
The distinction is practical:
| Test style | Chooses inputs | Chooses interleavings | Replays failure | Proves correctness |
|---|---|---|---|---|
| Ordinary integration test | Test | Operating system | Rarely | No |
| Repeated stress test | Test | Operating system | Usually not | No |
| Shuttle random scheduler | Test | Shuttle | Yes | No |
| Bounded exhaustive model checking | Test | Checker | Yes | Only within the model and bounds |
Shuttle deliberately chooses scale over exhaustive search. Its random scheduler can run realistic tests that would explode under full schedule enumeration. The cost is plain: 50,000 passing schedules mean those schedules passed. They say nothing conclusive about schedule 50,001.
That is an honest trade.
Giving Shuttle control
Shuttle cannot control a lock it cannot see. Production code that imports parking_lot::Mutex directly will still let the host runtime decide what happens around that mutex.
PR #4793 adds a third backend to the lock abstraction in snarkos-utilities: normal builds can keep their existing lock implementation, while a --cfg shuttle build selects shuttle-parkinglot. The BFT storage test then runs under Shuttle's scheduler.
Conceptually, the selection looks like this:
#[cfg(shuttle)]
use shuttle_parkinglot::{Mutex, RwLock};
#[cfg(not(shuttle))]
use parking_lot::{Mutex, RwLock};
The exact abstraction matters more than the syntax. snarkOS already has a shared place from which code obtains locks. Adding a scheduler-aware backend there avoids scattering test-specific imports across consensus code.
PR #4795 has a harder job because Primary, BFT, and Sync are async. Their behavior depends on spawned tasks, channel wakeups, lock acquisition, timer expiry, and future polling order. Swapping only the mutexes would leave most of the schedule outside Shuttle's control.
Under --cfg shuttle, workspace crates name shuttle-tokio-impl as the package behind their tokio dependency. Normal builds retain regular Tokio. Existing code can therefore keep using familiar tokio paths while the test build routes supported runtime operations through Shuttle.
That package substitution is a strong architectural choice. Consensus code should not grow a forest of if testing { ... } branches. The alternate runtime belongs at the dependency boundary, where Rust's configuration system can select it without changing protocol logic.
There are limits. A compatibility layer must cover every primitive the test uses, and behavior outside those wrappers can reintroduce uncontrolled nondeterminism. Raw operating-system threads, wall-clock calls, filesystem timing, foreign libraries, or random values from an untracked source may escape the model. Shuttle even has an uncontrolled-nondeterminism check that replays schedules to detect some of these leaks.
A replayable scheduler only stays replayable when the test owns its sources of chance.
Storage is the first target
Storage is a sensible starting point because its invariants are concrete and its concurrency has already produced failures.
snarkOS PR #4790 addressed certificate insertion and removal across four maps: rounds, certificates, batch IDs, and transmissions. Updating those maps under separate critical sections allowed readers to observe partial state. Two callers could also pass a pre-insertion check before either completed its write.
Nearby fixes show the same family of problem. PR #4794 handles garbage collection advancing while check_batch_header checks certificates from a previous round. PR #4802 prevents a certificate from being stored after garbage collection removes a transmission that the caller expected storage to retain.
These are not exotic memory-model puzzles. They are legal operations crossing at a bad boundary.
A good Shuttle test should avoid asserting one preferred sequence of internal calls. That makes refactoring painful and tests implementation trivia. Assert state relationships instead:
shuttle::check_random(
|| {
let storage = make_storage();
let writer = spawn_insertions(storage.clone());
let collector = spawn_garbage_collection(storage.clone());
writer.join().unwrap();
collector.join().unwrap();
assert_storage_consistent(&storage);
},
10_000,
);
assert_storage_consistent is where the real value lives. It can check that every indexed certificate exists, every retained certificate has the transmissions it requires, reverse indexes agree with primary storage, and no certificate below the effective garbage-collection boundary remains visible through an index that promises live data.
I would also add operation-level outcomes. If insertion reports success, the certificate must be fully readable afterward unless a completed garbage-collection action legitimately removed it. A caller should never receive success for a half-installed object.
The test does not need to know whether the implementation uses one coarse lock, a transaction object, immutable snapshots, or carefully ordered locks. Developers remain free to change the mechanism while preserving the contract.
Async BFT raises the stakes
Storage races can corrupt the local view. Async races can decide when that bad view enters consensus behavior.
Primary receives proposals and certificates. Sync fills missing history. BFT ordering consumes DAG state and tries to build blocks. Timers trigger retries or round movement. Channels connect these components, and a lock can suspend one task while another changes the condition that task planned to act upon.
A test that controls only threads misses much of this. Tokio may poll one future several times, wake a blocked receiver, or expire a timer before another ready task runs. Each decision can move a validation check across a storage update.
PR #4795 is therefore more than build plumbing. Routing Tokio tasks, channels, and timers through Shuttle extends the schedule boundary around the BFT machine.
Consider the stale-subdag race discussed in Why Aleo Must Never Build a Block from Already-Committed Certificates. A validator assembled a candidate subdag while sync advanced the ledger. The candidate was valid against an earlier view but contained certificates the ledger had now consumed.
A scheduler-controlled regression test can make the dangerous order explicit without adding sleeps:
BFT: order candidate subdag
BFT: pause before ledger update boundary
Sync: commit overlapping certificates
Sync: publish the newer ledger state
BFT: resume and attempt candidate
BFT: reject stale candidate, reorder, then continue
The invariant is not "BFT always wins the race." Sync is allowed to win. The required behavior is that BFT notices its candidate became stale and does not commit already-consumed certificates.
That difference is easy to lose in ordinary tests. A test that waits for BFT first proves only the friendly schedule. A test that waits for sync first proves another friendly schedule. Shuttle can pause between the read and the consequential write, which is where the lion tends to find the bones.
Channels deserve equal suspicion. Sending a notification does not mean the receiver has processed it. Closing a sender can race with shutdown. A bounded channel can block while its consumer waits on a lock held by the producer. Timer tests add another trap because wall-clock delays hide ordering assumptions behind milliseconds.
With controlled time and task polling, tests can state protocol properties instead:
- A retry timer firing before sync completion must not discard the later sync result.
- Shutdown must release task ownership cycles and let the ledger drop.
- Duplicate certificate delivery must produce one coherent stored result.
- A stale block candidate must be rejected before ledger mutation.
Four properties. No ceremonial group of three.
Replay turns races into defects
Random scheduling finds the failure. Replay makes it fixable.
When a Shuttle execution panics, it prints an encoded schedule. Passing that schedule to shuttle::replay runs the same scheduling decisions again. A failure that once appeared in a staging validator after six hours can become a single local test execution.
shuttle::replay(
|| run_storage_gc_scenario(),
"910102ccdedf9592aba2afd70104",
);
The schedule should be retained with the CI artifact and, for an important regression, checked into a focused replay test or recorded beside the issue. Keep the randomized version too. The fixed schedule protects against the known failure; randomized runs search nearby schedules for the next one.
Replay also changes review. A pull request can include the failing schedule, show that the old code panics under it, then show that the patch preserves the invariant. Reviewers no longer need to accept "I ran it overnight and could not reproduce it" as evidence.
Schedule strings are not eternal protocol fixtures. Changes to task creation or synchronization points may make an old schedule inapplicable even when behavior remains correct. The durable asset is the small scenario plus its invariant. A saved schedule is a debugging instrument attached to that test, not consensus data.
What CI should run
One giant randomized test would be a mistake. Large scenarios create enormous schedule spaces and produce long traces that are unpleasant to diagnose.
I would split the suite by ownership boundary. Storage tests should cover insertion against removal, garbage collection against validation, and shared-transmission lifetime. Primary tests should focus on proposal state and duplicate messages. Sync tests should cover concurrent arrival, replacement, and retry behavior. A smaller end-to-end BFT test can then verify the contracts between those pieces.
Pull requests can run a modest number of random schedules with a fixed CI budget. Nightly jobs can increase iterations and mix schedulers. PCT is useful when failures require a small number of well-placed preemptions, while bounded DFS can fully cover tiny helper primitives. Random scheduling remains the practical default for larger BFT scenarios.
Every harness needs a step limit. Deadlock is a result worth reporting, but a runaway timer loop should not occupy a CI worker forever. Tests also need deterministic fixture generation, small committees, and minimal DAGs. Extra certificates multiply possible task behavior without improving an invariant that two certificates can already violate.
Passing CI still does not establish race freedom. Shuttle's own documentation is direct about the soundness-versus-scale tradeoff. Random exploration samples schedules; it does not enumerate every execution or model every hardware effect.
Keep the other layers. Run ordinary unit tests for deterministic logic. Use multi-validator integration tests for networking and persistence behavior. Run staging networks for realistic load. Use static lock-order analysis where it fits. Shuttle fills the missing space between a hand-written unit test and a production incident.
The earlier telemetry work made a related architectural point in Why Aleo Is Taking Telemetry Out of the BFT Hot Path: removing shared ownership can erase bad schedules rather than testing around them. Shuttle helps find the ownership boundaries that still permit trouble. The best fix may be one lock, a single-owner worker, an atomic storage transaction, or a fresh validation at the commit boundary.
A controllable scheduler does not make concurrency safe. It makes bad timing available on demand, with an invariant standing nearby to catch it. For validator software, that is a much better deal than waiting for production to pick the schedule.