# You Can SIM Everything

> Source: <https://jjylab.com/en/posts/you-can-sim-everything/>
> Published: 2026-12-01 14:59:12+00:00

**Recommendation:** When AI reviews and unit tests keep finding new bugs, wrap clocks, I/O and randomness in a simulated environment with Tokio's turmoil, inject faults from a PRNG seed, and turn each caught bug into a reusable fault scenario.
More in the playbook "Evals and testing for LLM apps": <https://wpnews.pro/playbooks/evals-testing>

# You Can Sim Everything

## Endless AI Reviews

Since I started using AI, I’ve enjoyed using it most on side projects. Without strict testing or conventions to worry about, I can just enjoy the feeling of features pouring out.

Work projects are a different story. We still have to care about software engineering and make sure every release behaves properly, and that’s where AI starts to struggle. AI code reviews can catch plenty of bugs, yet they quickly turn into a slog: every pass turns up a bunch of issues, and fixing them just leads to even more issues on the next pass. Meanwhile, the unit tests AI writes are full of holes, packed with wrong assumptions and useless checks.

If we need stricter guarantees around implementation details and program state, all AI can do is write more unit tests to try to cover every state. The problem is that it’s hard to be sure those tests actually work, and reviews still find bugs anyway.

With subscription token limits continuing to shrink, I needed a tool that can reliably catch bugs on its own instead of leaning on AI reviews.

## Deterministic Simulation Tests

DST stands for Deterministic Simulation Testing. A few years ago, I read a post from TigerBeetle about how they use DST to keep their software reliable, then completely forgot about it until the term popped up on Twitter again. With agents around now, it felt like the right time to actually try it. Building a DST setup used to eat up too much engineering time, whereas with agents it only costs some tokens, and it sounded like the exact fix for my problem.

The way I think about DST is simple: put external dependencies like clocks, I/O, and randomness inside a simulated environment, inject faults on purpose, and run all kinds of scenarios through the software. Because each scenario runs alongside multiple randomly injected faults, we can check whether the system still holds its invariants under unexpected combinations of failures. Everything random in the simulation - which fault fires and when - is driven by a PRNG. So whenever a run fails, all we need is the commit ID and the seed to reproduce it deterministically.

With DST, we don’t have to maintain a huge pile of unit tests to cover every path. DST mixes and matches faults randomly, which is hard to do with unit tests. It’s also much easier to maintain over time: whenever an AI review catches a bug, we can take whatever generalizes and turn it into a new fault injection or random scenario in DST. That way, each bug fix doesn’t just add one isolated test - it adds a test that compounds with every other fault scenario, letting the test suite grow cleanly alongside the project.

## In Practice

The first project I tried this on was [Fiber](https://github.com/nervosnetwork/fiber). Fiber is a payment channel network where nodes talk over P2P, run complex protocols to execute transactions, and have to defend against Byzantine attacks. All the ways those things can fail together make it a natural fit for DST.

I asked an agent to analyze the codebase. It suggested using Tokio’s turmoil to simulate network faults and adding a few fault-injection hooks into our own code. Most of the simulation code lives in a separate crate, while the existing codebase just needs a handful of hooks for simulation mode.

```
#[cfg(all(feature = "simulation", not(target_arch = "wasm32")))]
crate::simulation::before_actor_message(myself.get_id()).await;
```

That change was about what I expected. Those external boundaries rarely move, while most day-to-day churn happens in the protocol interactions and business logic.

Next, I had the agent inject faults into P2P communication and protocol exchanges, like making peers deliberately delay responses, drop offline at random, or crash unexpectedly.

While running DST across random seeds, the agent kept hitting bugs in the simulation harness itself (the code driving the simulation). Luckily, it spotted that the harness was at fault and fixed it right away. After that, it surfaced 6 real state-handling bugs in Fiber.

Six bugs was way fewer than I expected. The faults we were injecting were still pretty basic, and we weren’t checking many invariants yet. So what faults should we inject next, and what state checks were we missing? I figured maybe we could learn something from history.

The only thing we learn from history is that we learn nothing from history.

We can, however, learn from Git history.

So I had the agent scan Fiber’s last 100 commits, pull out the bug fixes, and group them by failure type. I wanted to know: could our current DST setup actually catch the bugs we’d already run into in the past?

Based on those past bugs, the agent added several new fault types and tuned the injection strategy. After that round, the number of bugs it reported jumped to around 20.

## Dealing with AI Hallucinations

As I had the agent keep fleshing out DST, I noticed it would sometimes hallucinate badly and build “fake simulations”: we wanted to test a piece of real protocol logic, and the agent ended up mocking that logic away too. Sometimes it caught and fixed these mistakes during later reviews, yet a few bogus paths always slipped through and stayed in the codebase.

Take the code below. We should have been simulating at the P2P or network layer so we could exercise our actual protocol. Instead, the agent added special simulation-only hooks that completely bypassed things like the peer handshake.

```
/// Register the output queue for a simulated TCP link.
#[cfg(all(feature = "simulation", not(target_arch = "wasm32")))]
RegisterSimulatedPeer {
    pubkey: Pubkey,
    sender: crate::simulation::SimulatedPeerSender,
    features: FeatureVector,
    reply: RpcReplyPort<Result<(), String>>,
},
/// Resume channels after the simulated peer link is ready.
#[cfg(all(feature = "simulation", not(target_arch = "wasm32")))]
ActivateSimulatedPeer(Pubkey, RpcReplyPort<Result<(), String>>),
/// Disconnect channels from the simulated peer.
#[cfg(all(feature = "simulation", not(target_arch = "wasm32")))]
UnregisterSimulatedPeer(Pubkey),
```

To deal with this, I borrowed a few tricks from code-review skills that guard against hallucinations:

Each time, I bring in a fresh set of independent reviewer agents with no access to prior chat history. They only see the code and their assigned scope, and split up three checks based on codebase size:

1. Does the simulation entry point actually reach the real business logic?
2. Do fault injections actually fire during the expected window?
3. When the business logic breaks, does the corresponding invariant check actually fail?

Every claim has to cite a `path:line`, supporting evidence, and counter-evidence, and a script checks that the output format is valid and those line numbers actually exist.

Even fresh reviewers can be wrong, so I added a sabotage step on top. First, the reviewer predicts which assertion should fail if a specific line of business logic is broken. Then the coordinator mutates that single line in an isolated worktree, rebuilds, and reruns DST. Only when the predicted assertion actually fires do we count it as verified. If everything still passes, we’ve found a coverage gap.

```
Builder (writes DST)
   |  X  no chat history / no self-justification
   v
Fresh Reviewer(s) (read-only)
   +-- real logic : sim entry -> real business code
   +-- faults     : fault points fire in expected window
   +-- invariants : predict which assertion catches a bug
   v
Script Check & Isolated Sabotage
   +-- Verify format, real path:line & required checks
   +-- Mutate 1 line in worktree -> build -> rerun DST
         |-- Predicted assertion fails -> verified
         |-- Still green               -> coverage gap
         +-- Unrelated panic           -> unverified
```

The best way to push hallucinations down even further is to keep generalizing real bugs back into DST:

Whenever a new bug shows up in code review or production, I first ask the agent why DST missed it: was an external boundary left outside the simulation, was the right fault never injected, did random scenarios never hit that sequence of actions, or was an invariant missing? Whatever can be generalized gets turned into a reusable fault, scenario, or invariant and wired back into the random-seed loop so it naturally combines with existing faults.

```
Real Bug (review / incident / user report)
   |
   v
Why did DST miss it?
   |
   +-- Generalizable ------> Add fault / scenario / invariant
   |                         --> Reproduce (red) -> Fix code (green)
   |                         --> Wire into random-seed loop
   |
   +-- Not generalizable --> Write a fixed test
```

## You can sim everything

Distributed protocols like Fiber are classic DST territory, yet DST is still plenty useful outside complex distributed systems. I later brought it to [Canban](https://canban.dev), a UI-heavy desktop app, and it caught a bunch of real bugs in multi-machine communication and UI state refreshes there too.

I packaged this whole workflow into a [skill](https://github.com/jjyr/dst), so setting up DST on a project is pretty straightforward now. Once it’s in place, I add these two rules to the project’s `AGENTS.md` so agents default to this workflow during day-to-day development:

**Do NOT write new unit tests**: Never add new unit tests unless explicitly asked.
**DST-first & turn bug fixes into DST regressions**: Validate behavior through DST; when fixing a bug, reproduce it in DST via a scenario, injectable fault, or invariant, and record the failing seed.

You can sim everything.

## References

- TigerBeetle’s [Simulation Testing For Liveness](https://tigerbeetle.com/blog/2023-07-06-simulation-testing-for-liveness/)
- [jjyr/dst](https://github.com/jjyr/dst)

Translated by gemini-4-neon-medium.
