diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2120c04..f71cf36 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -50,5 +50,14 @@ jobs:
dotnet pack src/EpochSim.Execution -c Release --no-build
dotnet pack src/EpochSim.Serialization -c Release --no-build
dotnet pack src/EpochSim.Observability -c Release --no-build
+ dotnet pack src/EpochSim.Testing -c Release --no-build
+ dotnet pack src/EpochSim.Analyzers -c Release --no-build
+
+ - name: Verify analyzer is packed
+ run: |
+ for pkg in src/EpochSim/bin/Release/EpochSim.[0-9]*.nupkg src/EpochSim.Analyzers/bin/Release/EpochSim.Analyzers.[0-9]*.nupkg; do
+ unzip -Z1 "$pkg" | grep -Fx "analyzers/dotnet/cs/EpochSim.Analyzers.dll" > /dev/null
+ unzip -Z1 "$pkg" | grep -Fx "analyzers/dotnet/cs/EpochSim.Analyzers.CodeFixes.dll" > /dev/null
+ done
dotnet pack src/EpochSim.Cli -c Release --no-build
dotnet pack src/EpochSim.All -c Release --no-build
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 2ededb1..27413f3 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -42,6 +42,8 @@ jobs:
dotnet pack src/EpochSim.Execution -c Release --no-restore
dotnet pack src/EpochSim.Serialization -c Release --no-restore
dotnet pack src/EpochSim.Observability -c Release --no-restore
+ dotnet pack src/EpochSim.Testing -c Release --no-restore
+ dotnet pack src/EpochSim.Analyzers -c Release --no-restore
dotnet pack src/EpochSim.Cli -c Release --no-restore
dotnet pack src/EpochSim.All -c Release --no-restore
diff --git a/.gitignore b/.gitignore
index 8638396..42c28c6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -419,4 +419,7 @@ FodyWeavers.xsd
# Misc
.idea/
-snapshots/
\ No newline at end of file
+snapshots/
+
+# Superpowers
+docs/superpowers/
\ No newline at end of file
diff --git a/Directory.Build.props b/Directory.Build.props
index 977c47b..fa9b122 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,6 +1,6 @@
- 0.2.2
+ 0.3.0
14.0
false
false
diff --git a/Directory.Packages.props b/Directory.Packages.props
index ba88a0c..455f893 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -4,10 +4,19 @@
-
+
+
+
+
+
+
+
+
+
+
diff --git a/EpochSim.slnx b/EpochSim.slnx
index 0b6e060..dd1d377 100644
--- a/EpochSim.slnx
+++ b/EpochSim.slnx
@@ -1,5 +1,7 @@
+
+
@@ -8,8 +10,10 @@
+
+
diff --git a/README.md b/README.md
index e05ab84..0e0b355 100644
--- a/README.md
+++ b/README.md
@@ -17,10 +17,11 @@ Run a simulation from a seed, record fingerprints and events, then verify, repla
A simulation that cannot be reproduced cannot be debugged. EpochSim fixes the inputs of every tick, so the same seed and the same commands always produce the same state, and a divergence can be located to a single tick.
+- **Find the seed that breaks your logic.** `Epoch.Fuzz` runs your simulation on thousands of seeds, returns the failing seed and tick, and shows which state fields changed.
- **Deterministic by construction.** A run is defined by its state, seed and ordered input. Systems execute in a fixed order on one simulation thread.
- **Run presets.** `QuickRun`, `RecommendedRun` and `DebugRun` cover smoke tests, production diagnostics and strict invariant hunting with one call.
- **Artifacts for every run.** Manifest, per-tick state fingerprints and an optional event log are written to disk and readable from code.
-- **Replay and bisect.** Verify a run against its recorded fingerprints and find the first tick where two runs diverge.
+- **Replay and bisect.** Verify a run against its recorded fingerprints and find the first tick where an invariant is violated.
- **Deterministic input.** `CommandInbox` and `ScheduledCommandInbox` feed commands from HTTP, UI or queues in a stable order.
- **Long-lived sessions.** `SimulationSession` supports games, servers and interactive stepping.
- **A CLI for the whole workflow.** Run, list, inspect, validate, replay, bisect and reproduce runs from the terminal.
@@ -67,6 +68,58 @@ Always call `run.RunTicks(engine, ...)` rather than `engine.RunTicks(state, ...)
More in [Embedding](docs/en/embedding.md).
+## Find bugs by seed
+
+`Epoch.Fuzz` runs the simulation on a range of seeds and checks invariants, exceptions and, optionally, determinism. Every failure comes with a seed that reproduces it and the state fields that changed on the failing tick.
+
+```csharp
+var report = Epoch.Fuzz(f => f
+ .State(() => new JobQueueState())
+ .Engine(e => e.AddSystem(new JobQueueSystem()))
+ .Invariants(() => [new QueueNonNegativeInvariant()])
+ .Seeds(1, 1000)
+ .Ticks(500));
+
+report.ThrowIfFailed();
+```
+
+```
+Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81
+
+[InvariantViolation] seed=4 tick=426
+ QueueNonNegative: Pending=-1
+ StateDiff:
+ $.Completed: 198 -> 200
+ $.Pending: 0 -> -1
+ Repro: .Seeds(4, 4).Ticks(426)
+```
+
+Add `.CheckDeterminism()` to run every seed twice and catch `static` state, wall-clock time and other sources of non-determinism. The same run from the terminal:
+
+```bash
+epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500
+```
+
+More in [Fuzzing](docs/en/fuzzing.md).
+
+## Testing
+
+`EpochSim.Testing` brings the same checks to xUnit, NUnit and MSTest without depending on any of them:
+
+```bash
+dotnet add package EpochSim.Testing
+```
+
+```csharp
+SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
+ .Seeds(1, 50)
+ .Ticks(200));
+```
+
+A failure names the seed, the tick and the changed state fields. More in [Testing](docs/en/testing.md).
+
## Run presets
| Preset | Fingerprint cadence | Mutation guard | Typical use |
@@ -181,6 +234,7 @@ Determinism debugging:
```bash
epochsim verify-run artifacts
epochsim bisect artifacts
+epochsim fuzz --adapter fuzzbug --seeds 1..1000
```
| Command | Purpose |
@@ -188,7 +242,8 @@ epochsim bisect artifacts
| `init`, `run` | Create a starter app, run it |
| `list-runs`, `inspect-run`, `pretty-inspect` | Browse and inspect recorded runs |
| `validate-run`, `verify-run` | Check artifacts and fingerprints |
-| `fast-replay`, `bisect`, `repro` | Replay a run, find the first divergence |
+| `fast-replay`, `bisect`, `repro` | Replay a run, find the first violation |
+| `fuzz` | Run many seeds, find the one that breaks |
| `event-stats`, `timeline`, `list-adapters` | Analyze events and list available adapters |
## What is included
@@ -200,7 +255,10 @@ epochsim bisect artifacts
| Input | `CommandInbox`, `ScheduledCommandInbox` with stable ordering. |
| Artifacts | Manifest, state fingerprints, event log, failure artifacts, profiling. |
| Serialization | JSON state serializer and message codec discovered from an assembly. |
-| Diagnostics | Mutation guard, invariants, replay verification, bisect. |
+| Diagnostics | Mutation guard, invariants, replay verification, bisect, field-level state diff. |
+| Analyzer | Roslyn rules ESIM001-ESIM006 flag wall-clock time, `Random`, threads and more in simulation code. |
+| Testing | `EpochSim.Testing`: `SimAssert` for any test framework, golden fingerprints. |
+| Fuzzing | `Epoch.Fuzz`: seed ranges, invariants, determinism check, reproducible failures. |
| CLI | `epochsim` .NET tool covering the whole run lifecycle. |
## Documentation
@@ -211,10 +269,12 @@ epochsim bisect artifacts
| [Artifacts](docs/en/artifacts.md) | Run directory layout and file formats |
| [Sessions](docs/en/sessions.md) | Long-lived loops and stepping |
| [Determinism](docs/en/determinism.md) | Rules that keep runs reproducible |
+| [Fuzzing](docs/en/fuzzing.md) | Finding failing seeds and reproducing them |
+| [Testing](docs/en/testing.md) | `SimAssert` for xUnit, NUnit and MSTest |
## Samples
-[QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs) is the minimal starting point. [Population](src/EpochSim.Samples/Population/) is an event-heavy domain with invariants and replay.
+[QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs) is the minimal starting point. [Population](src/EpochSim.Samples/Population/) is an event-heavy domain with invariants and replay. [Fuzzing](src/EpochSim.Samples/Fuzzing/) has a rare seed-dependent bug for `Epoch.Fuzz` to find.
## Build and test
diff --git a/README.ru.md b/README.ru.md
index ba599aa..8d42cb1 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -17,10 +17,11 @@
Симуляцию, которую нельзя воспроизвести, нельзя отладить. EpochSim фиксирует входы каждого тика: один и тот же seed и те же команды всегда дают то же состояние, а расхождение локализуется до одного тика.
+- **Поиск seed, на котором ломается логика.** `Epoch.Fuzz` прогоняет симуляцию на тысячах seed, возвращает сбойный seed и тик и показывает, какие поля состояния изменились.
- **Детерминизм по построению.** Прогон определяется состоянием, seed и упорядоченным входом. Системы выполняются в фиксированном порядке в одном потоке симуляции.
- **Пресеты запуска.** `QuickRun`, `RecommendedRun` и `DebugRun` закрывают smoke-тесты, диагностику в production и строгий поиск нарушений инвариантов одним вызовом.
- **Артефакты каждого прогона.** Манифест, fingerprint'ы состояния по тикам и необязательный лог событий пишутся на диск и читаются из кода.
-- **Replay и bisect.** Проверка прогона по записанным fingerprint'ам и поиск первого тика, на котором два прогона расходятся.
+- **Replay и bisect.** Проверка прогона по записанным fingerprint'ам и поиск первого тика, на котором нарушается инвариант.
- **Детерминированный ввод.** `CommandInbox` и `ScheduledCommandInbox` передают команды из HTTP, UI или очередей в стабильном порядке.
- **Долгоживущие сессии.** `SimulationSession` для игр, серверов и пошагового режима.
- **CLI для всего процесса.** Запуск, список, инспекция, валидация, replay, bisect и воспроизведение прогонов из терминала.
@@ -67,6 +68,58 @@ public sealed class WorldState
Подробнее в [Embedding](docs/ru/embedding.md).
+## Поиск багов по seed
+
+`Epoch.Fuzz` прогоняет симуляцию на диапазоне seed и проверяет инварианты, исключения и, по желанию, детерминизм. Каждый сбой приходит с seed, который его воспроизводит, и полями состояния, изменившимися на сбойном тике.
+
+```csharp
+var report = Epoch.Fuzz(f => f
+ .State(() => new JobQueueState())
+ .Engine(e => e.AddSystem(new JobQueueSystem()))
+ .Invariants(() => [new QueueNonNegativeInvariant()])
+ .Seeds(1, 1000)
+ .Ticks(500));
+
+report.ThrowIfFailed();
+```
+
+```
+Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81
+
+[InvariantViolation] seed=4 tick=426
+ QueueNonNegative: Pending=-1
+ StateDiff:
+ $.Completed: 198 -> 200
+ $.Pending: 0 -> -1
+ Repro: .Seeds(4, 4).Ticks(426)
+```
+
+Добавьте `.CheckDeterminism()`, чтобы прогонять каждый seed дважды и ловить `static`-состояние, системное время и другие источники недетерминизма. Тот же прогон из терминала:
+
+```bash
+epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500
+```
+
+Подробнее в [Fuzzing](docs/ru/fuzzing.md).
+
+## Тестирование
+
+`EpochSim.Testing` даёт те же проверки в xUnit, NUnit и MSTest, не завися ни от одного из них:
+
+```bash
+dotnet add package EpochSim.Testing
+```
+
+```csharp
+SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
+ .Seeds(1, 50)
+ .Ticks(200));
+```
+
+Сообщение о сбое называет seed, тик и изменившиеся поля состояния. Подробнее в [Testing](docs/ru/testing.md).
+
## Пресеты запуска
| Пресет | Каденция fingerprint | Mutation guard | Когда использовать |
@@ -181,6 +234,7 @@ epochsim inspect-run artifacts
```bash
epochsim verify-run artifacts
epochsim bisect artifacts
+epochsim fuzz --adapter fuzzbug --seeds 1..1000
```
| Команда | Назначение |
@@ -188,7 +242,8 @@ epochsim bisect artifacts
| `init`, `run` | Создать стартовое приложение, запустить его |
| `list-runs`, `inspect-run`, `pretty-inspect` | Просмотр и инспекция записанных прогонов |
| `validate-run`, `verify-run` | Проверка артефактов и fingerprint'ов |
-| `fast-replay`, `bisect`, `repro` | Replay прогона, поиск первого расхождения |
+| `fast-replay`, `bisect`, `repro` | Replay прогона, поиск первого нарушения |
+| `fuzz` | Прогон многих seed, поиск сбойного |
| `event-stats`, `timeline`, `list-adapters` | Анализ событий и список доступных адаптеров |
## Состав
@@ -200,7 +255,10 @@ epochsim bisect artifacts
| Ввод | `CommandInbox`, `ScheduledCommandInbox` со стабильным порядком. |
| Артефакты | Манифест, fingerprint'ы состояния, лог событий, артефакты сбоев, профилирование. |
| Сериализация | JSON-сериализатор состояния и кодек сообщений, находимых в сборке. |
-| Диагностика | Mutation guard, инварианты, проверка replay, bisect. |
+| Диагностика | Mutation guard, инварианты, проверка replay, bisect, полевой дифф состояния. |
+| Анализатор | Roslyn-правила ESIM001-ESIM006 ловят системное время, `Random`, потоки и другое в коде симуляции. |
+| Тестирование | `EpochSim.Testing`: `SimAssert` для любого тестового фреймворка, золотые fingerprint'ы. |
+| Fuzzing | `Epoch.Fuzz`: диапазоны seed, инварианты, проверка детерминизма, воспроизводимые сбои. |
| CLI | .NET-утилита `epochsim` для всего жизненного цикла прогона. |
## Документация
@@ -211,10 +269,12 @@ epochsim bisect artifacts
| [Artifacts](docs/ru/artifacts.md) | Структура каталога прогона и форматы файлов |
| [Sessions](docs/ru/sessions.md) | Долгоживущие циклы и пошаговый режим |
| [Determinism](docs/ru/determinism.md) | Правила, сохраняющие воспроизводимость прогонов |
+| [Fuzzing](docs/ru/fuzzing.md) | Поиск сбойных seed и их воспроизведение |
+| [Testing](docs/ru/testing.md) | `SimAssert` для xUnit, NUnit и MSTest |
## Примеры
-[QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs) — минимальная отправная точка. [Population](src/EpochSim.Samples/Population/) — событийный домен с инвариантами и replay.
+[QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs) — минимальная отправная точка. [Population](src/EpochSim.Samples/Population/) — событийный домен с инвариантами и replay. [Fuzzing](src/EpochSim.Samples/Fuzzing/) — редкий баг, зависящий от seed, для поиска через `Epoch.Fuzz`.
## Сборка и тесты
diff --git a/docs/en/determinism.md b/docs/en/determinism.md
index 182a6e6..e0015d9 100644
--- a/docs/en/determinism.md
+++ b/docs/en/determinism.md
@@ -11,6 +11,66 @@ EpochSim guarantees deterministic execution for identical inputs: initial state,
- thread races that change event order
- uncontrolled floating-point behavior
+## Analyzer
+
+`EpochSim` ships a Roslyn analyzer that turns these pitfalls into compiler warnings. It is included in the `EpochSim` package and also available alone as `EpochSim.Analyzers`. It reports constructs only inside simulation code, so the rest of your project is never touched.
+
+### What counts as simulation code
+
+- Lambdas and method groups passed to `SimulationEngine.AddSystem(...)` and `OnCommand(...)`.
+- Every method of a type that implements `ISystem<>`, `ICommandHandler<,>` or `IInvariant<>`.
+- Types and methods marked with `[Deterministic]` (`EpochSim.Kernel.Determinism`).
+
+Calls into other methods are not followed. Mark a helper with `[Deterministic]` to check it too.
+
+```csharp
+using EpochSim.Kernel.Determinism;
+
+[Deterministic]
+public static class Pricing
+{
+ public static int Roll(IRng rng) => rng.NextInt(1, 7);
+}
+```
+
+### Rules
+
+| ID | Default severity | Reports |
+| ------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------- |
+| ESIM001 | warning | `DateTime.Now/UtcNow/Today`, `DateTimeOffset.Now/UtcNow`, `Stopwatch`, `Environment.TickCount/TickCount64`, `TimeProvider.System` |
+| ESIM002 | warning | `new Random(...)`, `Random.Shared`, `RandomNumberGenerator`, `Guid.NewGuid()` |
+| ESIM003 | warning | `Task.Run`, `Task.Factory.StartNew`, `new Thread`, `ThreadPool.*`, `Parallel.*`, `AsParallel()`, `async` lambdas, `await` |
+| ESIM004 | warning | `GetHashCode()` on `string` and `object`, enumeration of `ConcurrentDictionary`, `ConcurrentBag`, `ConcurrentQueue` |
+| ESIM005 | warning | `File.*`, `Directory.*`, `HttpClient`, `Environment.GetEnvironmentVariable`, `Environment.MachineName` |
+| ESIM006 | hidden | `foreach` and LINQ over `Dictionary<,>` and `HashSet<>` |
+
+ESIM006 is hidden by default: .NET enumerates these collections in a stable order for identical operations, so it is only fragile, not wrong. Raise it when you want the stricter check.
+
+### Configuring
+
+Use `.editorconfig`:
+
+```ini
+[*.cs]
+dotnet_diagnostic.ESIM001.severity = error
+dotnet_diagnostic.ESIM005.severity = none
+dotnet_diagnostic.ESIM006.severity = warning
+```
+
+A single occurrence can be suppressed with `#pragma warning disable ESIM001`.
+
+### Code fix
+
+ESIM002 offers a fix when a `TickContext<>` or `EventContext<>` parameter is in scope:
+
+| Before | After |
+| ----------------------------------- | -------------------------- |
+| `Random.Shared.Next(a, b)` | `ctx.Rng.NextInt(a, b)` |
+| `new Random(seed).Next(a, b)` | `ctx.Rng.NextInt(a, b)` |
+| `Random.Shared.NextDouble()` | `ctx.Rng.NextDouble01()` |
+
+The method-group check runs when the whole compilation is analyzed (a build). The IDE may show it only after a build.
+
## Recommended practices
- Use only `ctx.Rng` for domain randomness.
diff --git a/docs/en/fuzzing.md b/docs/en/fuzzing.md
new file mode 100644
index 0000000..ac2b71b
--- /dev/null
+++ b/docs/en/fuzzing.md
@@ -0,0 +1,138 @@
+# Fuzzing
+
+`Epoch.Fuzz` runs your simulation over a range of seeds and tells you which seed breaks it, on which tick, and which state fields changed on that tick. It finds three kinds of failure:
+
+- `InvariantViolation`: an `IInvariant` returned `false`.
+- `Exception`: a system or command handler threw.
+- `NonDeterminism`: two runs of the same seed produced different state (needs `CheckDeterminism`).
+
+Every failure is reproducible with the same seed.
+
+## Minimal example
+
+```csharp
+using EpochSim;
+
+var report = Epoch.Fuzz(f => f
+ .State(() => new JobQueueState())
+ .Engine(e => e.AddSystem(new JobQueueSystem()))
+ .Invariants(() => [new QueueNonNegativeInvariant()])
+ .Seeds(1, 1000)
+ .Ticks(500));
+
+Console.WriteLine(report.ToText());
+```
+
+Output:
+
+```
+Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81
+
+[InvariantViolation] seed=4 tick=426
+ QueueNonNegative: Pending=-1
+ StateDiff:
+ $.Completed: 198 -> 200
+ $.Pending: 0 -> -1
+ Repro: .Seeds(4, 4).Ticks(426)
+```
+
+In a test, call `report.ThrowIfFailed()` or use [EpochSim.Testing](testing.md).
+
+The runnable sample is in [src/EpochSim.Samples/Fuzzing](../../src/EpochSim.Samples/Fuzzing/): a job queue whose counter goes negative on a rare, seed-dependent sequence of draws from `ctx.Rng`.
+
+## Builder
+
+| Method | Required | Meaning |
+| ----------------------------------------- | -------- | ---------------------------------------------------------------------------------- |
+| `State(Func)` | yes | Factory for a fresh initial state. Called for every run. |
+| `Engine(Action>)` | yes | Registers systems and command handlers on a new engine. Called for every run. |
+| `Ticks(long)` | yes | Last tick of every run, inclusive. |
+| `Seeds(ulong from, ulong to)` | yes | Inclusive seed range. |
+| `Seeds(IEnumerable)` | yes | Explicit seeds. Use either overload. |
+| `Serializer(IStateSerializer)` | no | Used for fingerprints and diffs. Default: `JsonStateSerializer`. |
+| `Invariants(Func>>)` | no | Checked after every tick. A factory, so every run gets its own instances. |
+| `Commands(Action)` | no | Generates input commands for a seed. See below. |
+| `CheckDeterminism(bool)` | no | Run every seed twice and compare fingerprints after every tick. Default: `false`. |
+| `Parallelism(int)` | no | Concurrent runs. Default: `Environment.ProcessorCount`. |
+| `StopAtFirstFailure(bool)` | no | Stop handing out new seeds after the first failure. Default: `false`. |
+| `ArtifactsRoot(string)` | no | Write full run artifacts for failed seeds (at most the first 10, by seed). |
+| `EventCodec(IEventCodecV2)` | no | Adds the event log to those artifacts. |
+| `Progress(IProgress)` | no | Called after every finished seed. |
+
+Invalid values throw immediately: a missing required parameter, `Seeds` with `from > to`, `Ticks < 0`, `Parallelism < 1`.
+
+## Generating commands
+
+`Commands` is called once per seed, before the run starts. `plan.Rng` is a deterministic stream derived from the seed. It is separate from `ctx.Rng`, so generating commands never shifts the randomness of your systems.
+
+```csharp
+.Commands(plan =>
+{
+ for (var i = 0; i < 20; i++)
+ plan.Enqueue(plan.Rng.NextInt(0, (int)plan.EndTick), new AddPopulation(plan.Rng.NextInt(1, 10)));
+})
+```
+
+`Enqueue(tick, command)` accepts ticks from `0` to `plan.EndTick`. Commands are delivered through a `ScheduledCommandInbox`.
+
+## Reading the report
+
+`FuzzReport` has `Passed`, `SeedsRun`, `Duration`, `Failures`, `ToText()` and `ThrowIfFailed()`. `Failures` is always sorted by seed, whatever the `Parallelism`.
+
+Every `FuzzFailure` carries the `Seed`, the `Kind`, the `Tick`, a `Summary`, the `StateDiff` for that tick, the `ArtifactsDir` (when `ArtifactsRoot` is set) and `ReproCode`.
+
+`StateDiff` lists the fields that changed on the failing tick: from the end of the previous tick to the failing state. For `NonDeterminism` it lists the fields in which the two runs differ. Paths look like `$.Population`, `$.Items[3].Count`, `$["a.b"]`.
+
+## Reproducing a failure
+
+Add the `ReproCode` to your `Epoch.Fuzz` call to narrow it to the failing seed:
+
+```csharp
+.Seeds(4, 4).Ticks(426)
+```
+
+The run fails on the same tick. With `ArtifactsRoot` the directory `fuzz-` also holds `manifest.json`, `statefp.jsonl`, the failure report and, with an `EventCodec`, the event log, so `epochsim verify-run`, `bisect` and `repro` can work on it.
+
+## Checking determinism
+
+`CheckDeterminism(true)` runs each seed twice and compares the state fingerprint after every tick. It catches `static` state, `DateTime.UtcNow`, `Random`, hash-order dependence and anything else that makes two runs of one seed differ. Runs share no mutable state except what your code shares, such as `static` fields: that is what this check finds.
+
+## Parallelism
+
+Seeds run in parallel, one run per thread. The report does not depend on `Parallelism`. `StopAtFirstFailure(true)` stops handing out new seeds, but runs already in flight finish and their failures are reported. Which seeds were in flight depends on timing, so the set of reported failures is stable only with `Parallelism(1)`.
+
+## Command line
+
+```bash
+epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500
+```
+
+| Option | Default | Meaning |
+| --------------------- | ------------ | ----------------------------------------------- |
+| `--adapter name` | `population` | Domain adapter, see `epochsim list-adapters` |
+| `--seeds A..B` | `1..1000` | Seed range, or a single seed `N` |
+| `--ticks N` | `500` | Last tick of every run |
+| `--check-determinism` | off | Run every seed twice |
+| `--parallel N` | CPU count | Concurrent runs |
+| `--out dir` | `artifacts` | Artifacts directory for failed seeds |
+
+Exit code `0`: no failures. Exit code `2`: failures found, or invalid arguments. The CLI works with adapters registered in `DomainAdapterRegistry`; in your own code the library API is the main entry point.
+
+## Running in CI
+
+```csharp
+[Fact]
+public void World_SurvivesFuzzing()
+{
+ Epoch.Fuzz(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem(new WorldSystem()))
+ .Invariants(() => [new PopulationNonNegativeInvariant()])
+ .Seeds(1, 2000)
+ .Ticks(500)
+ .ArtifactsRoot("fuzz-artifacts")
+ .CheckDeterminism()).ThrowIfFailed();
+}
+```
+
+Upload `fuzz-artifacts` as a build artifact when the test fails.
diff --git a/docs/en/testing.md b/docs/en/testing.md
new file mode 100644
index 0000000..9855347
--- /dev/null
+++ b/docs/en/testing.md
@@ -0,0 +1,114 @@
+# Testing
+
+`EpochSim.Testing` adds simulation assertions to ordinary unit tests. It depends on no test framework: a failed check throws `SimulationAssertionException`, and every framework reports an unhandled exception as a failed test. Under the hood it runs [`Epoch.Fuzz`](fuzzing.md), so a failure message names the seed, the tick and the state fields that changed.
+
+## Installation
+
+```bash
+dotnet add package EpochSim.Testing
+```
+
+It is a test dependency and is not part of `EpochSim.All`.
+
+## Assertions
+
+| Method | Checks |
+| --------------------------------------------------- | ---------------------------------------------------------------------- |
+| `SimAssert.IsDeterministic(configure)` | Runs every seed twice and compares state after every tick. Always enables `CheckDeterminism`. |
+| `SimAssert.InvariantsHold(configure)` | Invariants, exceptions and, if `configure` enables it, determinism. |
+| `SimAssert.NoFailures(report)` | Throws when a `FuzzReport` has failures. |
+| `SimAssert.MatchesGolden(configure, path, seed)` | Compares fingerprints of one seed with a stored file. |
+
+`configure` is the same builder callback as in `Epoch.Fuzz`. A single seed is `Seeds(s, s)`.
+
+## xUnit
+
+```csharp
+using EpochSim.Testing;
+using Xunit;
+
+public sealed class WorldTests
+{
+ [Fact]
+ public void World_IsDeterministic()
+ {
+ SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
+ .Seeds(1, 50)
+ .Ticks(200));
+ }
+}
+```
+
+## NUnit
+
+```csharp
+using EpochSim.Testing;
+using NUnit.Framework;
+
+public sealed class WorldTests
+{
+ [Test]
+ public void World_IsDeterministic()
+ {
+ SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
+ .Seeds(1, 50)
+ .Ticks(200));
+ }
+}
+```
+
+## MSTest
+
+```csharp
+using EpochSim.Testing;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+[TestClass]
+public sealed class WorldTests
+{
+ [TestMethod]
+ public void World_IsDeterministic()
+ {
+ SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
+ .Seeds(1, 50)
+ .Ticks(200));
+ }
+}
+```
+
+## Reading a failure
+
+```
+Fuzz failed: Failures=1, SeedsRun=50, ElapsedMs=12
+
+[InvariantViolation] seed=4 tick=426
+ QueueNonNegative: Pending=-1
+ StateDiff:
+ $.Completed: 198 -> 200
+ $.Pending: 0 -> -1
+ Repro: .Seeds(4, 4).Ticks(426)
+```
+
+The first line is the totals. Each block gives the failure kind, the seed, the tick, what broke, the state fields that changed on that tick, and the `Repro:` fragment that narrows the same test to the failing seed.
+
+## Golden fingerprints
+
+`MatchesGolden` is a regression test for "I changed behavior by accident":
+
+```csharp
+SimAssert.MatchesGolden(
+ f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem(new WorldSystem()))
+ .Ticks(1000),
+ goldenPath: "golden/world-seed-7.json",
+ seed: 7);
+```
+
+The first run writes the file. It holds the state fingerprints of the seed on every 100th tick and on the last tick. Later runs compare against it and name the first tick that differs. After an intended change, run the tests once with `EPOCHSIM_UPDATE_GOLDEN=1` to rewrite the file and commit it.
diff --git a/docs/ru/determinism.md b/docs/ru/determinism.md
index ecf3c9a..eef6b34 100644
--- a/docs/ru/determinism.md
+++ b/docs/ru/determinism.md
@@ -11,6 +11,66 @@ EpochSim гарантирует детерминированное выполн
- гонки потоков, меняющие порядок событий
- неконтролируемое поведение с плавающей точкой
+## Анализатор
+
+В `EpochSim` входит Roslyn-анализатор, превращающий эти ошибки в предупреждения компилятора. Он лежит в пакете `EpochSim` и доступен отдельно как `EpochSim.Analyzers`. Анализатор срабатывает только внутри кода симуляции и не трогает остальной проект.
+
+### Что считается кодом симуляции
+
+- Лямбды и методовые группы, переданные в `SimulationEngine.AddSystem(...)` и `OnCommand(...)`.
+- Все методы типов, реализующих `ISystem<>`, `ICommandHandler<,>` или `IInvariant<>`.
+- Типы и методы с атрибутом `[Deterministic]` (`EpochSim.Kernel.Determinism`).
+
+Вызовы в другие методы не отслеживаются. Пометьте вспомогательный метод `[Deterministic]`, чтобы проверить и его.
+
+```csharp
+using EpochSim.Kernel.Determinism;
+
+[Deterministic]
+public static class Pricing
+{
+ public static int Roll(IRng rng) => rng.NextInt(1, 7);
+}
+```
+
+### Правила
+
+| ID | Серьёзность по умолчанию | Что ловит |
+| ------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------ |
+| ESIM001 | warning | `DateTime.Now/UtcNow/Today`, `DateTimeOffset.Now/UtcNow`, `Stopwatch`, `Environment.TickCount/TickCount64`, `TimeProvider.System` |
+| ESIM002 | warning | `new Random(...)`, `Random.Shared`, `RandomNumberGenerator`, `Guid.NewGuid()` |
+| ESIM003 | warning | `Task.Run`, `Task.Factory.StartNew`, `new Thread`, `ThreadPool.*`, `Parallel.*`, `AsParallel()`, `async`-лямбды, `await` |
+| ESIM004 | warning | `GetHashCode()` у `string` и `object`, перебор `ConcurrentDictionary`, `ConcurrentBag`, `ConcurrentQueue` |
+| ESIM005 | warning | `File.*`, `Directory.*`, `HttpClient`, `Environment.GetEnvironmentVariable`, `Environment.MachineName` |
+| ESIM006 | hidden | `foreach` и LINQ по `Dictionary<,>` и `HashSet<>` |
+
+ESIM006 скрыто по умолчанию: .NET перебирает эти коллекции в стабильном порядке при одинаковых операциях, поэтому код хрупкий, но не неверный. Повышайте серьёзность, когда нужна более строгая проверка.
+
+### Настройка
+
+Через `.editorconfig`:
+
+```ini
+[*.cs]
+dotnet_diagnostic.ESIM001.severity = error
+dotnet_diagnostic.ESIM005.severity = none
+dotnet_diagnostic.ESIM006.severity = warning
+```
+
+Отдельное срабатывание подавляется `#pragma warning disable ESIM001`.
+
+### Исправление
+
+ESIM002 предлагает исправление, когда в области видимости есть параметр `TickContext<>` или `EventContext<>`:
+
+| До | После |
+| ----------------------------------- | -------------------------- |
+| `Random.Shared.Next(a, b)` | `ctx.Rng.NextInt(a, b)` |
+| `new Random(seed).Next(a, b)` | `ctx.Rng.NextInt(a, b)` |
+| `Random.Shared.NextDouble()` | `ctx.Rng.NextDouble01()` |
+
+Проверка методовых групп выполняется при анализе всей компиляции (при сборке). В IDE она может появиться только после сборки.
+
## Рекомендации
- Используйте только `ctx.Rng` для доменной случайности.
diff --git a/docs/ru/fuzzing.md b/docs/ru/fuzzing.md
new file mode 100644
index 0000000..c3c4b00
--- /dev/null
+++ b/docs/ru/fuzzing.md
@@ -0,0 +1,138 @@
+# Fuzzing
+
+`Epoch.Fuzz` прогоняет симуляцию на диапазоне seed и показывает, какой seed её ломает, на каком тике и какие поля состояния изменились на этом тике. Находит три вида сбоев:
+
+- `InvariantViolation`: `IInvariant` вернул `false`.
+- `Exception`: исключение из системы или обработчика команды.
+- `NonDeterminism`: два прогона одного seed дали разное состояние (нужен `CheckDeterminism`).
+
+Любой сбой воспроизводится тем же seed.
+
+## Минимальный пример
+
+```csharp
+using EpochSim;
+
+var report = Epoch.Fuzz(f => f
+ .State(() => new JobQueueState())
+ .Engine(e => e.AddSystem(new JobQueueSystem()))
+ .Invariants(() => [new QueueNonNegativeInvariant()])
+ .Seeds(1, 1000)
+ .Ticks(500));
+
+Console.WriteLine(report.ToText());
+```
+
+Вывод:
+
+```
+Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81
+
+[InvariantViolation] seed=4 tick=426
+ QueueNonNegative: Pending=-1
+ StateDiff:
+ $.Completed: 198 -> 200
+ $.Pending: 0 -> -1
+ Repro: .Seeds(4, 4).Ticks(426)
+```
+
+В тесте вызывайте `report.ThrowIfFailed()` или используйте [EpochSim.Testing](testing.md).
+
+Рабочий пример лежит в [src/EpochSim.Samples/Fuzzing](../../src/EpochSim.Samples/Fuzzing/): очередь задач, счётчик которой уходит в минус на редкой последовательности значений `ctx.Rng`, зависящей от seed.
+
+## Билдер
+
+| Метод | Обязателен | Смысл |
+| ----------------------------------------- | ---------- | ---------------------------------------------------------------------------------- |
+| `State(Func)` | да | Фабрика свежего начального состояния. Вызывается для каждого прогона. |
+| `Engine(Action>)` | да | Регистрирует системы и обработчики команд на новом движке. Для каждого прогона. |
+| `Ticks(long)` | да | Последний тик каждого прогона, включительно. |
+| `Seeds(ulong from, ulong to)` | да | Диапазон seed, включительно. |
+| `Seeds(IEnumerable)` | да | Явный список seed. Используйте любую из двух перегрузок. |
+| `Serializer(IStateSerializer)` | нет | Для fingerprint'ов и диффа. По умолчанию `JsonStateSerializer`. |
+| `Invariants(Func>>)` | нет | Проверяются после каждого тика. Фабрика: у каждого прогона свои экземпляры. |
+| `Commands(Action)` | нет | Генерирует входные команды для seed. См. ниже. |
+| `CheckDeterminism(bool)` | нет | Прогнать каждый seed дважды и сравнить fingerprint'ы после каждого тика. По умолчанию `false`. |
+| `Parallelism(int)` | нет | Число одновременных прогонов. По умолчанию `Environment.ProcessorCount`. |
+| `StopAtFirstFailure(bool)` | нет | После первого сбоя не выдавать новые seed. По умолчанию `false`. |
+| `ArtifactsRoot(string)` | нет | Писать полные артефакты для сбойных seed (не больше первых 10 по возрастанию seed). |
+| `EventCodec(IEventCodecV2)` | нет | Добавляет лог событий в эти артефакты. |
+| `Progress(IProgress)` | нет | Вызывается после каждого завершённого seed. |
+
+Неверные значения бросают исключение сразу: нет обязательного параметра, `Seeds` с `from > to`, `Ticks < 0`, `Parallelism < 1`.
+
+## Генерация команд
+
+`Commands` вызывается один раз на seed до начала прогона. `plan.Rng` это детерминированный поток, выведенный из seed. Он отделён от `ctx.Rng`, поэтому генерация команд не сдвигает случайность ваших систем.
+
+```csharp
+.Commands(plan =>
+{
+ for (var i = 0; i < 20; i++)
+ plan.Enqueue(plan.Rng.NextInt(0, (int)plan.EndTick), new AddPopulation(plan.Rng.NextInt(1, 10)));
+})
+```
+
+`Enqueue(tick, command)` принимает тики от `0` до `plan.EndTick`. Команды доставляются через `ScheduledCommandInbox`.
+
+## Чтение отчёта
+
+У `FuzzReport` есть `Passed`, `SeedsRun`, `Duration`, `Failures`, `ToText()` и `ThrowIfFailed()`. `Failures` всегда отсортирован по seed, независимо от `Parallelism`.
+
+Каждый `FuzzFailure` содержит `Seed`, `Kind`, `Tick`, `Summary`, `StateDiff` этого тика, `ArtifactsDir` (если задан `ArtifactsRoot`) и `ReproCode`.
+
+`StateDiff` перечисляет поля, изменившиеся на сбойном тике: от конца предыдущего тика до сбойного состояния. Для `NonDeterminism` это поля, в которых два прогона различаются. Пути выглядят как `$.Population`, `$.Items[3].Count`, `$["a.b"]`.
+
+## Воспроизведение сбоя
+
+Добавьте `ReproCode` в вызов `Epoch.Fuzz`, чтобы сузить его до сбойного seed:
+
+```csharp
+.Seeds(4, 4).Ticks(426)
+```
+
+Прогон падает на том же тике. С `ArtifactsRoot` каталог `fuzz-` содержит ещё `manifest.json`, `statefp.jsonl`, отчёт о сбое и, при заданном `EventCodec`, лог событий, так что с ним работают `epochsim verify-run`, `bisect` и `repro`.
+
+## Проверка детерминизма
+
+`CheckDeterminism(true)` прогоняет каждый seed дважды и сравнивает fingerprint состояния после каждого тика. Ловит `static`-состояние, `DateTime.UtcNow`, `Random`, зависимость от порядка хэш-коллекций и всё остальное, из-за чего два прогона одного seed различаются. Прогоны не делят изменяемое состояние, кроме того, что делит ваш код, например `static`-полей: это и находит проверка.
+
+## Параллелизм
+
+Seed выполняются параллельно, один прогон на поток. Отчёт не зависит от `Parallelism`. `StopAtFirstFailure(true)` прекращает выдачу новых seed, но уже запущенные прогоны завершаются и их сбои попадают в отчёт. Какие seed были запущены, зависит от тайминга, поэтому набор сбоев стабилен только при `Parallelism(1)`.
+
+## Командная строка
+
+```bash
+epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500
+```
+
+| Опция | По умолчанию | Смысл |
+| --------------------- | ------------ | ----------------------------------------------- |
+| `--adapter name` | `population` | Доменный адаптер, см. `epochsim list-adapters` |
+| `--seeds A..B` | `1..1000` | Диапазон seed или один seed `N` |
+| `--ticks N` | `500` | Последний тик каждого прогона |
+| `--check-determinism` | выкл. | Прогнать каждый seed дважды |
+| `--parallel N` | число CPU | Число одновременных прогонов |
+| `--out dir` | `artifacts` | Каталог артефактов для сбойных seed |
+
+Код возврата `0`: сбоев нет. Код `2`: найдены сбои или неверные аргументы. CLI работает с адаптерами из `DomainAdapterRegistry`; в собственном коде основной вход это библиотечный API.
+
+## Запуск в CI
+
+```csharp
+[Fact]
+public void World_SurvivesFuzzing()
+{
+ Epoch.Fuzz(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem(new WorldSystem()))
+ .Invariants(() => [new PopulationNonNegativeInvariant()])
+ .Seeds(1, 2000)
+ .Ticks(500)
+ .ArtifactsRoot("fuzz-artifacts")
+ .CheckDeterminism()).ThrowIfFailed();
+}
+```
+
+Если тест упал, загрузите `fuzz-artifacts` как артефакт сборки.
diff --git a/docs/ru/testing.md b/docs/ru/testing.md
new file mode 100644
index 0000000..5c4b139
--- /dev/null
+++ b/docs/ru/testing.md
@@ -0,0 +1,114 @@
+# Testing
+
+`EpochSim.Testing` добавляет проверки симуляции в обычные юнит-тесты. Пакет не зависит ни от одного тестового фреймворка: упавшая проверка бросает `SimulationAssertionException`, а любой фреймворк считает необработанное исключение провалом теста. Внутри работает [`Epoch.Fuzz`](fuzzing.md), поэтому сообщение о сбое называет seed, тик и изменившиеся поля состояния.
+
+## Установка
+
+```bash
+dotnet add package EpochSim.Testing
+```
+
+Это тестовая зависимость, в `EpochSim.All` она не входит.
+
+## Проверки
+
+| Метод | Что проверяет |
+| --------------------------------------------------- | ---------------------------------------------------------------------- |
+| `SimAssert.IsDeterministic(configure)` | Прогоняет каждый seed дважды и сравнивает состояние после каждого тика. Всегда включает `CheckDeterminism`. |
+| `SimAssert.InvariantsHold(configure)` | Инварианты, исключения и, если `configure` включает, детерминизм. |
+| `SimAssert.NoFailures(report)` | Бросает исключение, если в `FuzzReport` есть сбои. |
+| `SimAssert.MatchesGolden(configure, path, seed)` | Сравнивает fingerprint'ы одного seed с сохранённым файлом. |
+
+`configure` это тот же билдер, что в `Epoch.Fuzz`. Один seed записывается как `Seeds(s, s)`.
+
+## xUnit
+
+```csharp
+using EpochSim.Testing;
+using Xunit;
+
+public sealed class WorldTests
+{
+ [Fact]
+ public void World_IsDeterministic()
+ {
+ SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
+ .Seeds(1, 50)
+ .Ticks(200));
+ }
+}
+```
+
+## NUnit
+
+```csharp
+using EpochSim.Testing;
+using NUnit.Framework;
+
+public sealed class WorldTests
+{
+ [Test]
+ public void World_IsDeterministic()
+ {
+ SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
+ .Seeds(1, 50)
+ .Ticks(200));
+ }
+}
+```
+
+## MSTest
+
+```csharp
+using EpochSim.Testing;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+[TestClass]
+public sealed class WorldTests
+{
+ [TestMethod]
+ public void World_IsDeterministic()
+ {
+ SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
+ .Seeds(1, 50)
+ .Ticks(200));
+ }
+}
+```
+
+## Как читать сообщение об ошибке
+
+```
+Fuzz failed: Failures=1, SeedsRun=50, ElapsedMs=12
+
+[InvariantViolation] seed=4 tick=426
+ QueueNonNegative: Pending=-1
+ StateDiff:
+ $.Completed: 198 -> 200
+ $.Pending: 0 -> -1
+ Repro: .Seeds(4, 4).Ticks(426)
+```
+
+Первая строка это итоги. В каждом блоке: вид сбоя, seed, тик, что сломалось, поля состояния, изменившиеся на этом тике, и фрагмент `Repro:`, который сужает тот же тест до сбойного seed.
+
+## Золотые fingerprint'ы
+
+`MatchesGolden` это регрессионный тест на случай «я случайно изменил поведение»:
+
+```csharp
+SimAssert.MatchesGolden(
+ f => f
+ .State(() => new WorldState())
+ .Engine(e => e.AddSystem(new WorldSystem()))
+ .Ticks(1000),
+ goldenPath: "golden/world-seed-7.json",
+ seed: 7);
+```
+
+Первый запуск создаёт файл. В нём fingerprint'ы состояния этого seed на каждом сотом тике и на последнем. Следующие запуски сравниваются с файлом и называют первый тик, на котором есть расхождение. После намеренного изменения запустите тесты один раз с `EPOCHSIM_UPDATE_GOLDEN=1`, чтобы перезаписать файл, и закоммитьте его.
diff --git a/src/EpochSim.Analyzers.CodeFixes/EpochSim.Analyzers.CodeFixes.csproj b/src/EpochSim.Analyzers.CodeFixes/EpochSim.Analyzers.CodeFixes.csproj
new file mode 100644
index 0000000..283317e
--- /dev/null
+++ b/src/EpochSim.Analyzers.CodeFixes/EpochSim.Analyzers.CodeFixes.csproj
@@ -0,0 +1,16 @@
+
+
+
+ netstandard2.0
+ enable
+ false
+ true
+ true
+
+
+
+
+
+
+
+
diff --git a/src/EpochSim.Analyzers.CodeFixes/RandomToRngCodeFixProvider.cs b/src/EpochSim.Analyzers.CodeFixes/RandomToRngCodeFixProvider.cs
new file mode 100644
index 0000000..0788f5b
--- /dev/null
+++ b/src/EpochSim.Analyzers.CodeFixes/RandomToRngCodeFixProvider.cs
@@ -0,0 +1,126 @@
+using System.Collections.Immutable;
+using System.Composition;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CodeActions;
+using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+
+namespace EpochSim.Analyzers;
+
+[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RandomToRngCodeFixProvider)), Shared]
+public sealed class RandomToRngCodeFixProvider : CodeFixProvider
+{
+ private const string RandomnessId = "ESIM002";
+ private const string TickContextName = "EpochSim.Kernel.Systems.TickContext`1";
+ private const string EventContextName = "EpochSim.Kernel.Systems.EventContext`1";
+
+ public override ImmutableArray FixableDiagnosticIds => ImmutableArray.Create(RandomnessId);
+
+ public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
+
+ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
+ {
+ var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
+ var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
+ if (root is null || model is null)
+ return;
+
+ var diagnostic = context.Diagnostics[0];
+ var source = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);
+
+ if (!TryMatchCall(source, out var invocation, out var replacementMethod))
+ return;
+
+ var contextName = FindContextParameter(model, invocation, context.CancellationToken);
+ if (contextName is null)
+ return;
+
+ var title = $"Use {contextName}.Rng.{replacementMethod}";
+ context.RegisterCodeFix(
+ CodeAction.Create(
+ title,
+ _ => Replace(context.Document, root, invocation, contextName, replacementMethod),
+ equivalenceKey: title),
+ diagnostic);
+ }
+
+ private static bool TryMatchCall(SyntaxNode source, out InvocationExpressionSyntax invocation, out string replacementMethod)
+ {
+ invocation = null!;
+ replacementMethod = string.Empty;
+
+ if (source.Parent is not MemberAccessExpressionSyntax access
+ || access.Expression != source
+ || access.Parent is not InvocationExpressionSyntax call
+ || call.Expression != access)
+ return false;
+
+ var argumentCount = call.ArgumentList.Arguments.Count;
+
+ if (access.Name.Identifier.ValueText == "Next" && argumentCount == 2)
+ replacementMethod = "NextInt";
+ else if (access.Name.Identifier.ValueText == "NextDouble" && argumentCount == 0)
+ replacementMethod = "NextDouble01";
+ else
+ return false;
+
+ invocation = call;
+ return true;
+ }
+
+ private static string? FindContextParameter(SemanticModel model, SyntaxNode site, CancellationToken cancellationToken)
+ {
+ foreach (var ancestor in site.Ancestors())
+ {
+ if (ancestor is not (LambdaExpressionSyntax or AnonymousMethodExpressionSyntax or BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax))
+ continue;
+
+ var method = ancestor is LambdaExpressionSyntax or AnonymousMethodExpressionSyntax
+ ? model.GetSymbolInfo(ancestor, cancellationToken).Symbol as IMethodSymbol
+ : model.GetDeclaredSymbol(ancestor, cancellationToken) as IMethodSymbol;
+
+ var parameter = method?.Parameters.FirstOrDefault(IsSimulationContext);
+ if (parameter is not null)
+ return parameter.Name;
+ }
+
+ return null;
+ }
+
+ private static bool IsSimulationContext(IParameterSymbol parameter)
+ {
+ if (parameter.Type is not INamedTypeSymbol { IsGenericType: true } type)
+ return false;
+
+ var definition = type.OriginalDefinition;
+ var name = definition.ContainingNamespace.ToDisplayString() + "." + definition.MetadataName;
+ return name == TickContextName || name == EventContextName;
+ }
+
+ private static Task Replace(
+ Document document,
+ SyntaxNode root,
+ InvocationExpressionSyntax invocation,
+ string contextName,
+ string replacementMethod)
+ {
+ var rng = SyntaxFactory.MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ SyntaxFactory.IdentifierName(contextName),
+ SyntaxFactory.IdentifierName("Rng"));
+
+ var replacement = SyntaxFactory.InvocationExpression(
+ SyntaxFactory.MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ rng,
+ SyntaxFactory.IdentifierName(replacementMethod)),
+ invocation.ArgumentList)
+ .WithTriviaFrom(invocation);
+
+ return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(invocation, replacement)));
+ }
+}
diff --git a/src/EpochSim.Analyzers/AnalyzerReleases.Shipped.md b/src/EpochSim.Analyzers/AnalyzerReleases.Shipped.md
new file mode 100644
index 0000000..f50bb1f
--- /dev/null
+++ b/src/EpochSim.Analyzers/AnalyzerReleases.Shipped.md
@@ -0,0 +1,2 @@
+; Shipped analyzer releases
+; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
diff --git a/src/EpochSim.Analyzers/AnalyzerReleases.Unshipped.md b/src/EpochSim.Analyzers/AnalyzerReleases.Unshipped.md
new file mode 100644
index 0000000..584ee08
--- /dev/null
+++ b/src/EpochSim.Analyzers/AnalyzerReleases.Unshipped.md
@@ -0,0 +1,10 @@
+### New Rules
+
+Rule ID | Category | Severity | Notes
+--------|----------|----------|-------
+ESIM001 | EpochSim.Determinism | Warning | Wall-clock time in simulation code
+ESIM002 | EpochSim.Determinism | Warning | Unseeded randomness in simulation code
+ESIM003 | EpochSim.Determinism | Warning | Concurrency in simulation code
+ESIM004 | EpochSim.Determinism | Warning | Process-dependent hashing or unordered enumeration in simulation code
+ESIM005 | EpochSim.Determinism | Warning | File, network or environment access in simulation code
+ESIM006 | EpochSim.Determinism | Hidden | Enumeration of Dictionary or HashSet in simulation code
diff --git a/src/EpochSim.Analyzers/ConstructCatalog.cs b/src/EpochSim.Analyzers/ConstructCatalog.cs
new file mode 100644
index 0000000..4941a25
--- /dev/null
+++ b/src/EpochSim.Analyzers/ConstructCatalog.cs
@@ -0,0 +1,190 @@
+using System.Collections.Generic;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Operations;
+
+namespace EpochSim.Analyzers;
+
+internal static class ConstructCatalog
+{
+ private const string WallClockHint = "Use the simulation tick (ctx.Time) instead of wall-clock time.";
+ private const string ConcurrencyHint = "Simulation code must run on the simulation thread; remove the concurrency.";
+ private const string ExternalHint = "Pass external data into the simulation through commands or state.";
+ private const string HashHint = "String and object hash codes differ between processes; use a stable hash.";
+ private const string ConcurrentOrderHint = "Enumeration order of concurrent collections is not deterministic; use an ordered collection.";
+ private const string HashCollectionHint = "Enumeration order depends on the history of inserts and removals; sort before iterating.";
+
+ private static readonly HashSet WallClockProperties = new()
+ {
+ "System.DateTime.Now",
+ "System.DateTime.UtcNow",
+ "System.DateTime.Today",
+ "System.DateTimeOffset.Now",
+ "System.DateTimeOffset.UtcNow",
+ "System.Environment.TickCount",
+ "System.Environment.TickCount64",
+ "System.TimeProvider.System"
+ };
+
+ private static readonly HashSet WallClockMethods = new()
+ {
+ "System.Diagnostics.Stopwatch.StartNew",
+ "System.Diagnostics.Stopwatch.GetTimestamp"
+ };
+
+ private static readonly HashSet ConcurrencyTypes = new()
+ {
+ "System.Threading.ThreadPool",
+ "System.Threading.Tasks.Parallel"
+ };
+
+ private static readonly HashSet ConcurrencyMethods = new()
+ {
+ "System.Threading.Tasks.Task.Run",
+ "System.Linq.ParallelEnumerable.AsParallel"
+ };
+
+ private static readonly HashSet TaskFactories = new()
+ {
+ "System.Threading.Tasks.TaskFactory",
+ "System.Threading.Tasks.TaskFactory`1"
+ };
+
+ private static readonly HashSet ExternalTypes = new()
+ {
+ "System.IO.File",
+ "System.IO.Directory",
+ "System.Net.Http.HttpClient"
+ };
+
+ private static readonly HashSet ExternalMethods = new()
+ {
+ "System.Environment.GetEnvironmentVariable",
+ "System.Environment.GetEnvironmentVariables"
+ };
+
+ private static readonly HashSet ConcurrentCollections = new()
+ {
+ "System.Collections.Concurrent.ConcurrentDictionary`2",
+ "System.Collections.Concurrent.ConcurrentBag`1",
+ "System.Collections.Concurrent.ConcurrentQueue`1"
+ };
+
+ private static readonly HashSet HashCollections = new()
+ {
+ "System.Collections.Generic.Dictionary`2",
+ "System.Collections.Generic.HashSet`1"
+ };
+
+ public static Finding? Inspect(IOperation operation)
+ => operation switch
+ {
+ IPropertyReferenceOperation property => InspectProperty(property),
+ IInvocationOperation invocation => InspectInvocation(invocation),
+ IObjectCreationOperation creation => InspectCreation(creation),
+ IForEachLoopOperation loop => InspectEnumeration(loop.Collection, operation),
+ IAwaitOperation => Create(Rules.Concurrency, "await", ConcurrencyHint, operation.Syntax.GetLocation()),
+ IAnonymousFunctionOperation { Symbol.IsAsync: true } lambda => InspectAsyncLambda(lambda),
+ _ => null
+ };
+
+ private static Finding? InspectProperty(IPropertyReferenceOperation operation)
+ {
+ var property = operation.Property;
+ var typeName = OperationTypes.MetadataName(property.ContainingType);
+ var key = typeName + "." + property.Name;
+ var display = property.ContainingType.Name + "." + property.Name;
+ var location = operation.Syntax.GetLocation();
+
+ if (WallClockProperties.Contains(key))
+ return Create(Rules.WallClock, display, WallClockHint, location);
+
+ if (key == "System.Random.Shared")
+ return Create(Rules.Randomness, display, "Use ctx.Rng instead of " + display, location);
+
+ if (key == "System.Environment.MachineName")
+ return Create(Rules.ExternalInput, display, ExternalHint, location);
+
+ return null;
+ }
+
+ private static Finding? InspectInvocation(IInvocationOperation operation)
+ {
+ var method = operation.TargetMethod;
+ var typeName = OperationTypes.MetadataName(method.ContainingType);
+ var key = typeName + "." + method.Name;
+ var display = method.ContainingType.Name + "." + method.Name;
+ var location = operation.Syntax.GetLocation();
+
+ if (WallClockMethods.Contains(key))
+ return Create(Rules.WallClock, display, WallClockHint, location);
+
+ if (key == "System.Guid.NewGuid" || typeName == "System.Security.Cryptography.RandomNumberGenerator")
+ return Create(Rules.Randomness, display, "Use ctx.Rng instead of " + display, location);
+
+ if (ConcurrencyMethods.Contains(key)
+ || ConcurrencyTypes.Contains(typeName)
+ || (TaskFactories.Contains(typeName) && method.Name == "StartNew"))
+ return Create(Rules.Concurrency, display, ConcurrencyHint, location);
+
+ if (ExternalTypes.Contains(typeName) || ExternalMethods.Contains(key))
+ return Create(Rules.ExternalInput, display, ExternalHint, location);
+
+ if (method.Name == "GetHashCode"
+ && method.Parameters.IsEmpty
+ && method.ContainingType.SpecialType is SpecialType.System_String or SpecialType.System_Object)
+ return Create(Rules.Hashing, display, HashHint, location);
+
+ if (typeName == "System.Linq.Enumerable" && !operation.Arguments.IsEmpty)
+ return InspectEnumeration(operation.Arguments[0].Value, operation);
+
+ return null;
+ }
+
+ private static Finding? InspectCreation(IObjectCreationOperation operation)
+ {
+ if (operation.Type is not INamedTypeSymbol type)
+ return null;
+
+ var display = "new " + type.Name;
+ var location = operation.Syntax.GetLocation();
+
+ return OperationTypes.MetadataName(type) switch
+ {
+ "System.Random" => Create(Rules.Randomness, display, "Use ctx.Rng instead of " + display, location),
+ "System.Diagnostics.Stopwatch" => Create(Rules.WallClock, display, WallClockHint, location),
+ "System.Threading.Thread" => Create(Rules.Concurrency, display, ConcurrencyHint, location),
+ "System.Net.Http.HttpClient" => Create(Rules.ExternalInput, display, ExternalHint, location),
+ _ => null
+ };
+ }
+
+ private static Finding? InspectEnumeration(IOperation collection, IOperation site)
+ {
+ if (OperationTypes.CollectionType(collection) is not { } type)
+ return null;
+
+ var typeName = OperationTypes.MetadataName(type.OriginalDefinition);
+ var location = site.Syntax.GetLocation();
+
+ if (ConcurrentCollections.Contains(typeName))
+ return Create(Rules.Hashing, type.Name, ConcurrentOrderHint, location);
+
+ if (HashCollections.Contains(typeName))
+ return Create(Rules.HashCollectionOrder, type.Name, HashCollectionHint, location);
+
+ return null;
+ }
+
+ private static Finding? InspectAsyncLambda(IAnonymousFunctionOperation operation)
+ {
+ var location = operation.Syntax is AnonymousFunctionExpressionSyntax function
+ ? function.AsyncKeyword.GetLocation()
+ : operation.Syntax.GetLocation();
+
+ return Create(Rules.Concurrency, "async lambda", ConcurrencyHint, location);
+ }
+
+ private static Finding Create(DiagnosticDescriptor rule, string construct, string hint, Location location)
+ => new(rule, construct, hint, location);
+}
diff --git a/src/EpochSim.Analyzers/DeterminismAnalyzer.cs b/src/EpochSim.Analyzers/DeterminismAnalyzer.cs
new file mode 100644
index 0000000..202e893
--- /dev/null
+++ b/src/EpochSim.Analyzers/DeterminismAnalyzer.cs
@@ -0,0 +1,59 @@
+using System.Collections.Immutable;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Operations;
+
+namespace EpochSim.Analyzers;
+
+[DiagnosticAnalyzer(LanguageNames.CSharp)]
+public sealed class DeterminismAnalyzer : DiagnosticAnalyzer
+{
+ public override ImmutableArray SupportedDiagnostics => Rules.All;
+
+ public override void Initialize(AnalysisContext context)
+ {
+ context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+ context.EnableConcurrentExecution();
+ context.RegisterCompilationStartAction(OnCompilationStart);
+ }
+
+ private static void OnCompilationStart(CompilationStartAnalysisContext start)
+ {
+ var scope = SimulationScope.Create(start.Compilation);
+ if (scope is null)
+ return;
+
+ var methodGroups = new MethodGroupFindings();
+
+ start.RegisterOperationAction(
+ context => Analyze(context, scope, methodGroups),
+ OperationKind.PropertyReference,
+ OperationKind.Invocation,
+ OperationKind.ObjectCreation,
+ OperationKind.Await,
+ OperationKind.AnonymousFunction,
+ OperationKind.Loop);
+
+ start.RegisterCompilationEndAction(context =>
+ {
+ foreach (var diagnostic in methodGroups.Resolve())
+ context.ReportDiagnostic(diagnostic);
+ });
+ }
+
+ private static void Analyze(OperationAnalysisContext context, SimulationScope scope, MethodGroupFindings methodGroups)
+ {
+ if (context.Operation is IInvocationOperation invocation && scope.IsRegistration(invocation.TargetMethod))
+ methodGroups.Register(invocation);
+
+ if (ConstructCatalog.Inspect(context.Operation) is not { } finding)
+ return;
+
+ var diagnostic = finding.ToDiagnostic();
+
+ if (scope.IsSimulationCode(context.Operation, context.ContainingSymbol))
+ context.ReportDiagnostic(diagnostic);
+ else if (context.ContainingSymbol is IMethodSymbol method)
+ methodGroups.Defer(method, diagnostic);
+ }
+}
diff --git a/src/EpochSim.Analyzers/EpochSim.Analyzers.csproj b/src/EpochSim.Analyzers/EpochSim.Analyzers.csproj
new file mode 100644
index 0000000..803b11d
--- /dev/null
+++ b/src/EpochSim.Analyzers/EpochSim.Analyzers.csproj
@@ -0,0 +1,45 @@
+
+
+
+ netstandard2.0
+ enable
+ true
+ true
+ true
+ false
+ false
+ true
+ $(NoWarn);NU5128
+ EpochSim.Analyzers
+
+ Roslyn analyzers that report constructs breaking determinism inside EpochSim simulation code.
+ epochsim;analyzers;roslyn;determinism;simulation
+ Echways
+ https://github.com/Echways/EpochSim
+ https://github.com/Echways/EpochSim
+ git
+ MIT
+ README.md
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/EpochSim.Analyzers/Finding.cs b/src/EpochSim.Analyzers/Finding.cs
new file mode 100644
index 0000000..fb79e44
--- /dev/null
+++ b/src/EpochSim.Analyzers/Finding.cs
@@ -0,0 +1,9 @@
+using Microsoft.CodeAnalysis;
+
+namespace EpochSim.Analyzers;
+
+internal readonly struct Finding(DiagnosticDescriptor rule, string construct, string hint, Location location)
+{
+ public Diagnostic ToDiagnostic()
+ => Diagnostic.Create(rule, location, construct, hint);
+}
diff --git a/src/EpochSim.Analyzers/MethodGroupFindings.cs b/src/EpochSim.Analyzers/MethodGroupFindings.cs
new file mode 100644
index 0000000..b9a7309
--- /dev/null
+++ b/src/EpochSim.Analyzers/MethodGroupFindings.cs
@@ -0,0 +1,36 @@
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Operations;
+
+namespace EpochSim.Analyzers;
+
+internal sealed class MethodGroupFindings
+{
+ private readonly ConcurrentDictionary _registered = new(SymbolEqualityComparer.Default);
+ private readonly ConcurrentDictionary> _pending = new(SymbolEqualityComparer.Default);
+
+ public void Register(IInvocationOperation registration)
+ {
+ foreach (var argument in registration.Arguments)
+ {
+ if (SimulationScope.ReferencedMethod(argument.Value) is { } method)
+ _registered.TryAdd(method, 0);
+ }
+ }
+
+ public void Defer(IMethodSymbol method, Diagnostic diagnostic)
+ => _pending.GetOrAdd(method.OriginalDefinition, _ => new ConcurrentBag()).Add(diagnostic);
+
+ public IEnumerable Resolve()
+ {
+ foreach (var method in _registered.Keys)
+ {
+ if (!_pending.TryGetValue(method, out var diagnostics))
+ continue;
+
+ foreach (var diagnostic in diagnostics)
+ yield return diagnostic;
+ }
+ }
+}
diff --git a/src/EpochSim.Analyzers/OperationTypes.cs b/src/EpochSim.Analyzers/OperationTypes.cs
new file mode 100644
index 0000000..3470e2c
--- /dev/null
+++ b/src/EpochSim.Analyzers/OperationTypes.cs
@@ -0,0 +1,23 @@
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Operations;
+
+namespace EpochSim.Analyzers;
+
+internal static class OperationTypes
+{
+ public static string MetadataName(INamedTypeSymbol type)
+ => type.ContainingNamespace is { IsGlobalNamespace: false } containingNamespace
+ ? containingNamespace.ToDisplayString() + "." + type.MetadataName
+ : type.MetadataName;
+
+ public static IOperation Unwrap(IOperation operation)
+ {
+ while (operation is IConversionOperation conversion)
+ operation = conversion.Operand;
+
+ return operation;
+ }
+
+ public static INamedTypeSymbol? CollectionType(IOperation collection)
+ => Unwrap(collection).Type as INamedTypeSymbol;
+}
diff --git a/src/EpochSim.Analyzers/Rules.cs b/src/EpochSim.Analyzers/Rules.cs
new file mode 100644
index 0000000..3b56041
--- /dev/null
+++ b/src/EpochSim.Analyzers/Rules.cs
@@ -0,0 +1,45 @@
+using System.Collections.Immutable;
+using Microsoft.CodeAnalysis;
+
+namespace EpochSim.Analyzers;
+
+internal static class Rules
+{
+ public const string RandomnessId = "ESIM002";
+
+ private const string Category = "EpochSim.Determinism";
+ private const string HelpLink = "https://github.com/Echways/EpochSim/blob/main/docs/en/determinism.md#analyzer";
+ private const string MessageFormat = "'{0}' breaks determinism in simulation code. {1}";
+
+ public static readonly DiagnosticDescriptor WallClock = Create(
+ "ESIM001", "Wall-clock time in simulation code", DiagnosticSeverity.Warning);
+
+ public static readonly DiagnosticDescriptor Randomness = Create(
+ RandomnessId, "Unseeded randomness in simulation code", DiagnosticSeverity.Warning);
+
+ public static readonly DiagnosticDescriptor Concurrency = Create(
+ "ESIM003", "Concurrency in simulation code", DiagnosticSeverity.Warning);
+
+ public static readonly DiagnosticDescriptor Hashing = Create(
+ "ESIM004", "Process-dependent hashing or unordered enumeration in simulation code", DiagnosticSeverity.Warning);
+
+ public static readonly DiagnosticDescriptor ExternalInput = Create(
+ "ESIM005", "File, network or environment access in simulation code", DiagnosticSeverity.Warning);
+
+ public static readonly DiagnosticDescriptor HashCollectionOrder = Create(
+ "ESIM006", "Enumeration of Dictionary or HashSet in simulation code", DiagnosticSeverity.Hidden);
+
+ public static readonly ImmutableArray All = ImmutableArray.Create(
+ WallClock, Randomness, Concurrency, Hashing, ExternalInput, HashCollectionOrder);
+
+ private static DiagnosticDescriptor Create(string id, string title, DiagnosticSeverity severity)
+ => new(
+ id,
+ title,
+ MessageFormat,
+ Category,
+ severity,
+ isEnabledByDefault: true,
+ description: title,
+ helpLinkUri: HelpLink);
+}
diff --git a/src/EpochSim.Analyzers/SimulationScope.cs b/src/EpochSim.Analyzers/SimulationScope.cs
new file mode 100644
index 0000000..b13560e
--- /dev/null
+++ b/src/EpochSim.Analyzers/SimulationScope.cs
@@ -0,0 +1,104 @@
+using System;
+using System.Collections.Concurrent;
+using System.Linq;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Operations;
+
+namespace EpochSim.Analyzers;
+
+internal sealed class SimulationScope
+{
+ private readonly INamedTypeSymbol? _engine;
+ private readonly INamedTypeSymbol? _system;
+ private readonly INamedTypeSymbol? _commandHandler;
+ private readonly INamedTypeSymbol? _invariant;
+ private readonly INamedTypeSymbol? _deterministic;
+ private readonly ConcurrentDictionary _simulationTypes = new(SymbolEqualityComparer.Default);
+
+ private SimulationScope(Compilation compilation)
+ {
+ _engine = compilation.GetTypeByMetadataName("EpochSim.Execution.SimulationEngine`1");
+ _system = compilation.GetTypeByMetadataName("EpochSim.Kernel.Systems.ISystem`1");
+ _commandHandler = compilation.GetTypeByMetadataName("EpochSim.Kernel.Messaging.ICommandHandler`2");
+ _invariant = compilation.GetTypeByMetadataName("EpochSim.Kernel.Validation.IInvariant`1");
+ _deterministic = compilation.GetTypeByMetadataName("EpochSim.Kernel.Determinism.DeterministicAttribute");
+ }
+
+ public static SimulationScope? Create(Compilation compilation)
+ {
+ var scope = new SimulationScope(compilation);
+ return scope.IsRelevant ? scope : null;
+ }
+
+ private bool IsRelevant
+ => _engine is not null || _system is not null || _commandHandler is not null
+ || _invariant is not null || _deterministic is not null;
+
+ public bool IsRegistration(IMethodSymbol method)
+ => _engine is not null
+ && SymbolEqualityComparer.Default.Equals(method.ContainingType?.OriginalDefinition, _engine)
+ && method.Name is "AddSystem" or "OnCommand";
+
+ public bool IsSimulationCode(IOperation operation, ISymbol containingSymbol)
+ {
+ for (var current = operation; current is not null; current = current.Parent)
+ {
+ if (current is IAnonymousFunctionOperation lambda && IsRegisteredLambda(lambda))
+ return true;
+ }
+
+ for (var symbol = containingSymbol; symbol is not null; symbol = symbol.ContainingSymbol)
+ {
+ if (symbol is IMethodSymbol method && HasDeterministicAttribute(method))
+ return true;
+
+ if (symbol is INamedTypeSymbol type && IsSimulationType(type))
+ return true;
+ }
+
+ return false;
+ }
+
+ private bool IsRegisteredLambda(IAnonymousFunctionOperation lambda)
+ {
+ var parent = lambda.Parent;
+ while (parent is IDelegateCreationOperation or IConversionOperation or IParenthesizedOperation)
+ parent = parent.Parent;
+
+ return parent is IArgumentOperation { Parent: IInvocationOperation invocation }
+ && IsRegistration(invocation.TargetMethod);
+ }
+
+ private bool IsSimulationType(INamedTypeSymbol type)
+ => _simulationTypes.GetOrAdd(type, candidate => HasDeterministicAttribute(candidate) || ImplementsSimulationInterface(candidate));
+
+ private bool ImplementsSimulationInterface(INamedTypeSymbol type)
+ => type.AllInterfaces.Any(candidate =>
+ {
+ var definition = candidate.OriginalDefinition;
+ return SymbolEqualityComparer.Default.Equals(definition, _system)
+ || SymbolEqualityComparer.Default.Equals(definition, _commandHandler)
+ || SymbolEqualityComparer.Default.Equals(definition, _invariant);
+ });
+
+ private bool HasDeterministicAttribute(ISymbol symbol)
+ => _deterministic is not null
+ && symbol.GetAttributes().Any(attribute => SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, _deterministic));
+
+ public static IMethodSymbol? ReferencedMethod(IOperation argumentValue)
+ {
+ var current = argumentValue;
+ while (current is IDelegateCreationOperation or IConversionOperation or IParenthesizedOperation)
+ {
+ current = current switch
+ {
+ IDelegateCreationOperation creation => creation.Target,
+ IConversionOperation conversion => conversion.Operand,
+ IParenthesizedOperation parenthesized => parenthesized.Operand,
+ _ => current
+ };
+ }
+
+ return (current as IMethodReferenceOperation)?.Method.OriginalDefinition;
+ }
+}
diff --git a/src/EpochSim.Cli/App/CliApp.cs b/src/EpochSim.Cli/App/CliApp.cs
index 6b35250..035ba17 100644
--- a/src/EpochSim.Cli/App/CliApp.cs
+++ b/src/EpochSim.Cli/App/CliApp.cs
@@ -28,6 +28,7 @@ public CliApp()
["inspect-run"] = new InspectRunCommand(),
["bisect"] = new BisectCommand(),
["repro"] = new ReproCommand(),
+ ["fuzz"] = new FuzzCommand(),
["list-adapters"] = new ListAdaptersCommand()
};
}
@@ -38,6 +39,11 @@ public Task RunAsync(string[] args)
var root = args.Length > 1 ? args[1] : "artifacts";
var commandArgs = args.Length > 2 ? args.Skip(2).ToArray() : Array.Empty();
+ if (string.Equals(commandName, "fuzz", StringComparison.OrdinalIgnoreCase))
+ {
+ commandArgs = args.Skip(1).ToArray();
+ }
+
if (string.Equals(commandName, "init", StringComparison.OrdinalIgnoreCase))
{
root = Directory.GetCurrentDirectory();
@@ -100,6 +106,7 @@ private static void PrintUsage()
Console.WriteLine(" list-runs [limit]");
Console.WriteLine(" inspect-run ");
Console.WriteLine(" repro [runId] [failureTick] [seedOverride]");
+ Console.WriteLine(" fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parallel N] [--out dir]");
Console.WriteLine(" list-adapters");
Console.WriteLine();
Console.WriteLine("Pass --help to any command for detailed usage.");
diff --git a/src/EpochSim.Cli/Commands/BisectCommand.cs b/src/EpochSim.Cli/Commands/BisectCommand.cs
index e7631dc..104c23c 100644
--- a/src/EpochSim.Cli/Commands/BisectCommand.cs
+++ b/src/EpochSim.Cli/Commands/BisectCommand.cs
@@ -9,11 +9,15 @@
using EpochSim.Execution.Snapshots;
using EpochSim.Kernel.Determinism;
using EpochSim.Kernel.Validation;
+using EpochSim.Serialization.EventLog;
namespace EpochSim.Cli.Commands;
public sealed class BisectCommand : DomainCommandBase
{
+ private const int MaxEventLines = 20;
+ private const string StateDiffFileName = "statediff.txt";
+
public string Help =>
"""
bisect [runId] [--end-tick N] [--seed N]
@@ -86,7 +90,7 @@ protected override int Execute(IDomainAdapter adapter, CommandCo
RngVersion = ResolveRngVersion(manifest?.RngVersion)
};
- bool FailsUpTo(long probeTick, out InvariantViolationException? ex)
+ bool FailsUpTo(long probeTick, out InvariantViolationException? ex, out TState probedState)
{
var engine = new SimulationEngine();
adapter.ConfigureEngine(engine);
@@ -103,7 +107,7 @@ bool FailsUpTo(long probeTick, out InvariantViolationException? ex)
try
{
- SnapshotRunner.LoadBestAndReplayTo(
+ probedState = SnapshotRunner.LoadBestAndReplayTo(
engine: engine,
snapshotsDir: paths.SnapshotsDir,
eventsPath: eventsPath,
@@ -121,6 +125,7 @@ bool FailsUpTo(long probeTick, out InvariantViolationException? ex)
catch (InvariantViolationException e)
{
ex = e;
+ probedState = world;
return true;
}
}
@@ -130,7 +135,7 @@ bool FailsUpTo(long probeTick, out InvariantViolationException? ex)
Console.WriteLine($"EndTick={endTick}");
Console.WriteLine($"Seed={seed}");
- if (!FailsUpTo(endTick, out var exAtEnd))
+ if (!FailsUpTo(endTick, out var exAtEnd, out _))
{
Console.WriteLine("NoInvariantViolationUpToEndTick");
return 0;
@@ -143,13 +148,13 @@ bool FailsUpTo(long probeTick, out InvariantViolationException? ex)
{
var mid = lo + ((hi - lo) / 2);
- if (FailsUpTo(mid, out var exMid))
+ if (FailsUpTo(mid, out var exMid, out _))
hi = exMid!.Time.Tick;
else
lo = mid + 1;
}
- FailsUpTo(lo, out var exFinal);
+ FailsUpTo(lo, out var exFinal, out var failedState);
Console.WriteLine($"FirstViolationTick={lo}");
@@ -158,6 +163,20 @@ bool FailsUpTo(long probeTick, out InvariantViolationException? ex)
Console.WriteLine($"Invariant={exFinal.InvariantName}");
Console.WriteLine($"Message={exFinal.Detail}");
+ var previousStateJson = lo > 0 && !FailsUpTo(lo - 1, out _, out var previousState)
+ ? stateSerializer.Serialize(previousState)
+ : stateSerializer.Serialize(adapter.CreateInitialState());
+
+ var diffReport = BuildDiffReport(
+ lo,
+ previousStateJson,
+ stateSerializer.Serialize(failedState),
+ EventLogReader.ReadStream(eventsPath).Where(e => e.Tick == lo).ToArray(),
+ adapter);
+
+ foreach (var line in diffReport)
+ Console.WriteLine(line);
+
var minDir = MinReproWriter.Create(
paths: paths,
failureTick: lo,
@@ -168,6 +187,8 @@ bool FailsUpTo(long probeTick, out InvariantViolationException? ex)
serializer: stateSerializer,
newState: adapter.CreateInitialState);
+ File.WriteAllLines(Path.Combine(minDir, StateDiffFileName), diffReport);
+
Console.WriteLine($"MinReproDir={minDir}");
Console.WriteLine("MinReproFiles=snapshot.json,events.jsonl,meta.txt");
}
@@ -175,6 +196,33 @@ bool FailsUpTo(long probeTick, out InvariantViolationException? ex)
return 2;
}
+ private static IReadOnlyList BuildDiffReport(
+ long tick,
+ string previousStateJson,
+ string failedStateJson,
+ IReadOnlyList eventsAtTick,
+ IDomainAdapter adapter)
+ {
+ var title = tick > 0
+ ? $"StateDiff (tick {tick - 1} -> {tick}):"
+ : "StateDiff (initial -> tick 0):";
+
+ var lines = new List(StateDiffReport.Describe(title, previousStateJson, failedStateJson))
+ {
+ $"EventsAtTick={eventsAtTick.Count}"
+ };
+
+ foreach (var entry in eventsAtTick.Take(MaxEventLines))
+ {
+ var text = adapter.PayloadFormatter.TryFormat(entry.Kind, entry.PayloadJson, out var formatted)
+ ? formatted
+ : entry.PayloadJson;
+ lines.Add($" [{entry.Kind}] {text}");
+ }
+
+ return lines;
+ }
+
private static RngVersion ResolveRngVersion(string? raw)
{
if (string.Equals(raw, "V1", StringComparison.OrdinalIgnoreCase))
diff --git a/src/EpochSim.Cli/Commands/FuzzCommand.cs b/src/EpochSim.Cli/Commands/FuzzCommand.cs
new file mode 100644
index 0000000..ff4c5a1
--- /dev/null
+++ b/src/EpochSim.Cli/Commands/FuzzCommand.cs
@@ -0,0 +1,76 @@
+using EpochSim.Cli.App;
+using EpochSim.Cli.Domain;
+using EpochSim.Fuzzing;
+
+namespace EpochSim.Cli.Commands;
+
+public sealed class FuzzCommand : ICliCommand
+{
+ private const int FailuresFoundExitCode = 2;
+
+ public string Help =>
+ """
+ fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parallel N] [--out dir]
+
+ Run the adapter's simulation over a range of seeds and report invariant violations,
+ exceptions and non-determinism. Returns exit code 2 when a failure is found, 0 otherwise.
+
+ --adapter name Domain adapter (default: population, see list-adapters)
+ --seeds A..B Seed range, or a single seed N (default: 1..1000)
+ --ticks N Last tick of every run (default: 500)
+ --check-determinism Run every seed twice and compare state fingerprints
+ --parallel N Concurrent runs (default: processor count)
+ --out dir Artifacts directory for failed seeds (default: artifacts)
+ """;
+
+ public int Execute(CommandContext ctx, string[] args)
+ {
+ var options = FuzzOptions.Parse(args);
+ var adapter = DomainAdapterRegistry.Resolve(options.AdapterName);
+ return DomainAdapterDispatch.Invoke(adapter, new Invoker(options));
+ }
+
+ private static int Run(IDomainAdapter adapter, FuzzOptions options)
+ {
+ var report = Epoch.Fuzz(fuzz =>
+ {
+ fuzz.State(adapter.CreateInitialState)
+ .Engine(adapter.ConfigureEngine)
+ .Serializer(adapter.Serializer)
+ .Invariants(adapter.CreateInvariants)
+ .EventCodec(adapter.Codec)
+ .Seeds(options.FromSeed, options.ToSeed)
+ .Ticks(options.Ticks)
+ .CheckDeterminism(options.CheckDeterminism)
+ .ArtifactsRoot(options.OutputDirectory);
+
+ if (options.Parallelism is { } degree)
+ fuzz.Parallelism(degree);
+ });
+
+ Console.WriteLine($"SeedsRun={report.SeedsRun} Failures={report.Failures.Count} ElapsedMs={(long)report.Duration.TotalMilliseconds}");
+
+ foreach (var failure in report.Failures)
+ {
+ var cliFailure = failure with
+ {
+ ReproCode = options.ReproCommand(
+ adapter.Name,
+ failure.Seed,
+ failure.Tick,
+ failure.Kind == FuzzFailureKind.NonDeterminism)
+ };
+
+ Console.WriteLine();
+ Console.WriteLine(cliFailure.ToText());
+ }
+
+ return report.Passed ? 0 : FailuresFoundExitCode;
+ }
+
+ private sealed class Invoker(FuzzOptions options) : IDomainAdapterInvoker
+ {
+ public int Invoke(IDomainAdapter adapter)
+ => Run(adapter, options);
+ }
+}
diff --git a/src/EpochSim.Cli/Commands/FuzzOptions.cs b/src/EpochSim.Cli/Commands/FuzzOptions.cs
new file mode 100644
index 0000000..e33b312
--- /dev/null
+++ b/src/EpochSim.Cli/Commands/FuzzOptions.cs
@@ -0,0 +1,79 @@
+using EpochSim.Cli.Parsing;
+
+namespace EpochSim.Cli.Commands;
+
+internal sealed record FuzzOptions(
+ string? AdapterName,
+ ulong FromSeed,
+ ulong ToSeed,
+ long Ticks,
+ bool CheckDeterminism,
+ int? Parallelism,
+ string OutputDirectory)
+{
+ private const ulong DefaultFromSeed = 1;
+ private const ulong DefaultToSeed = 1000;
+ private const long DefaultTicks = 500;
+ private const string DefaultOutputDirectory = "artifacts";
+
+ public static FuzzOptions Parse(string[] args)
+ {
+ var options = new FuzzOptions(null, DefaultFromSeed, DefaultToSeed, DefaultTicks, false, null, DefaultOutputDirectory);
+
+ for (var i = 0; i < args.Length; i++)
+ {
+ var option = args[i].ToLowerInvariant();
+
+ options = option switch
+ {
+ "--adapter" => options with { AdapterName = ReadValue(args, ref i, option) },
+ "--seeds" => WithSeeds(options, ReadValue(args, ref i, option)),
+ "--ticks" => options with { Ticks = ParseTicks(ReadValue(args, ref i, option)) },
+ "--check-determinism" => options with { CheckDeterminism = true },
+ "--parallel" => options with { Parallelism = ParseParallelism(ReadValue(args, ref i, option)) },
+ "--out" => options with { OutputDirectory = ReadValue(args, ref i, option) },
+ _ => throw new ArgumentException($"Unknown argument '{args[i]}'. Run 'fuzz --help' for usage.")
+ };
+ }
+
+ return options;
+ }
+
+ public string ReproCommand(string adapterName, ulong seed, long tick, bool checkDeterminism)
+ {
+ var command = $"epochsim fuzz --adapter {adapterName} --seeds {seed} --ticks {tick} --out {OutputDirectory}";
+ return checkDeterminism ? $"{command} --check-determinism" : command;
+ }
+
+ private static string ReadValue(string[] args, ref int index, string option)
+ {
+ if (index + 1 >= args.Length || CliParsing.IsOption(args[index + 1]))
+ throw new ArgumentException($"Option {option} requires a value.");
+
+ index++;
+ return args[index];
+ }
+
+ private static FuzzOptions WithSeeds(FuzzOptions options, string value)
+ {
+ var parts = value.Split("..", StringSplitOptions.None);
+
+ if (parts.Length is < 1 or > 2
+ || !CliParsing.TryParseUlong(parts[0], out var from)
+ || !CliParsing.TryParseUlong(parts[^1], out var to)
+ || from > to)
+ throw new ArgumentException($"Invalid --seeds value '{value}'. Expected N or A..B with A <= B.");
+
+ return options with { FromSeed = from, ToSeed = to };
+ }
+
+ private static long ParseTicks(string value)
+ => CliParsing.TryParseLong(value, out var ticks) && ticks >= 0
+ ? ticks
+ : throw new ArgumentException($"Invalid --ticks value '{value}'. Expected a non-negative integer.");
+
+ private static int ParseParallelism(string value)
+ => CliParsing.TryParseInt(value, out var degree) && degree >= 1
+ ? degree
+ : throw new ArgumentException($"Invalid --parallel value '{value}'. Expected an integer >= 1.");
+}
diff --git a/src/EpochSim.Cli/Commands/InitCommand.cs b/src/EpochSim.Cli/Commands/InitCommand.cs
index 6055978..bae88db 100644
--- a/src/EpochSim.Cli/Commands/InitCommand.cs
+++ b/src/EpochSim.Cli/Commands/InitCommand.cs
@@ -58,7 +58,7 @@ public int Execute(CommandContext ctx, string[] args)
-
+
diff --git a/src/EpochSim.Cli/Commands/StateDiffReport.cs b/src/EpochSim.Cli/Commands/StateDiffReport.cs
new file mode 100644
index 0000000..acbfeee
--- /dev/null
+++ b/src/EpochSim.Cli/Commands/StateDiffReport.cs
@@ -0,0 +1,19 @@
+using EpochSim.Serialization.State;
+
+namespace EpochSim.Cli.Commands;
+
+internal static class StateDiffReport
+{
+ public static IReadOnlyList Describe(string title, string beforeJson, string afterJson)
+ {
+ var lines = new List { title };
+ var diff = StateDiffFormatter.Format(StateDiff.Compute(beforeJson, afterJson));
+
+ if (diff.Count == 0)
+ lines.Add(" (no field changes)");
+ else
+ lines.AddRange(diff.Select(line => $" {line}"));
+
+ return lines;
+ }
+}
diff --git a/src/EpochSim.Cli/Commands/VerifyRunCommand.cs b/src/EpochSim.Cli/Commands/VerifyRunCommand.cs
index b95db56..7fd51ed 100644
--- a/src/EpochSim.Cli/Commands/VerifyRunCommand.cs
+++ b/src/EpochSim.Cli/Commands/VerifyRunCommand.cs
@@ -9,6 +9,7 @@
using EpochSim.Execution.Snapshots;
using EpochSim.Execution.StateFingerprint;
using EpochSim.Kernel.Determinism;
+using EpochSim.Serialization.Snapshots;
namespace EpochSim.Cli.Commands;
@@ -122,9 +123,49 @@ protected override int Execute(IDomainAdapter adapter, CommandCo
Console.WriteLine($"VerifyMismatchTick={mismatch.Value.Tick}");
Console.WriteLine($"Expected={mismatch.Value.Expected}");
Console.WriteLine($"Actual={mismatch.Value.Actual}");
+
+ foreach (var line in DescribeMismatch(adapter, paths, mismatch.Value.Tick, seed, options, ctx))
+ Console.WriteLine(line);
+
return 3;
}
+ private static IReadOnlyList DescribeMismatch(
+ IDomainAdapter adapter,
+ RunPaths paths,
+ long tick,
+ ulong seed,
+ RunOptions options,
+ CommandContext ctx)
+ {
+ var snapshotPath = Path.Combine(paths.SnapshotsDir, $"snapshot-{tick}.json");
+ if (!File.Exists(snapshotPath))
+ return [$"StateDiffUnavailable: no snapshot at tick {tick}"];
+
+ var snapshot = SnapshotReader.Read(snapshotPath);
+
+ var engine = new SimulationEngine();
+ adapter.ConfigureEngine(engine);
+
+ var replayed = SnapshotRunner.LoadBestAndReplayTo(
+ engine: engine,
+ snapshotsDir: paths.SnapshotsDir,
+ eventsPath: paths.ResolveEventsPath(),
+ serializer: adapter.Serializer,
+ codec: adapter.Codec,
+ seed: seed,
+ endTick: tick,
+ newState: adapter.CreateInitialState,
+ options: options,
+ cancellationToken: ctx.Cancellation,
+ maxSnapshotTick: tick - 1);
+
+ return StateDiffReport.Describe(
+ $"StateDiff (snapshot -> replay, tick {tick}):",
+ snapshot.StateJson,
+ adapter.Serializer.Serialize(replayed));
+ }
+
private static (long Tick, string Expected, string Actual)? FindFirstMismatch(
Dictionary expected,
IReadOnlyList<(long Tick, string Hash)> actual,
diff --git a/src/EpochSim.Cli/Domain/DomainAdapterRegistry.cs b/src/EpochSim.Cli/Domain/DomainAdapterRegistry.cs
index 6dde072..0e7f332 100644
--- a/src/EpochSim.Cli/Domain/DomainAdapterRegistry.cs
+++ b/src/EpochSim.Cli/Domain/DomainAdapterRegistry.cs
@@ -5,7 +5,8 @@ public static class DomainAdapterRegistry
private static readonly Dictionary Adapters =
new(StringComparer.OrdinalIgnoreCase)
{
- ["population"] = new PopulationDomainAdapter()
+ ["population"] = new PopulationDomainAdapter(),
+ ["fuzzbug"] = new FuzzBugDomainAdapter()
};
public static IDomainAdapter Default => Adapters["population"];
diff --git a/src/EpochSim.Cli/Domain/FuzzBugDomainAdapter.cs b/src/EpochSim.Cli/Domain/FuzzBugDomainAdapter.cs
new file mode 100644
index 0000000..e6f510a
--- /dev/null
+++ b/src/EpochSim.Cli/Domain/FuzzBugDomainAdapter.cs
@@ -0,0 +1,41 @@
+using EpochSim.Execution;
+using EpochSim.Execution.Diagnostics;
+using EpochSim.Kernel.Validation;
+using EpochSim.Samples.Fuzzing;
+using EpochSim.Serialization.EventLog;
+using EpochSim.Serialization.State;
+
+namespace EpochSim.Cli.Domain;
+
+public sealed class FuzzBugDomainAdapter : IDomainAdapter
+{
+ public string Name => "fuzzbug";
+ public Type StateType => typeof(JobQueueState);
+ public IEventCodecV2 Codec { get; } = new JsonEventCodecBuilder().Build();
+ public IStateSerializer Serializer { get; } = new JsonStateSerializer();
+ public IEventPayloadFormatter PayloadFormatter { get; } = new JsonEventPayloadFormatter();
+
+ object IDomainAdapter.Serializer => Serializer;
+
+ public JobQueueState CreateInitialState() => new();
+
+ object IDomainAdapter.CreateInitialState() => CreateInitialState();
+
+ public void ConfigureEngine(SimulationEngine engine)
+ => engine.AddSystem(new JobQueueSystem());
+
+ void IDomainAdapter.ConfigureEngine(object engine)
+ => ConfigureEngine((SimulationEngine)engine);
+
+ public IReadOnlyList> CreateInvariants()
+ => [new QueueNonNegativeInvariant()];
+
+ IReadOnlyList