A couple of days ago I wrote about Ferrous, which tries to push more of Rust's compile-time guarantees into .NET: Result<T, TError>, discriminated unions, typestates, data-owning locks, and Clippy-style lints.

That catches a lot of bugs at build time, which is great, but plenty of distributed-systems bugs compile cleanly and pass unit tests. Two nodes drift apart on the clock. A network partition drops traffic in one direction only. A Task.Delay fires in an unexpected order. A host crashes between File.WriteAllBytesAsync and fsync. Those bugs show up once a month in production, almost never reproduce locally, and turn integration test suites into flaky retry loops.

In Rust, libraries like MadSim (following FoundationDB's lead) tackle this with deterministic simulation testing (DST). You run an entire multi-node system inside a single-threaded, seed-driven simulator. Time, randomness, task scheduling, networking, and disk durability all derive from one ulong seed. If a race condition or split-brain bug trips on seed 481516, it trips on seed 481516 every time, on any machine, in milliseconds.

I wanted that in .NET too, so I built Faultline for .NET 10 and .NET 11.

Reproducible Confidence

In Impossible Mission: Reviewing PRs in the Agentic Coding Era and the Ferrous post, I split confidence in code you didn't read line by line into the compiler and the test suite. Ferrous covers the compiler side. Faultline covers the flaky distributed-systems tests that normally make people hit "re-run" in CI and move on.

Flaky tests are especially bad for coding agents. When a concurrent test fails once in fifty runs because of a ThreadPool timing quirk, an agent has no way to tell whether its last edit broke something or the runner just stuttered.

With Faultline, a failure prints the exact ulong seed, the virtual timestamp, the step count, and the trailing event trace (and can export the full run to chrome://tracing / Perfetto JSON). You or an agent can replay that exact interleaving locally, fix the bug, and fuzz a couple hundred more seeds before opening a PR.

Zero Production Footprint

The hard part of bringing DST to .NET is existing code. DateTime.UtcNow, Stopwatch.GetTimestamp, Task.Delay, Task.Run, Random.Shared, Guid.NewGuid(), HttpClient, Socket, and File are baked into the BCL. Nobody is going to thread custom abstractions through a decade of C# services just to run a simulation.

So production projects never reference Faultline. Instead, Faultline.Rewriter (built on AsmResolver.DotNet with bundled MSBuild buildTransitive targets) instruments your compiled assemblies post-build in the test output directory. It rewrites calls to:

  • Time and timers: DateTime, DateTimeOffset, Stopwatch, Environment.TickCount/TickCount64, TimeProvider.System, PeriodicTimer, System.Threading.Timer, Task.Delay, and CancellationTokenSource timeouts.
  • Scheduling: Task.Run, Task.Factory.StartNew, and ThreadPool.QueueUserWorkItem.
  • Randomness: Random.Shared, new Random(), Guid.NewGuid(), Guid.CreateVersion7(), and RandomNumberGenerator.Fill/GetBytes.
  • Networking and DNS: HttpClient, SocketsHttpHandler, Dns, TcpClient, TcpListener, and Socket.
  • Storage: System.IO.File and FileStream.

Rewritten DLLs are stamped with [assembly: FaultlineRewrittenAttribute] so incremental builds skip them. Outside a SimWorld (for example, in regular unit tests in the same test assembly), every hook checks SimContext.IsSimulating and falls straight through to the real BCL.

How a Simulation Runs

SimWorld and SimEngine run the whole cluster on one thread. Ready continuations are drained in a seeded order using Xoshiro256** (SimRandom), so different seeds explore different task interleavings. When no continuations are ready, virtual time jumps straight to the next scheduled event. Multi-minute timeouts and election intervals finish in microseconds. If both queues empty while the scenario is still incomplete, Faultline throws SimDeadlockException with the seed.

Each virtual host gets its own SimClock (with configurable offset and linear ppm drift), forked RNG, virtual IPv4 address, and SimFileSystem. Host affinity flows across await boundaries via AsyncLocal<SimHost>, so unmodified code calling DateTime.UtcNow or HttpClient automatically sees its own host's skewed clock and virtual network:

using Faultline;

var world = new SimWorld(new SimWorldOptions { Seed = 42 });

world.Run(async sim =>
{
    var api = sim.AddHost("api", async host =>
    {
        using var listener = host.Listen(80);
        await MyServer.ServeAsync(listener, host.ShutdownToken);
    }, clockOffset: TimeSpan.FromSeconds(4), clockDriftPpm: +100);

    sim.AddHost("caller", async _ =>
    {
        // Unmodified code using HttpClient, DateTime.UtcNow, Task.Delay, Random.Shared, File.*
        var ok = await MyClient.FetchAsync("http://api/ping");

        sim.Network.Partition("caller", "api");
        await sim.DelayAsync(TimeSpan.FromMinutes(5)); // runs in microseconds
        sim.Network.HealAll();
    });

    await sim.DelayAsync(TimeSpan.FromMinutes(15));
});

On top of the core loop, Faultline includes an in-memory SimNetwork (TCP and UDP with latency, jitter, drops, duplication, out-of-order datagrams, bandwidth limits, symmetric or one-way partitions, and host.Crash() / Restart() with TCP RSTs), a Kestrel virtual transport in Faultline.AspNetCore (services.AddFaultlineTransport(host)), and SimFileSystem for per-host storage with explicit fsync durability, crash-loss of unflushed writes, and configurable torn writes (TornWriteProbability).

The repo ships two end-to-end samples that exercise these together: a 3-node Raft-style leader election cluster (Faultline.Samples.LeaderElection) and a checksum-framed write-ahead log (Faultline.Samples.WriteAheadLog) with torn-tail recovery.

Analyzers, Testing, and dotnet fl

Some non-deterministic calls can't be safely virtualized by IL rewriting: new Thread, Parallel.* and PLINQ, Thread.Sleep, P/Invoke, and GC.Collect or finalizers. Faultline.Analyzers (FL0001 through FL0007) catches those at compile time. Hard escapes default to warnings, while FL0005 (unsafe) and FL0007 (ConfigureAwait(false)) default to Info so high-performance libraries still build cleanly under TreatWarningsAsErrors unless you opt in via .editorconfig.

Faultline.Testing adds SimRunner (Explore, Replay, AssertDeterministic) and an xUnit [SimSeeds] attribute. If you want to see how a codebase holds up before adding any packages, Faultline.Tool installs as dotnet fl:

dotnet tool install -g Faultline.Tool

# Scan a repo for non-deterministic escapes (FL0001-FL0007)
dotnet fl audit ./src

# List every BCL call site Faultline.Rewriter will intercept
dotnet fl inspect ./bin/Release/net10.0/MyService.dll

# Fuzz a simulation test project across 200 seeds
dotnet fl fuzz ./tests/MyApp.Tests/MyApp.Tests.csproj --seeds 200

# Replay a failing seed with trace logging enabled
dotnet fl replay ./tests/MyApp.Tests/MyApp.Tests.csproj --seed 481516 --filter RaftElectionTests

To test the analyzers and rewriter against real C# code, I ran a sweep across six open-source .NET repositories, including Polly, DotNext, NATS.Net, LiteDB, and Ferrous. dotnet fl audit scanned 2,599 C# files in under 10 seconds with zero crashes, and Faultline.Rewriter covered 721 of 721 tracked BCL call sites.

Packaging and What's Next

Faultline dogfoods Ferrous.Analyzers in src/ and uses dotnet fe doc to generate its API docs. Like Ferrous, the library packages multi-target net10.0 and net11.0 (with .NET 11 Runtime Async enabled) and enforce a 90% per-package line coverage floor in CI.

v0.3.2 is on NuGet across six packages (Faultline, Faultline.AspNetCore, Faultline.Rewriter, Faultline.Testing, Faultline.Analyzers, and Faultline.Tool). The docs are at faultline.westness.cc, and the source is at github.com/bradwestness/Faultline.

On the roadmap ahead of v1.0.0: automatic seed shrinking for minimal failure timelines, HTTP/2 and grpc-dotnet streaming over SimNetwork, UdpClient virtualization, and prebuilt chaos profiles for rolling restarts and clock-skew storms. If you're tired of chasing flaky timing bugs in .NET, run dotnet fl audit on one of your repos and see what turns up.