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 IDomainAdapter.CreateInvariants() + => CreateInvariants().Cast().ToList(); + + public IReadOnlyList DescribeState(JobQueueState state) + => [$"Pending={state.Pending}", $"Completed={state.Completed}"]; + + IReadOnlyList IDomainAdapter.DescribeState(object state) + => DescribeState((JobQueueState)state); +} diff --git a/src/EpochSim.Execution/Snapshots/SnapshotRunner.cs b/src/EpochSim.Execution/Snapshots/SnapshotRunner.cs index 0452144..2ff68b4 100644 --- a/src/EpochSim.Execution/Snapshots/SnapshotRunner.cs +++ b/src/EpochSim.Execution/Snapshots/SnapshotRunner.cs @@ -18,9 +18,10 @@ public static TState LoadBestAndReplayTo( long endTick, Func newState, RunOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default, + long? maxSnapshotTick = null) { - var snapshotPath = SnapshotLocator.FindBestSnapshot(snapshotsDir, endTick); + var snapshotPath = SnapshotLocator.FindBestSnapshot(snapshotsDir, maxSnapshotTick ?? endTick); TState state; long startTick; diff --git a/src/EpochSim.Kernel/Determinism/DeterministicAttribute.cs b/src/EpochSim.Kernel/Determinism/DeterministicAttribute.cs new file mode 100644 index 0000000..821f31e --- /dev/null +++ b/src/EpochSim.Kernel/Determinism/DeterministicAttribute.cs @@ -0,0 +1,4 @@ +namespace EpochSim.Kernel.Determinism; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +public sealed class DeterministicAttribute : Attribute; diff --git a/src/EpochSim.Samples/Fuzzing/JobQueueState.cs b/src/EpochSim.Samples/Fuzzing/JobQueueState.cs new file mode 100644 index 0000000..b91b822 --- /dev/null +++ b/src/EpochSim.Samples/Fuzzing/JobQueueState.cs @@ -0,0 +1,7 @@ +namespace EpochSim.Samples.Fuzzing; + +public sealed class JobQueueState +{ + public int Pending { get; set; } + public int Completed { get; set; } +} diff --git a/src/EpochSim.Samples/Fuzzing/JobQueueSystem.cs b/src/EpochSim.Samples/Fuzzing/JobQueueSystem.cs new file mode 100644 index 0000000..7365e65 --- /dev/null +++ b/src/EpochSim.Samples/Fuzzing/JobQueueSystem.cs @@ -0,0 +1,27 @@ +using EpochSim.Kernel.Systems; + +namespace EpochSim.Samples.Fuzzing; + +public sealed class JobQueueSystem : ISystem +{ + private const int DuplicateAcknowledgementOdds = 20_000; + + public string Name => "JobQueue"; + + public void Tick(TickContext ctx) + { + ctx.State.Pending += ctx.Rng.NextInt(0, 2); + + if (ctx.State.Pending > 0 && ctx.Rng.NextInt(0, 4) != 0) + Complete(ctx.State); + + if (ctx.Rng.NextInt(0, DuplicateAcknowledgementOdds) == 0) + Complete(ctx.State); + } + + private static void Complete(JobQueueState state) + { + state.Pending--; + state.Completed++; + } +} diff --git a/src/EpochSim.Samples/Fuzzing/QueueNonNegativeInvariant.cs b/src/EpochSim.Samples/Fuzzing/QueueNonNegativeInvariant.cs new file mode 100644 index 0000000..caf05e3 --- /dev/null +++ b/src/EpochSim.Samples/Fuzzing/QueueNonNegativeInvariant.cs @@ -0,0 +1,21 @@ +using EpochSim.Kernel.Time; +using EpochSim.Kernel.Validation; + +namespace EpochSim.Samples.Fuzzing; + +public sealed class QueueNonNegativeInvariant : IInvariant +{ + public string Name => "QueueNonNegative"; + + public bool Check(SimTime time, JobQueueState state, out string message) + { + if (state.Pending >= 0) + { + message = string.Empty; + return true; + } + + message = $"Pending={state.Pending}"; + return false; + } +} diff --git a/src/EpochSim.Samples/Fuzzing/StaticCounterState.cs b/src/EpochSim.Samples/Fuzzing/StaticCounterState.cs new file mode 100644 index 0000000..15b403e --- /dev/null +++ b/src/EpochSim.Samples/Fuzzing/StaticCounterState.cs @@ -0,0 +1,6 @@ +namespace EpochSim.Samples.Fuzzing; + +public sealed class StaticCounterState +{ + public long Value { get; set; } +} diff --git a/src/EpochSim.Samples/Fuzzing/StaticCounterSystem.cs b/src/EpochSim.Samples/Fuzzing/StaticCounterSystem.cs new file mode 100644 index 0000000..0f48a42 --- /dev/null +++ b/src/EpochSim.Samples/Fuzzing/StaticCounterSystem.cs @@ -0,0 +1,13 @@ +using EpochSim.Kernel.Systems; + +namespace EpochSim.Samples.Fuzzing; + +public sealed class StaticCounterSystem : ISystem +{ + private static long _shared; + + public string Name => "StaticCounter"; + + public void Tick(TickContext ctx) + => ctx.State.Value += Interlocked.Increment(ref _shared); +} diff --git a/src/EpochSim.Serialization/State/StateChange.cs b/src/EpochSim.Serialization/State/StateChange.cs new file mode 100644 index 0000000..63c6011 --- /dev/null +++ b/src/EpochSim.Serialization/State/StateChange.cs @@ -0,0 +1,5 @@ +namespace EpochSim.Serialization.State; + +public enum StateChangeKind { Added, Removed, Changed } + +public readonly record struct StateChange(string Path, StateChangeKind Kind, string? Before, string? After); diff --git a/src/EpochSim.Serialization/State/StateDiff.cs b/src/EpochSim.Serialization/State/StateDiff.cs new file mode 100644 index 0000000..72dd0fe --- /dev/null +++ b/src/EpochSim.Serialization/State/StateDiff.cs @@ -0,0 +1,109 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace EpochSim.Serialization.State; + +public static class StateDiff +{ + private const int MaxValueLength = 80; + private const string Ellipsis = "…"; + + private static readonly JsonSerializerOptions RenderOptions = new() + { + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }; + + public static IReadOnlyList Compute(string beforeJson, string afterJson) + { + ArgumentNullException.ThrowIfNull(beforeJson); + ArgumentNullException.ThrowIfNull(afterJson); + + var before = JsonNode.Parse(CanonicalJson.Canonicalize(beforeJson)); + var after = JsonNode.Parse(CanonicalJson.Canonicalize(afterJson)); + + var changes = new List(); + Compare("$", before, after, changes); + changes.Sort((left, right) => string.CompareOrdinal(left.Path, right.Path)); + return changes; + } + + private static void Compare(string path, JsonNode? before, JsonNode? after, List changes) + { + switch (before, after) + { + case (JsonObject beforeObject, JsonObject afterObject): + CompareObjects(path, beforeObject, afterObject, changes); + break; + + case (JsonArray beforeArray, JsonArray afterArray): + CompareArrays(path, beforeArray, afterArray, changes); + break; + + default: + var beforeText = Render(before); + var afterText = Render(after); + if (!string.Equals(beforeText, afterText, StringComparison.Ordinal)) + changes.Add(new StateChange(path, StateChangeKind.Changed, Truncate(beforeText), Truncate(afterText))); + break; + } + } + + private static void CompareObjects(string path, JsonObject before, JsonObject after, List changes) + { + foreach (var (key, beforeValue) in before) + { + var childPath = AppendKey(path, key); + if (after.TryGetPropertyValue(key, out var afterValue)) + Compare(childPath, beforeValue, afterValue, changes); + else + changes.Add(new StateChange(childPath, StateChangeKind.Removed, Truncate(Render(beforeValue)), null)); + } + + foreach (var (key, afterValue) in after) + { + if (!before.ContainsKey(key)) + changes.Add(new StateChange(AppendKey(path, key), StateChangeKind.Added, null, Truncate(Render(afterValue)))); + } + } + + private static void CompareArrays(string path, JsonArray before, JsonArray after, List changes) + { + var shared = Math.Min(before.Count, after.Count); + + for (var i = 0; i < shared; i++) + Compare(AppendIndex(path, i), before[i], after[i], changes); + + for (var i = shared; i < before.Count; i++) + changes.Add(new StateChange(AppendIndex(path, i), StateChangeKind.Removed, Truncate(Render(before[i])), null)); + + for (var i = shared; i < after.Count; i++) + changes.Add(new StateChange(AppendIndex(path, i), StateChangeKind.Added, null, Truncate(Render(after[i])))); + } + + private static string AppendIndex(string path, int index) + => $"{path}[{index}]"; + + private static string AppendKey(string path, string key) + => IsSimpleKey(key) + ? $"{path}.{key}" + : $"{path}[\"{key.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal)}\"]"; + + private static bool IsSimpleKey(string key) + => key.Length > 0 && key.All(static c => char.IsLetterOrDigit(c) || c == '_'); + + private static string Render(JsonNode? node) + => node is null ? "null" : node.ToJsonString(RenderOptions); + + private static string Truncate(string value) + { + if (value.Length <= MaxValueLength) + return value; + + var keep = MaxValueLength - Ellipsis.Length; + if (char.IsHighSurrogate(value[keep - 1])) + keep--; + + return string.Concat(value.AsSpan(0, keep), Ellipsis); + } +} diff --git a/src/EpochSim.Serialization/State/StateDiffFormatter.cs b/src/EpochSim.Serialization/State/StateDiffFormatter.cs new file mode 100644 index 0000000..3fd4805 --- /dev/null +++ b/src/EpochSim.Serialization/State/StateDiffFormatter.cs @@ -0,0 +1,28 @@ +namespace EpochSim.Serialization.State; + +public static class StateDiffFormatter +{ + public static IReadOnlyList Format(IReadOnlyList changes, int maxLines = 50) + { + ArgumentNullException.ThrowIfNull(changes); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxLines); + + var lines = new List(Math.Min(changes.Count, maxLines) + 1); + + for (var i = 0; i < changes.Count && i < maxLines; i++) + lines.Add(FormatChange(changes[i])); + + if (changes.Count > maxLines) + lines.Add($"... and {changes.Count - maxLines} more changes"); + + return lines; + } + + private static string FormatChange(StateChange change) + => change.Kind switch + { + StateChangeKind.Added => $"{change.Path}: added {change.After}", + StateChangeKind.Removed => $"{change.Path}: removed {change.Before}", + _ => $"{change.Path}: {change.Before} -> {change.After}" + }; +} diff --git a/src/EpochSim.Testing/EpochSim.Testing.csproj b/src/EpochSim.Testing/EpochSim.Testing.csproj new file mode 100644 index 0000000..8e6456d --- /dev/null +++ b/src/EpochSim.Testing/EpochSim.Testing.csproj @@ -0,0 +1,28 @@ + + + + + + + + net10.0 + enable + enable + true + EpochSim.Testing + + Framework-agnostic assertions for EpochSim: check determinism and invariants over seed ranges from xUnit, NUnit or MSTest. + epochsim;testing;assert;fuzz;deterministic;simulation;xunit;nunit;mstest + Echways + https://github.com/Echways/EpochSim + https://github.com/Echways/EpochSim + git + MIT + README.md + + + + + + + diff --git a/src/EpochSim.Testing/GoldenFile.cs b/src/EpochSim.Testing/GoldenFile.cs new file mode 100644 index 0000000..d79feb0 --- /dev/null +++ b/src/EpochSim.Testing/GoldenFile.cs @@ -0,0 +1,90 @@ +using System.Text.Json; +using EpochSim.Fuzzing; + +namespace EpochSim.Testing; + +internal sealed record GoldenFile(ulong Seed, long Ticks, SortedDictionary Fingerprints) +{ + private const long CheckpointInterval = 100; + private const string UpdateVariable = "EPOCHSIM_UPDATE_GOLDEN"; + + private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true }; + + public static GoldenFile Capture(FuzzRunResult result, ulong seed, long ticks) + { + if (result.Error is { } error) + throw new SimulationAssertionException($"The run failed before fingerprints could be compared: {error.GetType().Name}: {error.Message}"); + + var checkpoints = result.Fingerprints + .Where(record => record.Tick % CheckpointInterval == 0 || record.Tick == ticks) + .ToDictionary(record => record.Tick, record => record.Hash); + + if (checkpoints.Count == 0) + throw new SimulationAssertionException("A golden check needs a run of at least one tick."); + + return new GoldenFile(seed, ticks, new SortedDictionary(checkpoints)); + } + + public static void Verify(string path, GoldenFile actual) + { + if (!File.Exists(path) || UpdateRequested()) + { + Write(path, actual); + return; + } + + var expected = Read(path); + + if (expected.Seed != actual.Seed || expected.Ticks != actual.Ticks) + { + throw new SimulationAssertionException( + $"Golden file '{path}' was recorded with seed {expected.Seed} and {expected.Ticks} ticks, " + + $"but the check ran with seed {actual.Seed} and {actual.Ticks} ticks. {UpdateHint}"); + } + + var tick = expected.Fingerprints.Keys.Union(actual.Fingerprints.Keys).Order() + .FirstOrDefault(candidate => !Same(expected, actual, candidate), -1L); + + if (tick >= 0) + { + throw new SimulationAssertionException( + $"Golden fingerprint mismatch at tick {tick} (seed {actual.Seed}): " + + $"expected {Describe(expected, tick)}, actual {Describe(actual, tick)}. {UpdateHint}"); + } + } + + private static string UpdateHint => $"Set {UpdateVariable}=1 to accept the current behavior."; + + private static bool UpdateRequested() + => string.Equals(Environment.GetEnvironmentVariable(UpdateVariable), "1", StringComparison.Ordinal); + + private static bool Same(GoldenFile expected, GoldenFile actual, long tick) + => expected.Fingerprints.TryGetValue(tick, out var left) + && actual.Fingerprints.TryGetValue(tick, out var right) + && string.Equals(left, right, StringComparison.Ordinal); + + private static string Describe(GoldenFile file, long tick) + => file.Fingerprints.TryGetValue(tick, out var hash) ? hash : ""; + + private static GoldenFile Read(string path) + { + try + { + return JsonSerializer.Deserialize(File.ReadAllText(path), JsonOptions) + ?? throw new JsonException("The file is empty."); + } + catch (JsonException ex) + { + throw new SimulationAssertionException($"Golden file '{path}' is not valid: {ex.Message} {UpdateHint}"); + } + } + + private static void Write(string path, GoldenFile file) + { + var directory = Path.GetDirectoryName(Path.GetFullPath(path)); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + + File.WriteAllText(path, JsonSerializer.Serialize(file, JsonOptions)); + } +} diff --git a/src/EpochSim.Testing/SimAssert.cs b/src/EpochSim.Testing/SimAssert.cs new file mode 100644 index 0000000..2569acd --- /dev/null +++ b/src/EpochSim.Testing/SimAssert.cs @@ -0,0 +1,46 @@ +using EpochSim.Fuzzing; + +namespace EpochSim.Testing; + +public static class SimAssert +{ + public static void IsDeterministic(Action> configure) + { + ArgumentNullException.ThrowIfNull(configure); + + NoFailures(Epoch.Fuzz(builder => + { + configure(builder); + builder.CheckDeterminism(true); + })); + } + + public static void InvariantsHold(Action> configure) + { + ArgumentNullException.ThrowIfNull(configure); + + NoFailures(Epoch.Fuzz(configure)); + } + + public static void NoFailures(FuzzReport report) + { + ArgumentNullException.ThrowIfNull(report); + + if (!report.Passed) + throw new SimulationAssertionException(report.ToText()); + } + + public static void MatchesGolden(Action> configure, string goldenPath, ulong seed) + { + ArgumentNullException.ThrowIfNull(configure); + ArgumentException.ThrowIfNullOrWhiteSpace(goldenPath); + + var builder = new FuzzBuilder(); + configure(builder); + builder.Seeds(seed, seed); + + var settings = builder.Build(); + var actual = GoldenFile.Capture(FuzzRunner.Trace(settings, seed), seed, settings.EndTick); + GoldenFile.Verify(goldenPath, actual); + } +} diff --git a/src/EpochSim.Testing/SimulationAssertionException.cs b/src/EpochSim.Testing/SimulationAssertionException.cs new file mode 100644 index 0000000..ba9ca9c --- /dev/null +++ b/src/EpochSim.Testing/SimulationAssertionException.cs @@ -0,0 +1,3 @@ +namespace EpochSim.Testing; + +public sealed class SimulationAssertionException(string message) : Exception(message); diff --git a/src/EpochSim/AssemblyInfo.cs b/src/EpochSim/AssemblyInfo.cs new file mode 100644 index 0000000..6f0100d --- /dev/null +++ b/src/EpochSim/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("EpochSim.Testing")] diff --git a/src/EpochSim/Epoch.cs b/src/EpochSim/Epoch.cs index c77b57e..a0c6cd1 100644 --- a/src/EpochSim/Epoch.cs +++ b/src/EpochSim/Epoch.cs @@ -1,5 +1,6 @@ using System.Reflection; using EpochSim.Execution; +using EpochSim.Fuzzing; using EpochSim.Kernel.Validation; using EpochSim.Serialization.EventLog; using EpochSim.Serialization.State; @@ -32,6 +33,15 @@ public static IEventCodecV2 JsonCodecFromAssembly( return builder.Build(); } + public static FuzzReport Fuzz(Action> configure) + { + ArgumentNullException.ThrowIfNull(configure); + + var builder = new FuzzBuilder(); + configure(builder); + return FuzzRunner.Run(builder.Build()); + } + public static EpochSimRunScope QuickRun( TState state, string? rootDir = null) diff --git a/src/EpochSim/EpochSim.csproj b/src/EpochSim/EpochSim.csproj index 11f8b50..cb35710 100644 --- a/src/EpochSim/EpochSim.csproj +++ b/src/EpochSim/EpochSim.csproj @@ -4,6 +4,7 @@ + @@ -25,6 +26,8 @@ + + diff --git a/src/EpochSim/Fuzzing/FuzzBuilder.cs b/src/EpochSim/Fuzzing/FuzzBuilder.cs new file mode 100644 index 0000000..8c035ef --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzBuilder.cs @@ -0,0 +1,145 @@ +using EpochSim.Execution; +using EpochSim.Kernel.Validation; +using EpochSim.Serialization.EventLog; +using EpochSim.Serialization.State; + +namespace EpochSim.Fuzzing; + +public sealed class FuzzBuilder +{ + private Func? _stateFactory; + private Action>? _configureEngine; + private long? _endTick; + private IEnumerable? _seeds; + private IStateSerializer? _serializer; + private Func>>? _invariants; + private Action? _commands; + private bool _checkDeterminism; + private int _parallelism = Environment.ProcessorCount; + private bool _stopAtFirstFailure; + private string? _artifactsRoot; + private IEventCodecV2? _eventCodec; + private IProgress? _progress; + + internal FuzzBuilder() + { + } + + public FuzzBuilder State(Func factory) + { + _stateFactory = factory ?? throw new ArgumentNullException(nameof(factory)); + return this; + } + + public FuzzBuilder Engine(Action> configure) + { + _configureEngine = configure ?? throw new ArgumentNullException(nameof(configure)); + return this; + } + + public FuzzBuilder Ticks(long endTickInclusive) + { + ArgumentOutOfRangeException.ThrowIfNegative(endTickInclusive); + _endTick = endTickInclusive; + return this; + } + + public FuzzBuilder Seeds(ulong fromInclusive, ulong toInclusive) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan(fromInclusive, toInclusive, nameof(fromInclusive)); + _seeds = EnumerateSeeds(fromInclusive, toInclusive); + return this; + } + + public FuzzBuilder Seeds(IEnumerable seeds) + { + _seeds = seeds ?? throw new ArgumentNullException(nameof(seeds)); + return this; + } + + public FuzzBuilder Serializer(IStateSerializer serializer) + { + _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); + return this; + } + + public FuzzBuilder Invariants(Func>> factory) + { + _invariants = factory ?? throw new ArgumentNullException(nameof(factory)); + return this; + } + + public FuzzBuilder Commands(Action configure) + { + _commands = configure ?? throw new ArgumentNullException(nameof(configure)); + return this; + } + + public FuzzBuilder CheckDeterminism(bool enabled = true) + { + _checkDeterminism = enabled; + return this; + } + + public FuzzBuilder Parallelism(int degree) + { + ArgumentOutOfRangeException.ThrowIfLessThan(degree, 1); + _parallelism = degree; + return this; + } + + public FuzzBuilder StopAtFirstFailure(bool enabled = true) + { + _stopAtFirstFailure = enabled; + return this; + } + + public FuzzBuilder ArtifactsRoot(string rootDirectory) + { + ArgumentException.ThrowIfNullOrWhiteSpace(rootDirectory); + _artifactsRoot = rootDirectory; + return this; + } + + public FuzzBuilder EventCodec(IEventCodecV2 codec) + { + _eventCodec = codec ?? throw new ArgumentNullException(nameof(codec)); + return this; + } + + public FuzzBuilder Progress(IProgress progress) + { + _progress = progress ?? throw new ArgumentNullException(nameof(progress)); + return this; + } + + internal FuzzSettings Build() + => new( + _stateFactory ?? throw MissingParameter(nameof(State)), + _configureEngine ?? throw MissingParameter(nameof(Engine)), + _endTick ?? throw MissingParameter(nameof(Ticks)), + _seeds ?? throw MissingParameter(nameof(Seeds)), + _serializer ?? new JsonStateSerializer(), + _invariants, + _commands, + _checkDeterminism, + _parallelism, + _stopAtFirstFailure, + _artifactsRoot, + _eventCodec, + _progress); + + private static InvalidOperationException MissingParameter(string name) + => new($"Epoch.Fuzz requires {name}(...) to be configured."); + + private static IEnumerable EnumerateSeeds(ulong fromInclusive, ulong toInclusive) + { + for (var seed = fromInclusive; ; seed++) + { + yield return seed; + + if (seed == toInclusive) + yield break; + } + } +} diff --git a/src/EpochSim/Fuzzing/FuzzCommandPlan.cs b/src/EpochSim/Fuzzing/FuzzCommandPlan.cs new file mode 100644 index 0000000..e86c175 --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzCommandPlan.cs @@ -0,0 +1,47 @@ +using EpochSim.Kernel.Determinism; +using EpochSim.Kernel.Messaging; + +namespace EpochSim.Fuzzing; + +public sealed class FuzzCommandPlan +{ + private const ulong StreamConstant = 0xD1B54A32D192ED03UL; + + private readonly List<(long Tick, ICommand Command)> _entries = []; + + internal FuzzCommandPlan(ulong seed, long endTick) + { + Seed = seed; + EndTick = endTick; + Rng = new DeterministicRng(SplitMix64(seed ^ StreamConstant)); + } + + public ulong Seed { get; } + public long EndTick { get; } + public IRng Rng { get; } + + internal bool IsEmpty => _entries.Count == 0; + + public void Enqueue(long tick, ICommand command) + { + ArgumentNullException.ThrowIfNull(command); + ArgumentOutOfRangeException.ThrowIfNegative(tick); + ArgumentOutOfRangeException.ThrowIfGreaterThan(tick, EndTick); + + _entries.Add((tick, command)); + } + + internal void ScheduleInto(ScheduledCommandInbox inbox) + { + foreach (var (tick, command) in _entries) + inbox.Enqueue(tick, command); + } + + private static ulong SplitMix64(ulong value) + { + var z = value + 0x9E3779B97F4A7C15UL; + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL; + return z ^ (z >> 31); + } +} diff --git a/src/EpochSim/Fuzzing/FuzzFailedException.cs b/src/EpochSim/Fuzzing/FuzzFailedException.cs new file mode 100644 index 0000000..74799c1 --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzFailedException.cs @@ -0,0 +1,6 @@ +namespace EpochSim.Fuzzing; + +public sealed class FuzzFailedException(FuzzReport report) : Exception(report.ToText()) +{ + public FuzzReport Report { get; } = report; +} diff --git a/src/EpochSim/Fuzzing/FuzzFailure.cs b/src/EpochSim/Fuzzing/FuzzFailure.cs new file mode 100644 index 0000000..0734dfc --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzFailure.cs @@ -0,0 +1,34 @@ +using System.Text; +using EpochSim.Serialization.State; + +namespace EpochSim.Fuzzing; + +public sealed record FuzzFailure( + ulong Seed, + FuzzFailureKind Kind, + long Tick, + string Summary, + IReadOnlyList StateDiff, + string? ArtifactsDir, + string ReproCode) +{ + public string ToText() + { + var text = new StringBuilder(); + text.Append('[').Append(Kind).Append("] seed=").Append(Seed).Append(" tick=").Append(Tick).AppendLine(); + text.Append(" ").AppendLine(Summary); + + if (StateDiff.Count > 0) + { + text.AppendLine(" StateDiff:"); + foreach (var line in StateDiffFormatter.Format(StateDiff)) + text.Append(" ").AppendLine(line); + } + + if (ArtifactsDir is not null) + text.Append(" Artifacts: ").AppendLine(ArtifactsDir); + + text.Append(" Repro: ").Append(ReproCode); + return text.ToString(); + } +} diff --git a/src/EpochSim/Fuzzing/FuzzFailureKind.cs b/src/EpochSim/Fuzzing/FuzzFailureKind.cs new file mode 100644 index 0000000..84852df --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzFailureKind.cs @@ -0,0 +1,3 @@ +namespace EpochSim.Fuzzing; + +public enum FuzzFailureKind { InvariantViolation, Exception, NonDeterminism } diff --git a/src/EpochSim/Fuzzing/FuzzProgress.cs b/src/EpochSim/Fuzzing/FuzzProgress.cs new file mode 100644 index 0000000..b331f36 --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzProgress.cs @@ -0,0 +1,3 @@ +namespace EpochSim.Fuzzing; + +public readonly record struct FuzzProgress(int SeedsRun, int Failures); diff --git a/src/EpochSim/Fuzzing/FuzzReport.cs b/src/EpochSim/Fuzzing/FuzzReport.cs new file mode 100644 index 0000000..b63dee0 --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzReport.cs @@ -0,0 +1,41 @@ +using System.Text; + +namespace EpochSim.Fuzzing; + +public sealed class FuzzReport +{ + internal FuzzReport(int seedsRun, TimeSpan duration, IReadOnlyList failures) + { + SeedsRun = seedsRun; + Duration = duration; + Failures = failures; + } + + public bool Passed => Failures.Count == 0; + public int SeedsRun { get; } + public TimeSpan Duration { get; } + public IReadOnlyList Failures { get; } + + public string ToText() + { + var elapsedMs = (long)Duration.TotalMilliseconds; + if (Passed) + return $"Fuzz passed: SeedsRun={SeedsRun}, ElapsedMs={elapsedMs}"; + + var text = new StringBuilder(); + text.Append("Fuzz failed: Failures=").Append(Failures.Count) + .Append(", SeedsRun=").Append(SeedsRun) + .Append(", ElapsedMs=").Append(elapsedMs).AppendLine(); + + foreach (var failure in Failures) + text.AppendLine().AppendLine(failure.ToText()); + + return text.ToString().TrimEnd(); + } + + public void ThrowIfFailed() + { + if (!Passed) + throw new FuzzFailedException(this); + } +} diff --git a/src/EpochSim/Fuzzing/FuzzRunResult.cs b/src/EpochSim/Fuzzing/FuzzRunResult.cs new file mode 100644 index 0000000..a1132d3 --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzRunResult.cs @@ -0,0 +1,10 @@ +namespace EpochSim.Fuzzing; + +internal sealed record FuzzRunResult( + TState State, + Exception? Error, + long LastTick, + IReadOnlyList<(long Tick, string Hash)> Fingerprints) +{ + public string ErrorSignature => Error is null ? string.Empty : $"{Error.GetType().FullName}|{Error.Message}"; +} diff --git a/src/EpochSim/Fuzzing/FuzzRunner.cs b/src/EpochSim/Fuzzing/FuzzRunner.cs new file mode 100644 index 0000000..806e57c --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzRunner.cs @@ -0,0 +1,60 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Runtime.ExceptionServices; + +namespace EpochSim.Fuzzing; + +internal static class FuzzRunner +{ + private const int MaxArtifactSeeds = 10; + + public static FuzzRunResult Trace(FuzzSettings settings, ulong seed) + => new FuzzSeedRunner(settings).Trace(seed); + + public static FuzzReport Run(FuzzSettings settings) + { + var stopwatch = Stopwatch.StartNew(); + var runner = new FuzzSeedRunner(settings); + var failures = new ConcurrentBag(); + var seedsRun = 0; + var failureCount = 0; + + var options = new ParallelOptions { MaxDegreeOfParallelism = settings.Parallelism }; + var seeds = Partitioner.Create(settings.Seeds, EnumerablePartitionerOptions.NoBuffering); + + try + { + Parallel.ForEach(seeds, options, (seed, loop) => + { + var failure = runner.Check(seed); + var completed = Interlocked.Increment(ref seedsRun); + + if (failure is not null) + { + failures.Add(failure); + Interlocked.Increment(ref failureCount); + + if (settings.StopAtFirstFailure) + loop.Stop(); + } + + settings.Progress?.Report(new FuzzProgress(completed, Volatile.Read(ref failureCount))); + }); + } + catch (AggregateException aggregate) when (aggregate.InnerExceptions.Count == 1) + { + ExceptionDispatchInfo.Capture(aggregate.InnerExceptions[0]).Throw(); + } + + var ordered = failures.OrderBy(failure => failure.Seed).ToList(); + + if (settings.ArtifactsRoot is not null) + { + for (var i = 0; i < ordered.Count && i < MaxArtifactSeeds; i++) + ordered[i] = ordered[i] with { ArtifactsDir = runner.WriteArtifacts(ordered[i]) }; + } + + stopwatch.Stop(); + return new FuzzReport(seedsRun, stopwatch.Elapsed, ordered); + } +} diff --git a/src/EpochSim/Fuzzing/FuzzSeedRunner.cs b/src/EpochSim/Fuzzing/FuzzSeedRunner.cs new file mode 100644 index 0000000..a55309c --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzSeedRunner.cs @@ -0,0 +1,220 @@ +using EpochSim.Execution; +using EpochSim.Execution.Middleware; +using EpochSim.Execution.StateFingerprint; +using EpochSim.Kernel.Time; +using EpochSim.Kernel.Validation; +using EpochSim.Serialization.State; + +namespace EpochSim.Fuzzing; + +internal sealed class FuzzSeedRunner(FuzzSettings settings) +{ + public FuzzFailure? Check(ulong seed) + { + var first = Execute(seed, settings.EndTick, recordFingerprints: settings.CheckDeterminism); + + if (!settings.CheckDeterminism) + return ToFailure(seed, first); + + var second = Execute(seed, settings.EndTick, recordFingerprints: true); + + var divergenceTick = FindDivergenceTick(first, second); + return divergenceTick is { } tick + ? BuildNonDeterminismFailure(seed, tick) + : ToFailure(seed, first); + } + + public FuzzRunResult Trace(ulong seed) + => Execute(seed, settings.EndTick, recordFingerprints: true); + + public string WriteArtifacts(FuzzFailure failure) + { + var root = settings.ArtifactsRoot ?? throw new InvalidOperationException("ArtifactsRoot is not configured."); + var runId = $"fuzz-{failure.Seed}"; + var runDir = Path.Combine(root, runId); + if (Directory.Exists(runDir)) + Directory.Delete(runDir, recursive: true); + + var state = settings.StateFactory(); + var invariants = CreateInvariants(); + var builder = EpochSimRun.For(state) + .WithRootDirectory(root) + .WithRunId(runId); + + if (settings.EventCodec is { } codec) + builder.WithRecommendedDefaults(codec, settings.Serializer, invariants); + else + builder.WithRecommendedDefaults(settings.Serializer, invariants); + + builder.WithStateFingerprints(settings.Serializer, everyTicks: 1); + + using var scope = builder.Build(); + var engine = CreateEngine(failure.Seed); + + try + { + scope.RunTicks(engine, failure.Seed, failure.Tick); + } + catch (Exception ex) when (IsExpectedFailure(ex, failure)) + { + } + + return scope.Paths.RunDir; + } + + private static bool IsExpectedFailure(Exception exception, FuzzFailure failure) + => exception is not OperationCanceledException + && string.Equals(Describe(exception).Summary, failure.Summary, StringComparison.Ordinal); + + private FuzzRunResult Execute(ulong seed, long endTick, bool recordFingerprints) + { + var state = settings.StateFactory(); + var engine = CreateEngine(seed); + + var probe = new FuzzTickProbe(); + engine.AddMiddleware(probe); + + var sink = new InMemoryStateFingerprintSink(); + if (recordFingerprints) + engine.AddMiddleware(new StateFingerprintMiddleware(state, settings.Serializer, sink, intervalTicks: 1)); + + var invariants = CreateInvariants(); + if (invariants.Count > 0) + engine.AddMiddleware(new InvariantMiddleware(state, invariants, checkEveryTicks: 1)); + + Exception? error = null; + + try + { + engine.RunTicks(state, seed, SimTime.Zero, new SimTime(endTick)); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + error = ex; + } + + return new FuzzRunResult(state, error, probe.LastTick, sink.Records); + } + + private SimulationEngine CreateEngine(ulong seed) + { + var engine = new SimulationEngine(); + settings.ConfigureEngine(engine); + + if (settings.Commands is { } configureCommands) + { + var plan = new FuzzCommandPlan(seed, settings.EndTick); + configureCommands(plan); + + if (!plan.IsEmpty) + { + var inbox = new ScheduledCommandInbox(); + plan.ScheduleInto(inbox); + engine.AttachScheduledInbox(inbox); + } + } + + return engine; + } + + private IReadOnlyList> CreateInvariants() + => settings.Invariants is { } factory ? factory().ToArray() : []; + + private FuzzFailure? ToFailure(ulong seed, FuzzRunResult result) + { + if (result.Error is not { } error) + return null; + + var (kind, summary) = Describe(error); + var tick = error is InvariantViolationException violation ? violation.Time.Tick : result.LastTick; + + return new FuzzFailure( + seed, + kind, + tick, + summary, + ComputeFailureDiff(seed, tick, result.State), + ArtifactsDir: null, + ReproCode(seed, tick, kind)); + } + + private static (FuzzFailureKind Kind, string Summary) Describe(Exception error) + => error is InvariantViolationException violation + ? (FuzzFailureKind.InvariantViolation, $"{violation.InvariantName}: {violation.Detail}") + : (FuzzFailureKind.Exception, $"{error.GetType().Name}: {error.Message}"); + + private FuzzFailure BuildNonDeterminismFailure(ulong seed, long tick) + { + var left = Execute(seed, tick, recordFingerprints: false); + var right = Execute(seed, tick, recordFingerprints: false); + + return new FuzzFailure( + seed, + FuzzFailureKind.NonDeterminism, + tick, + $"Two runs of the same seed diverged at tick {tick}.", + SafeDiff(() => settings.Serializer.Serialize(left.State), () => settings.Serializer.Serialize(right.State)), + ArtifactsDir: null, + ReproCode(seed, tick, FuzzFailureKind.NonDeterminism)); + } + + private IReadOnlyList ComputeFailureDiff(ulong seed, long failureTick, TState failedState) + => SafeDiff( + () => failureTick > 0 + ? settings.Serializer.Serialize(Execute(seed, failureTick - 1, recordFingerprints: false).State) + : settings.Serializer.Serialize(settings.StateFactory()), + () => settings.Serializer.Serialize(failedState)); + + private static IReadOnlyList SafeDiff(Func before, Func after) + { + try + { + return StateDiff.Compute(before(), after()); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return []; + } + } + + private static long? FindDivergenceTick(FuzzRunResult first, FuzzRunResult second) + { + var left = first.Fingerprints; + var right = second.Fingerprints; + var shared = Math.Min(left.Count, right.Count); + + for (var i = 0; i < shared; i++) + { + if (left[i].Tick != right[i].Tick) + return Math.Min(left[i].Tick, right[i].Tick); + + if (!string.Equals(left[i].Hash, right[i].Hash, StringComparison.Ordinal)) + return left[i].Tick; + } + + if (left.Count != right.Count) + return (left.Count > right.Count ? left[shared] : right[shared]).Tick; + + if (!string.Equals(first.ErrorSignature, second.ErrorSignature, StringComparison.Ordinal)) + return Math.Min(FailureTick(first), FailureTick(second)); + + return null; + } + + private static long FailureTick(FuzzRunResult result) + => result.Error switch + { + InvariantViolationException violation => violation.Time.Tick, + null => long.MaxValue, + _ => result.LastTick + }; + + private static string ReproCode(ulong seed, long tick, FuzzFailureKind kind) + { + var code = $".Seeds({seed}, {seed}).Ticks({tick})"; + return kind == FuzzFailureKind.NonDeterminism ? $"{code}.CheckDeterminism(true)" : code; + } +} diff --git a/src/EpochSim/Fuzzing/FuzzSettings.cs b/src/EpochSim/Fuzzing/FuzzSettings.cs new file mode 100644 index 0000000..b5ce868 --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzSettings.cs @@ -0,0 +1,21 @@ +using EpochSim.Execution; +using EpochSim.Kernel.Validation; +using EpochSim.Serialization.EventLog; +using EpochSim.Serialization.State; + +namespace EpochSim.Fuzzing; + +internal sealed record FuzzSettings( + Func StateFactory, + Action> ConfigureEngine, + long EndTick, + IEnumerable Seeds, + IStateSerializer Serializer, + Func>>? Invariants, + Action? Commands, + bool CheckDeterminism, + int Parallelism, + bool StopAtFirstFailure, + string? ArtifactsRoot, + IEventCodecV2? EventCodec, + IProgress? Progress); diff --git a/src/EpochSim/Fuzzing/FuzzTickProbe.cs b/src/EpochSim/Fuzzing/FuzzTickProbe.cs new file mode 100644 index 0000000..d406321 --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzTickProbe.cs @@ -0,0 +1,12 @@ +using EpochSim.Execution.Middleware; +using EpochSim.Kernel.Time; + +namespace EpochSim.Fuzzing; + +internal sealed class FuzzTickProbe : IExecutionMiddleware +{ + public long LastTick { get; private set; } + + public void OnTickStart(SimTime time) + => LastTick = time.Tick; +} diff --git a/tests/EpochSim.Analyzers.Tests/AnalyzerVerifier.cs b/tests/EpochSim.Analyzers.Tests/AnalyzerVerifier.cs new file mode 100644 index 0000000..6346949 --- /dev/null +++ b/tests/EpochSim.Analyzers.Tests/AnalyzerVerifier.cs @@ -0,0 +1,41 @@ +using EpochSim.Analyzers; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; + +internal static class AnalyzerVerifier +{ + public static Task Verify(string source, string? editorConfig = null, params DiagnosticResult[] expected) + { + var test = new CSharpAnalyzerTest + { + TestCode = source, + ReferenceAssemblies = SimulationSource.Net10 + }; + + test.TestState.AdditionalReferences.AddRange(SimulationSource.EpochSimReferences()); + test.ExpectedDiagnostics.AddRange(expected); + + if (editorConfig is not null) + test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", editorConfig)); + + return test.RunAsync(); + } + + public static Task VerifyNoFix(string markedSource) + => VerifyFix(markedSource, markedSource, MarkupMode.Allow); + + public static Task VerifyFix(string source, string fixedSource, MarkupMode fixedMarkup = MarkupMode.None) + { + var test = new CSharpCodeFixTest + { + TestCode = source, + FixedCode = fixedSource, + ReferenceAssemblies = SimulationSource.Net10 + }; + + test.FixedState.MarkupHandling = fixedMarkup; + test.TestState.AdditionalReferences.AddRange(SimulationSource.EpochSimReferences()); + test.FixedState.AdditionalReferences.AddRange(SimulationSource.EpochSimReferences()); + return test.RunAsync(); + } +} diff --git a/tests/EpochSim.Analyzers.Tests/DeterminismAnalyzerTests.cs b/tests/EpochSim.Analyzers.Tests/DeterminismAnalyzerTests.cs new file mode 100644 index 0000000..7857f66 --- /dev/null +++ b/tests/EpochSim.Analyzers.Tests/DeterminismAnalyzerTests.cs @@ -0,0 +1,253 @@ +using System.Text.RegularExpressions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; + +public sealed partial class DeterminismAnalyzerTests +{ + private static readonly string[] WallClock = + [ + "var v = {|ESIM001:DateTime.Now|};", + "var v = {|ESIM001:DateTime.UtcNow|};", + "var v = {|ESIM001:DateTime.Today|};", + "var v = {|ESIM001:DateTimeOffset.Now|};", + "var v = {|ESIM001:DateTimeOffset.UtcNow|};", + "var v = {|ESIM001:Environment.TickCount|};", + "var v = {|ESIM001:Environment.TickCount64|};", + "var v = {|ESIM001:TimeProvider.System|};", + "var v = {|ESIM001:new Stopwatch()|};", + "var v = {|ESIM001:Stopwatch.StartNew()|};", + "var v = {|ESIM001:Stopwatch.GetTimestamp()|};" + ]; + + private static readonly string[] Randomness = + [ + "var v = {|ESIM002:Random.Shared|};", + "var v = {|ESIM002:new Random()|};", + "var v = {|ESIM002:new Random(1)|};", + "var v = {|ESIM002:Guid.NewGuid()|};", + "var v = {|ESIM002:RandomNumberGenerator.GetInt32(5)|};" + ]; + + private static readonly string[] Concurrency = + [ + "{|ESIM003:Task.Run(() => { })|};", + "{|ESIM003:Task.Factory.StartNew(() => { })|};", + "var v = {|ESIM003:new Thread(() => { })|};", + "{|ESIM003:ThreadPool.QueueUserWorkItem(_ => { })|};", + "{|ESIM003:Parallel.For(0, 1, _ => { })|};", + "var v = {|ESIM003:new[] { 1 }.AsParallel()|};" + ]; + + private static readonly string[] Hashing = + [ + "var v = {|ESIM004:\"abc\".GetHashCode()|};", + "object o = 1; var v = {|ESIM004:o.GetHashCode()|};", + "var d = new ConcurrentDictionary(); {|ESIM004:foreach (var p in d) { }|}", + "var b = new ConcurrentBag(); {|ESIM004:foreach (var p in b) { }|}", + "var q = new ConcurrentQueue(); var v = {|ESIM004:q.Select(x => x)|};" + ]; + + private static readonly string[] ExternalInput = + [ + "var v = {|ESIM005:File.ReadAllText(\"a\")|};", + "var v = {|ESIM005:File.Exists(\"a\")|};", + "var v = {|ESIM005:Directory.GetFiles(\".\")|};", + "var v = {|ESIM005:new HttpClient()|};", + "var v = {|ESIM005:Environment.GetEnvironmentVariable(\"A\")|};", + "var v = {|ESIM005:Environment.MachineName|};" + ]; + + private static readonly string[] Representative = + [ + WallClock[1], + Randomness[0], + Concurrency[0], + Hashing[0], + ExternalInput[0] + ]; + + private static readonly Dictionary> Contexts = new() + { + ["AddSystem lambda"] = SimulationSource.Lambda, + ["OnCommand lambda"] = SimulationSource.OnCommandLambda, + ["ISystem"] = SimulationSource.SystemClass, + ["IInvariant"] = SimulationSource.InvariantClass, + ["ICommandHandler"] = SimulationSource.CommandHandlerClass, + ["[Deterministic] method"] = SimulationSource.DeterministicMethod, + ["[Deterministic] class"] = SimulationSource.DeterministicClass, + ["method group"] = SimulationSource.MethodGroup + }; + + public static TheoryData EveryConstructInCommonContexts() + { + var data = new TheoryData(); + var statements = WallClock.Concat(Randomness).Concat(Concurrency).Concat(Hashing).Concat(ExternalInput); + + foreach (var statement in statements) + { + data.Add("AddSystem lambda", statement); + data.Add("ISystem", statement); + } + + return data; + } + + public static TheoryData RepresentativeConstructInEveryContext() + { + var data = new TheoryData(); + + foreach (var context in Contexts.Keys) + { + foreach (var statement in Representative) + data.Add(context, statement); + } + + return data; + } + + public static TheoryData EveryConstruct() + { + var data = new TheoryData(); + + foreach (var statement in WallClock.Concat(Randomness).Concat(Concurrency).Concat(Hashing).Concat(ExternalInput)) + data.Add(statement); + + return data; + } + + [Theory] + [MemberData(nameof(EveryConstructInCommonContexts))] + public Task ReportsConstruct(string context, string statement) + => AnalyzerVerifier.Verify(Contexts[context](statement)); + + [Theory] + [MemberData(nameof(RepresentativeConstructInEveryContext))] + public Task ReportsRepresentativeConstructInEverySimulationContext(string context, string statement) + => AnalyzerVerifier.Verify(Contexts[context](statement)); + + [Theory] + [MemberData(nameof(EveryConstruct))] + public Task IgnoresConstructsOutsideSimulationCode(string statement) + => AnalyzerVerifier.Verify(SimulationSource.Outside(StripMarkup(statement))); + + [Fact] + public Task ReportsAsyncLambdaAndAwaitInsideSystemLambda() + => AnalyzerVerifier.Verify( + SimulationSource.Lambda("").Replace( + "tick: ctx => { }", + "tick: {|ESIM003:async|} ctx => { {|ESIM003:await Task.Yield()|}; }")); + + [Fact] + public Task ReportsAwaitInsideSystemMethod() + => AnalyzerVerifier.Verify( + SimulationSource.SystemClass("").Replace( + "public void Tick(TickContext ctx) { }", + "public async void Tick(TickContext ctx) { {|ESIM003:await Task.Yield()|}; }")); + + [Fact] + public Task ReportsNestedLambdaInsideSystemLambda() + => AnalyzerVerifier.Verify(SimulationSource.Lambda( + "Action inner = () => { var v = {|ESIM001:DateTime.UtcNow|}; }; inner();")); + + [Fact] + public Task ReportsLocalFunctionInsideSystemLambda() + => AnalyzerVerifier.Verify(SimulationSource.Lambda( + "void Local() { var v = {|ESIM001:DateTime.UtcNow|}; } Local();")); + + [Fact] + public Task ReportsTypeNestedInDeterministicClass() + => AnalyzerVerifier.Verify(SimulationSource.DeterministicClass( + "var v = new Nested(); v.Run();").Replace( + "public static void Run()", + "public sealed class Nested { public void Run() { var t = {|ESIM001:DateTime.UtcNow|}; } }\n public static void Run()")); + + [Fact] + public Task ReportsEachConstructOnce() + => AnalyzerVerifier.Verify(SimulationSource.Lambda( + "var a = {|ESIM001:DateTime.UtcNow|}; var b = {|ESIM002:Random.Shared|}.Next(); var c = {|ESIM002:Guid.NewGuid()|};")); + + [Fact] + public Task IgnoresDeterministicHashCodes() + => AnalyzerVerifier.Verify(SimulationSource.Lambda( + "var a = 5.GetHashCode(); var b = \"abc\".GetHashCode(StringComparison.Ordinal);")); + + [Fact] + public Task IgnoresOrderedCollections() + => AnalyzerVerifier.Verify(SimulationSource.Lambda( + "var l = new List(); foreach (var x in l) { } var a = new int[0]; foreach (var y in a) { } var s = new SortedDictionary(); foreach (var z in s) { }")); + + [Fact] + public Task IgnoresClassesWithoutSimulationInterfaces() + => AnalyzerVerifier.Verify(SimulationSource.Outside("var a = DateTime.UtcNow; var b = new Random(); var c = Guid.NewGuid();")); + + [Fact] + public Task IgnoresMethodsThatAreNeverRegistered() + => AnalyzerVerifier.Verify( + SimulationSource.MethodGroup("").Replace( + "private static void Tick(TickContext ctx) { }", + "private static void Tick(TickContext ctx) { }\n private static void Other() { var v = DateTime.UtcNow; }")); + + [Fact] + public Task ReportsRegisteredMethodGroupButNotItsNeighbours() + => AnalyzerVerifier.Verify( + SimulationSource.MethodGroup("var v = {|ESIM001:DateTime.UtcNow|};").Replace( + "private static void Tick(", + "private static void Other() { var v = DateTime.UtcNow; }\n private static void Tick(")); + + [Fact] + public Task StaysSilentWhenEpochSimIsNotReferenced() + { + var test = new Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerTest + { + TestCode = "using System; public static class C { public static void Run() { var v = DateTime.UtcNow; } }", + ReferenceAssemblies = SimulationSource.Net10 + }; + + return test.RunAsync(); + } + + [Theory] + [InlineData("var d = new Dictionary(); {|#0:foreach (var p in d) { }|}")] + [InlineData("var h = new HashSet(); {|#0:foreach (var p in h) { }|}")] + [InlineData("var d = new Dictionary(); var v = {|#0:d.Select(p => p.Key)|};")] + public async Task HashCollectionEnumeration_IsHiddenUnlessRaisedInEditorConfig(string statement) + { + const string enable = "root = true\n\n[*.cs]\ndotnet_diagnostic.ESIM006.severity = warning\n"; + + await AnalyzerVerifier.Verify( + SimulationSource.Lambda(statement), + enable, + new DiagnosticResult("ESIM006", DiagnosticSeverity.Warning).WithLocation(0)); + + await AnalyzerVerifier.Verify( + SimulationSource.Lambda(statement), + expected: new DiagnosticResult("ESIM006", DiagnosticSeverity.Hidden).WithLocation(0)); + } + + [Fact] + public Task RulesCanBeDisabledThroughEditorConfig() + => AnalyzerVerifier.Verify( + SimulationSource.Lambda("var v = DateTime.UtcNow;"), + "root = true\n\n[*.cs]\ndotnet_diagnostic.ESIM001.severity = none\n"); + + [Fact] + public Task RulesCarryHelpLinkAndMessage() + { + var descriptor = new EpochSim.Analyzers.DeterminismAnalyzer().SupportedDiagnostics.Single(d => d.Id == "ESIM002"); + + Assert.Equal("EpochSim.Determinism", descriptor.Category); + Assert.Equal(DiagnosticSeverity.Warning, descriptor.DefaultSeverity); + Assert.Contains("determinism.md", descriptor.HelpLinkUri, StringComparison.Ordinal); + + return AnalyzerVerifier.Verify( + SimulationSource.Lambda("var v = {|#0:Random.Shared|};"), + expected: new DiagnosticResult(descriptor).WithLocation(0) + .WithArguments("Random.Shared", "Use ctx.Rng instead of Random.Shared")); + } + + private static string StripMarkup(string statement) + => MarkupPattern().Replace(statement, "$1"); + + [GeneratedRegex(@"\{\|ESIM\d+:(.*?)\|\}")] + private static partial Regex MarkupPattern(); +} diff --git a/tests/EpochSim.Analyzers.Tests/EpochSim.Analyzers.Tests.csproj b/tests/EpochSim.Analyzers.Tests/EpochSim.Analyzers.Tests.csproj new file mode 100644 index 0000000..ab4c3a8 --- /dev/null +++ b/tests/EpochSim.Analyzers.Tests/EpochSim.Analyzers.Tests.csproj @@ -0,0 +1,31 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/EpochSim.Analyzers.Tests/RandomToRngCodeFixTests.cs b/tests/EpochSim.Analyzers.Tests/RandomToRngCodeFixTests.cs new file mode 100644 index 0000000..c31e983 --- /dev/null +++ b/tests/EpochSim.Analyzers.Tests/RandomToRngCodeFixTests.cs @@ -0,0 +1,58 @@ +public sealed class RandomToRngCodeFixTests +{ + [Fact] + public Task Replaces_SharedRandomNext_InSystemLambda() + => AnalyzerVerifier.VerifyFix( + SimulationSource.Lambda("var v = {|ESIM002:Random.Shared|}.Next(1, 10);"), + SimulationSource.Lambda("var v = ctx.Rng.NextInt(1, 10);")); + + [Fact] + public Task Replaces_NewRandomNextDouble_InSystemLambda() + => AnalyzerVerifier.VerifyFix( + SimulationSource.Lambda("var v = {|ESIM002:new Random(5)|}.NextDouble();"), + SimulationSource.Lambda("var v = ctx.Rng.NextDouble01();")); + + [Fact] + public Task UsesActualParameterName_InSystemMethod() + => AnalyzerVerifier.VerifyFix( + SimulationSource.SystemClass("").Replace( + "public void Tick(TickContext ctx) { }", + "public void Tick(TickContext context) { var v = {|ESIM002:Random.Shared|}.Next(2, 4); }"), + SimulationSource.SystemClass("").Replace( + "public void Tick(TickContext ctx) { }", + "public void Tick(TickContext context) { var v = context.Rng.NextInt(2, 4); }")); + + [Fact] + public Task Replaces_InEventContextHandler() + => AnalyzerVerifier.VerifyFix( + SimulationSource.SystemClass("").Replace( + "public void Tick(TickContext ctx) { }", + "public void Tick(TickContext ctx) { }\n public void Handle(EventContext events, IEvent ev) { var v = {|ESIM002:Random.Shared|}.Next(0, 3); }"), + SimulationSource.SystemClass("").Replace( + "public void Tick(TickContext ctx) { }", + "public void Tick(TickContext ctx) { }\n public void Handle(EventContext events, IEvent ev) { var v = events.Rng.NextInt(0, 3); }")); + + [Fact] + public Task Replaces_InNestedLambdaUsingOuterContext() + => AnalyzerVerifier.VerifyFix( + SimulationSource.Lambda("Func f = () => {|ESIM002:Random.Shared|}.Next(1, 3);"), + SimulationSource.Lambda("Func f = () => ctx.Rng.NextInt(1, 3);")); + + [Fact] + public Task OffersNoFix_ForUnsupportedRandomCalls() + { + return AnalyzerVerifier.VerifyNoFix(SimulationSource.Lambda("var v = {|ESIM002:Random.Shared|}.Next(10);")); + } + + [Fact] + public Task OffersNoFix_ForGuid() + { + return AnalyzerVerifier.VerifyNoFix(SimulationSource.Lambda("var v = {|ESIM002:Guid.NewGuid()|};")); + } + + [Fact] + public Task OffersNoFix_WithoutContextInScope() + { + return AnalyzerVerifier.VerifyNoFix(SimulationSource.DeterministicMethod("var v = {|ESIM002:Random.Shared|}.Next(1, 4);")); + } +} diff --git a/tests/EpochSim.Analyzers.Tests/SimulationSource.cs b/tests/EpochSim.Analyzers.Tests/SimulationSource.cs new file mode 100644 index 0000000..a6ba189 --- /dev/null +++ b/tests/EpochSim.Analyzers.Tests/SimulationSource.cs @@ -0,0 +1,146 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; + +internal static class SimulationSource +{ + public const string StatementMarker = "__STATEMENT__"; + + private const string Usings = + """ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Net.Http; + using System.Security.Cryptography; + using System.Threading; + using System.Threading.Tasks; + using EpochSim.Execution; + using EpochSim.Kernel.Determinism; + using EpochSim.Kernel.Messaging; + using EpochSim.Kernel.Systems; + using EpochSim.Kernel.Time; + using EpochSim.Kernel.Validation; + + public sealed class S { public int N; } + public sealed record Cmd() : ICommand; + + """; + + public static readonly ReferenceAssemblies Net10 = new( + "net10.0", + new PackageIdentity("Microsoft.NETCore.App.Ref", "10.0.0"), + Path.Combine("ref", "net10.0")); + + public static IEnumerable EpochSimReferences() + { + yield return MetadataReference.CreateFromFile(typeof(EpochSim.Epoch).Assembly.Location); + yield return MetadataReference.CreateFromFile(typeof(EpochSim.Kernel.Determinism.IRng).Assembly.Location); + yield return MetadataReference.CreateFromFile(typeof(EpochSim.Execution.SimulationEngine<>).Assembly.Location); + } + + public static string Lambda(string statements) + => Usings + $$""" + public static class Host + { + public static void Configure(SimulationEngine engine) + { + engine.AddSystem("s", tick: ctx => { {{StatementMarker}} }); + } + } + """.Replace(StatementMarker, statements); + + public static string OnCommandLambda(string statements) + => Usings + $$""" + public static class Host + { + public static void Configure(SimulationEngine engine) + { + engine.OnCommand((state, command, events) => { {{StatementMarker}} }); + } + } + """.Replace(StatementMarker, statements); + + public static string SystemClass(string statements) + => Usings + $$""" + public sealed class Sys : ISystem + { + public void Tick(TickContext ctx) { {{StatementMarker}} } + } + """.Replace(StatementMarker, statements); + + public static string InvariantClass(string statements) + => Usings + $$""" + public sealed class Inv : IInvariant + { + public string Name => "inv"; + public bool Check(SimTime time, S state, out string message) + { + {{StatementMarker}} + message = ""; + return true; + } + } + """.Replace(StatementMarker, statements); + + public static string CommandHandlerClass(string statements) + => Usings + $$""" + public sealed class Handler : ICommandHandler + { + public void Handle(S state, Cmd command, IEventBuffer events) { {{StatementMarker}} } + } + """.Replace(StatementMarker, statements); + + public static string DeterministicMethod(string statements) + => Usings + $$""" + public static class Helpers + { + [Deterministic] + public static void Run() { {{StatementMarker}} } + } + """.Replace(StatementMarker, statements); + + public static string DeterministicClass(string statements) + => Usings + $$""" + [Deterministic] + public static class Helpers + { + public static void Run() { {{StatementMarker}} } + } + """.Replace(StatementMarker, statements); + + public static string MethodGroup(string statements) + => Usings + $$""" + public static class Host + { + public static void Configure(SimulationEngine engine) + { + engine.AddSystem("s", Tick); + } + + private static void Tick(TickContext ctx) { {{StatementMarker}} } + } + """.Replace(StatementMarker, statements); + + public static string Outside(string statements) + => Usings + $$""" + public static class Plain + { + public static void Run() { {{StatementMarker}} } + } + """.Replace(StatementMarker, statements); + + public static IEnumerable> SimulationContexts { get; } = + [ + Lambda, + OnCommandLambda, + SystemClass, + InvariantClass, + CommandHandlerClass, + DeterministicMethod, + DeterministicClass, + MethodGroup + ]; +} diff --git a/tests/EpochSim.Determinism.Tests/CliInitCommandTests.cs b/tests/EpochSim.Determinism.Tests/CliInitCommandTests.cs index ff931b8..86555b5 100644 --- a/tests/EpochSim.Determinism.Tests/CliInitCommandTests.cs +++ b/tests/EpochSim.Determinism.Tests/CliInitCommandTests.cs @@ -25,7 +25,7 @@ public async Task InitCommand_ScaffoldsMinimalProject() Assert.DoesNotContain("engine.RunTicks(state", program, StringComparison.Ordinal); var csproj = File.ReadAllText(Path.Combine(targetDir, "EpochSim.App.csproj")); - Assert.Contains("Version=\"0.2.2\"", csproj, StringComparison.Ordinal); + Assert.Contains("Version=\"0.3.0\"", csproj, StringComparison.Ordinal); var inboxExample = File.ReadAllText(Path.Combine(targetDir, "SessionInboxExample.cs")); Assert.Contains("CommandInbox", inboxExample, StringComparison.Ordinal); diff --git a/tests/EpochSim.Determinism.Tests/EpochSim.Determinism.Tests.csproj b/tests/EpochSim.Determinism.Tests/EpochSim.Determinism.Tests.csproj index 03771c3..cd41514 100644 --- a/tests/EpochSim.Determinism.Tests/EpochSim.Determinism.Tests.csproj +++ b/tests/EpochSim.Determinism.Tests/EpochSim.Determinism.Tests.csproj @@ -24,6 +24,7 @@ + diff --git a/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs b/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs new file mode 100644 index 0000000..3d65d72 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs @@ -0,0 +1,114 @@ +using EpochSim.Cli.App; + +[Collection("Console")] +public sealed class FuzzCliTests : IDisposable +{ + private readonly string _out = Path.Combine(Path.GetTempPath(), $"epochsim-fuzzcli-{Guid.NewGuid():N}"); + + public void Dispose() + { + if (Directory.Exists(_out)) + Directory.Delete(_out, recursive: true); + } + + [Fact] + public async Task Fuzz_OnBuggyAdapter_Returns2AndPrintsSeedDiffAndRepro() + { + var (rc, output) = await RunCli("fuzz", "--adapter", "fuzzbug", "--seeds", "1..10", "--ticks", "500", "--out", _out); + + Assert.Equal(2, rc); + Assert.Contains("SeedsRun=10 Failures=1", output, StringComparison.Ordinal); + Assert.Contains("seed=4 tick=426", output, StringComparison.Ordinal); + Assert.Contains("$.Pending", output, StringComparison.Ordinal); + Assert.Contains($"epochsim fuzz --adapter fuzzbug --seeds 4 --ticks 426 --out {_out}", output, StringComparison.Ordinal); + Assert.True(File.Exists(Path.Combine(_out, "fuzz-4", "manifest.json"))); + } + + [Fact] + public async Task Fuzz_ReproCommand_FailsOnSameSeedAndTick() + { + var (rc, output) = await RunCli("fuzz", "--adapter", "fuzzbug", "--seeds", "4", "--ticks", "426", "--out", _out); + + Assert.Equal(2, rc); + Assert.Contains("seed=4 tick=426", output, StringComparison.Ordinal); + } + + [Fact] + public async Task Fuzz_OnPopulationAdapter_Returns0() + { + var (rc, output) = await RunCli("fuzz", "--seeds", "1..20", "--ticks", "100", "--parallel", "2", "--out", _out); + + Assert.Equal(0, rc); + Assert.Contains("SeedsRun=20 Failures=0", output, StringComparison.Ordinal); + } + + [Fact] + public async Task Fuzz_CheckDeterminism_OnDeterministicAdapter_Returns0() + { + var (rc, _) = await RunCli("fuzz", "--seeds", "1..5", "--ticks", "50", "--check-determinism", "--out", _out); + + Assert.Equal(0, rc); + } + + [Theory] + [InlineData("--seeds", "nope")] + [InlineData("--seeds", "9..1")] + [InlineData("--ticks", "-1")] + [InlineData("--parallel", "0")] + [InlineData("--adapter", "unknown-adapter")] + [InlineData("--bogus", "1")] + [InlineData("--ticks", "")] + public async Task Fuzz_InvalidArguments_Return2WithoutRunning(string option, string value) + { + var (rc, output) = await RunCli("fuzz", option, value, "--out", _out); + + Assert.Equal(2, rc); + Assert.DoesNotContain("SeedsRun=", output, StringComparison.Ordinal); + } + + [Fact] + public async Task Fuzz_MissingOptionValue_Returns2() + { + var (rc, _) = await RunCli("fuzz", "--ticks"); + + Assert.Equal(2, rc); + } + + [Fact] + public async Task Fuzz_Help_PrintsUsageAndReturns0() + { + var (rc, output) = await RunCli("fuzz", "--help"); + + Assert.Equal(0, rc); + Assert.Contains("--check-determinism", output, StringComparison.Ordinal); + } + + [Fact] + public async Task ListAdapters_IncludesFuzzBug() + { + var (rc, output) = await RunCli("list-adapters"); + + Assert.Equal(0, rc); + Assert.Contains("fuzzbug", output, StringComparison.Ordinal); + } + + private static async Task<(int ExitCode, string Output)> RunCli(params string[] args) + { + var originalOut = Console.Out; + var originalError = Console.Error; + using var writer = new StringWriter(); + Console.SetOut(writer); + Console.SetError(TextWriter.Null); + + try + { + var rc = await new CliApp().RunAsync(args); + return (rc, writer.ToString()); + } + finally + { + Console.SetOut(originalOut); + Console.SetError(originalError); + } + } +} diff --git a/tests/EpochSim.Determinism.Tests/FuzzTests.cs b/tests/EpochSim.Determinism.Tests/FuzzTests.cs new file mode 100644 index 0000000..e04ecaf --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/FuzzTests.cs @@ -0,0 +1,371 @@ +using EpochSim; +using EpochSim.Fuzzing; +using EpochSim.Samples.Fuzzing; +using EpochSim.Samples.Population; +using EpochSim.Serialization.EventLog; + +public sealed class FuzzTests : IDisposable +{ + private const ulong BugSeed = 4; + private const long BugTick = 426; + private const long RunTicks = 500; + + private readonly string _artifactsRoot = Path.Combine(Path.GetTempPath(), $"epochsim-fuzz-{Guid.NewGuid():N}"); + + public void Dispose() + { + if (Directory.Exists(_artifactsRoot)) + Directory.Delete(_artifactsRoot, recursive: true); + } + + [Fact] + public void Fuzz_FindsSeedWithRareBug() + { + var report = FuzzJobQueue(f => f.Seeds(1, 10).Ticks(RunTicks)); + + var failure = Assert.Single(report.Failures); + Assert.False(report.Passed); + Assert.Equal(10, report.SeedsRun); + Assert.Equal(BugSeed, failure.Seed); + Assert.Equal(FuzzFailureKind.InvariantViolation, failure.Kind); + Assert.Equal(BugTick, failure.Tick); + Assert.Contains("QueueNonNegative", failure.Summary, StringComparison.Ordinal); + Assert.Contains(failure.StateDiff, change => change.Path == "$.Pending" && change.After == "-1"); + Assert.Equal(".Seeds(4, 4).Ticks(426)", failure.ReproCode); + } + + [Fact] + public void Fuzz_FailedSeed_ReproducesWithSingleSeedAtSameTick() + { + var reproduced = FuzzJobQueue(f => f.Seeds(BugSeed, BugSeed).Ticks(BugTick)); + var earlier = FuzzJobQueue(f => f.Seeds(BugSeed, BugSeed).Ticks(BugTick - 1)); + + Assert.Equal(BugTick, Assert.Single(reproduced.Failures).Tick); + Assert.True(earlier.Passed); + } + + [Fact] + public void Fuzz_Failures_DoNotDependOnParallelism() + { + var sequential = FuzzJobQueue(f => f.Seeds(1, 400).Ticks(RunTicks).Parallelism(1)); + var parallel = FuzzJobQueue(f => f.Seeds(1, 400).Ticks(RunTicks).Parallelism(8)); + + Assert.NotEmpty(sequential.Failures); + Assert.Equal(sequential.SeedsRun, parallel.SeedsRun); + Assert.Equal(Project(sequential), Project(parallel)); + Assert.Equal(sequential.Failures.Select(f => f.Seed).Order(), sequential.Failures.Select(f => f.Seed)); + } + + [Fact] + public void Fuzz_StopAtFirstFailure_WithSingleWorker_StopsAfterFirstFailingSeed() + { + var report = FuzzJobQueue(f => f.Seeds(1, 1000).Ticks(RunTicks).Parallelism(1).StopAtFirstFailure()); + + Assert.Equal(BugSeed, Assert.Single(report.Failures).Seed); + Assert.Equal((int)BugSeed, report.SeedsRun); + } + + [Fact] + public void Fuzz_CheckDeterminism_CatchesStaticState() + { + var report = Epoch.Fuzz(f => f + .State(() => new StaticCounterState()) + .Engine(e => e.AddSystem(new StaticCounterSystem())) + .Seeds(1, 5) + .Ticks(20) + .CheckDeterminism()); + + Assert.Equal([1UL, 2UL, 3UL, 4UL, 5UL], report.Failures.Select(f => f.Seed)); + Assert.All(report.Failures, failure => + { + Assert.Equal(FuzzFailureKind.NonDeterminism, failure.Kind); + Assert.Equal(1, failure.Tick); + Assert.Contains(failure.StateDiff, change => change.Path == "$.Value"); + Assert.EndsWith(".CheckDeterminism(true)", failure.ReproCode, StringComparison.Ordinal); + }); + } + + [Fact] + public void Fuzz_CheckDeterminism_CatchesWallClockUsage() + { + var report = Epoch.Fuzz(f => f + .State(() => new StaticCounterState()) + .Engine(e => e.AddSystem("Clock", tick: ctx => ctx.State.Value = DateTime.UtcNow.Ticks)) + .Seeds(1, 3) + .Ticks(10) + .CheckDeterminism()); + + Assert.Equal(3, report.Failures.Count); + Assert.All(report.Failures, failure => Assert.Equal(FuzzFailureKind.NonDeterminism, failure.Kind)); + } + + [Fact] + public void Fuzz_CheckDeterminism_AcceptsDeterministicLogic() + { + var report = FuzzJobQueue(f => f.Seeds(1, 30).Ticks(200).CheckDeterminism(), withInvariants: false); + + Assert.True(report.Passed); + Assert.Equal(30, report.SeedsRun); + } + + [Fact] + public void Fuzz_ExceptionFromSystem_IsClassifiedAsException() + { + var report = Epoch.Fuzz(f => f + .State(() => new JobQueueState()) + .Engine(e => e.AddSystem("Boom", tick: ctx => + { + if (ctx.Time.Tick == 5) + throw new InvalidOperationException("boom"); + })) + .Seeds(1, 2) + .Ticks(10)); + + Assert.Equal(2, report.Failures.Count); + Assert.All(report.Failures, failure => + { + Assert.Equal(FuzzFailureKind.Exception, failure.Kind); + Assert.Equal(5, failure.Tick); + Assert.Equal("InvalidOperationException: boom", failure.Summary); + }); + } + + [Fact] + public void Fuzz_OperationCanceledFromSystem_IsNotAFailure() + { + var report = Epoch.Fuzz(f => f + .State(() => new JobQueueState()) + .Engine(e => e.AddSystem("Cancel", tick: _ => throw new OperationCanceledException())) + .Seeds(1, 2) + .Ticks(3)); + + Assert.True(report.Passed); + Assert.Equal(2, report.SeedsRun); + } + + [Fact] + public void ThrowIfFailed_ThrowsFuzzFailedExceptionWithReportText() + { + var failed = FuzzJobQueue(f => f.Seeds(1, 10).Ticks(RunTicks)); + + var exception = Assert.Throws(failed.ThrowIfFailed); + + Assert.Equal(failed.ToText(), exception.Message); + Assert.Same(failed, exception.Report); + Assert.Contains("seed=4", exception.Message, StringComparison.Ordinal); + Assert.Contains("tick=426", exception.Message, StringComparison.Ordinal); + Assert.Contains("$.Pending", exception.Message, StringComparison.Ordinal); + Assert.Contains(".Seeds(4, 4).Ticks(426)", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void ThrowIfFailed_OnPassedReport_DoesNotThrow() + { + var passed = FuzzJobQueue(f => f.Seeds(1, 3).Ticks(50)); + + passed.ThrowIfFailed(); + + Assert.True(passed.Passed); + Assert.Contains("SeedsRun=3", passed.ToText(), StringComparison.Ordinal); + } + + [Fact] + public void Commands_SameSeedProducesSameSchedule() + { + var first = RecordSchedule(seed: 7); + var second = RecordSchedule(seed: 7); + var other = RecordSchedule(seed: 8); + + Assert.NotEmpty(first); + Assert.Equal(first, second); + Assert.NotEqual(first, other); + } + + [Fact] + public void Commands_AreDeliveredAtScheduledTick() + { + var states = new List(); + + var report = Epoch.Fuzz(f => f + .State(() => + { + var created = new WorldState { Population = 0 }; + states.Add(created); + return created; + }) + .Engine(e => e.OnCommand((state, command, _) => state.Population += command.Delta)) + .Commands(plan => + { + plan.Enqueue(3, new GrowPopulationCommand(5)); + plan.Enqueue(plan.EndTick, new GrowPopulationCommand(7)); + }) + .Seeds(1, 1) + .Ticks(10)); + + Assert.True(report.Passed); + Assert.Equal(12, Assert.Single(states).Population); + } + + [Fact] + public void Commands_OutsideRun_AreRejected() + { + Assert.Throws(() => Epoch.Fuzz(f => f + .State(() => new WorldState()) + .Engine(_ => { }) + .Commands(plan => plan.Enqueue(plan.EndTick + 1, new GrowPopulationCommand(1))) + .Seeds(1, 1) + .Ticks(10))); + } + + [Fact] + public void ArtifactsRoot_WritesArtifactsForFailedSeed() + { + var report = FuzzJobQueue(f => f + .Seeds(BugSeed, BugSeed) + .Ticks(RunTicks) + .ArtifactsRoot(_artifactsRoot) + .EventCodec(new JsonEventCodecBuilder().Build())); + + var failure = Assert.Single(report.Failures); + Assert.Equal(Path.Combine(_artifactsRoot, "fuzz-4"), failure.ArtifactsDir); + Assert.True(File.Exists(Path.Combine(failure.ArtifactsDir!, "manifest.json"))); + Assert.True(File.Exists(Path.Combine(failure.ArtifactsDir!, "statefp.jsonl"))); + Assert.True(File.Exists(Path.Combine(failure.ArtifactsDir!, "failure-report.json"))); + Assert.Contains(failure.ArtifactsDir!, failure.ToText(), StringComparison.Ordinal); + } + + [Fact] + public void ArtifactsRoot_WithoutCodec_StillWritesManifestAndFingerprints() + { + var report = FuzzJobQueue(f => f.Seeds(BugSeed, BugSeed).Ticks(RunTicks).ArtifactsRoot(_artifactsRoot)); + + var directory = Assert.Single(report.Failures).ArtifactsDir; + Assert.True(File.Exists(Path.Combine(directory!, "manifest.json"))); + Assert.True(File.Exists(Path.Combine(directory!, "statefp.jsonl"))); + } + + [Fact] + public void ArtifactsRoot_LimitsArtifactsToTenFailures() + { + var report = Epoch.Fuzz(f => f + .State(() => new JobQueueState()) + .Engine(e => e.AddSystem("Boom", tick: _ => throw new InvalidOperationException("boom"))) + .Seeds(1, 15) + .Ticks(3) + .ArtifactsRoot(_artifactsRoot)); + + Assert.Equal(15, report.Failures.Count); + Assert.Equal(10, report.Failures.Count(failure => failure.ArtifactsDir is not null)); + Assert.All(report.Failures.Take(10), failure => Assert.NotNull(failure.ArtifactsDir)); + } + + [Fact] + public void Fuzz_ReportsProgressForEverySeed() + { + var progress = new RecordingProgress(); + + var report = FuzzJobQueue(f => f.Seeds(1, 25).Ticks(20).Progress(progress)); + + Assert.Equal(report.SeedsRun, progress.Reports.Count); + Assert.Equal(25, progress.Reports.Max(p => p.SeedsRun)); + } + + [Fact] + public void Fuzz_EmptySeedList_Passes() + { + var report = FuzzJobQueue(f => f.Seeds(Array.Empty()).Ticks(10)); + + Assert.True(report.Passed); + Assert.Equal(0, report.SeedsRun); + } + + [Fact] + public void Fuzz_SeedRangeEndingAtUlongMaxValue_Terminates() + { + var report = FuzzJobQueue(f => f.Seeds(ulong.MaxValue - 1, ulong.MaxValue).Ticks(5)); + + Assert.True(report.Passed); + Assert.Equal(2, report.SeedsRun); + } + + [Fact] + public void Fuzz_MissingRequiredParameters_ThrowsWithParameterName() + { + var noState = Assert.Throws(() => Epoch.Fuzz(f => f + .Engine(_ => { }).Seeds(1, 2).Ticks(3))); + var noEngine = Assert.Throws(() => Epoch.Fuzz(f => f + .State(() => new JobQueueState()).Seeds(1, 2).Ticks(3))); + var noTicks = Assert.Throws(() => Epoch.Fuzz(f => f + .State(() => new JobQueueState()).Engine(_ => { }).Seeds(1, 2))); + var noSeeds = Assert.Throws(() => Epoch.Fuzz(f => f + .State(() => new JobQueueState()).Engine(_ => { }).Ticks(3))); + + Assert.Contains("State", noState.Message, StringComparison.Ordinal); + Assert.Contains("Engine", noEngine.Message, StringComparison.Ordinal); + Assert.Contains("Ticks", noTicks.Message, StringComparison.Ordinal); + Assert.Contains("Seeds", noSeeds.Message, StringComparison.Ordinal); + } + + [Fact] + public void Fuzz_InvalidValues_Throw() + { + Assert.Throws(() => Epoch.Fuzz(f => f.Seeds(5, 4))); + Assert.Throws(() => Epoch.Fuzz(f => f.Ticks(-1))); + Assert.Throws(() => Epoch.Fuzz(f => f.Parallelism(0))); + } + + private static FuzzReport FuzzJobQueue(Action> configure, bool withInvariants = true) + => Epoch.Fuzz(f => + { + f.State(() => new JobQueueState()) + .Engine(e => e.AddSystem(new JobQueueSystem())); + + if (withInvariants) + f.Invariants(() => [new QueueNonNegativeInvariant()]); + + configure(f); + }); + + private static List RecordSchedule(ulong seed) + { + var schedule = new List(); + + Epoch.Fuzz(f => f + .State(() => new WorldState()) + .Engine(e => e.OnCommand((_, _, _) => { })) + .Commands(plan => + { + schedule.Clear(); + for (var i = 0; i < 5; i++) + { + var tick = plan.Rng.NextInt(0, 50); + var delta = plan.Rng.NextInt(1, 9); + plan.Enqueue(tick, new GrowPopulationCommand(delta)); + schedule.Add($"{tick}:{delta}"); + } + }) + .Seeds(seed, seed) + .Ticks(50) + .Parallelism(1)); + + return schedule; + } + + private static IEnumerable Project(FuzzReport report) + => report.Failures.Select(failure => + $"{failure.Seed}|{failure.Kind}|{failure.Tick}|{failure.Summary}|{failure.ReproCode}|" + + string.Join(";", failure.StateDiff.Select(change => $"{change.Path}:{change.Before}>{change.After}"))); + + private sealed class RecordingProgress : IProgress + { + private readonly object _gate = new(); + + public List Reports { get; } = []; + + public void Report(FuzzProgress value) + { + lock (_gate) + Reports.Add(value); + } + } +} diff --git a/tests/EpochSim.Determinism.Tests/SimAssertTests.cs b/tests/EpochSim.Determinism.Tests/SimAssertTests.cs new file mode 100644 index 0000000..251729f --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/SimAssertTests.cs @@ -0,0 +1,250 @@ +using EpochSim; +using EpochSim.Fuzzing; +using EpochSim.Samples.Fuzzing; +using EpochSim.Testing; + +[Collection("GoldenEnvironment")] +public sealed class SimAssertTests : IDisposable +{ + private const string UpdateVariable = "EPOCHSIM_UPDATE_GOLDEN"; + + private readonly string _directory = Path.Combine(Path.GetTempPath(), $"epochsim-golden-{Guid.NewGuid():N}"); + private readonly string? _originalUpdateValue = Environment.GetEnvironmentVariable(UpdateVariable); + + public SimAssertTests() + => Environment.SetEnvironmentVariable(UpdateVariable, null); + + public void Dispose() + { + Environment.SetEnvironmentVariable(UpdateVariable, _originalUpdateValue); + + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } + + [Fact] + public void IsDeterministic_OnDeterministicSystem_Passes() + { + SimAssert.IsDeterministic(f => f + .State(() => new JobQueueState()) + .Engine(e => e.AddSystem(new JobQueueSystem())) + .Seeds(1, 20) + .Ticks(100)); + } + + [Fact] + public void IsDeterministic_OnNonDeterministicSystem_FailsWithSeedInMessage() + { + var exception = Assert.Throws(() => + SimAssert.IsDeterministic(f => f + .State(() => new StaticCounterState()) + .Engine(e => e.AddSystem(new StaticCounterSystem())) + .Seeds(1, 3) + .Ticks(10))); + + Assert.Contains("seed=1", exception.Message, StringComparison.Ordinal); + Assert.Contains("NonDeterminism", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void IsDeterministic_ForcesCheckEvenWhenConfiguredOff() + { + Assert.Throws(() => + SimAssert.IsDeterministic(f => f + .State(() => new StaticCounterState()) + .Engine(e => e.AddSystem(new StaticCounterSystem())) + .CheckDeterminism(false) + .Seeds(1, 1) + .Ticks(10))); + } + + [Fact] + public void InvariantsHold_OnSystemWithBug_FailsWithSeedAndTick() + { + var exception = Assert.Throws(() => + SimAssert.InvariantsHold(f => f + .State(() => new JobQueueState()) + .Engine(e => e.AddSystem(new JobQueueSystem())) + .Invariants(() => [new QueueNonNegativeInvariant()]) + .Seeds(1, 10) + .Ticks(500))); + + Assert.Contains("seed=4", exception.Message, StringComparison.Ordinal); + Assert.Contains("tick=426", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void InvariantsHold_OnHealthySystem_Passes() + { + SimAssert.InvariantsHold(f => f + .State(() => new JobQueueState()) + .Engine(e => e.AddSystem(new JobQueueSystem())) + .Invariants(() => [new QueueNonNegativeInvariant()]) + .Seeds(1, 3) + .Ticks(500)); + } + + [Fact] + public void InvariantsHold_DoesNotForceDeterminismCheck() + { + SimAssert.InvariantsHold(f => f + .State(() => new StaticCounterState()) + .Engine(e => e.AddSystem(new StaticCounterSystem())) + .Seeds(1, 3) + .Ticks(10)); + } + + [Fact] + public void NoFailures_OnPassedReport_DoesNotThrow() + { + var report = Epoch.Fuzz(f => f + .State(() => new JobQueueState()) + .Engine(_ => { }) + .Seeds(1, 2) + .Ticks(5)); + + SimAssert.NoFailures(report); + } + + [Fact] + public void NoFailures_OnFailedReport_ThrowsWithReportText() + { + var report = Epoch.Fuzz(f => f + .State(() => new JobQueueState()) + .Engine(e => e.AddSystem("Boom", tick: _ => throw new InvalidOperationException("boom"))) + .Seeds(1, 2) + .Ticks(5)); + + var exception = Assert.Throws(() => SimAssert.NoFailures(report)); + + Assert.Equal(report.ToText(), exception.Message); + } + + [Fact] + public void Assertions_RejectNullArguments() + { + Assert.Throws(() => SimAssert.NoFailures(null!)); + Assert.Throws(() => SimAssert.IsDeterministic(null!)); + Assert.Throws(() => SimAssert.InvariantsHold(null!)); + } + + [Fact] + public void TestingAssembly_DoesNotReferenceTestFrameworks() + { + var references = typeof(SimAssert).Assembly.GetReferencedAssemblies() + .Select(reference => reference.Name ?? string.Empty); + + Assert.DoesNotContain(references, name => + name.StartsWith("xunit", StringComparison.OrdinalIgnoreCase) + || name.StartsWith("nunit", StringComparison.OrdinalIgnoreCase) + || name.StartsWith("Microsoft.VisualStudio.TestTools", StringComparison.OrdinalIgnoreCase) + || name.StartsWith("MSTest", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public void MatchesGolden_CreatesFileOnFirstRunAndPassesOnSecond() + { + var path = GoldenPath(); + + SimAssert.MatchesGolden(JobQueue, path, seed: 1); + var created = File.ReadAllText(path); + SimAssert.MatchesGolden(JobQueue, path, seed: 1); + + Assert.Equal(created, File.ReadAllText(path)); + Assert.Contains("\"100\"", created, StringComparison.Ordinal); + Assert.Contains("\"200\"", created, StringComparison.Ordinal); + Assert.Contains("\"250\"", created, StringComparison.Ordinal); + Assert.DoesNotContain("\"150\"", created, StringComparison.Ordinal); + } + + [Fact] + public void MatchesGolden_OnChangedBehavior_ReportsFirstDivergingCheckpoint() + { + var path = GoldenPath(); + SimAssert.MatchesGolden(JobQueue, path, seed: 1); + + var exception = Assert.Throws(() => + SimAssert.MatchesGolden( + f => ConfigureJobQueue(f).Engine(e => + { + e.AddSystem(new JobQueueSystem()); + e.AddSystem("Extra", tick: ctx => ctx.State.Completed++); + }), + path, + seed: 1)); + + Assert.Contains("tick 100", exception.Message, StringComparison.Ordinal); + Assert.Contains(UpdateVariable, exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void MatchesGolden_WithUpdateVariable_OverwritesFile() + { + var path = GoldenPath(); + SimAssert.MatchesGolden(JobQueue, path, seed: 1); + var original = File.ReadAllText(path); + + Environment.SetEnvironmentVariable(UpdateVariable, "1"); + SimAssert.MatchesGolden( + f => ConfigureJobQueue(f).Engine(e => e.AddSystem("Extra", tick: ctx => ctx.State.Completed++)), + path, + seed: 1); + + Assert.NotEqual(original, File.ReadAllText(path)); + } + + [Fact] + public void MatchesGolden_WithDifferentSeed_Fails() + { + var path = GoldenPath(); + SimAssert.MatchesGolden(JobQueue, path, seed: 1); + + var exception = Assert.Throws(() => + SimAssert.MatchesGolden(JobQueue, path, seed: 2)); + + Assert.Contains("seed 1", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void MatchesGolden_WithCorruptedFile_Fails() + { + var path = GoldenPath(); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, "{ not json"); + + Assert.Throws(() => + SimAssert.MatchesGolden(JobQueue, path, seed: 1)); + } + + [Fact] + public void MatchesGolden_WhenRunFails_Throws() + { + var exception = Assert.Throws(() => + SimAssert.MatchesGolden( + f => f.State(() => new JobQueueState()) + .Engine(e => e.AddSystem("Boom", tick: _ => throw new InvalidOperationException("boom"))) + .Ticks(10), + GoldenPath(), + seed: 1)); + + Assert.Contains("boom", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void MatchesGolden_WithoutTicks_Throws() + { + Assert.Throws(() => + SimAssert.MatchesGolden(f => ConfigureJobQueue(f).Ticks(0), GoldenPath(), seed: 1)); + } + + private string GoldenPath() + => Path.Combine(_directory, "nested", "golden.json"); + + private static void JobQueue(FuzzBuilder f) + => ConfigureJobQueue(f); + + private static FuzzBuilder ConfigureJobQueue(FuzzBuilder f) + => f.State(() => new JobQueueState()) + .Engine(e => e.AddSystem(new JobQueueSystem())) + .Ticks(250); +} diff --git a/tests/EpochSim.Determinism.Tests/StateDiffCliTests.cs b/tests/EpochSim.Determinism.Tests/StateDiffCliTests.cs new file mode 100644 index 0000000..b1036fc --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/StateDiffCliTests.cs @@ -0,0 +1,140 @@ +using EpochSim; +using EpochSim.Cli.App; +using EpochSim.Cli.Domain; +using EpochSim.Execution; +using EpochSim.Samples.Population; + +[Collection("Console")] +public sealed class StateDiffCliTests : IDisposable +{ + private const string RunId = "run-diff"; + private const long PokeTick = 7; + + private readonly string _root = Path.Combine(Path.GetTempPath(), $"epochsim-statediff-{Guid.NewGuid():N}"); + + public void Dispose() + { + if (Directory.Exists(_root)) + Directory.Delete(_root, recursive: true); + } + + [Fact] + public async Task Bisect_OnViolatedInvariant_PrintsStateDiffAndWritesFile() + { + RecordPokedRun(snapshotEveryTick: false); + + var (rc, output) = await RunCli("bisect", _root, RunId, "--end-tick", "20"); + + Assert.Equal(2, rc); + Assert.Contains($"FirstViolationTick={PokeTick}", output, StringComparison.Ordinal); + Assert.Contains($"StateDiff (tick {PokeTick - 1} -> {PokeTick}):", output, StringComparison.Ordinal); + Assert.Contains("$.Population: 100 -> -400", output, StringComparison.Ordinal); + Assert.Contains("EventsAtTick=1", output, StringComparison.Ordinal); + Assert.True(output.IndexOf("Message=", StringComparison.Ordinal) < output.IndexOf("StateDiff", StringComparison.Ordinal)); + + var diffFile = Path.Combine(_root, RunId, "minrepro", $"tick-{PokeTick}", "statediff.txt"); + Assert.True(File.Exists(diffFile)); + Assert.Contains("$.Population: 100 -> -400", File.ReadAllText(diffFile), StringComparison.Ordinal); + } + + [Fact] + public async Task Bisect_WithoutViolation_PrintsNoStateDiff() + { + RecordRun(snapshotEveryTick: false, poke: false); + + var (rc, output) = await RunCli("bisect", _root, RunId, "--end-tick", "20"); + + Assert.Equal(0, rc); + Assert.DoesNotContain("StateDiff", output, StringComparison.Ordinal); + } + + [Fact] + public async Task VerifyRun_MismatchWithoutSnapshot_ReportsUnavailable() + { + RecordRun(snapshotEveryTick: false, poke: false); + TamperFingerprint(tick: 3); + + var (rc, output) = await RunCli("verify-run", _root, RunId); + + Assert.Equal(3, rc); + Assert.Contains("VerifyMismatchTick=3", output, StringComparison.Ordinal); + Assert.Contains("StateDiffUnavailable: no snapshot at tick 3", output, StringComparison.Ordinal); + } + + [Fact] + public async Task VerifyRun_MismatchWithSnapshot_PrintsSnapshotToReplayDiff() + { + RecordRun(snapshotEveryTick: true, poke: false); + var snapshotPath = Path.Combine(_root, RunId, "snapshots", "snapshot-1.json"); + File.WriteAllText(snapshotPath, File.ReadAllText(snapshotPath).Replace("\"Population\":100", "\"Population\":999", StringComparison.Ordinal)); + + var (rc, output) = await RunCli("verify-run", _root, RunId); + + Assert.Equal(3, rc); + Assert.Contains("VerifyMismatchTick=1", output, StringComparison.Ordinal); + Assert.Contains("StateDiff (snapshot -> replay, tick 1):", output, StringComparison.Ordinal); + Assert.Contains("$.Population: 999 -> 100", output, StringComparison.Ordinal); + } + + private void RecordPokedRun(bool snapshotEveryTick) + => RecordRun(snapshotEveryTick, poke: true); + + private void RecordRun(bool snapshotEveryTick, bool poke) + { + var adapter = new PopulationDomainAdapter(); + var state = adapter.CreateInitialState(); + var engine = new SimulationEngine(); + adapter.ConfigureEngine(engine); + + if (poke) + { + engine.AddSystem( + "Poke", + tick: ctx => + { + if (ctx.Time.Tick == PokeTick - 1) + ctx.Scheduler.ScheduleNextTick(new PopulationDeltaEvent(-500)); + }); + } + + var builder = EpochSimRun.For(state) + .WithRootDirectory(_root) + .WithRunId(RunId) + .WithDomain(adapter.Name) + .WithEventLog(adapter.Codec) + .WithStateFingerprints(adapter.Serializer, everyTicks: 1); + + if (snapshotEveryTick) + builder.WithSnapshots(adapter.Serializer, everyTicks: 1); + + using var run = builder.Build(); + run.RunTicks(engine, seed: 1, endTickInclusive: 12); + } + + private void TamperFingerprint(long tick) + { + var path = Path.Combine(_root, RunId, "statefp.jsonl"); + var lines = File.ReadAllLines(path) + .Select(line => line.StartsWith($"{{\"t\":{tick},", StringComparison.Ordinal) + ? $"{{\"t\":{tick},\"h\":\"{new string('0', 64)}\"}}" + : line); + File.WriteAllLines(path, lines); + } + + private static async Task<(int ExitCode, string Output)> RunCli(params string[] args) + { + var original = Console.Out; + using var writer = new StringWriter(); + Console.SetOut(writer); + + try + { + var rc = await new CliApp().RunAsync(args); + return (rc, writer.ToString()); + } + finally + { + Console.SetOut(original); + } + } +} diff --git a/tests/EpochSim.Determinism.Tests/StateDiffTests.cs b/tests/EpochSim.Determinism.Tests/StateDiffTests.cs new file mode 100644 index 0000000..8a9e116 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/StateDiffTests.cs @@ -0,0 +1,163 @@ +using EpochSim.Serialization.State; + +public sealed class StateDiffTests +{ + [Fact] + public void Compute_EqualDocumentsWithDifferentPropertyOrder_ReturnsEmpty() + { + var changes = StateDiff.Compute("""{"a":1,"b":{"x":true,"y":[1,2]}}""", """{"b":{"y":[1,2],"x":true},"a":1}"""); + + Assert.Empty(changes); + } + + [Fact] + public void Compute_ChangedScalar_ReportsPathAndValues() + { + var changes = StateDiff.Compute("""{"Population":3}""", """{"Population":-2}"""); + + var change = Assert.Single(changes); + Assert.Equal(new StateChange("$.Population", StateChangeKind.Changed, "3", "-2"), change); + } + + [Fact] + public void Compute_AddedAndRemovedProperties_AreReported() + { + var changes = StateDiff.Compute("""{"Old":1,"Kept":2}""", """{"Kept":2,"New":"x"}"""); + + Assert.Equal( + [ + new StateChange("$.New", StateChangeKind.Added, null, "\"x\""), + new StateChange("$.Old", StateChangeKind.Removed, "1", null) + ], + changes); + } + + [Fact] + public void Compute_NestedObject_UsesDottedPath() + { + var changes = StateDiff.Compute("""{"Map":{"key":1}}""", """{"Map":{"key":2}}"""); + + Assert.Equal("$.Map.key", Assert.Single(changes).Path); + } + + [Fact] + public void Compute_ArraysOfDifferentLength_ReportTailByIndex() + { + var grown = StateDiff.Compute("""{"Items":[1,2]}""", """{"Items":[1,2,7]}"""); + var shrunk = StateDiff.Compute("""{"Items":[1,2,7]}""", """{"Items":[1]}"""); + + Assert.Equal(new StateChange("$.Items[2]", StateChangeKind.Added, null, "7"), Assert.Single(grown)); + Assert.Equal( + [ + new StateChange("$.Items[1]", StateChangeKind.Removed, "2", null), + new StateChange("$.Items[2]", StateChangeKind.Removed, "7", null) + ], + shrunk); + } + + [Fact] + public void Compute_ArrayElementField_UsesIndexedPath() + { + var changes = StateDiff.Compute("""{"Items":[{"Count":1},{"Count":2}]}""", """{"Items":[{"Count":1},{"Count":5}]}"""); + + Assert.Equal("$.Items[1].Count", Assert.Single(changes).Path); + } + + [Fact] + public void Compute_KeysWithDotsAndSpaces_UseBracketNotation() + { + var changes = StateDiff.Compute("""{"a.b":1,"c d":1}""", """{"a.b":2,"c d":2}"""); + + Assert.Equal(["$[\"a.b\"]", "$[\"c d\"]"], changes.Select(c => c.Path)); + } + + [Fact] + public void Compute_TypeChange_IsReportedAsChanged() + { + var changes = StateDiff.Compute("""{"v":1}""", """{"v":{"a":1}}"""); + + var change = Assert.Single(changes); + Assert.Equal(StateChangeKind.Changed, change.Kind); + Assert.Equal("{\"a\":1}", change.After); + } + + [Fact] + public void Compute_NullValue_IsDistinctFromMissing() + { + var changes = StateDiff.Compute("""{"v":null}""", """{"v":1}"""); + + Assert.Equal(new StateChange("$.v", StateChangeKind.Changed, "null", "1"), Assert.Single(changes)); + } + + [Fact] + public void Compute_RootScalars_UseRootPath() + { + var changes = StateDiff.Compute("1", "2"); + + Assert.Equal(new StateChange("$", StateChangeKind.Changed, "1", "2"), Assert.Single(changes)); + } + + [Fact] + public void Compute_IsDeterministicAndOrdinallyOrdered() + { + const string before = """{"b":1,"a":1,"c":1}"""; + const string after = """{"c":2,"b":2,"a":2}"""; + + var first = StateDiff.Compute(before, after); + var second = StateDiff.Compute(before, after); + + Assert.Equal(first, second); + Assert.Equal(["$.a", "$.b", "$.c"], first.Select(c => c.Path)); + } + + [Fact] + public void Compute_LongValues_AreTruncatedWithEllipsis() + { + var longValue = new string('x', 200); + + var changes = StateDiff.Compute($$"""{"v":"{{longValue}}"}""", """{"v":"short"}"""); + + var change = Assert.Single(changes); + Assert.Equal(80, change.Before!.Length); + Assert.EndsWith("…", change.Before); + Assert.Equal("\"short\"", change.After); + } + + [Fact] + public void Compute_InvalidJson_Throws() + { + Assert.ThrowsAny(() => StateDiff.Compute("{", "{}")); + } + + [Fact] + public void Format_ProducesOneLinePerChange() + { + var lines = StateDiffFormatter.Format( + [ + new StateChange("$.Population", StateChangeKind.Changed, "3", "-2"), + new StateChange("$.Items[2]", StateChangeKind.Added, null, "7"), + new StateChange("$.Flag", StateChangeKind.Removed, "true", null) + ]); + + Assert.Equal(["$.Population: 3 -> -2", "$.Items[2]: added 7", "$.Flag: removed true"], lines); + } + + [Fact] + public void Format_MoreThanMaxLines_AppendsSummaryLine() + { + var changes = Enumerable.Range(0, 5) + .Select(i => new StateChange($"$.p{i}", StateChangeKind.Changed, "1", "2")) + .ToArray(); + + var lines = StateDiffFormatter.Format(changes, maxLines: 2); + + Assert.Equal(3, lines.Count); + Assert.Equal("... and 3 more changes", lines[^1]); + } + + [Fact] + public void Format_NonPositiveMaxLines_Throws() + { + Assert.Throws(() => StateDiffFormatter.Format([], maxLines: 0)); + } +}