{"slug": "you-can-sim-everything", "title": "You Can SIM Everything", "summary": "A developer building the Fiber payment-channel network on Nervos used AI coding agents to set up deterministic simulation testing (DST) with Tokio's turmoil library, after finding that AI code reviews and AI-written unit tests kept surfacing new bugs on each pass. The DST harness places clocks, I/O and randomness inside a simulated environment, injects faults such as delayed peer responses, random offline drops and unexpected crashes, and drives every random choice from a PRNG so a failed run can be reproduced from the commit ID and seed. The developer reports that each bug an AI review catches can be converted into a new fault injection or random scenario, so the test suite compounds rather than accumulating isolated unit tests.", "body_md": "# You Can Sim Everything\n\n## Endless AI Reviews\n\nSince 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.\n\nWork 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.\n\nIf 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.\n\nWith subscription token limits continuing to shrink, I needed a tool that can reliably catch bugs on its own instead of leaning on AI reviews.\n\n## Deterministic Simulation Tests\n\nDST 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.\n\nThe 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.\n\nWith 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.\n\n## In Practice\n\nThe 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.\n\nI 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.\n\n```\n#[cfg(all(feature = \"simulation\", not(target_arch = \"wasm32\")))]\ncrate::simulation::before_actor_message(myself.get_id()).await;\n```\n\nThat 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.\n\nNext, 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.\n\nWhile 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.\n\nSix 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.\n\nThe only thing we learn from history is that we learn nothing from history.\n\nWe can, however, learn from Git history.\n\nSo 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?\n\nBased 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.\n\n## Dealing with AI Hallucinations\n\nAs 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.\n\nTake 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.\n\n```\n/// Register the output queue for a simulated TCP link.\n#[cfg(all(feature = \"simulation\", not(target_arch = \"wasm32\")))]\nRegisterSimulatedPeer {\n    pubkey: Pubkey,\n    sender: crate::simulation::SimulatedPeerSender,\n    features: FeatureVector,\n    reply: RpcReplyPort<Result<(), String>>,\n},\n/// Resume channels after the simulated peer link is ready.\n#[cfg(all(feature = \"simulation\", not(target_arch = \"wasm32\")))]\nActivateSimulatedPeer(Pubkey, RpcReplyPort<Result<(), String>>),\n/// Disconnect channels from the simulated peer.\n#[cfg(all(feature = \"simulation\", not(target_arch = \"wasm32\")))]\nUnregisterSimulatedPeer(Pubkey),\n```\n\nTo deal with this, I borrowed a few tricks from code-review skills that guard against hallucinations:\n\nEach 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:\n\n1. Does the simulation entry point actually reach the real business logic?\n2. Do fault injections actually fire during the expected window?\n3. When the business logic breaks, does the corresponding invariant check actually fail?\n\nEvery 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.\n\nEven 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.\n\n```\nBuilder (writes DST)\n   |  X  no chat history / no self-justification\n   v\nFresh Reviewer(s) (read-only)\n   +-- real logic : sim entry -> real business code\n   +-- faults     : fault points fire in expected window\n   +-- invariants : predict which assertion catches a bug\n   v\nScript Check & Isolated Sabotage\n   +-- Verify format, real path:line & required checks\n   +-- Mutate 1 line in worktree -> build -> rerun DST\n         |-- Predicted assertion fails -> verified\n         |-- Still green               -> coverage gap\n         +-- Unrelated panic           -> unverified\n```\n\nThe best way to push hallucinations down even further is to keep generalizing real bugs back into DST:\n\nWhenever 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.\n\n```\nReal Bug (review / incident / user report)\n   |\n   v\nWhy did DST miss it?\n   |\n   +-- Generalizable ------> Add fault / scenario / invariant\n   |                         --> Reproduce (red) -> Fix code (green)\n   |                         --> Wire into random-seed loop\n   |\n   +-- Not generalizable --> Write a fixed test\n```\n\n## You can sim everything\n\nDistributed 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.\n\nI 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:\n\n**Do NOT write new unit tests**: Never add new unit tests unless explicitly asked.\n**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.\n\nYou can sim everything.\n\n## References\n\n- TigerBeetle’s [Simulation Testing For Liveness](https://tigerbeetle.com/blog/2023-07-06-simulation-testing-for-liveness/)\n- [jjyr/dst](https://github.com/jjyr/dst)\n\nTranslated by gemini-4-neon-medium.", "url": "https://wpnews.pro/news/you-can-sim-everything", "canonical_source": "https://jjylab.com/en/posts/you-can-sim-everything/", "published_at": "2026-12-01 14:59:12+00:00", "updated_at": "2026-12-01 15:18:43.726263+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "ai-products"], "entities": ["Fiber", "Nervos", "Tokio", "turmoil", "TigerBeetle"], "also_reported_by": [], "takeaway": "Replace sprawling AI-written unit tests with deterministic simulation testing: run the system under randomly injected faults driven by a PRNG so any failure reproduces from a commit ID and seed, and convert each bug an AI review finds into a new fault scenario.", "recommendation": {"advice": "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.", "playbook": "evals-testing", "playbook_url": "https://wpnews.pro/playbooks/evals-testing"}, "alternates": {"html": "https://wpnews.pro/news/you-can-sim-everything", "markdown": "https://wpnews.pro/news/you-can-sim-everything.md", "text": "https://wpnews.pro/news/you-can-sim-everything.txt", "jsonld": "https://wpnews.pro/news/you-can-sim-everything.jsonld"}}