From 9731320b09a0117755a3e6060b9e063601c5caa5 Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 12:31:06 +0300 Subject: [PATCH 01/10] feat(fuzz): shrink failing command plans with ddmin Adds Shrink(bool), OnlyCommands(indices) and the FuzzFailure shrink fields. Command plans of failed seeds are minimized by delta debugging within a fixed attempt and time budget. Repro code expresses the minimal scenario as OnlyCommands. Adds epochsim fuzz --no-shrink and the Account sample. --- src/EpochSim.Cli/App/CliApp.cs | 2 +- src/EpochSim.Cli/Commands/FuzzCommand.cs | 6 +- src/EpochSim.Cli/Commands/FuzzOptions.cs | 6 +- .../Fuzzing/AccountCommands.cs | 9 + src/EpochSim.Samples/Fuzzing/AccountLedger.cs | 29 ++ src/EpochSim.Samples/Fuzzing/AccountState.cs | 6 + .../Fuzzing/BalanceNonNegativeInvariant.cs | 15 + src/EpochSim/AssemblyInfo.cs | 1 + src/EpochSim/Fuzzing/CommandShrinker.cs | 115 +++++++ src/EpochSim/Fuzzing/FuzzBuilder.cs | 33 +- src/EpochSim/Fuzzing/FuzzCommandPlan.cs | 15 +- src/EpochSim/Fuzzing/FuzzCommandRef.cs | 3 + src/EpochSim/Fuzzing/FuzzFailure.cs | 28 ++ src/EpochSim/Fuzzing/FuzzFailureIdentity.cs | 13 + src/EpochSim/Fuzzing/FuzzSeedRunner.cs | 123 ++++++-- src/EpochSim/Fuzzing/FuzzSettings.cs | 5 +- src/EpochSim/Fuzzing/FuzzShrinkBudget.cs | 9 + .../FuzzCliTests.cs | 11 + .../FuzzShrinkTests.cs | 285 ++++++++++++++++++ 19 files changed, 675 insertions(+), 39 deletions(-) create mode 100644 src/EpochSim.Samples/Fuzzing/AccountCommands.cs create mode 100644 src/EpochSim.Samples/Fuzzing/AccountLedger.cs create mode 100644 src/EpochSim.Samples/Fuzzing/AccountState.cs create mode 100644 src/EpochSim.Samples/Fuzzing/BalanceNonNegativeInvariant.cs create mode 100644 src/EpochSim/Fuzzing/CommandShrinker.cs create mode 100644 src/EpochSim/Fuzzing/FuzzCommandRef.cs create mode 100644 src/EpochSim/Fuzzing/FuzzFailureIdentity.cs create mode 100644 src/EpochSim/Fuzzing/FuzzShrinkBudget.cs create mode 100644 tests/EpochSim.Determinism.Tests/FuzzShrinkTests.cs diff --git a/src/EpochSim.Cli/App/CliApp.cs b/src/EpochSim.Cli/App/CliApp.cs index 035ba17..0dea776 100644 --- a/src/EpochSim.Cli/App/CliApp.cs +++ b/src/EpochSim.Cli/App/CliApp.cs @@ -106,7 +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(" fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parallel N] [--out dir] [--no-shrink]"); Console.WriteLine(" list-adapters"); Console.WriteLine(); Console.WriteLine("Pass --help to any command for detailed usage."); diff --git a/src/EpochSim.Cli/Commands/FuzzCommand.cs b/src/EpochSim.Cli/Commands/FuzzCommand.cs index ff4c5a1..9e4b51a 100644 --- a/src/EpochSim.Cli/Commands/FuzzCommand.cs +++ b/src/EpochSim.Cli/Commands/FuzzCommand.cs @@ -10,7 +10,7 @@ public sealed class FuzzCommand : ICliCommand public string Help => """ - fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parallel N] [--out dir] + fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parallel N] [--out dir] [--no-shrink] 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. @@ -21,6 +21,7 @@ fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parall --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) + --no-shrink Keep the full command plan of a failed seed instead of minimizing it """; public int Execute(CommandContext ctx, string[] args) @@ -42,7 +43,8 @@ private static int Run(IDomainAdapter adapter, FuzzOptions optio .Seeds(options.FromSeed, options.ToSeed) .Ticks(options.Ticks) .CheckDeterminism(options.CheckDeterminism) - .ArtifactsRoot(options.OutputDirectory); + .ArtifactsRoot(options.OutputDirectory) + .Shrink(options.Shrink); if (options.Parallelism is { } degree) fuzz.Parallelism(degree); diff --git a/src/EpochSim.Cli/Commands/FuzzOptions.cs b/src/EpochSim.Cli/Commands/FuzzOptions.cs index e33b312..19e6d00 100644 --- a/src/EpochSim.Cli/Commands/FuzzOptions.cs +++ b/src/EpochSim.Cli/Commands/FuzzOptions.cs @@ -9,7 +9,8 @@ internal sealed record FuzzOptions( long Ticks, bool CheckDeterminism, int? Parallelism, - string OutputDirectory) + string OutputDirectory, + bool Shrink) { private const ulong DefaultFromSeed = 1; private const ulong DefaultToSeed = 1000; @@ -18,7 +19,7 @@ internal sealed record FuzzOptions( public static FuzzOptions Parse(string[] args) { - var options = new FuzzOptions(null, DefaultFromSeed, DefaultToSeed, DefaultTicks, false, null, DefaultOutputDirectory); + var options = new FuzzOptions(null, DefaultFromSeed, DefaultToSeed, DefaultTicks, false, null, DefaultOutputDirectory, true); for (var i = 0; i < args.Length; i++) { @@ -32,6 +33,7 @@ public static FuzzOptions Parse(string[] args) "--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) }, + "--no-shrink" => options with { Shrink = false }, _ => throw new ArgumentException($"Unknown argument '{args[i]}'. Run 'fuzz --help' for usage.") }; } diff --git a/src/EpochSim.Samples/Fuzzing/AccountCommands.cs b/src/EpochSim.Samples/Fuzzing/AccountCommands.cs new file mode 100644 index 0000000..96f32d8 --- /dev/null +++ b/src/EpochSim.Samples/Fuzzing/AccountCommands.cs @@ -0,0 +1,9 @@ +using EpochSim.Kernel.Messaging; + +namespace EpochSim.Samples.Fuzzing; + +[MessageKind("Deposit")] +public sealed record DepositCommand(int Amount) : ICommand; + +[MessageKind("Withdraw")] +public sealed record WithdrawCommand(int Amount) : ICommand; diff --git a/src/EpochSim.Samples/Fuzzing/AccountLedger.cs b/src/EpochSim.Samples/Fuzzing/AccountLedger.cs new file mode 100644 index 0000000..28305c8 --- /dev/null +++ b/src/EpochSim.Samples/Fuzzing/AccountLedger.cs @@ -0,0 +1,29 @@ +using EpochSim.Execution; +using EpochSim.Fuzzing; + +namespace EpochSim.Samples.Fuzzing; + +public static class AccountLedger +{ + public const int CommandsPerSeed = 300; + + private const int MaxDeposit = 30; + private const int MaxWithdrawal = 60; + + public static void Register(SimulationEngine engine) + { + engine.OnCommand((state, command, _) => state.Balance += command.Amount); + engine.OnCommand((state, command, _) => state.Balance -= command.Amount); + } + + public static void PlanCommands(FuzzCommandPlan plan) + { + for (var i = 0; i < CommandsPerSeed; i++) + { + var tick = plan.Rng.NextInt(0, (int)plan.EndTick + 1); + plan.Enqueue(tick, plan.Rng.NextInt(0, 2) == 0 + ? new DepositCommand(plan.Rng.NextInt(1, MaxDeposit + 1)) + : new WithdrawCommand(plan.Rng.NextInt(1, MaxWithdrawal + 1))); + } + } +} diff --git a/src/EpochSim.Samples/Fuzzing/AccountState.cs b/src/EpochSim.Samples/Fuzzing/AccountState.cs new file mode 100644 index 0000000..9b78380 --- /dev/null +++ b/src/EpochSim.Samples/Fuzzing/AccountState.cs @@ -0,0 +1,6 @@ +namespace EpochSim.Samples.Fuzzing; + +public sealed class AccountState +{ + public int Balance { get; set; } = 100; +} diff --git a/src/EpochSim.Samples/Fuzzing/BalanceNonNegativeInvariant.cs b/src/EpochSim.Samples/Fuzzing/BalanceNonNegativeInvariant.cs new file mode 100644 index 0000000..2363fcb --- /dev/null +++ b/src/EpochSim.Samples/Fuzzing/BalanceNonNegativeInvariant.cs @@ -0,0 +1,15 @@ +using EpochSim.Kernel.Time; +using EpochSim.Kernel.Validation; + +namespace EpochSim.Samples.Fuzzing; + +public sealed class BalanceNonNegativeInvariant : IInvariant +{ + public string Name => "BalanceNonNegative"; + + public bool Check(SimTime time, AccountState state, out string message) + { + message = state.Balance >= 0 ? string.Empty : $"Balance={state.Balance}"; + return state.Balance >= 0; + } +} diff --git a/src/EpochSim/AssemblyInfo.cs b/src/EpochSim/AssemblyInfo.cs index 6f0100d..ca85705 100644 --- a/src/EpochSim/AssemblyInfo.cs +++ b/src/EpochSim/AssemblyInfo.cs @@ -1,3 +1,4 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("EpochSim.Testing")] +[assembly: InternalsVisibleTo("EpochSim.Determinism.Tests")] diff --git a/src/EpochSim/Fuzzing/CommandShrinker.cs b/src/EpochSim/Fuzzing/CommandShrinker.cs new file mode 100644 index 0000000..4b517b2 --- /dev/null +++ b/src/EpochSim/Fuzzing/CommandShrinker.cs @@ -0,0 +1,115 @@ +using System.Diagnostics; + +namespace EpochSim.Fuzzing; + +internal sealed record CommandShrinkResult(IReadOnlyList Indices, int Attempts, bool BudgetExhausted); + +internal static class CommandShrinker +{ + public static CommandShrinkResult Minimize( + IReadOnlyList indices, + Func, bool> stillFails, + FuzzShrinkBudget budget) + { + var stopwatch = Stopwatch.StartNew(); + var attempts = 0; + var exhausted = false; + + bool Fails(IReadOnlyList candidate) + { + if (attempts >= budget.MaxAttempts || stopwatch.Elapsed >= budget.TimeLimit) + { + exhausted = true; + return false; + } + + attempts++; + return stillFails(candidate); + } + + var current = indices; + + if (current.Count > 0 && Fails([])) + return new CommandShrinkResult([], attempts, exhausted); + + var granularity = 2; + + while (current.Count >= 2 && !exhausted) + { + var chunks = Split(current, granularity); + + if (TryReduceToChunk(chunks, Fails, out var chunk)) + { + current = chunk; + granularity = 2; + } + else if (TryReduceToComplement(chunks, Fails, out var complement)) + { + current = complement; + granularity = Math.Max(granularity - 1, 2); + } + else if (granularity < current.Count) + { + granularity = Math.Min(granularity * 2, current.Count); + } + else + { + break; + } + } + + return new CommandShrinkResult(current, attempts, exhausted); + } + + private static bool TryReduceToChunk( + IReadOnlyList> chunks, + Func, bool> fails, + out IReadOnlyList reduced) + { + foreach (var chunk in chunks) + { + if (fails(chunk)) + { + reduced = chunk; + return true; + } + } + + reduced = []; + return false; + } + + private static bool TryReduceToComplement( + IReadOnlyList> chunks, + Func, bool> fails, + out IReadOnlyList reduced) + { + for (var skipped = 0; skipped < chunks.Count; skipped++) + { + var complement = chunks.Where((_, position) => position != skipped).SelectMany(chunk => chunk).ToArray(); + if (fails(complement)) + { + reduced = complement; + return true; + } + } + + reduced = []; + return false; + } + + private static IReadOnlyList> Split(IReadOnlyList items, int parts) + { + var chunks = new List>(parts); + var start = 0; + + for (var part = 0; part < parts; part++) + { + var size = (items.Count - start) / (parts - part); + chunks.Add(items.Skip(start).Take(size).ToArray()); + start += size; + } + + return chunks; + } +} diff --git a/src/EpochSim/Fuzzing/FuzzBuilder.cs b/src/EpochSim/Fuzzing/FuzzBuilder.cs index 8c035ef..2573a3b 100644 --- a/src/EpochSim/Fuzzing/FuzzBuilder.cs +++ b/src/EpochSim/Fuzzing/FuzzBuilder.cs @@ -20,6 +20,9 @@ public sealed class FuzzBuilder private string? _artifactsRoot; private IEventCodecV2? _eventCodec; private IProgress? _progress; + private bool? _shrink; + private IReadOnlyList? _onlyCommands; + private FuzzShrinkBudget _shrinkBudget = FuzzShrinkBudget.Default; internal FuzzBuilder() { @@ -113,6 +116,31 @@ public FuzzBuilder Progress(IProgress progress) return this; } + public FuzzBuilder Shrink(bool enabled = true) + { + _shrink = enabled; + return this; + } + + public FuzzBuilder OnlyCommands(IReadOnlyList indices) + { + ArgumentNullException.ThrowIfNull(indices); + + foreach (var index in indices) + ArgumentOutOfRangeException.ThrowIfNegative(index, nameof(indices)); + + _onlyCommands = indices.Distinct().Order().ToArray(); + return this; + } + + internal FuzzBuilder ShrinkBudget(int maxAttempts, TimeSpan timeLimit) + { + ArgumentOutOfRangeException.ThrowIfNegative(maxAttempts); + ArgumentOutOfRangeException.ThrowIfLessThan(timeLimit, TimeSpan.Zero); + _shrinkBudget = new FuzzShrinkBudget(maxAttempts, timeLimit); + return this; + } + internal FuzzSettings Build() => new( _stateFactory ?? throw MissingParameter(nameof(State)), @@ -127,7 +155,10 @@ internal FuzzSettings Build() _stopAtFirstFailure, _artifactsRoot, _eventCodec, - _progress); + _progress, + _shrink ?? _commands is not null, + _onlyCommands, + _shrinkBudget); private static InvalidOperationException MissingParameter(string name) => new($"Epoch.Fuzz requires {name}(...) to be configured."); diff --git a/src/EpochSim/Fuzzing/FuzzCommandPlan.cs b/src/EpochSim/Fuzzing/FuzzCommandPlan.cs index e86c175..6865a75 100644 --- a/src/EpochSim/Fuzzing/FuzzCommandPlan.cs +++ b/src/EpochSim/Fuzzing/FuzzCommandPlan.cs @@ -20,6 +20,7 @@ internal FuzzCommandPlan(ulong seed, long endTick) public long EndTick { get; } public IRng Rng { get; } + internal int Count => _entries.Count; internal bool IsEmpty => _entries.Count == 0; public void Enqueue(long tick, ICommand command) @@ -31,12 +32,20 @@ public void Enqueue(long tick, ICommand command) _entries.Add((tick, command)); } - internal void ScheduleInto(ScheduledCommandInbox inbox) + internal void ScheduleInto(ScheduledCommandInbox inbox, IReadOnlySet? selection) { - foreach (var (tick, command) in _entries) - inbox.Enqueue(tick, command); + for (var index = 0; index < _entries.Count; index++) + { + if (selection is null || selection.Contains(index)) + inbox.Enqueue(_entries[index].Tick, _entries[index].Command); + } } + internal IReadOnlyList Describe(IReadOnlyList indices) + => indices + .Select(index => new FuzzCommandRef(index, _entries[index].Tick, _entries[index].Command.GetType().Name)) + .ToArray(); + private static ulong SplitMix64(ulong value) { var z = value + 0x9E3779B97F4A7C15UL; diff --git a/src/EpochSim/Fuzzing/FuzzCommandRef.cs b/src/EpochSim/Fuzzing/FuzzCommandRef.cs new file mode 100644 index 0000000..b66cccf --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzCommandRef.cs @@ -0,0 +1,3 @@ +namespace EpochSim.Fuzzing; + +public readonly record struct FuzzCommandRef(int Index, long Tick, string Type); diff --git a/src/EpochSim/Fuzzing/FuzzFailure.cs b/src/EpochSim/Fuzzing/FuzzFailure.cs index 0734dfc..04accd6 100644 --- a/src/EpochSim/Fuzzing/FuzzFailure.cs +++ b/src/EpochSim/Fuzzing/FuzzFailure.cs @@ -12,12 +12,22 @@ public sealed record FuzzFailure( string? ArtifactsDir, string ReproCode) { + public int OriginalCommandCount { get; init; } + public IReadOnlyList? MinimalCommandIndices { get; init; } + public IReadOnlyList MinimalCommands { get; init; } = []; + public int ShrinkAttempts { get; init; } + public bool ShrinkBudgetExhausted { get; init; } + public string? ShrinkSkipReason { get; init; } + public long ReproTicks { get; init; } + public string ToText() { var text = new StringBuilder(); text.Append('[').Append(Kind).Append("] seed=").Append(Seed).Append(" tick=").Append(Tick).AppendLine(); text.Append(" ").AppendLine(Summary); + AppendShrink(text); + if (StateDiff.Count > 0) { text.AppendLine(" StateDiff:"); @@ -25,10 +35,28 @@ public string ToText() text.Append(" ").AppendLine(line); } + if (ShrinkSkipReason is not null) + text.Append(" Shrink skipped: ").AppendLine(ShrinkSkipReason); + if (ArtifactsDir is not null) text.Append(" Artifacts: ").AppendLine(ArtifactsDir); text.Append(" Repro: ").Append(ReproCode); return text.ToString(); } + + private void AppendShrink(StringBuilder text) + { + if (MinimalCommandIndices is not { } indices) + return; + + text.Append(" Commands: ").Append(OriginalCommandCount).Append(" -> ").Append(indices.Count); + text.Append(ShrinkBudgetExhausted + ? $" (shrink budget exhausted after {ShrinkAttempts} attempts, result may not be minimal)" + : $" (shrunk in {ShrinkAttempts} attempts)"); + text.AppendLine(); + + foreach (var command in MinimalCommands) + text.Append(" #").Append(command.Index).Append(" tick ").Append(command.Tick).Append(": ").AppendLine(command.Type); + } } diff --git a/src/EpochSim/Fuzzing/FuzzFailureIdentity.cs b/src/EpochSim/Fuzzing/FuzzFailureIdentity.cs new file mode 100644 index 0000000..9c2d3f1 --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzFailureIdentity.cs @@ -0,0 +1,13 @@ +using EpochSim.Kernel.Validation; + +namespace EpochSim.Fuzzing; + +internal readonly record struct FuzzFailureIdentity(FuzzFailureKind Kind, string Name) +{ + public static FuzzFailureIdentity Of(Exception error) + => error is InvariantViolationException violation + ? new FuzzFailureIdentity(FuzzFailureKind.InvariantViolation, violation.InvariantName) + : new FuzzFailureIdentity(FuzzFailureKind.Exception, error.GetType().FullName ?? error.GetType().Name); + + public static FuzzFailureIdentity NonDeterminism { get; } = new(FuzzFailureKind.NonDeterminism, nameof(FuzzFailureKind.NonDeterminism)); +} diff --git a/src/EpochSim/Fuzzing/FuzzSeedRunner.cs b/src/EpochSim/Fuzzing/FuzzSeedRunner.cs index a55309c..954dacf 100644 --- a/src/EpochSim/Fuzzing/FuzzSeedRunner.cs +++ b/src/EpochSim/Fuzzing/FuzzSeedRunner.cs @@ -11,21 +11,21 @@ internal sealed class FuzzSeedRunner(FuzzSettings settings) { public FuzzFailure? Check(ulong seed) { - var first = Execute(seed, settings.EndTick, recordFingerprints: settings.CheckDeterminism); + var first = Execute(seed, settings.EndTick, recordFingerprints: settings.CheckDeterminism, settings.OnlyCommands); if (!settings.CheckDeterminism) - return ToFailure(seed, first); + return ShrinkIfNeeded(seed, first); - var second = Execute(seed, settings.EndTick, recordFingerprints: true); + var second = Execute(seed, settings.EndTick, recordFingerprints: true, settings.OnlyCommands); var divergenceTick = FindDivergenceTick(first, second); return divergenceTick is { } tick ? BuildNonDeterminismFailure(seed, tick) - : ToFailure(seed, first); + : ShrinkIfNeeded(seed, first); } public FuzzRunResult Trace(ulong seed) - => Execute(seed, settings.EndTick, recordFingerprints: true); + => Execute(seed, settings.EndTick, recordFingerprints: true, settings.OnlyCommands); public string WriteArtifacts(FuzzFailure failure) { @@ -49,7 +49,7 @@ public string WriteArtifacts(FuzzFailure failure) builder.WithStateFingerprints(settings.Serializer, everyTicks: 1); using var scope = builder.Build(); - var engine = CreateEngine(failure.Seed); + var engine = CreateEngine(failure.Seed, failure.MinimalCommandIndices ?? settings.OnlyCommands); try { @@ -66,10 +66,10 @@ 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) + private FuzzRunResult Execute(ulong seed, long endTick, bool recordFingerprints, IReadOnlyList? selection) { var state = settings.StateFactory(); - var engine = CreateEngine(seed); + var engine = CreateEngine(seed, selection); var probe = new FuzzTickProbe(); engine.AddMiddleware(probe); @@ -99,31 +99,40 @@ private FuzzRunResult Execute(ulong seed, long endTick, bool recordFinge return new FuzzRunResult(state, error, probe.LastTick, sink.Records); } - private SimulationEngine CreateEngine(ulong seed) + private SimulationEngine CreateEngine(ulong seed, IReadOnlyList? selection) { var engine = new SimulationEngine(); settings.ConfigureEngine(engine); - if (settings.Commands is { } configureCommands) + if (BuildPlan(seed) is { IsEmpty: false } plan) { - var plan = new FuzzCommandPlan(seed, settings.EndTick); - configureCommands(plan); - - if (!plan.IsEmpty) - { - var inbox = new ScheduledCommandInbox(); - plan.ScheduleInto(inbox); - engine.AttachScheduledInbox(inbox); - } + var inbox = new ScheduledCommandInbox(); + plan.ScheduleInto(inbox, selection?.ToHashSet()); + engine.AttachScheduledInbox(inbox); } return engine; } + private FuzzCommandPlan? BuildPlan(ulong seed) + { + if (settings.Commands is not { } configureCommands) + return null; + + var plan = new FuzzCommandPlan(seed, settings.EndTick); + configureCommands(plan); + + if (settings.OnlyCommands is { Count: > 0 } selection && selection[^1] >= plan.Count) + throw new InvalidOperationException( + $"OnlyCommands refers to command #{selection[^1]}, but the plan for seed {seed} has {plan.Count} commands."); + + return plan; + } + private IReadOnlyList> CreateInvariants() => settings.Invariants is { } factory ? factory().ToArray() : []; - private FuzzFailure? ToFailure(ulong seed, FuzzRunResult result) + private FuzzFailure? ToFailure(ulong seed, FuzzRunResult result, IReadOnlyList? selection) { if (result.Error is not { } error) return null; @@ -136,9 +145,49 @@ private IReadOnlyList> CreateInvariants() kind, tick, summary, - ComputeFailureDiff(seed, tick, result.State), + ComputeFailureDiff(seed, tick, result.State, selection), ArtifactsDir: null, - ReproCode(seed, tick, kind)); + ReproCode(seed, tick, kind, selection)) + { + ReproTicks = ReproTicks(tick) + }; + } + + private FuzzFailure? ShrinkIfNeeded(ulong seed, FuzzRunResult result) + { + var failure = ToFailure(seed, result, settings.OnlyCommands); + + if (failure is null || !settings.Shrink || result.Error is not { } error) + return failure; + + if (BuildPlan(seed) is not { IsEmpty: false } plan) + return failure; + + var identity = FuzzFailureIdentity.Of(error); + var original = settings.OnlyCommands ?? Enumerable.Range(0, plan.Count).ToArray(); + + var shrink = CommandShrinker.Minimize( + original, + candidate => Execute(seed, settings.EndTick, recordFingerprints: false, candidate) is { Error: { } replayed } + && FuzzFailureIdentity.Of(replayed) == identity, + settings.ShrinkBudget); + + var minimal = ToFailure( + seed, + Execute(seed, settings.EndTick, recordFingerprints: false, shrink.Indices), + shrink.Indices); + + if (minimal is null || minimal.Kind != failure.Kind) + return failure with { ShrinkSkipReason = "the failure did not reproduce while shrinking; the simulation may be non-deterministic, try CheckDeterminism" }; + + return minimal with + { + OriginalCommandCount = original.Count, + MinimalCommandIndices = shrink.Indices, + MinimalCommands = plan.Describe(shrink.Indices), + ShrinkAttempts = shrink.Attempts, + ShrinkBudgetExhausted = shrink.BudgetExhausted + }; } private static (FuzzFailureKind Kind, string Summary) Describe(Exception error) @@ -148,8 +197,8 @@ private static (FuzzFailureKind Kind, string Summary) Describe(Exception error) private FuzzFailure BuildNonDeterminismFailure(ulong seed, long tick) { - var left = Execute(seed, tick, recordFingerprints: false); - var right = Execute(seed, tick, recordFingerprints: false); + var left = Execute(seed, tick, recordFingerprints: false, settings.OnlyCommands); + var right = Execute(seed, tick, recordFingerprints: false, settings.OnlyCommands); return new FuzzFailure( seed, @@ -158,13 +207,22 @@ private FuzzFailure BuildNonDeterminismFailure(ulong seed, long 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)); + ReproCode(seed, tick, FuzzFailureKind.NonDeterminism, settings.OnlyCommands)) + { + ReproTicks = ReproTicks(tick), + ShrinkSkipReason = ShrinkSkipReasonFor(seed) + }; } - private IReadOnlyList ComputeFailureDiff(ulong seed, long failureTick, TState failedState) + private string? ShrinkSkipReasonFor(ulong seed) + => settings.Shrink && BuildPlan(seed) is { IsEmpty: false } + ? "non-deterministic failures are not shrunk: replays of the same seed disagree, so a smaller command set cannot be checked reliably" + : null; + + private IReadOnlyList ComputeFailureDiff(ulong seed, long failureTick, TState failedState, IReadOnlyList? selection) => SafeDiff( () => failureTick > 0 - ? settings.Serializer.Serialize(Execute(seed, failureTick - 1, recordFingerprints: false).State) + ? settings.Serializer.Serialize(Execute(seed, failureTick - 1, recordFingerprints: false, selection).State) : settings.Serializer.Serialize(settings.StateFactory()), () => settings.Serializer.Serialize(failedState)); @@ -212,9 +270,16 @@ private static long FailureTick(FuzzRunResult result) _ => result.LastTick }; - private static string ReproCode(ulong seed, long tick, FuzzFailureKind kind) + private long ReproTicks(long failureTick) + => settings.Commands is null ? failureTick : settings.EndTick; + + private string ReproCode(ulong seed, long tick, FuzzFailureKind kind, IReadOnlyList? selection) { - var code = $".Seeds({seed}, {seed}).Ticks({tick})"; + var code = $".Seeds({seed}, {seed}).Ticks({ReproTicks(tick)})"; + + if (selection is not null) + code += $".OnlyCommands([{string.Join(", ", selection)}])"; + return kind == FuzzFailureKind.NonDeterminism ? $"{code}.CheckDeterminism(true)" : code; } } diff --git a/src/EpochSim/Fuzzing/FuzzSettings.cs b/src/EpochSim/Fuzzing/FuzzSettings.cs index b5ce868..ad28aec 100644 --- a/src/EpochSim/Fuzzing/FuzzSettings.cs +++ b/src/EpochSim/Fuzzing/FuzzSettings.cs @@ -18,4 +18,7 @@ internal sealed record FuzzSettings( bool StopAtFirstFailure, string? ArtifactsRoot, IEventCodecV2? EventCodec, - IProgress? Progress); + IProgress? Progress, + bool Shrink, + IReadOnlyList? OnlyCommands, + FuzzShrinkBudget ShrinkBudget); diff --git a/src/EpochSim/Fuzzing/FuzzShrinkBudget.cs b/src/EpochSim/Fuzzing/FuzzShrinkBudget.cs new file mode 100644 index 0000000..88c6cdc --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzShrinkBudget.cs @@ -0,0 +1,9 @@ +namespace EpochSim.Fuzzing; + +internal readonly record struct FuzzShrinkBudget(int MaxAttempts, TimeSpan TimeLimit) +{ + public static FuzzShrinkBudget Default { get; } = new(MaxAttemptsLimit, TimeSpan.FromSeconds(TimeLimitSeconds)); + + private const int MaxAttemptsLimit = 1000; + private const int TimeLimitSeconds = 10; +} diff --git a/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs b/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs index 3d65d72..0c48976 100644 --- a/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs +++ b/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs @@ -83,6 +83,17 @@ public async Task Fuzz_Help_PrintsUsageAndReturns0() Assert.Contains("--check-determinism", output, StringComparison.Ordinal); } + [Fact] + public async Task Fuzz_NoShrinkOption_IsAcceptedAndDocumented() + { + var (rc, output) = await RunCli("fuzz", "--adapter", "fuzzbug", "--seeds", "4", "--ticks", "426", "--no-shrink", "--out", _out); + var (_, help) = await RunCli("fuzz", "--help"); + + Assert.Equal(2, rc); + Assert.Contains("seed=4 tick=426", output, StringComparison.Ordinal); + Assert.Contains("--no-shrink", help, StringComparison.Ordinal); + } + [Fact] public async Task ListAdapters_IncludesFuzzBug() { diff --git a/tests/EpochSim.Determinism.Tests/FuzzShrinkTests.cs b/tests/EpochSim.Determinism.Tests/FuzzShrinkTests.cs new file mode 100644 index 0000000..7a568b4 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/FuzzShrinkTests.cs @@ -0,0 +1,285 @@ +using EpochSim; +using EpochSim.Fuzzing; +using EpochSim.Kernel.Messaging; +using EpochSim.Kernel.Time; +using EpochSim.Kernel.Validation; +using EpochSim.Samples.Fuzzing; + +public sealed class FuzzShrinkTests +{ + private const int CommandCount = 300; + private const long RunTicks = 60; + private static readonly int[] CulpritIndices = [17, 120, 254]; + + [Fact] + public void Shrink_ReducesThreeCulpritsOutOfThreeHundredCommands() + { + var failure = Assert.Single(FuzzMarks(f => f.Seeds(1, 1)).Failures); + + Assert.Equal(FuzzFailureKind.InvariantViolation, failure.Kind); + Assert.Equal(CommandCount, failure.OriginalCommandCount); + Assert.Equal(CulpritIndices, failure.MinimalCommandIndices); + Assert.True(failure.ShrinkAttempts > 0); + Assert.False(failure.ShrinkBudgetExhausted); + Assert.Null(failure.ShrinkSkipReason); + Assert.Equal( + ["MarkCommand", "MarkCommand", "MarkCommand"], + failure.MinimalCommands.Select(command => command.Type)); + Assert.Equal(CulpritIndices, failure.MinimalCommands.Select(command => command.Index)); + Assert.Equal(CulpritIndices.Select(index => (long)(index % 50)), failure.MinimalCommands.Select(command => command.Tick)); + } + + [Fact] + public void Shrink_ReportsMinimalScenarioTickAndRepro() + { + var failure = Assert.Single(FuzzMarks(f => f.Seeds(1, 1)).Failures); + + Assert.Equal(20, failure.Tick); + Assert.Equal(".Seeds(1, 1).Ticks(60).OnlyCommands([17, 120, 254])", failure.ReproCode); + Assert.Equal(RunTicks, failure.ReproTicks); + Assert.Contains(failure.StateDiff, change => change.Path == "$.Marks[2]" && change.After == "120"); + } + + [Fact] + public void Shrink_ResultDoesNotDependOnParallelism() + { + var sequential = FuzzMarks(f => f.Seeds(1, 12).Parallelism(1)); + var parallel = FuzzMarks(f => f.Seeds(1, 12).Parallelism(8)); + + Assert.Equal(12, sequential.Failures.Count); + Assert.Equal(Project(sequential), Project(parallel)); + } + + [Fact] + public void OnlyCommands_WithMinimalIndices_ReproducesSameKind() + { + var shrunk = Assert.Single(FuzzMarks(f => f.Seeds(1, 1)).Failures); + + var reproduced = Assert.Single(FuzzMarks(f => f + .Seeds(1, 1) + .Ticks(RunTicks) + .OnlyCommands(shrunk.MinimalCommandIndices!)).Failures); + + Assert.Equal(shrunk.Kind, reproduced.Kind); + Assert.Equal(shrunk.Tick, reproduced.Tick); + Assert.Equal(shrunk.Summary, reproduced.Summary); + } + + [Fact] + public void OnlyCommands_WithoutCulprit_Passes() + { + var report = FuzzMarks(f => f.Seeds(1, 1).OnlyCommands([17, 120])); + + Assert.True(report.Passed); + } + + [Fact] + public void OnlyCommands_IndexOutsidePlan_Throws() + { + var error = Assert.Throws(() => FuzzMarks(f => f.Seeds(1, 1).OnlyCommands([CommandCount]))); + + Assert.Contains("OnlyCommands", error.Message, StringComparison.Ordinal); + Assert.Contains(CommandCount.ToString(), error.Message, StringComparison.Ordinal); + } + + [Fact] + public void OnlyCommands_NegativeIndex_Throws() + { + Assert.Throws(() => FuzzMarks(f => f.OnlyCommands([-1]))); + } + + [Fact] + public void Shrink_WhenBudgetIsExhausted_ReturnsValidFailingScenario() + { + var report = FuzzMarks(f => f.Seeds(1, 1).ShrinkBudget(maxAttempts: 12, timeLimit: TimeSpan.FromMinutes(5))); + + var failure = Assert.Single(report.Failures); + Assert.True(failure.ShrinkBudgetExhausted); + Assert.True(failure.ShrinkAttempts <= 12); + Assert.InRange(failure.MinimalCommandIndices!.Count, CulpritIndices.Length, CommandCount - 1); + Assert.Subset(failure.MinimalCommandIndices.ToHashSet(), CulpritIndices.ToHashSet()); + Assert.Contains("budget", failure.ToText(), StringComparison.OrdinalIgnoreCase); + + var reproduced = FuzzMarks(f => f.Seeds(1, 1).OnlyCommands(failure.MinimalCommandIndices)); + Assert.Equal(failure.Kind, Assert.Single(reproduced.Failures).Kind); + } + + [Fact] + public void Shrink_WhenTimeLimitIsZero_ReturnsOriginalScenario() + { + var report = FuzzMarks(f => f.Seeds(1, 1).ShrinkBudget(maxAttempts: 1000, timeLimit: TimeSpan.Zero)); + + var failure = Assert.Single(report.Failures); + Assert.True(failure.ShrinkBudgetExhausted); + Assert.Equal(0, failure.ShrinkAttempts); + Assert.Equal(CommandCount, failure.MinimalCommandIndices!.Count); + } + + [Fact] + public void Shrink_WithoutCommands_IsNotRunAndFieldsAreEmpty() + { + var report = Epoch.Fuzz(f => f + .State(() => new JobQueueState()) + .Engine(e => e.AddSystem(new JobQueueSystem())) + .Invariants(() => [new QueueNonNegativeInvariant()]) + .Seeds(4, 4) + .Ticks(500)); + + var failure = Assert.Single(report.Failures); + Assert.Equal(0, failure.OriginalCommandCount); + Assert.Null(failure.MinimalCommandIndices); + Assert.Empty(failure.MinimalCommands); + Assert.Equal(0, failure.ShrinkAttempts); + Assert.Null(failure.ShrinkSkipReason); + Assert.DoesNotContain("Commands:", failure.ToText(), StringComparison.Ordinal); + Assert.Equal(".Seeds(4, 4).Ticks(426)", failure.ReproCode); + } + + [Fact] + public void Shrink_Disabled_KeepsFullCommandPlan() + { + var failure = Assert.Single(FuzzMarks(f => f.Seeds(1, 1).Shrink(false)).Failures); + + Assert.Null(failure.MinimalCommandIndices); + Assert.Equal(0, failure.ShrinkAttempts); + Assert.Equal(".Seeds(1, 1).Ticks(60)", failure.ReproCode); + } + + [Fact] + public void Shrink_NonDeterministicFailure_IsNotShrunkAndExplainsWhy() + { + var report = Epoch.Fuzz(f => f + .State(() => new MarkState()) + .Engine(e => + { + e.OnCommand((state, command, _) => state.Marks.Add(command.Id)); + e.AddSystem("Clock", tick: ctx => ctx.State.Stamp = DateTime.UtcNow.Ticks); + }) + .Commands(PlanMarks) + .Seeds(1, 1) + .Ticks(RunTicks) + .CheckDeterminism()); + + var failure = Assert.Single(report.Failures); + Assert.Equal(FuzzFailureKind.NonDeterminism, failure.Kind); + Assert.Null(failure.MinimalCommandIndices); + Assert.Equal(0, failure.ShrinkAttempts); + Assert.NotNull(failure.ShrinkSkipReason); + Assert.Contains(failure.ShrinkSkipReason, failure.ToText(), StringComparison.Ordinal); + } + + [Fact] + public void Shrink_ExceptionFailure_MatchesOnExceptionType() + { + var report = Epoch.Fuzz(f => f + .State(() => new MarkState()) + .Engine(e => + { + e.OnCommand((state, command, _) => + { + if (command.Id is 40 or 41) + throw new InvalidOperationException($"bad {command.Id}"); + + state.Marks.Add(command.Id); + }); + }) + .Commands(PlanMarks) + .Seeds(1, 1) + .Ticks(RunTicks)); + + var failure = Assert.Single(report.Failures); + Assert.Equal(FuzzFailureKind.Exception, failure.Kind); + Assert.Single(failure.MinimalCommandIndices!); + Assert.Contains(failure.MinimalCommandIndices![0], new[] { 40, 41 }); + } + + [Fact] + public void ToText_ShowsShrinkSummaryCommandsAndDiff() + { + var failure = Assert.Single(FuzzMarks(f => f.Seeds(1, 1)).Failures); + + var text = failure.ToText(); + + Assert.Contains($"Commands: {CommandCount} -> 3 (shrunk in {failure.ShrinkAttempts} attempts)", text, StringComparison.Ordinal); + Assert.Contains("#17 tick 17: MarkCommand", text, StringComparison.Ordinal); + Assert.Contains("#254 tick 4: MarkCommand", text, StringComparison.Ordinal); + Assert.True(text.IndexOf("Commands:", StringComparison.Ordinal) < text.IndexOf("StateDiff:", StringComparison.Ordinal)); + Assert.EndsWith(".OnlyCommands([17, 120, 254])", text, StringComparison.Ordinal); + } + + [Fact] + public void Shrink_IsEnabledByDefaultOnlyWithCommands() + { + var withCommands = FuzzMarks(f => f.Seeds(1, 1)); + var shrinkTrueWithoutCommands = Epoch.Fuzz(f => f + .State(() => new JobQueueState()) + .Engine(e => e.AddSystem(new JobQueueSystem())) + .Invariants(() => [new QueueNonNegativeInvariant()]) + .Seeds(4, 4) + .Ticks(500) + .Shrink()); + + Assert.NotNull(Assert.Single(withCommands.Failures).MinimalCommandIndices); + Assert.Null(Assert.Single(shrinkTrueWithoutCommands.Failures).MinimalCommandIndices); + } + + [Fact] + public void Shrink_AccountSample_ReducesTheLedgerToAHandfulOfCommands() + { + var report = Epoch.Fuzz(f => f + .State(() => new AccountState()) + .Engine(AccountLedger.Register) + .Invariants(() => [new BalanceNonNegativeInvariant()]) + .Commands(AccountLedger.PlanCommands) + .Seeds(1, 20) + .Ticks(100)); + + var failure = report.Failures[0]; + Assert.Equal(AccountLedger.CommandsPerSeed, failure.OriginalCommandCount); + Assert.InRange(failure.MinimalCommandIndices!.Count, 1, 5); + Assert.Contains("BalanceNonNegative", failure.Summary, StringComparison.Ordinal); + } + + private static void PlanMarks(FuzzCommandPlan plan) + { + for (var id = 0; id < CommandCount; id++) + plan.Enqueue(id % 50, new MarkCommand(id)); + } + + private static FuzzReport FuzzMarks(Action> configure) + => Epoch.Fuzz(f => + { + f.State(() => new MarkState()) + .Engine(e => e.OnCommand((state, command, _) => state.Marks.Add(command.Id))) + .Invariants(() => [new CulpritInvariant()]) + .Commands(PlanMarks) + .Ticks(RunTicks); + + configure(f); + }); + + private static IEnumerable Project(FuzzReport report) + => report.Failures.Select(failure => + $"{failure.Seed}|{failure.Kind}|{failure.Tick}|{failure.Summary}|{failure.ReproCode}|{failure.ShrinkAttempts}|" + + string.Join(",", failure.MinimalCommandIndices ?? [])); + + public sealed class MarkState + { + public List Marks { get; set; } = []; + public long Stamp { get; set; } + } + + public sealed record MarkCommand(int Id) : ICommand; + + private sealed class CulpritInvariant : IInvariant + { + public string Name => "NoCulpritTrio"; + + public bool Check(SimTime time, MarkState state, out string message) + { + var culpritsPresent = CulpritIndices.All(state.Marks.Contains); + message = culpritsPresent ? "all three culprits delivered" : string.Empty; + return !culpritsPresent; + } + } +} From 11719e4e194c7cb6b2e6dfe431a0b9bec3cb449d Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 12:38:27 +0300 Subject: [PATCH 02/10] feat(fuzz): persist failures and generate regression tests Adds FuzzFailureStore (versioned, atomic, cross-process safe), Name and FailureStore on the builder, new/known/fixed classification in the report, SimAssert.Regression and StoredFailuresStayFixed, epochsim failures list|prune|export-test and epochsim fuzz --store. --- Directory.Packages.props | 10 +- src/EpochSim.Cli/App/CliApp.cs | 7 +- src/EpochSim.Cli/Commands/ConfigureMethod.cs | 22 ++ src/EpochSim.Cli/Commands/FailuresCommand.cs | 121 ++++++ src/EpochSim.Cli/Commands/FailuresOptions.cs | 45 +++ src/EpochSim.Cli/Commands/FuzzCommand.cs | 9 +- src/EpochSim.Cli/Commands/FuzzOptions.cs | 6 +- .../Commands/RegressionTestFramework.cs | 19 + .../Commands/RegressionTestGenerator.cs | 88 +++++ src/EpochSim.Testing/SimAssert.cs | 54 +++ src/EpochSim/Fuzzing/FailureSignature.cs | 15 + src/EpochSim/Fuzzing/FailureStoreMerge.cs | 62 +++ src/EpochSim/Fuzzing/FuzzBuilder.cs | 29 +- src/EpochSim/Fuzzing/FuzzFailure.cs | 5 +- src/EpochSim/Fuzzing/FuzzFailureStore.cs | 147 +++++++ src/EpochSim/Fuzzing/FuzzReport.cs | 53 ++- src/EpochSim/Fuzzing/FuzzRunner.cs | 29 +- src/EpochSim/Fuzzing/FuzzSeedRunner.cs | 7 +- src/EpochSim/Fuzzing/FuzzSettings.cs | 5 +- src/EpochSim/Fuzzing/FuzzStoredFailure.cs | 21 + src/EpochSim/Fuzzing/TypeDisplayName.cs | 20 + .../EpochSim.Determinism.Tests.csproj | 3 + .../FailuresCliTests.cs | 309 +++++++++++++++ .../FuzzCliTests.cs | 17 + .../FuzzFailureStoreTests.cs | 370 ++++++++++++++++++ .../RegressionFixtures.cs | 51 +++ .../SimAssertRegressionTests.cs | 152 +++++++ 27 files changed, 1652 insertions(+), 24 deletions(-) create mode 100644 src/EpochSim.Cli/Commands/ConfigureMethod.cs create mode 100644 src/EpochSim.Cli/Commands/FailuresCommand.cs create mode 100644 src/EpochSim.Cli/Commands/FailuresOptions.cs create mode 100644 src/EpochSim.Cli/Commands/RegressionTestFramework.cs create mode 100644 src/EpochSim.Cli/Commands/RegressionTestGenerator.cs create mode 100644 src/EpochSim/Fuzzing/FailureSignature.cs create mode 100644 src/EpochSim/Fuzzing/FailureStoreMerge.cs create mode 100644 src/EpochSim/Fuzzing/FuzzFailureStore.cs create mode 100644 src/EpochSim/Fuzzing/FuzzStoredFailure.cs create mode 100644 src/EpochSim/Fuzzing/TypeDisplayName.cs create mode 100644 tests/EpochSim.Determinism.Tests/FailuresCliTests.cs create mode 100644 tests/EpochSim.Determinism.Tests/FuzzFailureStoreTests.cs create mode 100644 tests/EpochSim.Determinism.Tests/RegressionFixtures.cs create mode 100644 tests/EpochSim.Determinism.Tests/SimAssertRegressionTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 455f893..90ad92e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,13 +17,15 @@ - - + + + + - + - + diff --git a/src/EpochSim.Cli/App/CliApp.cs b/src/EpochSim.Cli/App/CliApp.cs index 0dea776..c7114f9 100644 --- a/src/EpochSim.Cli/App/CliApp.cs +++ b/src/EpochSim.Cli/App/CliApp.cs @@ -29,6 +29,7 @@ public CliApp() ["bisect"] = new BisectCommand(), ["repro"] = new ReproCommand(), ["fuzz"] = new FuzzCommand(), + ["failures"] = new FailuresCommand(), ["list-adapters"] = new ListAdaptersCommand() }; } @@ -39,7 +40,8 @@ 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)) + if (string.Equals(commandName, "fuzz", StringComparison.OrdinalIgnoreCase) + || string.Equals(commandName, "failures", StringComparison.OrdinalIgnoreCase)) { commandArgs = args.Skip(1).ToArray(); } @@ -106,7 +108,8 @@ 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] [--no-shrink]"); + Console.WriteLine(" fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parallel N] [--out dir] [--no-shrink] [--store path]"); + Console.WriteLine(" failures list|prune|export-test [--store path] (see failures --help)"); Console.WriteLine(" list-adapters"); Console.WriteLine(); Console.WriteLine("Pass --help to any command for detailed usage."); diff --git a/src/EpochSim.Cli/Commands/ConfigureMethod.cs b/src/EpochSim.Cli/Commands/ConfigureMethod.cs new file mode 100644 index 0000000..3a04907 --- /dev/null +++ b/src/EpochSim.Cli/Commands/ConfigureMethod.cs @@ -0,0 +1,22 @@ +using System.Text.RegularExpressions; + +namespace EpochSim.Cli.Commands; + +internal sealed partial record ConfigureMethod(string Namespace, string TypeName, string MethodName) +{ + public string FullName + => $"global::{(Namespace.Length > 0 ? Namespace + "." : string.Empty)}{TypeName}.{MethodName}"; + + public static ConfigureMethod Parse(string? value) + { + var parts = (value ?? string.Empty).Split('.'); + + if (parts.Length < 2 || !parts.All(part => Identifier().IsMatch(part))) + throw new ArgumentException("Option --configure requires a static method as Namespace.Type.Method."); + + return new ConfigureMethod(string.Join('.', parts[..^2]), parts[^2], parts[^1]); + } + + [GeneratedRegex(@"^[A-Za-z_]\w*$")] + private static partial Regex Identifier(); +} diff --git a/src/EpochSim.Cli/Commands/FailuresCommand.cs b/src/EpochSim.Cli/Commands/FailuresCommand.cs new file mode 100644 index 0000000..1e1b4f2 --- /dev/null +++ b/src/EpochSim.Cli/Commands/FailuresCommand.cs @@ -0,0 +1,121 @@ +using EpochSim.Cli.App; +using EpochSim.Cli.Parsing; +using EpochSim.Fuzzing; + +namespace EpochSim.Cli.Commands; + +public sealed class FailuresCommand : ICliCommand +{ + public string Help => + """ + failures list [--store path] + failures prune [--store path] + failures export-test --framework xunit|nunit|mstest --configure Namespace.Type.Method --out dir + [--name suite] [--state-type Namespace.Type] [--store path] + + Work with the failures that Epoch.Fuzz recorded in the failure store (default: epochsim-failures.json). + + list Print every stored failure. + prune Delete the failures already marked as fixed. + export-test Generate one regression test per stored failure. The tests call the static + method given by --configure, which must be 'static void Method(FuzzBuilder)' + and configure the same simulation as your Epoch.Fuzz call. + + --store path Failure store file (default: epochsim-failures.json) + --name suite Suite to export when the store holds several (see FuzzBuilder.Name) + --state-type type State type of the suite, when the store does not record it + """; + + public int Execute(CommandContext ctx, string[] args) + { + if (args.Length == 0 || CliParsing.IsOption(args[0])) + throw new ArgumentException("Specify a subcommand: list, prune or export-test. Run 'failures --help' for usage."); + + var options = FailuresOptions.Parse(args[1..]); + var store = new FuzzFailureStore(options.StorePath); + + return args[0].ToLowerInvariant() switch + { + "list" => List(store), + "prune" => Prune(store), + "export-test" => ExportTest(store, options), + _ => throw new ArgumentException($"Unknown subcommand '{args[0]}'. Run 'failures --help' for usage.") + }; + } + + private static int List(FuzzFailureStore store) + { + var failures = store.Load(); + + if (failures.Count == 0) + { + Console.WriteLine($"No stored failures in '{store.Path}'."); + return 0; + } + + foreach (var failure in failures) + { + var otherSeeds = failure.OtherSeeds.Count > 0 ? $" (other seeds: {string.Join(", ", failure.OtherSeeds)})" : string.Empty; + Console.WriteLine( + $"{failure.Name}: seed={failure.Seed} {failure.Kind} {failure.Identity} tick={failure.Tick} " + + $"{(failure.Fixed ? "fixed" : "open")}, first seen {failure.FirstSeen:yyyy-MM-dd}{otherSeeds}"); + } + + return 0; + } + + private static int Prune(FuzzFailureStore store) + { + var pruned = 0; + + store.Update(failures => + { + var remaining = failures.Where(failure => !failure.Fixed).ToArray(); + pruned = failures.Count - remaining.Length; + return remaining; + }); + + Console.WriteLine($"Pruned {pruned} fixed failure{(pruned == 1 ? string.Empty : "s")} from '{store.Path}'."); + return 0; + } + + private static int ExportTest(FuzzFailureStore store, FailuresOptions options) + { + var framework = RegressionTestFramework.Parse(options.Framework); + var configure = ConfigureMethod.Parse(options.Configure); + var outputDirectory = options.OutputDirectory + ?? throw new ArgumentException("Option --out requires a directory."); + + var failures = SelectSuite(store, options.SuiteName); + var stateType = options.StateType ?? failures[0].StateType; + + if (string.IsNullOrWhiteSpace(stateType)) + throw new ArgumentException("The store does not record the state type of this suite. Pass --state-type Namespace.Type."); + + Directory.CreateDirectory(outputDirectory); + var path = Path.Combine(outputDirectory, RegressionTestGenerator.ClassName(configure) + ".cs"); + File.WriteAllText(path, RegressionTestGenerator.Generate(framework, configure, stateType, failures)); + + Console.WriteLine($"Created: {path}"); + return 0; + } + + private static IReadOnlyList SelectSuite(FuzzFailureStore store, string? suiteName) + { + var all = store.Load(); + + if (all.Count == 0) + throw new ArgumentException($"No stored failures in '{store.Path}'."); + + var suites = all.Select(failure => failure.Name).Distinct().Order(StringComparer.Ordinal).ToArray(); + + if (suiteName is null && suites.Length > 1) + throw new ArgumentException($"The store holds several suites ({string.Join(", ", suites)}). Pass --name."); + + var selected = all.Where(failure => failure.Name == (suiteName ?? suites[0])).ToArray(); + + return selected.Length > 0 + ? selected + : throw new ArgumentException($"No stored failures for suite '{suiteName}'. Known suites: {string.Join(", ", suites)}."); + } +} diff --git a/src/EpochSim.Cli/Commands/FailuresOptions.cs b/src/EpochSim.Cli/Commands/FailuresOptions.cs new file mode 100644 index 0000000..36e82d3 --- /dev/null +++ b/src/EpochSim.Cli/Commands/FailuresOptions.cs @@ -0,0 +1,45 @@ +using EpochSim.Cli.Parsing; +using EpochSim.Fuzzing; + +namespace EpochSim.Cli.Commands; + +internal sealed record FailuresOptions( + string StorePath, + string? Framework, + string? Configure, + string? OutputDirectory, + string? SuiteName, + string? StateType) +{ + public static FailuresOptions Parse(string[] args) + { + var options = new FailuresOptions(FuzzFailureStore.DefaultPath, null, null, null, null, null); + + for (var i = 0; i < args.Length; i++) + { + var option = args[i].ToLowerInvariant(); + + options = option switch + { + "--store" => options with { StorePath = ReadValue(args, ref i, option) }, + "--framework" => options with { Framework = ReadValue(args, ref i, option) }, + "--configure" => options with { Configure = ReadValue(args, ref i, option) }, + "--out" => options with { OutputDirectory = ReadValue(args, ref i, option) }, + "--name" => options with { SuiteName = ReadValue(args, ref i, option) }, + "--state-type" => options with { StateType = ReadValue(args, ref i, option) }, + _ => throw new ArgumentException($"Unknown argument '{args[i]}'. Run 'failures --help' for usage.") + }; + } + + return options; + } + + 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]; + } +} diff --git a/src/EpochSim.Cli/Commands/FuzzCommand.cs b/src/EpochSim.Cli/Commands/FuzzCommand.cs index 9e4b51a..c144b01 100644 --- a/src/EpochSim.Cli/Commands/FuzzCommand.cs +++ b/src/EpochSim.Cli/Commands/FuzzCommand.cs @@ -10,7 +10,7 @@ public sealed class FuzzCommand : ICliCommand public string Help => """ - fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parallel N] [--out dir] [--no-shrink] + fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parallel N] [--out dir] [--no-shrink] [--store path] 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. @@ -22,6 +22,7 @@ fuzz [--adapter name] [--seeds A..B] [--ticks N] [--check-determinism] [--parall --parallel N Concurrent runs (default: processor count) --out dir Artifacts directory for failed seeds (default: artifacts) --no-shrink Keep the full command plan of a failed seed instead of minimizing it + --store path Record failures in a failure store and replay its seeds first (see failures --help) """; public int Execute(CommandContext ctx, string[] args) @@ -48,10 +49,16 @@ private static int Run(IDomainAdapter adapter, FuzzOptions optio if (options.Parallelism is { } degree) fuzz.Parallelism(degree); + + if (options.StorePath is { } storePath) + fuzz.Name(adapter.Name).FailureStore(storePath); }); Console.WriteLine($"SeedsRun={report.SeedsRun} Failures={report.Failures.Count} ElapsedMs={(long)report.Duration.TotalMilliseconds}"); + foreach (var seed in report.FixedSeeds) + Console.WriteLine($"Previously failing seed {seed} now passes."); + foreach (var failure in report.Failures) { var cliFailure = failure with diff --git a/src/EpochSim.Cli/Commands/FuzzOptions.cs b/src/EpochSim.Cli/Commands/FuzzOptions.cs index 19e6d00..fd6d923 100644 --- a/src/EpochSim.Cli/Commands/FuzzOptions.cs +++ b/src/EpochSim.Cli/Commands/FuzzOptions.cs @@ -10,7 +10,8 @@ internal sealed record FuzzOptions( bool CheckDeterminism, int? Parallelism, string OutputDirectory, - bool Shrink) + bool Shrink, + string? StorePath) { private const ulong DefaultFromSeed = 1; private const ulong DefaultToSeed = 1000; @@ -19,7 +20,7 @@ internal sealed record FuzzOptions( public static FuzzOptions Parse(string[] args) { - var options = new FuzzOptions(null, DefaultFromSeed, DefaultToSeed, DefaultTicks, false, null, DefaultOutputDirectory, true); + var options = new FuzzOptions(null, DefaultFromSeed, DefaultToSeed, DefaultTicks, false, null, DefaultOutputDirectory, true, null); for (var i = 0; i < args.Length; i++) { @@ -34,6 +35,7 @@ public static FuzzOptions Parse(string[] args) "--parallel" => options with { Parallelism = ParseParallelism(ReadValue(args, ref i, option)) }, "--out" => options with { OutputDirectory = ReadValue(args, ref i, option) }, "--no-shrink" => options with { Shrink = false }, + "--store" => options with { StorePath = ReadValue(args, ref i, option) }, _ => throw new ArgumentException($"Unknown argument '{args[i]}'. Run 'fuzz --help' for usage.") }; } diff --git a/src/EpochSim.Cli/Commands/RegressionTestFramework.cs b/src/EpochSim.Cli/Commands/RegressionTestFramework.cs new file mode 100644 index 0000000..01b4d13 --- /dev/null +++ b/src/EpochSim.Cli/Commands/RegressionTestFramework.cs @@ -0,0 +1,19 @@ +namespace EpochSim.Cli.Commands; + +internal sealed record RegressionTestFramework( + string Name, + string NamespaceUsing, + string? ClassAttribute, + string MethodAttribute) +{ + public static IReadOnlyList All { get; } = + [ + new("xunit", "Xunit", null, "Fact"), + new("nunit", "NUnit.Framework", "TestFixture", "Test"), + new("mstest", "Microsoft.VisualStudio.TestTools.UnitTesting", "TestClass", "TestMethod") + ]; + + public static RegressionTestFramework Parse(string? name) + => All.FirstOrDefault(framework => string.Equals(framework.Name, name, StringComparison.OrdinalIgnoreCase)) + ?? throw new ArgumentException($"Option --framework requires one of: {string.Join(", ", All.Select(framework => framework.Name))}."); +} diff --git a/src/EpochSim.Cli/Commands/RegressionTestGenerator.cs b/src/EpochSim.Cli/Commands/RegressionTestGenerator.cs new file mode 100644 index 0000000..a0a5e92 --- /dev/null +++ b/src/EpochSim.Cli/Commands/RegressionTestGenerator.cs @@ -0,0 +1,88 @@ +using System.Text; +using System.Text.RegularExpressions; +using EpochSim.Fuzzing; + +namespace EpochSim.Cli.Commands; + +internal static partial class RegressionTestGenerator +{ + private const string Indent = " "; + + public static string ClassName(ConfigureMethod configure) + => $"{configure.TypeName}RegressionTests"; + + public static string Generate( + RegressionTestFramework framework, + ConfigureMethod configure, + string stateType, + IReadOnlyList failures) + { + var text = new StringBuilder(); + + foreach (var line in new[] { "EpochSim.Testing", framework.NamespaceUsing }.Order(StringComparer.Ordinal)) + text.Append("using ").Append(line).AppendLine(";"); + + text.AppendLine(); + + if (configure.Namespace.Length > 0) + text.Append("namespace ").Append(configure.Namespace).AppendLine(";").AppendLine(); + + if (framework.ClassAttribute is { } classAttribute) + text.Append('[').Append(classAttribute).AppendLine("]"); + + text.Append("public sealed class ").AppendLine(ClassName(configure)); + text.AppendLine("{"); + + var usedNames = new HashSet(StringComparer.Ordinal); + var methods = failures.Select(failure => Method(framework, configure, stateType, failure, UniqueName(failure, usedNames))); + text.AppendJoin(Environment.NewLine + Environment.NewLine, methods); + + text.AppendLine().AppendLine("}"); + return text.ToString().ReplaceLineEndings("\n"); + } + + private static string Method( + RegressionTestFramework framework, + ConfigureMethod configure, + string stateType, + FuzzStoredFailure failure, + string methodName) + { + var text = new StringBuilder(); + text.Append(Indent).Append('[').Append(framework.MethodAttribute).AppendLine("]"); + text.Append(Indent).Append("public void ").Append(methodName).AppendLine("()"); + text.Append(Indent).AppendLine("{"); + text.Append(Indent).Append(Indent).Append(Call(configure, stateType, failure)).AppendLine(); + text.Append(Indent).Append('}'); + return text.ToString(); + } + + private static string Call(ConfigureMethod configure, string stateType, FuzzStoredFailure failure) + { + var target = failure.Kind == FuzzFailureKind.NonDeterminism + ? $"fuzz => {{ {configure.FullName}(fuzz); fuzz.CheckDeterminism(); }}" + : configure.FullName; + + var arguments = $"{target}, {failure.Seed}, {failure.ReproTicks}"; + + if (failure.CommandIndices is { } indices) + arguments += $", [{string.Join(", ", indices)}]"; + + return $"SimAssert.Regression({arguments});"; + } + + private static string UniqueName(FuzzStoredFailure failure, HashSet usedNames) + { + var identity = IdentifierCharacters().Replace(failure.Identity.Split('.')[^1], "_"); + var baseName = $"Seed{failure.Seed}_{(identity.Length > 0 ? identity : failure.Kind.ToString())}_AtTick{failure.Tick}"; + + var name = baseName; + for (var suffix = 2; !usedNames.Add(name); suffix++) + name = $"{baseName}_{suffix}"; + + return name; + } + + [GeneratedRegex(@"\W+")] + private static partial Regex IdentifierCharacters(); +} diff --git a/src/EpochSim.Testing/SimAssert.cs b/src/EpochSim.Testing/SimAssert.cs index 2569acd..a20f81e 100644 --- a/src/EpochSim.Testing/SimAssert.cs +++ b/src/EpochSim.Testing/SimAssert.cs @@ -30,6 +30,35 @@ public static void NoFailures(FuzzReport report) throw new SimulationAssertionException(report.ToText()); } + public static void Regression( + Action> configure, + ulong seed, + long ticks, + IReadOnlyList? commandIndices = null) + { + ArgumentNullException.ThrowIfNull(configure); + + NoFailures(Replay(configure, seed, ticks, commandIndices)); + } + + public static void StoredFailuresStayFixed(Action> configure, string storePath) + { + ArgumentNullException.ThrowIfNull(configure); + ArgumentException.ThrowIfNullOrWhiteSpace(storePath); + + var probe = new FuzzBuilder(); + configure(probe); + var suiteName = probe.Build().Name; + + var failures = new FuzzFailureStore(storePath).Load() + .Where(entry => entry.Name == suiteName) + .SelectMany(entry => ReplayEntry(configure, entry)) + .ToArray(); + + if (failures.Length > 0) + throw new SimulationAssertionException(string.Join(Environment.NewLine + Environment.NewLine, failures.Select(failure => failure.ToText()))); + } + public static void MatchesGolden(Action> configure, string goldenPath, ulong seed) { ArgumentNullException.ThrowIfNull(configure); @@ -43,4 +72,29 @@ public static void MatchesGolden(Action> configure, var actual = GoldenFile.Capture(FuzzRunner.Trace(settings, seed), seed, settings.EndTick); GoldenFile.Verify(goldenPath, actual); } + + private static IEnumerable ReplayEntry(Action> configure, FuzzStoredFailure entry) + { + var primary = Replay(configure, entry.Seed, entry.ReproTicks, entry.CommandIndices); + var others = entry.OtherSeeds.Select(seed => Replay(configure, seed, ticks: null, commandIndices: null)); + + return others.Prepend(primary).SelectMany(report => report.Failures); + } + + private static FuzzReport Replay( + Action> configure, + ulong seed, + long? ticks, + IReadOnlyList? commandIndices) + => Epoch.Fuzz(builder => + { + configure(builder); + builder.Seeds(seed, seed).Shrink(false).WithoutFailureStore(); + + if (ticks is { } endTick) + builder.Ticks(endTick); + + if (commandIndices is not null) + builder.OnlyCommands(commandIndices); + }); } diff --git a/src/EpochSim/Fuzzing/FailureSignature.cs b/src/EpochSim/Fuzzing/FailureSignature.cs new file mode 100644 index 0000000..1a3e5a3 --- /dev/null +++ b/src/EpochSim/Fuzzing/FailureSignature.cs @@ -0,0 +1,15 @@ +using System.Security.Cryptography; +using System.Text; + +namespace EpochSim.Fuzzing; + +internal static class FailureSignature +{ + private const int HexLength = 16; + + public static string Of(FuzzFailureIdentity identity) + { + var hash = SHA256.HashData(Encoding.UTF8.GetBytes($"{identity.Kind}|{identity.Name}")); + return Convert.ToHexStringLower(hash)[..HexLength]; + } +} diff --git a/src/EpochSim/Fuzzing/FailureStoreMerge.cs b/src/EpochSim/Fuzzing/FailureStoreMerge.cs new file mode 100644 index 0000000..45ae261 --- /dev/null +++ b/src/EpochSim/Fuzzing/FailureStoreMerge.cs @@ -0,0 +1,62 @@ +namespace EpochSim.Fuzzing; + +internal sealed class FailureStoreMerge(FuzzSettings settings, TimeProvider timeProvider) +{ + public IReadOnlyList Apply( + IReadOnlyList current, + IReadOnlyList failures, + IReadOnlySet passedStoredSeeds, + List newlyFixed) + { + var entries = current.ToList(); + + foreach (var group in failures.GroupBy(failure => failure.Signature).OrderBy(group => group.Key, StringComparer.Ordinal)) + Record(entries, group.OrderBy(failure => failure.Seed).ToArray()); + + for (var i = 0; i < entries.Count; i++) + { + var entry = entries[i]; + if (entry.Name == settings.Name && !entry.Fixed && entry.AllSeeds.All(passedStoredSeeds.Contains)) + { + entries[i] = entry with { Fixed = true }; + newlyFixed.Add(entry.Seed); + } + } + + return entries; + } + + private void Record(List entries, IReadOnlyList group) + { + var primary = group[0]; + var index = entries.FindIndex(entry => entry.Name == settings.Name && entry.Signature == primary.Signature); + + if (index < 0) + { + entries.Add(new FuzzStoredFailure( + settings.Name, + settings.StateType, + primary.Seed, + primary.Kind, + primary.Identity, + primary.Tick, + primary.ReproTicks, + primary.Signature, + primary.MinimalCommandIndices ?? settings.OnlyCommands, + group.Skip(1).Select(failure => failure.Seed).ToArray(), + timeProvider.GetUtcNow(), + Fixed: false)); + return; + } + + var existing = entries[index]; + var otherSeeds = existing.OtherSeeds + .Concat(group.Select(failure => failure.Seed)) + .Where(seed => seed != existing.Seed) + .Distinct() + .Order() + .ToArray(); + + entries[index] = existing with { OtherSeeds = otherSeeds, Fixed = false }; + } +} diff --git a/src/EpochSim/Fuzzing/FuzzBuilder.cs b/src/EpochSim/Fuzzing/FuzzBuilder.cs index 2573a3b..e4ee6d0 100644 --- a/src/EpochSim/Fuzzing/FuzzBuilder.cs +++ b/src/EpochSim/Fuzzing/FuzzBuilder.cs @@ -23,6 +23,8 @@ public sealed class FuzzBuilder private bool? _shrink; private IReadOnlyList? _onlyCommands; private FuzzShrinkBudget _shrinkBudget = FuzzShrinkBudget.Default; + private string? _name; + private string? _storePath; internal FuzzBuilder() { @@ -133,6 +135,28 @@ public FuzzBuilder OnlyCommands(IReadOnlyList indices) return this; } + public FuzzBuilder Name(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + _name = name; + return this; + } + + public FuzzBuilder FailureStore(string? path = null) + { + if (path is not null) + ArgumentException.ThrowIfNullOrWhiteSpace(path); + + _storePath = path ?? FuzzFailureStore.DefaultPath; + return this; + } + + internal FuzzBuilder WithoutFailureStore() + { + _storePath = null; + return this; + } + internal FuzzBuilder ShrinkBudget(int maxAttempts, TimeSpan timeLimit) { ArgumentOutOfRangeException.ThrowIfNegative(maxAttempts); @@ -158,7 +182,10 @@ internal FuzzSettings Build() _progress, _shrink ?? _commands is not null, _onlyCommands, - _shrinkBudget); + _shrinkBudget, + _name ?? typeof(TState).FullName ?? typeof(TState).Name, + TypeDisplayName.Of(typeof(TState)), + _storePath is null ? null : new FuzzFailureStore(_storePath)); private static InvalidOperationException MissingParameter(string name) => new($"Epoch.Fuzz requires {name}(...) to be configured."); diff --git a/src/EpochSim/Fuzzing/FuzzFailure.cs b/src/EpochSim/Fuzzing/FuzzFailure.cs index 04accd6..300b469 100644 --- a/src/EpochSim/Fuzzing/FuzzFailure.cs +++ b/src/EpochSim/Fuzzing/FuzzFailure.cs @@ -19,11 +19,14 @@ public sealed record FuzzFailure( public bool ShrinkBudgetExhausted { get; init; } public string? ShrinkSkipReason { get; init; } public long ReproTicks { get; init; } + public string Identity { get; init; } = string.Empty; + public string Signature { get; init; } = string.Empty; + public bool IsKnown { get; init; } public string ToText() { var text = new StringBuilder(); - text.Append('[').Append(Kind).Append("] seed=").Append(Seed).Append(" tick=").Append(Tick).AppendLine(); + text.Append('[').Append(Kind).Append("] seed=").Append(Seed).Append(" tick=").Append(Tick).Append(IsKnown ? " (known)" : string.Empty).AppendLine(); text.Append(" ").AppendLine(Summary); AppendShrink(text); diff --git a/src/EpochSim/Fuzzing/FuzzFailureStore.cs b/src/EpochSim/Fuzzing/FuzzFailureStore.cs new file mode 100644 index 0000000..33bfe7d --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzFailureStore.cs @@ -0,0 +1,147 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace EpochSim.Fuzzing; + +public sealed class FuzzFailureStore +{ + public const string DefaultPath = "epochsim-failures.json"; + + private const int SchemaVersion = 1; + private static readonly TimeSpan LockTimeout = TimeSpan.FromSeconds(30); + + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Converters = { new JsonStringEnumConverter() } + }; + + public FuzzFailureStore(string path) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + Path = System.IO.Path.GetFullPath(path); + } + + public string Path { get; } + + public IReadOnlyList Load() + => ReadFile(out _); + + public void Update(Func, IReadOnlyList> change) + { + ArgumentNullException.ThrowIfNull(change); + + using var gate = AcquireGate(); + var current = ReadFile(out var currentText); + var updated = change(current); + var updatedText = Serialize(updated); + + if (string.Equals(currentText, updatedText, StringComparison.Ordinal) || (currentText is null && updated.Count == 0)) + return; + + WriteAtomically(updatedText); + } + + private IReadOnlyList ReadFile(out string? text) + { + if (!File.Exists(Path)) + { + text = null; + return []; + } + + text = File.ReadAllText(Path); + + try + { + var file = JsonSerializer.Deserialize(text, JsonOptions) + ?? throw new JsonException("The file is empty."); + + if (file.Version > SchemaVersion) + throw new InvalidDataException( + $"'{Path}' uses failure store schema version {file.Version}, but this EpochSim reads up to version {SchemaVersion}. Upgrade EpochSim."); + + return (file.Failures ?? []).Select(Normalize).ToArray(); + } + catch (JsonException error) + { + throw new InvalidDataException($"'{Path}' is not a valid failure store: {error.Message}", error); + } + } + + private static FuzzStoredFailure Normalize(FuzzStoredFailure entry) + => entry with + { + Name = entry.Name ?? string.Empty, + StateType = entry.StateType ?? string.Empty, + Identity = entry.Identity ?? string.Empty, + Signature = entry.Signature ?? string.Empty, + OtherSeeds = entry.OtherSeeds ?? [] + }; + + private static string Serialize(IReadOnlyList entries) + { + var ordered = entries + .OrderBy(entry => entry.Name, StringComparer.Ordinal) + .ThenBy(entry => entry.Signature, StringComparer.Ordinal) + .ThenBy(entry => entry.Seed) + .ToArray(); + + return JsonSerializer.Serialize(new StoreFile(SchemaVersion, ordered), JsonOptions) + "\n"; + } + + private void WriteAtomically(string text) + { + var directory = System.IO.Path.GetDirectoryName(Path)!; + Directory.CreateDirectory(directory); + + var temporary = $"{Path}.{Guid.NewGuid():N}.tmp"; + + try + { + File.WriteAllText(temporary, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + File.Move(temporary, Path, overwrite: true); + } + finally + { + File.Delete(temporary); + } + } + + private Gate AcquireGate() + { + var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path))); + var mutex = new Mutex(false, $"Global\\EpochSim.FailureStore.{hash}"); + + try + { + if (!mutex.WaitOne(LockTimeout)) + throw new TimeoutException($"Timed out waiting for another process to finish writing '{Path}'."); + } + catch (AbandonedMutexException) + { + } + catch + { + mutex.Dispose(); + throw; + } + + return new Gate(mutex); + } + + private sealed record StoreFile(int Version, IReadOnlyList? Failures); + + private readonly struct Gate(Mutex mutex) : IDisposable + { + public void Dispose() + { + mutex.ReleaseMutex(); + mutex.Dispose(); + } + } +} diff --git a/src/EpochSim/Fuzzing/FuzzReport.cs b/src/EpochSim/Fuzzing/FuzzReport.cs index b63dee0..fc895d4 100644 --- a/src/EpochSim/Fuzzing/FuzzReport.cs +++ b/src/EpochSim/Fuzzing/FuzzReport.cs @@ -4,33 +4,56 @@ namespace EpochSim.Fuzzing; public sealed class FuzzReport { - internal FuzzReport(int seedsRun, TimeSpan duration, IReadOnlyList failures) + private readonly bool _usesFailureStore; + + internal FuzzReport( + int seedsRun, + TimeSpan duration, + IReadOnlyList failures, + IReadOnlyList fixedSeeds, + bool usesFailureStore) { SeedsRun = seedsRun; Duration = duration; Failures = failures; + FixedSeeds = fixedSeeds; + _usesFailureStore = usesFailureStore; } public bool Passed => Failures.Count == 0; public int SeedsRun { get; } public TimeSpan Duration { get; } public IReadOnlyList Failures { get; } + public IReadOnlyList FixedSeeds { get; } + public IReadOnlyList NewFailures => Failures.Where(failure => !failure.IsKnown).ToArray(); + public IReadOnlyList KnownFailures => Failures.Where(failure => failure.IsKnown).ToArray(); public string ToText() { var elapsedMs = (long)Duration.TotalMilliseconds; + var text = new StringBuilder(); + if (Passed) - return $"Fuzz passed: SeedsRun={SeedsRun}, ElapsedMs={elapsedMs}"; + text.Append($"Fuzz passed: SeedsRun={SeedsRun}, ElapsedMs={elapsedMs}"); + else + text.Append("Fuzz failed: Failures=").Append(Failures.Count).Append(FailureBreakdown()) + .Append(", SeedsRun=").Append(SeedsRun) + .Append(", ElapsedMs=").Append(elapsedMs); - var text = new StringBuilder(); - text.Append("Fuzz failed: Failures=").Append(Failures.Count) - .Append(", SeedsRun=").Append(SeedsRun) - .Append(", ElapsedMs=").Append(elapsedMs).AppendLine(); + foreach (var seed in FixedSeeds) + text.AppendLine().Append("Previously failing seed ").Append(seed).Append(" now passes."); + + if (_usesFailureStore) + { + AppendSection(text, "New failures:", NewFailures); + AppendSection(text, "Known failures:", KnownFailures); + return text.ToString(); + } foreach (var failure in Failures) - text.AppendLine().AppendLine(failure.ToText()); + text.AppendLine().AppendLine().Append(failure.ToText()); - return text.ToString().TrimEnd(); + return text.ToString(); } public void ThrowIfFailed() @@ -38,4 +61,18 @@ public void ThrowIfFailed() if (!Passed) throw new FuzzFailedException(this); } + + private string FailureBreakdown() + => _usesFailureStore ? $" (new={NewFailures.Count}, known={KnownFailures.Count})" : string.Empty; + + private static void AppendSection(StringBuilder text, string title, IReadOnlyList failures) + { + if (failures.Count == 0) + return; + + text.AppendLine().AppendLine().Append(title); + + foreach (var failure in failures) + text.AppendLine().AppendLine().Append(failure.ToText()); + } } diff --git a/src/EpochSim/Fuzzing/FuzzRunner.cs b/src/EpochSim/Fuzzing/FuzzRunner.cs index 806e57c..c5ef08f 100644 --- a/src/EpochSim/Fuzzing/FuzzRunner.cs +++ b/src/EpochSim/Fuzzing/FuzzRunner.cs @@ -20,7 +20,10 @@ public static FuzzReport Run(FuzzSettings settings) var failureCount = 0; var options = new ParallelOptions { MaxDegreeOfParallelism = settings.Parallelism }; - var seeds = Partitioner.Create(settings.Seeds, EnumerablePartitionerOptions.NoBuffering); + var stored = settings.Store?.Load().Where(entry => entry.Name == settings.Name).ToArray() ?? []; + var storedSeeds = stored.SelectMany(entry => entry.AllSeeds).ToHashSet(); + var passedStoredSeeds = new ConcurrentDictionary(); + var seeds = Partitioner.Create(StoredSeedsFirst(storedSeeds, settings.Seeds), EnumerablePartitionerOptions.NoBuffering); try { @@ -29,6 +32,9 @@ public static FuzzReport Run(FuzzSettings settings) var failure = runner.Check(seed); var completed = Interlocked.Increment(ref seedsRun); + if (failure is null && storedSeeds.Contains(seed)) + passedStoredSeeds[seed] = 0; + if (failure is not null) { failures.Add(failure); @@ -46,7 +52,19 @@ public static FuzzReport Run(FuzzSettings settings) ExceptionDispatchInfo.Capture(aggregate.InnerExceptions[0]).Throw(); } - var ordered = failures.OrderBy(failure => failure.Seed).ToList(); + var knownSignatures = stored.Where(entry => !entry.Fixed).Select(entry => entry.Signature).ToHashSet(); + var ordered = failures + .Select(failure => failure with { IsKnown = knownSignatures.Contains(failure.Signature) }) + .OrderBy(failure => failure.Seed) + .ToList(); + var newlyFixed = new List(); + + if (settings.Store is { } store) + { + var merge = new FailureStoreMerge(settings, TimeProvider.System); + var passed = passedStoredSeeds.Keys.ToHashSet(); + store.Update(current => merge.Apply(current, ordered, passed, newlyFixed)); + } if (settings.ArtifactsRoot is not null) { @@ -55,6 +73,11 @@ public static FuzzReport Run(FuzzSettings settings) } stopwatch.Stop(); - return new FuzzReport(seedsRun, stopwatch.Elapsed, ordered); + return new FuzzReport(seedsRun, stopwatch.Elapsed, ordered, newlyFixed, settings.Store is not null); } + + private static IEnumerable StoredSeedsFirst(IReadOnlySet storedSeeds, IEnumerable seeds) + => storedSeeds.Count == 0 + ? seeds + : storedSeeds.Order().Concat(seeds.Where(seed => !storedSeeds.Contains(seed))); } diff --git a/src/EpochSim/Fuzzing/FuzzSeedRunner.cs b/src/EpochSim/Fuzzing/FuzzSeedRunner.cs index 954dacf..7ed7a3f 100644 --- a/src/EpochSim/Fuzzing/FuzzSeedRunner.cs +++ b/src/EpochSim/Fuzzing/FuzzSeedRunner.cs @@ -138,6 +138,7 @@ private IReadOnlyList> CreateInvariants() return null; var (kind, summary) = Describe(error); + var identity = FuzzFailureIdentity.Of(error); var tick = error is InvariantViolationException violation ? violation.Time.Tick : result.LastTick; return new FuzzFailure( @@ -149,7 +150,9 @@ private IReadOnlyList> CreateInvariants() ArtifactsDir: null, ReproCode(seed, tick, kind, selection)) { - ReproTicks = ReproTicks(tick) + ReproTicks = ReproTicks(tick), + Identity = identity.Name, + Signature = FailureSignature.Of(identity) }; } @@ -210,6 +213,8 @@ private FuzzFailure BuildNonDeterminismFailure(ulong seed, long tick) ReproCode(seed, tick, FuzzFailureKind.NonDeterminism, settings.OnlyCommands)) { ReproTicks = ReproTicks(tick), + Identity = FuzzFailureIdentity.NonDeterminism.Name, + Signature = FailureSignature.Of(FuzzFailureIdentity.NonDeterminism), ShrinkSkipReason = ShrinkSkipReasonFor(seed) }; } diff --git a/src/EpochSim/Fuzzing/FuzzSettings.cs b/src/EpochSim/Fuzzing/FuzzSettings.cs index ad28aec..2937d01 100644 --- a/src/EpochSim/Fuzzing/FuzzSettings.cs +++ b/src/EpochSim/Fuzzing/FuzzSettings.cs @@ -21,4 +21,7 @@ internal sealed record FuzzSettings( IProgress? Progress, bool Shrink, IReadOnlyList? OnlyCommands, - FuzzShrinkBudget ShrinkBudget); + FuzzShrinkBudget ShrinkBudget, + string Name, + string StateType, + FuzzFailureStore? Store); diff --git a/src/EpochSim/Fuzzing/FuzzStoredFailure.cs b/src/EpochSim/Fuzzing/FuzzStoredFailure.cs new file mode 100644 index 0000000..166ce17 --- /dev/null +++ b/src/EpochSim/Fuzzing/FuzzStoredFailure.cs @@ -0,0 +1,21 @@ +using System.Text.Json.Serialization; + +namespace EpochSim.Fuzzing; + +public sealed record FuzzStoredFailure( + string Name, + string StateType, + ulong Seed, + FuzzFailureKind Kind, + string Identity, + long Tick, + long ReproTicks, + string Signature, + IReadOnlyList? CommandIndices, + IReadOnlyList OtherSeeds, + DateTimeOffset FirstSeen, + bool Fixed) +{ + [JsonIgnore] + public IEnumerable AllSeeds => OtherSeeds.Prepend(Seed); +} diff --git a/src/EpochSim/Fuzzing/TypeDisplayName.cs b/src/EpochSim/Fuzzing/TypeDisplayName.cs new file mode 100644 index 0000000..6f7f3d7 --- /dev/null +++ b/src/EpochSim/Fuzzing/TypeDisplayName.cs @@ -0,0 +1,20 @@ +namespace EpochSim.Fuzzing; + +internal static class TypeDisplayName +{ + public static string Of(Type type) + { + if (type.IsArray) + return Of(type.GetElementType()!) + "[]"; + + var prefix = type.IsNested + ? Of(type.DeclaringType!) + "." + : string.IsNullOrEmpty(type.Namespace) ? string.Empty : type.Namespace + "."; + + if (!type.IsGenericType) + return prefix + type.Name; + + var arguments = type.GetGenericArguments().Select(Of); + return $"{prefix}{type.Name[..type.Name.IndexOf('`')]}<{string.Join(", ", arguments)}>"; + } +} diff --git a/tests/EpochSim.Determinism.Tests/EpochSim.Determinism.Tests.csproj b/tests/EpochSim.Determinism.Tests/EpochSim.Determinism.Tests.csproj index cd41514..9a3f3a7 100644 --- a/tests/EpochSim.Determinism.Tests/EpochSim.Determinism.Tests.csproj +++ b/tests/EpochSim.Determinism.Tests/EpochSim.Determinism.Tests.csproj @@ -9,6 +9,9 @@ + + + diff --git a/tests/EpochSim.Determinism.Tests/FailuresCliTests.cs b/tests/EpochSim.Determinism.Tests/FailuresCliTests.cs new file mode 100644 index 0000000..6f23460 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/FailuresCliTests.cs @@ -0,0 +1,309 @@ +using System.Reflection; +using System.Text.RegularExpressions; +using EpochSim; +using EpochSim.Cli.App; +using EpochSim.Fuzzing; +using EpochSim.Samples.Fuzzing; +using EpochSim.Testing; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using RegressionFixtures; + +[Collection("Console")] +public sealed partial class FailuresCliTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), $"epochsim-failures-cli-{Guid.NewGuid():N}"); + private readonly string _storePath; + private readonly string _outDirectory; + + public FailuresCliTests() + { + Directory.CreateDirectory(_directory); + _storePath = Path.Combine(_directory, "epochsim-failures.json"); + _outDirectory = Path.Combine(_directory, "tests"); + } + + public void Dispose() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } + + [Fact] + public async Task List_PrintsEveryStoredFailure() + { + StoreAccountFailures(); + + var (rc, output) = await RunCli("failures", "list", "--store", _storePath); + + Assert.Equal(0, rc); + Assert.Contains("accounts", output, StringComparison.Ordinal); + Assert.Contains("seed=1", output, StringComparison.Ordinal); + Assert.Contains("InvariantViolation", output, StringComparison.Ordinal); + Assert.Contains("BalanceNonNegative", output, StringComparison.Ordinal); + Assert.Contains("other seeds: 2, 3", output, StringComparison.Ordinal); + Assert.Contains("open", output, StringComparison.Ordinal); + } + + [Fact] + public async Task List_WithoutStoreFile_ReportsNothingStored() + { + var (rc, output) = await RunCli("failures", "list", "--store", _storePath); + + Assert.Equal(0, rc); + Assert.Contains("No stored failures", output, StringComparison.Ordinal); + } + + [Fact] + public async Task Prune_RemovesOnlyFixedEntries() + { + StoreAccountFailures(); + Epoch.Fuzz(fuzz => + { + NonDeterministicSuite.Configure(fuzz); + fuzz.FailureStore(_storePath); + }); + Epoch.Fuzz(fuzz => + { + FixedAccountSuite.Configure(fuzz); + fuzz.FailureStore(_storePath); + }); + Assert.Equal(2, new FuzzFailureStore(_storePath).Load().Count); + Assert.Single(new FuzzFailureStore(_storePath).Load(), entry => entry.Fixed); + + var (rc, output) = await RunCli("failures", "prune", "--store", _storePath); + + Assert.Equal(0, rc); + Assert.Contains("Pruned 1 fixed failure", output, StringComparison.Ordinal); + var remaining = Assert.Single(new FuzzFailureStore(_storePath).Load()); + Assert.Equal(NonDeterministicSuite.SuiteName, remaining.Name); + } + + [Theory] + [InlineData("xunit", "[Fact]", "using Xunit;")] + [InlineData("nunit", "[Test]", "using NUnit.Framework;")] + [InlineData("mstest", "[TestMethod]", "using Microsoft.VisualStudio.TestTools.UnitTesting;")] + public async Task ExportTest_GeneratesCompilableTestsThatFailUntilTheBugIsFixed(string framework, string attribute, string usingLine) + { + var entry = StoreAccountFailures(); + + var (rc, _) = await RunCli( + "failures", "export-test", + "--framework", framework, + "--configure", "RegressionFixtures.BuggyAccountSuite.Configure", + "--out", _outDirectory, + "--store", _storePath); + + Assert.Equal(0, rc); + var file = Assert.Single(Directory.GetFiles(_outDirectory)); + Assert.Equal("BuggyAccountSuiteRegressionTests.cs", Path.GetFileName(file)); + var source = File.ReadAllText(file); + Assert.Contains(usingLine, source, StringComparison.Ordinal); + Assert.Contains(attribute, source, StringComparison.Ordinal); + Assert.Contains($"Seed1_BalanceNonNegative_AtTick{entry.Tick}", source, StringComparison.Ordinal); + Assert.DoesNotContain("Seed2_", source, StringComparison.Ordinal); + Assert.DoesNotContain("//", source, StringComparison.Ordinal); + Assert.DoesNotContain("/*", source, StringComparison.Ordinal); + + var assembly = Compile(source); + var generated = assembly.GetTypes().Single(type => type.Name == "BuggyAccountSuiteRegressionTests"); + var tests = TestMethods(generated); + Assert.Single(tests); + Assert.All(tests, test => Assert.Throws(() => Invoke(generated, test))); + + var fixedSource = source.Replace("global::RegressionFixtures.BuggyAccountSuite.Configure", "global::RegressionFixtures.FixedAccountSuite.Configure", StringComparison.Ordinal); + var fixedGenerated = Compile(fixedSource).GetTypes().Single(type => type.Name == "BuggyAccountSuiteRegressionTests"); + Assert.All(TestMethods(fixedGenerated), test => Invoke(fixedGenerated, test)); + } + + [Fact] + public async Task ExportTest_PassesRecordedCommandIndicesAndTicks() + { + var entry = StoreAccountFailures(); + + await RunCli( + "failures", "export-test", + "--framework", "xunit", + "--configure", "RegressionFixtures.BuggyAccountSuite.Configure", + "--out", _outDirectory, + "--store", _storePath); + + var source = File.ReadAllText(Path.Combine(_outDirectory, "BuggyAccountSuiteRegressionTests.cs")); + var indices = string.Join(", ", entry.CommandIndices!); + Assert.Contains( + $"SimAssert.Regression(global::RegressionFixtures.BuggyAccountSuite.Configure, 1, {entry.ReproTicks}, [{indices}])", + source, + StringComparison.Ordinal); + Assert.Contains("namespace RegressionFixtures;", source, StringComparison.Ordinal); + } + + [Fact] + public async Task ExportTest_ForNonDeterminism_EnablesTheDeterminismCheck() + { + Epoch.Fuzz(fuzz => + { + NonDeterministicSuite.Configure(fuzz); + fuzz.FailureStore(_storePath); + }); + + var (rc, _) = await RunCli( + "failures", "export-test", + "--framework", "xunit", + "--configure", "RegressionFixtures.NonDeterministicSuite.Configure", + "--out", _outDirectory, + "--store", _storePath); + + Assert.Equal(0, rc); + var source = File.ReadAllText(Path.Combine(_outDirectory, "NonDeterministicSuiteRegressionTests.cs")); + var generated = Compile(source).GetTypes().Single(type => type.Name == "NonDeterministicSuiteRegressionTests"); + var tests = TestMethods(generated); + Assert.Contains(tests, test => test.Name.StartsWith("Seed1_NonDeterminism_AtTick", StringComparison.Ordinal)); + Assert.All(tests, test => Assert.Throws(() => Invoke(generated, test))); + } + + [Fact] + public async Task ExportTest_WithSeveralSuites_RequiresName() + { + StoreAccountFailures(); + Epoch.Fuzz(fuzz => + { + NonDeterministicSuite.Configure(fuzz); + fuzz.FailureStore(_storePath); + }); + string[] common = + [ + "failures", "export-test", "--framework", "xunit", + "--configure", "RegressionFixtures.BuggyAccountSuite.Configure", + "--out", _outDirectory, "--store", _storePath + ]; + + var (withoutName, _) = await RunCli(common); + var (withName, _) = await RunCli([.. common, "--name", "accounts"]); + + Assert.Equal(2, withoutName); + Assert.Equal(0, withName); + Assert.Contains("Seed1_BalanceNonNegative", File.ReadAllText(Directory.GetFiles(_outDirectory).Single()), StringComparison.Ordinal); + } + + [Theory] + [InlineData("--framework", "junit")] + [InlineData("--configure", "NoMethod")] + public async Task ExportTest_InvalidArguments_Return2WithoutWriting(string option, string value) + { + StoreAccountFailures(); + var arguments = new Dictionary + { + ["--framework"] = "xunit", + ["--configure"] = "RegressionFixtures.BuggyAccountSuite.Configure", + ["--out"] = _outDirectory, + ["--store"] = _storePath, + [option] = value + }; + + var (rc, _) = await RunCli(["failures", "export-test", .. arguments.SelectMany(pair => new[] { pair.Key, pair.Value })]); + + Assert.Equal(2, rc); + Assert.False(Directory.Exists(_outDirectory)); + } + + [Fact] + public async Task ExportTest_WithoutStoredFailures_Returns2() + { + var (rc, _) = await RunCli( + "failures", "export-test", "--framework", "xunit", + "--configure", "RegressionFixtures.BuggyAccountSuite.Configure", + "--out", _outDirectory, "--store", _storePath); + + Assert.Equal(2, rc); + } + + [Fact] + public async Task UnknownSubcommand_Returns2() + { + var (rc, _) = await RunCli("failures", "bogus"); + + Assert.Equal(2, rc); + } + + [Fact] + public async Task Help_ListsSubcommands() + { + var (rc, output) = await RunCli("failures", "--help"); + + Assert.Equal(0, rc); + Assert.Contains("list", output, StringComparison.Ordinal); + Assert.Contains("prune", output, StringComparison.Ordinal); + Assert.Contains("export-test", output, StringComparison.Ordinal); + } + + private FuzzStoredFailure StoreAccountFailures() + { + Epoch.Fuzz(fuzz => + { + BuggyAccountSuite.Configure(fuzz); + fuzz.FailureStore(_storePath); + }); + + return new FuzzFailureStore(_storePath).Load().Single(entry => entry.Name == BuggyAccountSuite.SuiteName); + } + + private static Assembly Compile(string source) + { + var references = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator) + .Select(path => MetadataReference.CreateFromFile(path)); + + var compilation = CSharpCompilation.Create( + $"Generated{Guid.NewGuid():N}", + [CSharpSyntaxTree.ParseText(source)], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + + using var stream = new MemoryStream(); + var result = compilation.Emit(stream); + var problems = result.Diagnostics.Where(diagnostic => diagnostic.Severity >= DiagnosticSeverity.Warning).ToArray(); + Assert.True(result.Success && problems.Length == 0, string.Join(Environment.NewLine, problems.Select(problem => problem.ToString()))); + + return Assembly.Load(stream.ToArray()); + } + + private static List TestMethods(Type generated) + => generated.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(method => SeedMethodName().IsMatch(method.Name)) + .ToList(); + + private static void Invoke(Type generated, MethodInfo method) + { + try + { + method.Invoke(Activator.CreateInstance(generated), null); + } + catch (TargetInvocationException error) when (error.InnerException is { } inner) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(inner).Throw(); + } + } + + [GeneratedRegex(@"^Seed\d+_\w+_AtTick\d+(_\d+)?$")] + private static partial Regex SeedMethodName(); + + 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/FuzzCliTests.cs b/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs index 0c48976..4aa58ca 100644 --- a/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs +++ b/tests/EpochSim.Determinism.Tests/FuzzCliTests.cs @@ -94,6 +94,23 @@ public async Task Fuzz_NoShrinkOption_IsAcceptedAndDocumented() Assert.Contains("--no-shrink", help, StringComparison.Ordinal); } + [Fact] + public async Task Fuzz_WithStore_RecordsFailuresAndMarksTheNextRunAsKnown() + { + var store = Path.Combine(_out, "epochsim-failures.json"); + + var (firstRc, first) = await RunCli("fuzz", "--adapter", "fuzzbug", "--seeds", "1..10", "--ticks", "500", "--store", store, "--out", _out); + var (secondRc, second) = await RunCli("fuzz", "--adapter", "fuzzbug", "--seeds", "1..10", "--ticks", "500", "--store", store, "--out", _out); + + Assert.Equal(2, firstRc); + Assert.Equal(2, secondRc); + Assert.DoesNotContain("(known)", first, StringComparison.Ordinal); + Assert.Contains("seed=4 tick=426 (known)", second, StringComparison.Ordinal); + var entry = Assert.Single(new EpochSim.Fuzzing.FuzzFailureStore(store).Load()); + Assert.Equal("fuzzbug", entry.Name); + Assert.Equal(4UL, entry.Seed); + } + [Fact] public async Task ListAdapters_IncludesFuzzBug() { diff --git a/tests/EpochSim.Determinism.Tests/FuzzFailureStoreTests.cs b/tests/EpochSim.Determinism.Tests/FuzzFailureStoreTests.cs new file mode 100644 index 0000000..fa43440 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/FuzzFailureStoreTests.cs @@ -0,0 +1,370 @@ +using System.Text.Json; +using EpochSim; +using EpochSim.Execution; +using EpochSim.Fuzzing; +using EpochSim.Kernel.Time; +using EpochSim.Kernel.Validation; +using EpochSim.Samples.Fuzzing; + +public sealed class FuzzFailureStoreTests : IDisposable +{ + private const string SuiteName = "accounts"; + private const long RunTicks = 100; + + private readonly string _directory = Path.Combine(Path.GetTempPath(), $"epochsim-store-{Guid.NewGuid():N}"); + private readonly string _path; + + public FuzzFailureStoreTests() + { + Directory.CreateDirectory(_directory); + _path = Path.Combine(_directory, "epochsim-failures.json"); + } + + public void Dispose() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } + + [Fact] + public void Store_KeepsOneEntryPerSignatureAndListsOtherSeeds() + { + var report = RunAccounts(buggy: true, seeds: (1, 5)); + + Assert.Equal(5, report.Failures.Count); + var entry = Assert.Single(new FuzzFailureStore(_path).Load()); + Assert.Equal(SuiteName, entry.Name); + Assert.Equal("EpochSim.Samples.Fuzzing.AccountState", entry.StateType); + Assert.Equal(1UL, entry.Seed); + Assert.Equal([2UL, 3UL, 4UL, 5UL], entry.OtherSeeds); + Assert.Equal(FuzzFailureKind.InvariantViolation, entry.Kind); + Assert.Equal("BalanceNonNegative", entry.Identity); + Assert.Equal(report.Failures[0].Tick, entry.Tick); + Assert.Equal(RunTicks, entry.ReproTicks); + Assert.Equal(report.Failures[0].MinimalCommandIndices, entry.CommandIndices); + Assert.Equal(report.Failures[0].Signature, entry.Signature); + Assert.False(entry.Fixed); + Assert.InRange(DateTimeOffset.UtcNow - entry.FirstSeen, TimeSpan.Zero, TimeSpan.FromMinutes(5)); + Assert.Equal(TimeSpan.Zero, entry.FirstSeen.Offset); + } + + [Fact] + public void Signature_IsStableAcrossSeedsAndDiffersAcrossBugs() + { + var invariantBug = RunAccounts(buggy: true, seeds: (1, 3)); + var exceptionBug = Epoch.Fuzz(f => f + .State(() => new AccountState()) + .Engine(e => e.AddSystem("Boom", tick: _ => throw new InvalidOperationException("boom"))) + .Seeds(1, 2) + .Ticks(3)); + + Assert.Single(invariantBug.Failures.Select(failure => failure.Signature).Distinct()); + Assert.Single(exceptionBug.Failures.Select(failure => failure.Signature).Distinct()); + Assert.NotEqual(invariantBug.Failures[0].Signature, exceptionBug.Failures[0].Signature); + Assert.Equal(16, invariantBug.Failures[0].Signature.Length); + } + + [Fact] + public void SecondRun_ReportsFailuresAsKnown() + { + RunAccounts(buggy: true, seeds: (1, 3)); + var firstSeen = Assert.Single(new FuzzFailureStore(_path).Load()).FirstSeen; + + var second = RunAccounts(buggy: true, seeds: (1, 4)); + + Assert.Empty(second.NewFailures); + Assert.Equal(4, second.KnownFailures.Count); + Assert.All(second.Failures, failure => Assert.True(failure.IsKnown)); + Assert.Contains("Known failures", second.ToText(), StringComparison.Ordinal); + Assert.DoesNotContain("New failures", second.ToText(), StringComparison.Ordinal); + + var entry = Assert.Single(new FuzzFailureStore(_path).Load()); + Assert.Equal(firstSeen, entry.FirstSeen); + Assert.Equal([2UL, 3UL, 4UL], entry.OtherSeeds); + } + + [Fact] + public void DifferentBug_IsNewNextToTheStoredOne() + { + RunAccounts(buggy: true, seeds: (1, 2), invariantName: "BalanceNonNegative"); + + var second = RunAccounts(buggy: true, seeds: (1, 2), invariantName: "BalanceNeverBelowZero"); + + Assert.Equal(2, second.NewFailures.Count); + Assert.Empty(second.KnownFailures); + Assert.Contains("New failures", second.ToText(), StringComparison.Ordinal); + Assert.Equal(2, new FuzzFailureStore(_path).Load().Count); + } + + [Fact] + public void StoredSeeds_RunFirstRegardlessOfConfiguredRange() + { + RunAccounts(buggy: true, seeds: (7, 7)); + var order = new List(); + + var report = RunAccounts(buggy: true, seeds: (1, 10), configure: f => f + .Parallelism(1) + .Shrink(false) + .Commands(plan => + { + order.Add(plan.Seed); + AccountLedger.PlanCommands(plan); + })); + + Assert.Equal(7UL, order.First()); + Assert.Equal(10, report.SeedsRun); + Assert.Equal(Enumerable.Range(1, 10).Select(seed => (ulong)seed).Order(), order.Distinct().Order()); + } + + [Fact] + public void StoredSeeds_RunEvenWhenRangeExcludesThem() + { + RunAccounts(buggy: true, seeds: (3, 3)); + + var report = RunAccounts(buggy: true, seeds: (100, 101)); + + Assert.Equal(3, report.SeedsRun); + Assert.Contains(report.Failures, failure => failure.Seed == 3); + } + + [Fact] + public void FixedBug_IsMarkedFixedAndReportedOnce() + { + RunAccounts(buggy: true, seeds: (1, 3)); + + var afterFix = RunAccounts(buggy: false, seeds: (50, 50)); + + Assert.True(afterFix.Passed); + Assert.Equal([1UL], afterFix.FixedSeeds); + Assert.Contains("Previously failing seed 1 now passes.", afterFix.ToText(), StringComparison.Ordinal); + Assert.True(Assert.Single(new FuzzFailureStore(_path).Load()).Fixed); + + var again = RunAccounts(buggy: false, seeds: (50, 50)); + + Assert.Empty(again.FixedSeeds); + Assert.DoesNotContain("Previously failing", again.ToText(), StringComparison.Ordinal); + Assert.Single(new FuzzFailureStore(_path).Load()); + } + + [Fact] + public void FixedBug_ThatReturns_IsReportedAsNewAndReopened() + { + RunAccounts(buggy: true, seeds: (1, 2)); + RunAccounts(buggy: false, seeds: (1, 2)); + + var regression = RunAccounts(buggy: true, seeds: (1, 2)); + + Assert.Equal(2, regression.NewFailures.Count); + Assert.False(Assert.Single(new FuzzFailureStore(_path).Load()).Fixed); + } + + [Fact] + public void Store_IsNotCreatedUnlessConfigured() + { + Epoch.Fuzz(f => f + .State(() => new AccountState()) + .Engine(e => AccountLedger.Register(e)) + .Invariants(() => [new BalanceNonNegativeInvariant()]) + .Commands(AccountLedger.PlanCommands) + .Seeds(1, 2) + .Ticks(RunTicks)); + + Assert.False(File.Exists(_path)); + Assert.Empty(Directory.GetFileSystemEntries(_directory)); + } + + [Fact] + public void Store_FailuresOfOtherSuitesAreLeftAlone() + { + RunAccounts(buggy: true, seeds: (1, 2)); + + Epoch.Fuzz(f => f + .Name("other-suite") + .State(() => new AccountState()) + .Engine(e => e.AddSystem("Boom", tick: _ => throw new InvalidOperationException("boom"))) + .Seeds(9, 9) + .Ticks(3) + .FailureStore(_path)); + + var entries = new FuzzFailureStore(_path).Load(); + Assert.Equal([SuiteName, "other-suite"], entries.Select(entry => entry.Name).Order()); + Assert.Equal(1UL, entries.Single(entry => entry.Name == SuiteName).Seed); + } + + [Fact] + public void Name_DefaultsToTheFullStateTypeName() + { + Epoch.Fuzz(f => f + .State(() => new AccountState()) + .Engine(e => e.AddSystem("Boom", tick: _ => throw new InvalidOperationException("boom"))) + .Seeds(1, 1) + .Ticks(3) + .FailureStore(_path)); + + Assert.Equal(typeof(AccountState).FullName, Assert.Single(new FuzzFailureStore(_path).Load()).Name); + } + + [Fact] + public void Store_WithoutCommandsKeepsNullCommandIndices() + { + Epoch.Fuzz(f => f + .State(() => new AccountState()) + .Engine(e => e.AddSystem("Boom", tick: _ => throw new InvalidOperationException("boom"))) + .Seeds(1, 1) + .Ticks(3) + .FailureStore(_path)); + + var entry = Assert.Single(new FuzzFailureStore(_path).Load()); + Assert.Null(entry.CommandIndices); + Assert.Equal(0, entry.Tick); + Assert.Equal(entry.Tick, entry.ReproTicks); + Assert.Equal("System.InvalidOperationException", entry.Identity); + } + + [Fact] + public async Task Store_ConcurrentUpdates_KeepTheFileValid() + { + var store = new FuzzFailureStore(_path); + + await Task.WhenAll(Enumerable.Range(0, 24).Select(index => Task.Run(() => + store.Update(entries => [.. entries, StoredFailure($"suite-{index:D2}", (ulong)index)])))); + + var entries = store.Load(); + Assert.Equal(24, entries.Count); + Assert.Equal(24, entries.Select(entry => entry.Name).Distinct().Count()); + using var document = JsonDocument.Parse(File.ReadAllText(_path)); + Assert.Equal(24, document.RootElement.GetProperty("failures").GetArrayLength()); + Assert.Equal([Path.GetFileName(_path)], Directory.GetFiles(_directory).Select(Path.GetFileName)); + } + + [Fact] + public async Task Store_ConcurrentFuzzRuns_KeepEveryRunsFailures() + { + await Task.WhenAll(Enumerable.Range(0, 6).Select(index => Task.Run(() => + Epoch.Fuzz(f => f + .Name($"parallel-{index}") + .State(() => new AccountState()) + .Engine(e => e.AddSystem("Boom", tick: _ => throw new InvalidOperationException("boom"))) + .Seeds(1, 3) + .Ticks(3) + .FailureStore(_path))))); + + var entries = new FuzzFailureStore(_path).Load(); + Assert.Equal(6, entries.Count); + Assert.All(entries, entry => Assert.Equal([2UL, 3UL], entry.OtherSeeds)); + } + + [Fact] + public void Store_WritesVersionedStableFile() + { + RunAccounts(buggy: true, seeds: (1, 2)); + var first = File.ReadAllText(_path); + + RunAccounts(buggy: true, seeds: (1, 2)); + + Assert.Equal(first, File.ReadAllText(_path)); + using var document = JsonDocument.Parse(first); + Assert.Equal(1, document.RootElement.GetProperty("version").GetInt32()); + var entry = document.RootElement.GetProperty("failures")[0]; + Assert.Equal(SuiteName, entry.GetProperty("name").GetString()); + Assert.Equal("InvariantViolation", entry.GetProperty("kind").GetString()); + Assert.Equal(1UL, entry.GetProperty("seed").GetUInt64()); + Assert.False(entry.GetProperty("fixed").GetBoolean()); + Assert.EndsWith("\n", first, StringComparison.Ordinal); + } + + [Fact] + public void Load_MissingFile_ReturnsNoEntries() + => Assert.Empty(new FuzzFailureStore(_path).Load()); + + [Fact] + public void Load_FileWithOnlyRequiredFields_FillsDefaults() + { + File.WriteAllText(_path, """ + { "version": 1, "failures": [ + { "name": "legacy", "seed": 5, "kind": "Exception", "tick": 3, "signature": "abc" } + ] } + """); + + var entry = Assert.Single(new FuzzFailureStore(_path).Load()); + Assert.Equal("legacy", entry.Name); + Assert.Equal(5UL, entry.Seed); + Assert.Equal(FuzzFailureKind.Exception, entry.Kind); + Assert.Empty(entry.OtherSeeds); + Assert.Null(entry.CommandIndices); + Assert.False(entry.Fixed); + } + + [Fact] + public void Load_FileFromNewerSchema_IsRejectedWithTheVersion() + { + File.WriteAllText(_path, """{ "version": 2, "failures": [] }"""); + + var error = Assert.Throws(() => new FuzzFailureStore(_path).Load()); + + Assert.Contains("version 2", error.Message, StringComparison.Ordinal); + Assert.Contains(_path, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Load_CorruptFile_IsRejectedAndNeverOverwritten() + { + File.WriteAllText(_path, "{ not json"); + + Assert.Throws(() => new FuzzFailureStore(_path).Load()); + Assert.Throws(() => RunAccounts(buggy: true, seeds: (1, 2))); + Assert.Equal("{ not json", File.ReadAllText(_path)); + } + + private FuzzReport RunAccounts( + bool buggy, + (ulong From, ulong To) seeds, + string invariantName = "BalanceNonNegative", + Action>? configure = null) + => Epoch.Fuzz(f => + { + f.Name(SuiteName) + .State(() => new AccountState()) + .Engine(engine => ConfigureAccounts(engine, buggy)) + .Invariants(() => [new NamedBalanceInvariant(invariantName)]) + .Commands(AccountLedger.PlanCommands) + .Seeds(seeds.From, seeds.To) + .Ticks(RunTicks) + .FailureStore(_path); + + configure?.Invoke(f); + }); + + private static void ConfigureAccounts(SimulationEngine engine, bool buggy) + { + engine.OnCommand((state, command, _) => state.Balance += command.Amount); + engine.OnCommand((state, command, _) => + state.Balance = buggy ? state.Balance - command.Amount : Math.Max(0, state.Balance - command.Amount)); + } + + private static FuzzStoredFailure StoredFailure(string name, ulong seed) + => new( + name, + "Some.State", + seed, + FuzzFailureKind.Exception, + "System.InvalidOperationException", + 3, + 3, + $"signature-{seed}", + null, + [], + DateTimeOffset.UnixEpoch, + false); + + private sealed class NamedBalanceInvariant(string name) : IInvariant + { + public string Name => name; + + public bool Check(SimTime time, AccountState state, out string message) + { + message = state.Balance >= 0 ? string.Empty : $"Balance={state.Balance}"; + return state.Balance >= 0; + } + } +} diff --git a/tests/EpochSim.Determinism.Tests/RegressionFixtures.cs b/tests/EpochSim.Determinism.Tests/RegressionFixtures.cs new file mode 100644 index 0000000..6c2398a --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/RegressionFixtures.cs @@ -0,0 +1,51 @@ +using EpochSim.Execution; +using EpochSim.Fuzzing; +using EpochSim.Samples.Fuzzing; + +namespace RegressionFixtures; + +public static class BuggyAccountSuite +{ + public const string SuiteName = "accounts"; + + public static void Configure(FuzzBuilder fuzz) + => AccountSuite.Apply(fuzz, buggy: true); +} + +public static class FixedAccountSuite +{ + public static void Configure(FuzzBuilder fuzz) + => AccountSuite.Apply(fuzz, buggy: false); +} + +public static class NonDeterministicSuite +{ + public const string SuiteName = "counter"; + + public static void Configure(FuzzBuilder fuzz) + => fuzz.Name(SuiteName) + .State(() => new StaticCounterState()) + .Engine(engine => engine.AddSystem(new StaticCounterSystem())) + .CheckDeterminism() + .Seeds(1, 2) + .Ticks(10); +} + +internal static class AccountSuite +{ + public static void Apply(FuzzBuilder fuzz, bool buggy) + => fuzz.Name(BuggyAccountSuite.SuiteName) + .State(() => new AccountState()) + .Engine(engine => Register(engine, buggy)) + .Invariants(() => [new BalanceNonNegativeInvariant()]) + .Commands(AccountLedger.PlanCommands) + .Seeds(1, 3) + .Ticks(100); + + private static void Register(SimulationEngine engine, bool buggy) + { + engine.OnCommand((state, command, _) => state.Balance += command.Amount); + engine.OnCommand((state, command, _) => + state.Balance = buggy ? state.Balance - command.Amount : Math.Max(0, state.Balance - command.Amount)); + } +} diff --git a/tests/EpochSim.Determinism.Tests/SimAssertRegressionTests.cs b/tests/EpochSim.Determinism.Tests/SimAssertRegressionTests.cs new file mode 100644 index 0000000..f349c52 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/SimAssertRegressionTests.cs @@ -0,0 +1,152 @@ +using EpochSim; +using EpochSim.Fuzzing; +using EpochSim.Testing; +using RegressionFixtures; + +public sealed class SimAssertRegressionTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), $"epochsim-regression-{Guid.NewGuid():N}"); + private readonly string _storePath; + + public SimAssertRegressionTests() + { + Directory.CreateDirectory(_directory); + _storePath = Path.Combine(_directory, "epochsim-failures.json"); + } + + public void Dispose() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } + + [Fact] + public void Regression_OnBuggyLogic_FailsWithTheStoredScenario() + { + var entry = StoreBuggyAccountFailure(); + + var error = Assert.Throws(() => + SimAssert.Regression( + BuggyAccountSuite.Configure, + entry.Seed, + entry.ReproTicks, + entry.CommandIndices)); + + Assert.Contains($"seed={entry.Seed}", error.Message, StringComparison.Ordinal); + Assert.Contains("BalanceNonNegative", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Regression_OnFixedLogic_Passes() + { + var entry = StoreBuggyAccountFailure(); + + SimAssert.Regression( + FixedAccountSuite.Configure, + entry.Seed, + entry.ReproTicks, + entry.CommandIndices); + } + + [Fact] + public void Regression_RunsExactlyTheGivenSeedAndIgnoresConfiguredStore() + { + var entry = StoreBuggyAccountFailure(); + var before = File.ReadAllText(_storePath); + + Assert.Throws(() => + SimAssert.Regression( + fuzz => + { + BuggyAccountSuite.Configure(fuzz); + fuzz.FailureStore(_storePath); + }, + entry.Seed, + entry.ReproTicks, + entry.CommandIndices)); + + Assert.Equal(before, File.ReadAllText(_storePath)); + } + + [Fact] + public void Regression_WithEmptyCommandSelection_DoesNotFail() + { + var entry = StoreBuggyAccountFailure(); + + SimAssert.Regression( + BuggyAccountSuite.Configure, + entry.Seed, + entry.ReproTicks, + []); + } + + [Fact] + public void StoredFailuresStayFixed_WhileBugIsPresent_Fails() + { + var entry = StoreBuggyAccountFailure(); + + var error = Assert.Throws(() => + SimAssert.StoredFailuresStayFixed(BuggyAccountSuite.Configure, _storePath)); + + Assert.Contains($"seed={entry.Seed}", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void StoredFailuresStayFixed_ReplaysEveryRecordedSeed() + { + var entry = StoreBuggyAccountFailure(); + Assert.NotEmpty(entry.OtherSeeds); + + var error = Assert.Throws(() => + SimAssert.StoredFailuresStayFixed(BuggyAccountSuite.Configure, _storePath)); + + foreach (var seed in entry.OtherSeeds) + Assert.Contains($"seed={seed}", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void StoredFailuresStayFixed_AfterFix_Passes() + { + StoreBuggyAccountFailure(); + + SimAssert.StoredFailuresStayFixed(FixedAccountSuite.Configure, _storePath); + } + + [Fact] + public void StoredFailuresStayFixed_WithoutStoreFile_Passes() + => SimAssert.StoredFailuresStayFixed(BuggyAccountSuite.Configure, _storePath); + + [Fact] + public void StoredFailuresStayFixed_IgnoresOtherSuites() + { + Epoch.Fuzz(fuzz => + { + NonDeterministicSuite.Configure(fuzz); + fuzz.FailureStore(_storePath); + }); + + SimAssert.StoredFailuresStayFixed(BuggyAccountSuite.Configure, _storePath); + } + + [Fact] + public void StoredFailuresStayFixed_DoesNotModifyTheStore() + { + StoreBuggyAccountFailure(); + var before = File.ReadAllText(_storePath); + + SimAssert.StoredFailuresStayFixed(FixedAccountSuite.Configure, _storePath); + + Assert.Equal(before, File.ReadAllText(_storePath)); + } + + private FuzzStoredFailure StoreBuggyAccountFailure() + { + Epoch.Fuzz(fuzz => + { + BuggyAccountSuite.Configure(fuzz); + fuzz.FailureStore(_storePath); + }); + + return Assert.Single(new FuzzFailureStore(_storePath).Load()); + } +} From 9d6a8647fa437d965e39b6d9205dbc4d4514c0e5 Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 12:54:42 +0300 Subject: [PATCH 03/10] feat(fuzz): fuzz existing code with Step, Invariant, Project and AsRandom Step and Invariant make Epoch.Fuzz usable without writing systems or invariant classes. StepContext exposes the deterministic Rng, the tick and a FakeTimeProvider that advances one second per tick. IRng.AsRandom adapts the deterministic stream to System.Random. Project replaces the state serializer for state that is not JSON-friendly. Adds the Inventory onboarding sample. --- Directory.Packages.props | 4 + src/EpochSim.Samples/Onboarding/Inventory.cs | 24 ++ src/EpochSim/EpochSim.csproj | 4 + src/EpochSim/Fuzzing/FuzzBuilder.cs | 69 +++- src/EpochSim/Fuzzing/PredicateInvariant.cs | 16 + .../Fuzzing/ProjectedStateSerializer.cs | 14 + src/EpochSim/Fuzzing/StepContext.cs | 20 ++ src/EpochSim/Fuzzing/StepSystem.cs | 18 + src/EpochSim/RngExtensions.cs | 15 + src/EpochSim/RngRandom.cs | 80 +++++ .../FuzzOnboardingTests.cs | 327 ++++++++++++++++++ .../RngRandomTests.cs | 116 +++++++ 12 files changed, 704 insertions(+), 3 deletions(-) create mode 100644 src/EpochSim.Samples/Onboarding/Inventory.cs create mode 100644 src/EpochSim/Fuzzing/PredicateInvariant.cs create mode 100644 src/EpochSim/Fuzzing/ProjectedStateSerializer.cs create mode 100644 src/EpochSim/Fuzzing/StepContext.cs create mode 100644 src/EpochSim/Fuzzing/StepSystem.cs create mode 100644 src/EpochSim/RngExtensions.cs create mode 100644 src/EpochSim/RngRandom.cs create mode 100644 tests/EpochSim.Determinism.Tests/FuzzOnboardingTests.cs create mode 100644 tests/EpochSim.Determinism.Tests/RngRandomTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 90ad92e..bf4d043 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,6 +7,10 @@ + + + + diff --git a/src/EpochSim.Samples/Onboarding/Inventory.cs b/src/EpochSim.Samples/Onboarding/Inventory.cs new file mode 100644 index 0000000..c52310d --- /dev/null +++ b/src/EpochSim.Samples/Onboarding/Inventory.cs @@ -0,0 +1,24 @@ +namespace EpochSim.Samples.Onboarding; + +public sealed class Inventory +{ + private const int RestockOdds = 3; + private const int RestockUnits = 4; + private const int BulkOrderOdds = 400; + private const int BulkOrderUnits = 5; + + public int Stock { get; private set; } = 5; + + public void Tick(Random random) + { + if (random.Next(0, RestockOdds) == 0) + Stock += RestockUnits; + + var demand = random.Next(0, 3); + if (Stock >= demand) + Stock -= demand; + + if (random.Next(0, BulkOrderOdds) == 0) + Stock -= BulkOrderUnits; + } +} diff --git a/src/EpochSim/EpochSim.csproj b/src/EpochSim/EpochSim.csproj index cb35710..2f99af2 100644 --- a/src/EpochSim/EpochSim.csproj +++ b/src/EpochSim/EpochSim.csproj @@ -7,6 +7,10 @@ + + + + net10.0 enable diff --git a/src/EpochSim/Fuzzing/FuzzBuilder.cs b/src/EpochSim/Fuzzing/FuzzBuilder.cs index e4ee6d0..ca6c4ea 100644 --- a/src/EpochSim/Fuzzing/FuzzBuilder.cs +++ b/src/EpochSim/Fuzzing/FuzzBuilder.cs @@ -25,6 +25,9 @@ public sealed class FuzzBuilder private FuzzShrinkBudget _shrinkBudget = FuzzShrinkBudget.Default; private string? _name; private string? _storePath; + private readonly List> _steps = []; + private readonly List<(string Name, Func Predicate)> _predicates = []; + private Func? _projection; internal FuzzBuilder() { @@ -42,6 +45,27 @@ public FuzzBuilder Engine(Action> configure) return this; } + public FuzzBuilder Step(Action step) + { + ArgumentNullException.ThrowIfNull(step); + _steps.Add(step); + return this; + } + + public FuzzBuilder Invariant(string name, Func predicate) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(predicate); + _predicates.Add((name, predicate)); + return this; + } + + public FuzzBuilder Project(Func projection) + { + _projection = projection ?? throw new ArgumentNullException(nameof(projection)); + return this; + } + public FuzzBuilder Ticks(long endTickInclusive) { ArgumentOutOfRangeException.ThrowIfNegative(endTickInclusive); @@ -168,11 +192,11 @@ internal FuzzBuilder ShrinkBudget(int maxAttempts, TimeSpan timeLimit) internal FuzzSettings Build() => new( _stateFactory ?? throw MissingParameter(nameof(State)), - _configureEngine ?? throw MissingParameter(nameof(Engine)), + ComposeEngineConfiguration(), _endTick ?? throw MissingParameter(nameof(Ticks)), _seeds ?? throw MissingParameter(nameof(Seeds)), - _serializer ?? new JsonStateSerializer(), - _invariants, + ResolveSerializer(), + ComposeInvariants(), _commands, _checkDeterminism, _parallelism, @@ -187,6 +211,45 @@ internal FuzzSettings Build() TypeDisplayName.Of(typeof(TState)), _storePath is null ? null : new FuzzFailureStore(_storePath)); + private Action> ComposeEngineConfiguration() + { + if (_configureEngine is null && _steps.Count == 0) + throw new InvalidOperationException("Epoch.Fuzz requires Engine(...) or Step(...) to be configured."); + + var steps = _steps.ToArray(); + var configureEngine = _configureEngine; + + return engine => + { + configureEngine?.Invoke(engine); + + if (steps.Length > 0) + engine.AddSystem("Step", new StepSystem(steps).Tick); + }; + } + + private IStateSerializer ResolveSerializer() + { + if (_projection is null) + return _serializer ?? new JsonStateSerializer(); + + return _serializer is null + ? new ProjectedStateSerializer(_projection) + : throw new InvalidOperationException("Project(...) and Serializer(...) cannot be combined: both decide how the state is serialized."); + } + + private Func>>? ComposeInvariants() + { + if (_predicates.Count == 0) + return _invariants; + + var factory = _invariants; + var predicates = _predicates.ToArray(); + + return () => (factory?.Invoke() ?? []) + .Concat(predicates.Select(entry => new PredicateInvariant(entry.Name, entry.Predicate))); + } + private static InvalidOperationException MissingParameter(string name) => new($"Epoch.Fuzz requires {name}(...) to be configured."); diff --git a/src/EpochSim/Fuzzing/PredicateInvariant.cs b/src/EpochSim/Fuzzing/PredicateInvariant.cs new file mode 100644 index 0000000..8b7bf09 --- /dev/null +++ b/src/EpochSim/Fuzzing/PredicateInvariant.cs @@ -0,0 +1,16 @@ +using EpochSim.Kernel.Time; +using EpochSim.Kernel.Validation; + +namespace EpochSim.Fuzzing; + +internal sealed class PredicateInvariant(string name, Func predicate) : IInvariant +{ + public string Name => name; + + public bool Check(SimTime time, TState state, out string message) + { + var holds = predicate(state); + message = holds ? string.Empty : "predicate returned false"; + return holds; + } +} diff --git a/src/EpochSim/Fuzzing/ProjectedStateSerializer.cs b/src/EpochSim/Fuzzing/ProjectedStateSerializer.cs new file mode 100644 index 0000000..8cd046d --- /dev/null +++ b/src/EpochSim/Fuzzing/ProjectedStateSerializer.cs @@ -0,0 +1,14 @@ +using EpochSim.Serialization.State; + +namespace EpochSim.Fuzzing; + +internal sealed class ProjectedStateSerializer(Func projection) : IStateSerializer +{ + private readonly JsonStateSerializer _json = new(); + + public string Serialize(TState state) + => _json.Serialize(projection(state)); + + public TState Deserialize(string json) + => throw new NotSupportedException("A projected state cannot be deserialized."); +} diff --git a/src/EpochSim/Fuzzing/StepContext.cs b/src/EpochSim/Fuzzing/StepContext.cs new file mode 100644 index 0000000..c38067c --- /dev/null +++ b/src/EpochSim/Fuzzing/StepContext.cs @@ -0,0 +1,20 @@ +using EpochSim.Kernel.Determinism; + +namespace EpochSim.Fuzzing; + +public readonly struct StepContext +{ + public static readonly DateTimeOffset ClockStart = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); + public static readonly TimeSpan TickDuration = TimeSpan.FromSeconds(1); + + internal StepContext(IRng rng, long tick, TimeProvider timeProvider) + { + Rng = rng; + Tick = tick; + TimeProvider = timeProvider; + } + + public IRng Rng { get; } + public long Tick { get; } + public TimeProvider TimeProvider { get; } +} diff --git a/src/EpochSim/Fuzzing/StepSystem.cs b/src/EpochSim/Fuzzing/StepSystem.cs new file mode 100644 index 0000000..17e1824 --- /dev/null +++ b/src/EpochSim/Fuzzing/StepSystem.cs @@ -0,0 +1,18 @@ +using EpochSim.Kernel.Systems; +using Microsoft.Extensions.Time.Testing; + +namespace EpochSim.Fuzzing; + +internal sealed class StepSystem(IReadOnlyList> steps) +{ + private readonly FakeTimeProvider _clock = new(StepContext.ClockStart); + + public void Tick(TickContext ctx) + { + _clock.SetUtcNow(StepContext.ClockStart + ctx.Time.Tick * StepContext.TickDuration); + var context = new StepContext(ctx.Rng, ctx.Time.Tick, _clock); + + foreach (var step in steps) + step(ctx.State, context); + } +} diff --git a/src/EpochSim/RngExtensions.cs b/src/EpochSim/RngExtensions.cs new file mode 100644 index 0000000..79b1586 --- /dev/null +++ b/src/EpochSim/RngExtensions.cs @@ -0,0 +1,15 @@ +using System.Runtime.CompilerServices; +using EpochSim.Kernel.Determinism; + +namespace EpochSim; + +public static class RngExtensions +{ + private static readonly ConditionalWeakTable Adapters = []; + + public static Random AsRandom(this IRng rng) + { + ArgumentNullException.ThrowIfNull(rng); + return Adapters.GetValue(rng, static stream => new RngRandom(stream)); + } +} diff --git a/src/EpochSim/RngRandom.cs b/src/EpochSim/RngRandom.cs new file mode 100644 index 0000000..453ce5a --- /dev/null +++ b/src/EpochSim/RngRandom.cs @@ -0,0 +1,80 @@ +using EpochSim.Kernel.Determinism; + +namespace EpochSim; + +internal sealed class RngRandom(IRng rng) : Random +{ + public override int Next() + => (int)NextBelow(int.MaxValue); + + public override int Next(int maxValue) + { + ArgumentOutOfRangeException.ThrowIfNegative(maxValue); + return (int)NextBelow((ulong)maxValue); + } + + public override int Next(int minValue, int maxValue) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan(minValue, maxValue, nameof(minValue)); + return (int)NextInRange(minValue, maxValue); + } + + public override long NextInt64() + => (long)NextBelow(long.MaxValue); + + public override long NextInt64(long maxValue) + { + ArgumentOutOfRangeException.ThrowIfNegative(maxValue); + return (long)NextBelow((ulong)maxValue); + } + + public override long NextInt64(long minValue, long maxValue) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan(minValue, maxValue, nameof(minValue)); + return NextInRange(minValue, maxValue); + } + + public override double NextDouble() + => rng.NextDouble01(); + + public override float NextSingle() + => (rng.NextU64() >> 40) * (1.0f / (1 << 24)); + + public override void NextBytes(byte[] buffer) + { + ArgumentNullException.ThrowIfNull(buffer); + NextBytes(buffer.AsSpan()); + } + + public override void NextBytes(Span buffer) + { + Span word = stackalloc byte[sizeof(ulong)]; + + for (var offset = 0; offset < buffer.Length; offset += word.Length) + { + BitConverter.TryWriteBytes(word, rng.NextU64()); + word[..Math.Min(word.Length, buffer.Length - offset)].CopyTo(buffer[offset..]); + } + } + + protected override double Sample() + => rng.NextDouble01(); + + private long NextInRange(long minValue, long maxValue) + => unchecked(minValue + (long)NextBelow(unchecked((ulong)maxValue - (ulong)minValue))); + + private ulong NextBelow(ulong range) + { + if (range == 0) + return 0; + + var limit = ulong.MaxValue - (ulong.MaxValue % range); + + while (true) + { + var value = rng.NextU64(); + if (value < limit) + return value % range; + } + } +} diff --git a/tests/EpochSim.Determinism.Tests/FuzzOnboardingTests.cs b/tests/EpochSim.Determinism.Tests/FuzzOnboardingTests.cs new file mode 100644 index 0000000..e5964a7 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/FuzzOnboardingTests.cs @@ -0,0 +1,327 @@ +using EpochSim; +using EpochSim.Fuzzing; +using EpochSim.Kernel.Messaging; +using EpochSim.Samples.Onboarding; + +public sealed class FuzzOnboardingTests +{ + [Fact] + public void Step_WithInventoryThatKnowsNothingAboutEpochSim_FindsTheRareBug() + { + var report = Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((inventory, ctx) => inventory.Tick(ctx.Rng.AsRandom())) + .Invariant("StockNonNegative", inventory => inventory.Stock >= 0) + .Seeds(1, 1000) + .Ticks(500)); + + Assert.False(report.Passed); + Assert.InRange(report.Failures.Count, 1, 200); + Assert.All(report.Failures, failure => + { + Assert.Equal(FuzzFailureKind.InvariantViolation, failure.Kind); + Assert.StartsWith("StockNonNegative: ", failure.Summary, StringComparison.Ordinal); + Assert.Contains(failure.StateDiff, change => change.Path == "$.Stock"); + }); + } + + [Fact] + public void Step_FailureIsReproducibleFromItsReportedSeedAndTick() + { + var report = FuzzInventory(f => f.Seeds(1, 1000).Ticks(500)); + var failure = report.Failures[0]; + + var reproduced = FuzzInventory(f => f.Seeds(failure.Seed, failure.Seed).Ticks(failure.Tick)); + var earlier = FuzzInventory(f => f.Seeds(failure.Seed, failure.Seed).Ticks(failure.Tick - 1)); + + Assert.Equal(failure.Tick, Assert.Single(reproduced.Failures).Tick); + Assert.True(earlier.Passed); + } + + [Fact] + public void Step_ReportDoesNotDependOnParallelism() + { + var sequential = FuzzInventory(f => f.Seeds(1, 300).Ticks(500).Parallelism(1)); + var parallel = FuzzInventory(f => f.Seeds(1, 300).Ticks(500).Parallelism(8)); + + Assert.Equal( + sequential.Failures.Select(failure => (failure.Seed, failure.Tick)), + parallel.Failures.Select(failure => (failure.Seed, failure.Tick))); + } + + [Fact] + public void Step_SeesEveryTickInOrderAndADeterministicRng() + { + var observed = new List<(long Tick, int Draw)>(); + + Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((_, ctx) => observed.Add((ctx.Tick, ctx.Rng.NextInt(0, 1000)))) + .Seeds(5, 5) + .Ticks(9) + .Parallelism(1)); + + var again = new List<(long Tick, int Draw)>(); + Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((_, ctx) => again.Add((ctx.Tick, ctx.Rng.NextInt(0, 1000)))) + .Seeds(5, 5) + .Ticks(9) + .Parallelism(1)); + + Assert.Equal(Enumerable.Range(0, 10).Select(tick => (long)tick), observed.Select(entry => entry.Tick)); + Assert.Equal(observed, again); + } + + [Fact] + public void Step_TimeProviderAdvancesOneTickDurationPerTick() + { + var times = new List(); + + Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((_, ctx) => times.Add(ctx.TimeProvider.GetUtcNow())) + .Seeds(1, 1) + .Ticks(3) + .Parallelism(1)); + + Assert.Equal( + Enumerable.Range(0, 4).Select(tick => StepContext.ClockStart + tick * StepContext.TickDuration), + times); + } + + [Fact] + public void Step_TimeProviderKeepsTimeDependentLogicDeterministic() + { + var report = Epoch.Fuzz(f => f + .State(() => new TimedState()) + .Step((state, ctx) => state.LastSeenUnixSeconds = ctx.TimeProvider.GetUtcNow().ToUnixTimeSeconds()) + .CheckDeterminism() + .Seeds(1, 5) + .Ticks(20)); + + Assert.True(report.Passed); + } + + [Fact] + public void Step_SeveralStepsRunInRegistrationOrderOnEveryTick() + { + var calls = new List(); + + Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((_, ctx) => calls.Add($"a{ctx.Tick}")) + .Step((_, ctx) => calls.Add($"b{ctx.Tick}")) + .Seeds(1, 1) + .Ticks(1) + .Parallelism(1)); + + Assert.Equal(["a0", "b0", "a1", "b1"], calls); + } + + [Fact] + public void Step_CombinesWithEngineConfiguration() + { + var order = new List(); + + Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Engine(e => e.AddSystem("Engine", tick: _ => order.Add("engine"))) + .Step((_, _) => order.Add("step")) + .Seeds(1, 1) + .Ticks(0) + .Parallelism(1)); + + Assert.Equal(["engine", "step"], order); + } + + [Fact] + public void Step_ExceptionIsReportedAsExceptionFailure() + { + var report = Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((_, ctx) => + { + if (ctx.Tick == 3) + throw new InvalidOperationException("kaput"); + }) + .Seeds(1, 1) + .Ticks(10)); + + var failure = Assert.Single(report.Failures); + Assert.Equal(FuzzFailureKind.Exception, failure.Kind); + Assert.Equal(3, failure.Tick); + } + + [Fact] + public void Invariant_NameAppearsInTheReport() + { + var report = Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((_, _) => { }) + .Invariant("StockAtLeastOne", inventory => inventory.Stock >= 100) + .Seeds(1, 1) + .Ticks(5)); + + var failure = Assert.Single(report.Failures); + Assert.Equal(0, failure.Tick); + Assert.Equal("StockAtLeastOne", failure.Identity); + Assert.Contains("StockAtLeastOne", report.ToText(), StringComparison.Ordinal); + } + + [Fact] + public void Invariant_CombinesWithInvariantFactoryAndOtherPredicates() + { + var report = Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((_, _) => { }) + .Invariants(() => [new FailingInventoryInvariant()]) + .Invariant("First", _ => true) + .Invariant("Second", _ => false) + .Seeds(1, 1) + .Ticks(0)); + + var failure = Assert.Single(report.Failures); + Assert.Equal("FactoryInvariant", failure.Identity); + } + + [Fact] + public void Invariant_PredicatesAreCheckedInOrder() + { + var report = Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((_, _) => { }) + .Invariant("First", _ => false) + .Invariant("Second", _ => false) + .Seeds(1, 1) + .Ticks(0)); + + Assert.Equal("First", Assert.Single(report.Failures).Identity); + } + + [Fact] + public void Invariant_InvalidArguments_Throw() + { + Assert.Throws(() => Epoch.Fuzz(f => f.Invariant(" ", _ => true))); + Assert.Throws(() => Epoch.Fuzz(f => f.Invariant("Name", null!))); + Assert.Throws(() => Epoch.Fuzz(f => f.Step(null!))); + Assert.Throws(() => Epoch.Fuzz(f => f.Project(null!))); + } + + [Fact] + public void Fuzz_WithoutEngineAndStep_ExplainsWhatIsMissing() + { + var error = Assert.Throws(() => Epoch.Fuzz(f => f + .State(() => new Inventory()).Seeds(1, 2).Ticks(3))); + + Assert.Contains("Engine", error.Message, StringComparison.Ordinal); + Assert.Contains("Step", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Project_LetsUnserializableStateBeFingerprintedAndDiffed() + { + var report = Epoch.Fuzz(f => f + .State(() => new GraphState()) + .Step((graph, ctx) => graph.Weight += ctx.Rng.NextInt(1, 4)) + .Project(graph => new { graph.Weight }) + .Invariant("WeightBelowTen", graph => graph.Weight < 10) + .CheckDeterminism() + .Seeds(1, 3) + .Ticks(50)); + + Assert.Equal(3, report.Failures.Count); + Assert.All(report.Failures, failure => + { + Assert.Equal(FuzzFailureKind.InvariantViolation, failure.Kind); + Assert.Contains(failure.StateDiff, change => change.Path == "$.Weight"); + }); + } + + [Fact] + public void Project_WithoutProjection_CyclicStateFailsInTheDefaultSerializer() + { + var report = Epoch.Fuzz(f => f + .State(() => new GraphState()) + .Step((graph, ctx) => graph.Weight += ctx.Rng.NextInt(1, 4)) + .CheckDeterminism() + .Seeds(1, 1) + .Ticks(5)); + + var failure = Assert.Single(report.Failures); + Assert.Equal(FuzzFailureKind.Exception, failure.Kind); + Assert.Contains("cycle", failure.Summary, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Project_CannotBeCombinedWithSerializer() + { + var error = Assert.Throws(() => Epoch.Fuzz(f => f + .State(() => new GraphState()) + .Step((_, _) => { }) + .Project(graph => new { graph.Weight }) + .Serializer(new EpochSim.Serialization.State.JsonStateSerializer()) + .Seeds(1, 1) + .Ticks(1))); + + Assert.Contains("Project", error.Message, StringComparison.Ordinal); + Assert.Contains("Serializer", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Project_WorksTogetherWithShrinking() + { + var report = Epoch.Fuzz(f => f + .State(() => new GraphState()) + .Engine(e => e.OnCommand((graph, command, _) => graph.Weight += command.Amount)) + .Project(graph => new { graph.Weight }) + .Invariant("WeightBelowTen", graph => graph.Weight < 10) + .Commands(plan => + { + for (var i = 0; i < 20; i++) + plan.Enqueue(i, new AddWeight(i == 7 ? 12 : 0)); + }) + .Seeds(1, 1) + .Ticks(30)); + + var failure = Assert.Single(report.Failures); + Assert.Equal([7], failure.MinimalCommandIndices); + } + + private static FuzzReport FuzzInventory(Action> configure) + => Epoch.Fuzz(f => + { + f.State(() => new Inventory()) + .Step((inventory, ctx) => inventory.Tick(ctx.Rng.AsRandom())) + .Invariant("StockNonNegative", inventory => inventory.Stock >= 0); + + configure(f); + }); + + private sealed class TimedState + { + public long LastSeenUnixSeconds { get; set; } + } + + private sealed class GraphState + { + public GraphState() + => Self = this; + + public GraphState Self { get; } + public int Weight { get; set; } + } + + private sealed record AddWeight(int Amount) : ICommand; + + private sealed class FailingInventoryInvariant : EpochSim.Kernel.Validation.IInvariant + { + public string Name => "FactoryInvariant"; + + public bool Check(EpochSim.Kernel.Time.SimTime time, Inventory state, out string message) + { + message = "always"; + return false; + } + } +} diff --git a/tests/EpochSim.Determinism.Tests/RngRandomTests.cs b/tests/EpochSim.Determinism.Tests/RngRandomTests.cs new file mode 100644 index 0000000..1fa4ec9 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/RngRandomTests.cs @@ -0,0 +1,116 @@ +using EpochSim; +using EpochSim.Kernel.Determinism; + +public sealed class RngRandomTests +{ + [Fact] + public void AsRandom_SameStream_ProducesSameSequence() + { + var first = new DeterministicRng(42).AsRandom(); + var second = new DeterministicRng(42).AsRandom(); + + Assert.Equal(Sample(first), Sample(second)); + Assert.NotEqual(Sample(new DeterministicRng(43).AsRandom()), Sample(new DeterministicRng(42).AsRandom())); + } + + [Fact] + public void AsRandom_ConsumesTheUnderlyingStream() + { + var rng = new DeterministicRng(7); + var mirror = new DeterministicRng(7); + + var drawn = rng.AsRandom().Next(0, 1000); + + Assert.Equal(mirror.NextInt(0, 1000), drawn); + Assert.Equal(mirror.NextU64(), rng.NextU64()); + } + + [Fact] + public void AsRandom_ReturnsTheSameAdapterForTheSameStream() + { + var rng = new DeterministicRng(1); + + Assert.Same(rng.AsRandom(), rng.AsRandom()); + Assert.NotSame(rng.AsRandom(), new DeterministicRng(1).AsRandom()); + } + + [Fact] + public void AsRandom_RespectsRangesOfEveryOverload() + { + var random = new DeterministicRng(99).AsRandom(); + + for (var i = 0; i < 2000; i++) + { + Assert.InRange(random.Next(), 0, int.MaxValue - 1); + Assert.InRange(random.Next(10), 0, 9); + Assert.InRange(random.Next(-5, 5), -5, 4); + Assert.InRange(random.Next(int.MinValue, int.MaxValue), int.MinValue, int.MaxValue - 1); + Assert.InRange(random.NextInt64(), 0L, long.MaxValue - 1); + Assert.InRange(random.NextInt64(100L), 0L, 99L); + Assert.InRange(random.NextInt64(long.MinValue, long.MaxValue), long.MinValue, long.MaxValue - 1); + Assert.InRange(random.NextDouble(), 0.0, 0.9999999999999999); + Assert.InRange(random.NextSingle(), 0f, 0.99999994f); + } + } + + [Fact] + public void AsRandom_CoversTheWholeRange() + { + var random = new DeterministicRng(5).AsRandom(); + + var seen = Enumerable.Range(0, 500).Select(_ => random.Next(0, 4)).Distinct().Order(); + + Assert.Equal([0, 1, 2, 3], seen); + } + + [Fact] + public void AsRandom_DegenerateRangesFollowRandomSemantics() + { + var random = new DeterministicRng(3).AsRandom(); + + Assert.Equal(0, random.Next(0)); + Assert.Equal(7, random.Next(7, 7)); + Assert.Equal(9L, random.NextInt64(9L, 9L)); + Assert.Throws(() => random.Next(-1)); + Assert.Throws(() => random.Next(5, 4)); + Assert.Throws(() => random.NextInt64(-1L)); + Assert.Throws(() => random.NextInt64(5L, 4L)); + } + + [Fact] + public void AsRandom_FillsBuffersDeterministically() + { + var first = new byte[19]; + var second = new byte[19]; + var span = new byte[19]; + + new DeterministicRng(11).AsRandom().NextBytes(first); + new DeterministicRng(11).AsRandom().NextBytes(second); + new DeterministicRng(11).AsRandom().NextBytes(span.AsSpan()); + + Assert.Equal(first, second); + Assert.Equal(first, span); + Assert.Contains(first, value => value != 0); + } + + [Fact] + public void AsRandom_WorksWithFrameworkHelpersThatTakeRandom() + { + var items = Enumerable.Range(0, 20).ToArray(); + var other = items.ToArray(); + + new DeterministicRng(8).AsRandom().Shuffle(items); + new DeterministicRng(8).AsRandom().Shuffle(other); + + Assert.Equal(items, other); + Assert.NotEqual(Enumerable.Range(0, 20), items); + Assert.Equal(Enumerable.Range(0, 20), items.Order()); + } + + [Fact] + public void AsRandom_NullStream_Throws() + => Assert.Throws(() => ((IRng)null!).AsRandom()); + + private static List Sample(Random random) + => Enumerable.Range(0, 16).Select(_ => random.Next(0, 1_000_000)).ToList(); +} From 7626bb7fff1712c1d44c79f13a91e0d92048edc8 Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 12:54:42 +0300 Subject: [PATCH 04/10] feat(analyzer): treat FuzzBuilder.Step and Invariant lambdas as simulation code --- src/EpochSim.Analyzers/SimulationScope.cs | 17 ++++++++++--- .../DeterminismAnalyzerTests.cs | 13 ++++++++++ .../SimulationSource.cs | 25 +++++++++++++++++++ 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/src/EpochSim.Analyzers/SimulationScope.cs b/src/EpochSim.Analyzers/SimulationScope.cs index b13560e..4e8d58f 100644 --- a/src/EpochSim.Analyzers/SimulationScope.cs +++ b/src/EpochSim.Analyzers/SimulationScope.cs @@ -9,6 +9,7 @@ namespace EpochSim.Analyzers; internal sealed class SimulationScope { private readonly INamedTypeSymbol? _engine; + private readonly INamedTypeSymbol? _fuzzBuilder; private readonly INamedTypeSymbol? _system; private readonly INamedTypeSymbol? _commandHandler; private readonly INamedTypeSymbol? _invariant; @@ -18,6 +19,7 @@ internal sealed class SimulationScope private SimulationScope(Compilation compilation) { _engine = compilation.GetTypeByMetadataName("EpochSim.Execution.SimulationEngine`1"); + _fuzzBuilder = compilation.GetTypeByMetadataName("EpochSim.Fuzzing.FuzzBuilder`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"); @@ -31,13 +33,20 @@ private SimulationScope(Compilation compilation) } private bool IsRelevant - => _engine is not null || _system is not null || _commandHandler is not null + => _engine is not null || _fuzzBuilder 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"; + { + var owner = method.ContainingType?.OriginalDefinition; + + return (_engine is not null + && SymbolEqualityComparer.Default.Equals(owner, _engine) + && method.Name is "AddSystem" or "OnCommand") + || (_fuzzBuilder is not null + && SymbolEqualityComparer.Default.Equals(owner, _fuzzBuilder) + && method.Name is "Step" or "Invariant"); + } public bool IsSimulationCode(IOperation operation, ISymbol containingSymbol) { diff --git a/tests/EpochSim.Analyzers.Tests/DeterminismAnalyzerTests.cs b/tests/EpochSim.Analyzers.Tests/DeterminismAnalyzerTests.cs index 7857f66..39b4e17 100644 --- a/tests/EpochSim.Analyzers.Tests/DeterminismAnalyzerTests.cs +++ b/tests/EpochSim.Analyzers.Tests/DeterminismAnalyzerTests.cs @@ -70,6 +70,8 @@ public sealed partial class DeterminismAnalyzerTests { ["AddSystem lambda"] = SimulationSource.Lambda, ["OnCommand lambda"] = SimulationSource.OnCommandLambda, + ["Step lambda"] = SimulationSource.StepLambda, + ["Invariant lambda"] = SimulationSource.InvariantLambda, ["ISystem"] = SimulationSource.SystemClass, ["IInvariant"] = SimulationSource.InvariantClass, ["ICommandHandler"] = SimulationSource.CommandHandlerClass, @@ -86,6 +88,7 @@ public static TheoryData EveryConstructInCommonContexts() foreach (var statement in statements) { data.Add("AddSystem lambda", statement); + data.Add("Step lambda", statement); data.Add("ISystem", statement); } @@ -130,6 +133,16 @@ public Task ReportsRepresentativeConstructInEverySimulationContext(string contex public Task IgnoresConstructsOutsideSimulationCode(string statement) => AnalyzerVerifier.Verify(SimulationSource.Outside(StripMarkup(statement))); + [Fact] + public Task ReportsRandomAndWallClockInsideStepOfAFuzzBuilder() + => AnalyzerVerifier.Verify( + SimulationSource.StepLambda("var random = {|ESIM002:new Random()|}; var now = {|ESIM001:DateTime.Now|};")); + + [Fact] + public Task ReportsRandomInsideInvariantPredicateOfAFuzzBuilder() + => AnalyzerVerifier.Verify( + SimulationSource.InvariantLambda("var random = {|ESIM002:new Random()|};")); + [Fact] public Task ReportsAsyncLambdaAndAwaitInsideSystemLambda() => AnalyzerVerifier.Verify( diff --git a/tests/EpochSim.Analyzers.Tests/SimulationSource.cs b/tests/EpochSim.Analyzers.Tests/SimulationSource.cs index a6ba189..a51e345 100644 --- a/tests/EpochSim.Analyzers.Tests/SimulationSource.cs +++ b/tests/EpochSim.Analyzers.Tests/SimulationSource.cs @@ -18,6 +18,7 @@ internal static class SimulationSource using System.Threading; using System.Threading.Tasks; using EpochSim.Execution; + using EpochSim.Fuzzing; using EpochSim.Kernel.Determinism; using EpochSim.Kernel.Messaging; using EpochSim.Kernel.Systems; @@ -63,6 +64,28 @@ public static void Configure(SimulationEngine engine) } """.Replace(StatementMarker, statements); + public static string StepLambda(string statements) + => Usings + $$""" + public static class Host + { + public static void Configure(FuzzBuilder fuzz) + { + fuzz.Step((state, ctx) => { {{StatementMarker}} }); + } + } + """.Replace(StatementMarker, statements); + + public static string InvariantLambda(string statements) + => Usings + $$""" + public static class Host + { + public static void Configure(FuzzBuilder fuzz) + { + fuzz.Invariant("inv", state => { {{StatementMarker}} return true; }); + } + } + """.Replace(StatementMarker, statements); + public static string SystemClass(string statements) => Usings + $$""" public sealed class Sys : ISystem @@ -136,6 +159,8 @@ public static void Run() { {{StatementMarker}} } [ Lambda, OnCommandLambda, + StepLambda, + InvariantLambda, SystemClass, InvariantClass, CommandHandlerClass, From 455bf0a417e8d0398bdde61ac6f241840a787ebf Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 12:54:42 +0300 Subject: [PATCH 05/10] feat(cli): epochsim init scaffolds a ready Epoch.Fuzz call The scaffold now contains WorldFuzz.cs, runs it from Program.cs and takes the EpochSim package version from the tool assembly instead of a literal. --- src/EpochSim.Cli/Commands/InitCommand.cs | 33 ++++++++- .../CliInitCommandTests.cs | 73 ++++++++++++++++++- 2 files changed, 100 insertions(+), 6 deletions(-) diff --git a/src/EpochSim.Cli/Commands/InitCommand.cs b/src/EpochSim.Cli/Commands/InitCommand.cs index bae88db..5f1fd93 100644 --- a/src/EpochSim.Cli/Commands/InitCommand.cs +++ b/src/EpochSim.Cli/Commands/InitCommand.cs @@ -1,3 +1,4 @@ +using System.Reflection; using EpochSim.Cli.App; namespace EpochSim.Cli.Commands; @@ -14,11 +15,12 @@ public int Execute(CommandContext ctx, string[] args) { ["Program.cs"] = ProgramTemplate, ["WorldState.cs"] = WorldStateTemplate, - ["SessionInboxExample.cs"] = SessionInboxTemplate + ["SessionInboxExample.cs"] = SessionInboxTemplate, + ["WorldFuzz.cs"] = WorldFuzzTemplate }; if (!Directory.EnumerateFiles(targetDir, "*.csproj").Any()) - filesToCreate["EpochSim.App.csproj"] = ProjectTemplate; + filesToCreate["EpochSim.App.csproj"] = ProjectTemplate(); var existingFiles = filesToCreate.Keys .Where(fileName => File.Exists(Path.Combine(targetDir, fileName))) @@ -47,7 +49,12 @@ public int Execute(CommandContext ctx, string[] args) return 0; } - private const string ProjectTemplate = """ + private static string PackageVersion + => Assembly.GetExecutingAssembly().GetCustomAttribute()! + .InformationalVersion.Split('+')[0]; + + private static string ProjectTemplate() + => $$""" @@ -58,7 +65,7 @@ public int Execute(CommandContext ctx, string[] args) - + @@ -79,6 +86,24 @@ public int Execute(CommandContext ctx, string[] args) Console.WriteLine($"RunId={run.RunId}"); Console.WriteLine($"RunDir={run.Paths.RunDir}"); Console.WriteLine($"Population={state.Population}"); + + Console.WriteLine(WorldFuzz.Run().ToText()); + """; + + private const string WorldFuzzTemplate = """ + using EpochSim; + using EpochSim.Fuzzing; + + public static class WorldFuzz + { + public static FuzzReport Run() + => Epoch.Fuzz(f => f + .State(() => new WorldState()) + .Step((world, ctx) => world.Population += ctx.Rng.AsRandom().Next(0, 3)) + .Invariant("PopulationNonNegative", world => world.Population >= 0) + .Seeds(1, 1000) + .Ticks(500)); + } """; private const string WorldStateTemplate = """ diff --git a/tests/EpochSim.Determinism.Tests/CliInitCommandTests.cs b/tests/EpochSim.Determinism.Tests/CliInitCommandTests.cs index 86555b5..7b17e1f 100644 --- a/tests/EpochSim.Determinism.Tests/CliInitCommandTests.cs +++ b/tests/EpochSim.Determinism.Tests/CliInitCommandTests.cs @@ -1,6 +1,11 @@ +using System.Reflection; +using System.Text.RegularExpressions; using EpochSim.Cli.App; +using EpochSim.Fuzzing; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; -public sealed class CliInitCommandTests +public sealed partial class CliInitCommandTests { [Fact] public async Task InitCommand_ScaffoldsMinimalProject() @@ -17,6 +22,7 @@ public async Task InitCommand_ScaffoldsMinimalProject() Assert.True(File.Exists(Path.Combine(targetDir, "Program.cs"))); Assert.True(File.Exists(Path.Combine(targetDir, "WorldState.cs"))); Assert.True(File.Exists(Path.Combine(targetDir, "SessionInboxExample.cs"))); + Assert.True(File.Exists(Path.Combine(targetDir, "WorldFuzz.cs"))); Assert.True(File.Exists(Path.Combine(targetDir, "EpochSim.App.csproj"))); var program = File.ReadAllText(Path.Combine(targetDir, "Program.cs")); @@ -25,7 +31,8 @@ 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.3.0\"", csproj, StringComparison.Ordinal); + Assert.Contains($"Version=\"{PackageVersion()}\"", csproj, StringComparison.Ordinal); + Assert.Matches(VersionPattern(), PackageVersion()); var inboxExample = File.ReadAllText(Path.Combine(targetDir, "SessionInboxExample.cs")); Assert.Contains("CommandInbox", inboxExample, StringComparison.Ordinal); @@ -37,4 +44,66 @@ public async Task InitCommand_ScaffoldsMinimalProject() Directory.Delete(targetDir, recursive: true); } } + + [Fact] + public async Task InitCommand_ScaffoldsAFuzzCallThatCompilesAndRuns() + { + var targetDir = Path.Combine(Path.GetTempPath(), $"epochsim-init-{Guid.NewGuid():N}"); + + try + { + Assert.Equal(0, await new CliApp().RunAsync(["init", targetDir])); + + var fuzz = File.ReadAllText(Path.Combine(targetDir, "WorldFuzz.cs")); + Assert.Contains("Epoch.Fuzz", fuzz, StringComparison.Ordinal); + Assert.Contains(".Step(", fuzz, StringComparison.Ordinal); + Assert.Contains(".Invariant(", fuzz, StringComparison.Ordinal); + Assert.DoesNotContain("//", fuzz, StringComparison.Ordinal); + + var program = File.ReadAllText(Path.Combine(targetDir, "Program.cs")); + Assert.Contains("WorldFuzz.Run()", program, StringComparison.Ordinal); + + var assembly = Compile(Directory.GetFiles(targetDir, "*.cs")); + var report = (FuzzReport)assembly.GetType("WorldFuzz")!.GetMethod("Run")!.Invoke(null, null)!; + Assert.True(report.Passed, report.ToText()); + Assert.Equal(1000, report.SeedsRun); + } + finally + { + if (Directory.Exists(targetDir)) + Directory.Delete(targetDir, recursive: true); + } + } + + private const string ImplicitUsings = + "global using System; global using System.Collections.Generic; global using System.IO; " + + "global using System.Linq; global using System.Threading; global using System.Threading.Tasks;"; + + private static string PackageVersion() + => typeof(EpochSim.Epoch).Assembly.GetCustomAttribute()! + .InformationalVersion.Split('+')[0]; + + private static Assembly Compile(IEnumerable files) + { + var references = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator) + .Select(path => MetadataReference.CreateFromFile(path)); + + var compilation = CSharpCompilation.Create( + $"Scaffold{Guid.NewGuid():N}", + files.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), new CSharpParseOptions(LanguageVersion.Latest))) + .Append(CSharpSyntaxTree.ParseText(ImplicitUsings, new CSharpParseOptions(LanguageVersion.Latest))), + references, + new CSharpCompilationOptions(OutputKind.ConsoleApplication, nullableContextOptions: NullableContextOptions.Enable)); + + using var stream = new MemoryStream(); + var result = compilation.Emit(stream); + var problems = result.Diagnostics.Where(diagnostic => diagnostic.Severity >= DiagnosticSeverity.Warning).ToArray(); + Assert.True(result.Success && problems.Length == 0, string.Join(Environment.NewLine, problems.Select(problem => problem.ToString()))); + + return Assembly.Load(stream.ToArray()); + } + + [GeneratedRegex(@"^\d+\.\d+\.\d+$")] + private static partial Regex VersionPattern(); } From a97fef61d459fbeb6319b5a210e5d4c33c8df44e Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 12:54:42 +0300 Subject: [PATCH 06/10] docs: executable README and fuzzing snippets, shrinking, failure store README and the fuzzing pages are checked by a test that compiles and runs every csharp block. This already caught a README example that did not compile and one that threw at runtime. Adds the testing page section for Regression and StoredFailuresStayFixed, EN and RU. --- README.md | 165 ++++++-- README.ru.md | 165 ++++++-- docs/en/fuzzing.md | 380 +++++++++++++++--- docs/en/testing.md | 21 + docs/ru/fuzzing.md | 380 +++++++++++++++--- docs/ru/testing.md | 21 + .../DocumentationSnippetTests.cs | 196 +++++++++ 7 files changed, 1166 insertions(+), 162 deletions(-) create mode 100644 tests/EpochSim.Determinism.Tests/DocumentationSnippetTests.cs diff --git a/README.md b/README.md index 0e0b355..4486bfb 100644 --- a/README.md +++ b/README.md @@ -70,31 +70,55 @@ 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. +`Epoch.Fuzz` runs your code on a range of seeds and checks invariants, exceptions and, optionally, determinism. Existing code needs no rewrite: call it from `Step`, state what must always hold in `Invariant` and pick the seeds. `ctx.Rng.AsRandom()` hands code that takes a `System.Random` a deterministic stream. + ```csharp -var report = Epoch.Fuzz(f => f - .State(() => new JobQueueState()) - .Engine(e => e.AddSystem(new JobQueueSystem())) - .Invariants(() => [new QueueNonNegativeInvariant()]) +using EpochSim; + +var report = Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((inventory, ctx) => inventory.Tick(ctx.Rng.AsRandom())) + .Invariant("StockNonNegative", inventory => inventory.Stock >= 0) .Seeds(1, 1000) .Ticks(500)); report.ThrowIfFailed(); -``` +public sealed class Inventory +{ + public int Stock { get; private set; } = 5; + + public void Tick(Random random) + { + if (random.Next(0, 3) == 0) + Stock += 4; + + var demand = random.Next(0, 3); + if (Stock >= demand) + Stock -= demand; + + if (random.Next(0, 400) == 0) + Stock -= 5; + } +} ``` -Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81 -[InvariantViolation] seed=4 tick=426 - QueueNonNegative: Pending=-1 +`Inventory` is an ordinary class with no reference to EpochSim. The run finds the seeds on which its stock goes negative, and names the tick and the state fields that changed: + +```text +Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150 + +[InvariantViolation] seed=18 tick=19 + StockNonNegative: predicate returned false StateDiff: - $.Completed: 198 -> 200 - $.Pending: 0 -> -1 - Repro: .Seeds(4, 4).Ticks(426) + $.Stock: 1 -> -2 + Repro: .Seeds(18, 18).Ticks(19) + +... ``` -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: +Add `.Seeds(18, 18).Ticks(19)` from the `Repro` line to your call to run only that failure. When commands drive the simulation, `Commands(...)` failures are shrunk to a minimal scenario, `FailureStore()` keeps failing seeds in a file you commit, and `epochsim failures export-test` turns them into regression tests. Add `.CheckDeterminism()` to run every seed twice and catch `static` state, wall-clock time and other sources of non-determinism. The same search from the terminal: ```bash epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500 @@ -111,11 +135,18 @@ dotnet add package EpochSim.Testing ``` ```csharp +using EpochSim.Testing; + SimAssert.IsDeterministic(f => f .State(() => new WorldState()) - .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++)) + .Step((world, _) => world.Population++) .Seeds(1, 50) .Ticks(200)); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` A failure names the seed, the tick and the changed state fields. More in [Testing](docs/en/testing.md). @@ -128,49 +159,71 @@ A failure names the seed, the tick and the changed state fields. More in [Testin | `RecommendedRun` | every 50 ticks | No | Production diagnostics | | `DebugRun` | every tick | Yes | Invariant hunting, strict mode | -The mutation guard serializes state before and after each system and throws `InvalidOperationException` when the fingerprint changes. It finds systems that mutate state outside event handlers, at a significant serialization cost: use it in `DebugRun` only. - ```csharp +using EpochSim; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + using var quick = Epoch.QuickRun(state, rootDir: "artifacts"); quick.RunTicks(engine, seed: 1, endTickInclusive: 100); using var recommended = Epoch.RecommendedRun(state, rootDir: "artifacts"); recommended.RunTicks(engine, seed: 1, endTickInclusive: 1000); -var serializer = Epoch.JsonStateSerializer(); -using var debug = Epoch.DebugRun(state, serializer, rootDir: "artifacts"); -debug.RunTicks(engine, seed: 1, endTickInclusive: 200); +public sealed class WorldState +{ + public int Population { get; set; } +} ``` -For full control use `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` or `EpochSimRun.For(state)...Build()`. - -## Event log and replay - -The event log is optional and required for `verify-run`, `bisect` and `fast-replay`. +The mutation guard serializes the state before and after each system and throws `InvalidOperationException` when the fingerprint changes. It finds systems that mutate state outside event handlers, at a significant serialization cost: use it in `DebugRun` only. The system above changes `Population` directly, so `DebugRun` rejects it with the tick and the system name: + ```csharp using EpochSim; -using EpochSim.Kernel.Messaging; -var codec = Epoch.JsonCodecFromAssembly(t => t == typeof(Changed)); -var serializer = Epoch.JsonStateSerializer(); +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); -using var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts"); +using var debug = Epoch.DebugRun(state, rootDir: "artifacts"); +debug.RunTicks(engine, seed: 1, endTickInclusive: 200); -[MessageKind("Changed")] -public sealed record Changed(int Delta) : IEvent; +public sealed class WorldState +{ + public int Population { get; set; } +} ``` -## Reading artifacts +For full control use `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` or `EpochSimRun.For(state)...Build()`. + +## Event log and artifacts -Artifacts are plain files in the run directory and can be read in-process: +The event log is optional and required for `verify-run`, `bisect` and `fast-replay`. Artifacts are plain files in the run directory and can be read in-process: ```csharp using EpochSim; using EpochSim.Execution.RunArtifacts; using EpochSim.Execution.StateFingerprint; +using EpochSim.Kernel.Messaging; using EpochSim.Serialization.EventLog; +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +var inbox = new ScheduledCommandInbox(); +engine.AttachScheduledInbox(inbox); +engine.OnCommand((world, command, events) => +{ + world.Population += command.Delta; + events.Emit(new Changed(command.Delta)); +}); +inbox.Enqueue(5, new AddPopulation(3)); + +var codec = Epoch.JsonCodecFromAssembly(type => type == typeof(Changed)); +var serializer = Epoch.JsonStateSerializer(); + string runDir; using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts")) { @@ -183,6 +236,17 @@ var fingerprints = JsonlStateFingerprintWriter.ReadAll(Path.Combine(runDir, "sta var entries = EventLogReader.ReadAll(Path.Combine(runDir, "events.jsonl")); Console.WriteLine($"EndTick={manifest?.EndTick}, fingerprints={fingerprints.Count}, events={entries.Count}"); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +[MessageKind("Changed")] +public sealed record Changed(int Delta) : IEvent; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Layout and formats are described in [Artifacts](docs/en/artifacts.md). @@ -192,6 +256,13 @@ Layout and formats are described in [Artifacts](docs/en/artifacts.md). `RunTicks` fits batch jobs. `SimulationSession` fits long-lived loops: ```csharp +using EpochSim; +using EpochSim.Kernel.Messaging; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.OnCommand((world, command, _) => world.Population += command.Delta); + var inbox = new CommandInbox(); engine.AttachInbox(inbox); @@ -202,6 +273,11 @@ session.RunUntil(100); [MessageKind("AddPopulation")] public sealed record AddPopulation(int Delta) : ICommand; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Inboxes feed external commands into the simulation thread deterministically: @@ -210,12 +286,30 @@ Inboxes feed external commands into the simulation thread deterministically: - `ScheduledCommandInbox`: commands for a specific tick, ordered by tick ascending, then by insertion order. ```csharp +using EpochSim; +using EpochSim.Kernel.Messaging; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.OnCommand((world, command, _) => world.Population += command.Delta); + var scheduled = new ScheduledCommandInbox(); engine.AttachScheduledInbox(scheduled); scheduled.Enqueue(10, new AddPopulation(3)); scheduled.Enqueue(10, new AddPopulation(7)); scheduled.Enqueue(12, new AddPopulation(1)); + +using var session = engine.CreateSession(state, seed: 1, startTick: 0); +session.RunUntil(100); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` More in [Sessions](docs/en/sessions.md). @@ -235,6 +329,7 @@ Determinism debugging: epochsim verify-run artifacts epochsim bisect artifacts epochsim fuzz --adapter fuzzbug --seeds 1..1000 +epochsim failures list ``` | Command | Purpose | @@ -243,7 +338,7 @@ epochsim fuzz --adapter fuzzbug --seeds 1..1000 | `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 violation | -| `fuzz` | Run many seeds, find the one that breaks | +| `fuzz`, `failures` | Find the seed that breaks, manage stored failures | | `event-stats`, `timeline`, `list-adapters` | Analyze events and list available adapters | ## What is included @@ -258,7 +353,7 @@ epochsim fuzz --adapter fuzzbug --seeds 1..1000 | 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. | +| Fuzzing | `Epoch.Fuzz`: seed ranges, invariants, determinism check, shrinking, failure store, regression tests. | | CLI | `epochsim` .NET tool covering the whole run lifecycle. | ## Documentation @@ -274,7 +369,7 @@ epochsim fuzz --adapter fuzzbug --seeds 1..1000 ## 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. [Fuzzing](src/EpochSim.Samples/Fuzzing/) has a rare seed-dependent bug for `Epoch.Fuzz` to find. +[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. [Onboarding](src/EpochSim.Samples/Onboarding/) holds the `Inventory` class from the fuzzing example. [Fuzzing](src/EpochSim.Samples/Fuzzing/) has rare seed-dependent and command-dependent bugs for `Epoch.Fuzz` to find. ## Build and test diff --git a/README.ru.md b/README.ru.md index 8d42cb1..0ac3447 100644 --- a/README.ru.md +++ b/README.ru.md @@ -70,31 +70,55 @@ public sealed class WorldState ## Поиск багов по seed -`Epoch.Fuzz` прогоняет симуляцию на диапазоне seed и проверяет инварианты, исключения и, по желанию, детерминизм. Каждый сбой приходит с seed, который его воспроизводит, и полями состояния, изменившимися на сбойном тике. +`Epoch.Fuzz` прогоняет ваш код на диапазоне seed и проверяет инварианты, исключения и, по желанию, детерминизм. Переписывать существующий код не нужно: вызовите его из `Step`, опишите в `Invariant`, что должно выполняться всегда, и задайте seed. `ctx.Rng.AsRandom()` отдаёт коду, принимающему `System.Random`, детерминированный поток. + ```csharp -var report = Epoch.Fuzz(f => f - .State(() => new JobQueueState()) - .Engine(e => e.AddSystem(new JobQueueSystem())) - .Invariants(() => [new QueueNonNegativeInvariant()]) +using EpochSim; + +var report = Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((inventory, ctx) => inventory.Tick(ctx.Rng.AsRandom())) + .Invariant("StockNonNegative", inventory => inventory.Stock >= 0) .Seeds(1, 1000) .Ticks(500)); report.ThrowIfFailed(); -``` +public sealed class Inventory +{ + public int Stock { get; private set; } = 5; + + public void Tick(Random random) + { + if (random.Next(0, 3) == 0) + Stock += 4; + + var demand = random.Next(0, 3); + if (Stock >= demand) + Stock -= demand; + + if (random.Next(0, 400) == 0) + Stock -= 5; + } +} ``` -Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81 -[InvariantViolation] seed=4 tick=426 - QueueNonNegative: Pending=-1 +`Inventory` это обычный класс без ссылок на EpochSim. Прогон находит seed, на которых остаток уходит в минус, и называет тик и изменившиеся поля состояния: + +```text +Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150 + +[InvariantViolation] seed=18 tick=19 + StockNonNegative: predicate returned false StateDiff: - $.Completed: 198 -> 200 - $.Pending: 0 -> -1 - Repro: .Seeds(4, 4).Ticks(426) + $.Stock: 1 -> -2 + Repro: .Seeds(18, 18).Ticks(19) + +... ``` -Добавьте `.CheckDeterminism()`, чтобы прогонять каждый seed дважды и ловить `static`-состояние, системное время и другие источники недетерминизма. Тот же прогон из терминала: +Добавьте `.Seeds(18, 18).Ticks(19)` из строки `Repro` в свой вызов, чтобы прогнать только этот сбой. Если симуляцию ведут команды, сбои при `Commands(...)` сокращаются до минимального сценария, `FailureStore()` хранит сбойные seed в файле, который вы коммитите, а `epochsim failures export-test` превращает их в регрессионные тесты. `.CheckDeterminism()` прогоняет каждый seed дважды и ловит `static`-состояние, системное время и другие источники недетерминизма. Тот же поиск из терминала: ```bash epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500 @@ -111,11 +135,18 @@ dotnet add package EpochSim.Testing ``` ```csharp +using EpochSim.Testing; + SimAssert.IsDeterministic(f => f .State(() => new WorldState()) - .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++)) + .Step((world, _) => world.Population++) .Seeds(1, 50) .Ticks(200)); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Сообщение о сбое называет seed, тик и изменившиеся поля состояния. Подробнее в [Testing](docs/ru/testing.md). @@ -128,49 +159,71 @@ SimAssert.IsDeterministic(f => f | `RecommendedRun` | каждые 50 тиков | Нет | Диагностика в production | | `DebugRun` | каждый тик | Да | Поиск инвариантов, строгий режим | -Mutation guard сериализует state до и после каждой системы и бросает `InvalidOperationException`, если fingerprint изменился. Он находит системы, меняющие state вне обработчиков событий, но заметно замедляет прогон: используйте его только в `DebugRun`. - ```csharp +using EpochSim; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + using var quick = Epoch.QuickRun(state, rootDir: "artifacts"); quick.RunTicks(engine, seed: 1, endTickInclusive: 100); using var recommended = Epoch.RecommendedRun(state, rootDir: "artifacts"); recommended.RunTicks(engine, seed: 1, endTickInclusive: 1000); -var serializer = Epoch.JsonStateSerializer(); -using var debug = Epoch.DebugRun(state, serializer, rootDir: "artifacts"); -debug.RunTicks(engine, seed: 1, endTickInclusive: 200); +public sealed class WorldState +{ + public int Population { get; set; } +} ``` -Для полного контроля: `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` или `EpochSimRun.For(state)...Build()`. - -## Лог событий и replay - -Лог событий необязателен и нужен для `verify-run`, `bisect` и `fast-replay`. +Mutation guard сериализует state до и после каждой системы и бросает `InvalidOperationException`, если fingerprint изменился. Он находит системы, меняющие state вне обработчиков событий, но заметно замедляет прогон: используйте его только в `DebugRun`. Система выше меняет `Population` напрямую, поэтому `DebugRun` отклоняет её, называя тик и систему: + ```csharp using EpochSim; -using EpochSim.Kernel.Messaging; -var codec = Epoch.JsonCodecFromAssembly(t => t == typeof(Changed)); -var serializer = Epoch.JsonStateSerializer(); +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); -using var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts"); +using var debug = Epoch.DebugRun(state, rootDir: "artifacts"); +debug.RunTicks(engine, seed: 1, endTickInclusive: 200); -[MessageKind("Changed")] -public sealed record Changed(int Delta) : IEvent; +public sealed class WorldState +{ + public int Population { get; set; } +} ``` -## Чтение артефактов +Для полного контроля: `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` или `EpochSimRun.For(state)...Build()`. + +## Лог событий и артефакты -Артефакты лежат обычными файлами в каталоге прогона и читаются из кода: +Лог событий необязателен и нужен для `verify-run`, `bisect` и `fast-replay`. Артефакты лежат обычными файлами в каталоге прогона и читаются из кода: ```csharp using EpochSim; using EpochSim.Execution.RunArtifacts; using EpochSim.Execution.StateFingerprint; +using EpochSim.Kernel.Messaging; using EpochSim.Serialization.EventLog; +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +var inbox = new ScheduledCommandInbox(); +engine.AttachScheduledInbox(inbox); +engine.OnCommand((world, command, events) => +{ + world.Population += command.Delta; + events.Emit(new Changed(command.Delta)); +}); +inbox.Enqueue(5, new AddPopulation(3)); + +var codec = Epoch.JsonCodecFromAssembly(type => type == typeof(Changed)); +var serializer = Epoch.JsonStateSerializer(); + string runDir; using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts")) { @@ -183,6 +236,17 @@ var fingerprints = JsonlStateFingerprintWriter.ReadAll(Path.Combine(runDir, "sta var entries = EventLogReader.ReadAll(Path.Combine(runDir, "events.jsonl")); Console.WriteLine($"EndTick={manifest?.EndTick}, fingerprints={fingerprints.Count}, events={entries.Count}"); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +[MessageKind("Changed")] +public sealed record Changed(int Delta) : IEvent; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Структура и форматы описаны в [Artifacts](docs/ru/artifacts.md). @@ -192,6 +256,13 @@ Console.WriteLine($"EndTick={manifest?.EndTick}, fingerprints={fingerprints.Coun `RunTicks` подходит для batch-прогонов. `SimulationSession` подходит для долгоживущих циклов: ```csharp +using EpochSim; +using EpochSim.Kernel.Messaging; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.OnCommand((world, command, _) => world.Population += command.Delta); + var inbox = new CommandInbox(); engine.AttachInbox(inbox); @@ -202,6 +273,11 @@ session.RunUntil(100); [MessageKind("AddPopulation")] public sealed record AddPopulation(int Delta) : ICommand; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Inbox'ы детерминированно передают внешние команды в поток симуляции: @@ -210,12 +286,30 @@ Inbox'ы детерминированно передают внешние ком - `ScheduledCommandInbox`: команды на заданный тик, порядок: сначала тик по возрастанию, затем порядок добавления. ```csharp +using EpochSim; +using EpochSim.Kernel.Messaging; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.OnCommand((world, command, _) => world.Population += command.Delta); + var scheduled = new ScheduledCommandInbox(); engine.AttachScheduledInbox(scheduled); scheduled.Enqueue(10, new AddPopulation(3)); scheduled.Enqueue(10, new AddPopulation(7)); scheduled.Enqueue(12, new AddPopulation(1)); + +using var session = engine.CreateSession(state, seed: 1, startTick: 0); +session.RunUntil(100); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Подробнее в [Sessions](docs/ru/sessions.md). @@ -235,6 +329,7 @@ epochsim inspect-run artifacts epochsim verify-run artifacts epochsim bisect artifacts epochsim fuzz --adapter fuzzbug --seeds 1..1000 +epochsim failures list ``` | Команда | Назначение | @@ -243,7 +338,7 @@ epochsim fuzz --adapter fuzzbug --seeds 1..1000 | `list-runs`, `inspect-run`, `pretty-inspect` | Просмотр и инспекция записанных прогонов | | `validate-run`, `verify-run` | Проверка артефактов и fingerprint'ов | | `fast-replay`, `bisect`, `repro` | Replay прогона, поиск первого нарушения | -| `fuzz` | Прогон многих seed, поиск сбойного | +| `fuzz`, `failures` | Поиск сбойного seed, сохранённые сбои | | `event-stats`, `timeline`, `list-adapters` | Анализ событий и список доступных адаптеров | ## Состав @@ -258,7 +353,7 @@ epochsim fuzz --adapter fuzzbug --seeds 1..1000 | Диагностика | Mutation guard, инварианты, проверка replay, bisect, полевой дифф состояния. | | Анализатор | Roslyn-правила ESIM001-ESIM006 ловят системное время, `Random`, потоки и другое в коде симуляции. | | Тестирование | `EpochSim.Testing`: `SimAssert` для любого тестового фреймворка, золотые fingerprint'ы. | -| Fuzzing | `Epoch.Fuzz`: диапазоны seed, инварианты, проверка детерминизма, воспроизводимые сбои. | +| Fuzzing | `Epoch.Fuzz`: диапазоны seed, инварианты, проверка детерминизма, шринкинг, хранилище сбоев, регрессионные тесты. | | CLI | .NET-утилита `epochsim` для всего жизненного цикла прогона. | ## Документация @@ -274,7 +369,7 @@ epochsim fuzz --adapter fuzzbug --seeds 1..1000 ## Примеры -[QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs) — минимальная отправная точка. [Population](src/EpochSim.Samples/Population/) — событийный домен с инвариантами и replay. [Fuzzing](src/EpochSim.Samples/Fuzzing/) — редкий баг, зависящий от seed, для поиска через `Epoch.Fuzz`. +[QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs) — минимальная отправная точка. [Population](src/EpochSim.Samples/Population/) — событийный домен с инвариантами и replay. [Onboarding](src/EpochSim.Samples/Onboarding/) — класс `Inventory` из примера поиска багов. [Fuzzing](src/EpochSim.Samples/Fuzzing/) — редкие баги, зависящие от seed и от команд, для поиска через `Epoch.Fuzz`. ## Сборка и тесты diff --git a/docs/en/fuzzing.md b/docs/en/fuzzing.md index ac2b71b..4ac018e 100644 --- a/docs/en/fuzzing.md +++ b/docs/en/fuzzing.md @@ -1,85 +1,241 @@ # 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: +`Epoch.Fuzz` runs your code 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. +- `InvariantViolation`: an invariant returned `false`. +- `Exception`: a system, step or command handler threw. - `NonDeterminism`: two runs of the same seed produced different state (needs `CheckDeterminism`). -Every failure is reproducible with the same seed. +Every failure is reproducible with the same seed. When commands drive the simulation, the report also reduces them to a minimal scenario ([Shrinking](#shrinking)), and failing seeds can be kept in a file so that a bug found once is checked forever ([Failure store](#failure-store)). ## Minimal example +`Inventory` is an ordinary class that knows nothing about EpochSim. `Step` calls it on every tick, `Invariant` says what must always hold, `Seeds` and `Ticks` say how much to try: + ```csharp using EpochSim; -var report = Epoch.Fuzz(f => f - .State(() => new JobQueueState()) - .Engine(e => e.AddSystem(new JobQueueSystem())) - .Invariants(() => [new QueueNonNegativeInvariant()]) +var report = Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((inventory, ctx) => inventory.Tick(ctx.Rng.AsRandom())) + .Invariant("StockNonNegative", inventory => inventory.Stock >= 0) .Seeds(1, 1000) .Ticks(500)); Console.WriteLine(report.ToText()); + +public sealed class Inventory +{ + public int Stock { get; private set; } = 5; + + public void Tick(Random random) + { + if (random.Next(0, 3) == 0) + Stock += 4; + + var demand = random.Next(0, 3); + if (Stock >= demand) + Stock -= demand; + + if (random.Next(0, 400) == 0) + Stock -= 5; + } +} +``` + +Output (the first of 21 failures; `ElapsedMs` depends on the machine): + +```text +Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150 + +[InvariantViolation] seed=18 tick=19 + StockNonNegative: predicate returned false + StateDiff: + $.Stock: 1 -> -2 + Repro: .Seeds(18, 18).Ticks(19) +``` + +In a test, call `report.ThrowIfFailed()` or use [EpochSim.Testing](testing.md). The same class lives in [src/EpochSim.Samples/Onboarding](../../src/EpochSim.Samples/Onboarding/), where the test suite runs the call above against it. + +## Connecting existing code + +You do not have to restructure your code into systems, invariant classes and serializable state. + +| Method | What it does | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------ | +| `Step(Action)` | Runs on every tick, after the systems added with `Engine`. Several steps run in registration order. | +| `Invariant(string, Func)` | A named invariant, checked after every tick. The name goes into the report and into `Signature`. | +| `ctx.Rng.AsRandom()` | A `System.Random` over the deterministic stream, for code that already takes a `Random`. | +| `ctx.TimeProvider` | A `TimeProvider` (a `FakeTimeProvider`) that starts at `StepContext.ClockStart` and advances `StepContext.TickDuration` (one second) per tick. | +| `ctx.Tick` | The current tick. | +| `Project(Func)` | The part of the state used for fingerprints and `StateDiff`, when the state itself cannot be serialized to JSON. | + +`AsRandom()` returns one adapter per stream, so calling it on every tick costs a table lookup. Values come from the same stream as `ctx.Rng`: they are the same for the same seed and never read the system entropy. + +Code that reads time takes a `TimeProvider` instead of calling `DateTime.UtcNow`, and the run stays deterministic: + +```csharp +using EpochSim; + +var report = Epoch.Fuzz(f => f + .State(() => new Cache(TimeSpan.FromSeconds(5))) + .Step((cache, ctx) => + { + var random = ctx.Rng.AsRandom(); + var now = ctx.TimeProvider.GetUtcNow(); + cache.Get(random.Next(0, 20), now); + cache.Put(random.Next(0, 20), now); + if (cache.Count > 15) + cache.Evict(now); + }) + .Invariant("NeverServesStaleEntries", cache => cache.StaleHits == 0) + .CheckDeterminism() + .Seeds(1, 100) + .Ticks(200)); + +Console.WriteLine(report.Failures.Count > 0 ? report.Failures[0].ToText() : report.ToText()); + +public sealed class Cache(TimeSpan lifetime) +{ + private readonly Dictionary _storedAt = []; + + public int Count => _storedAt.Count; + public int StaleHits { get; private set; } + + public void Put(int key, DateTimeOffset now) => _storedAt[key] = now; + + public void Get(int key, DateTimeOffset now) + { + if (_storedAt.TryGetValue(key, out var storedAt) && now - storedAt > lifetime) + StaleHits++; + } + + public void Evict(DateTimeOffset now) + { + foreach (var key in _storedAt.Where(entry => now - entry.Value > lifetime).Select(entry => entry.Key).ToList()) + _storedAt.Remove(key); + } +} ``` -Output: +State that cannot be serialized to JSON (cycles, dictionaries keyed by objects) makes the default serializer throw. `Project` replaces it with a projection of the fields you care about: + +```csharp +using EpochSim; + +var report = Epoch.Fuzz(f => f + .State(() => new Graph()) + .Step((graph, ctx) => graph.Grow(ctx.Rng.AsRandom())) + .Project(graph => new { graph.NodeCount, graph.MaxChildren }) + .Invariant("AtMostThreeChildren", graph => graph.MaxChildren <= 3) + .CheckDeterminism() + .Seeds(1, 5) + .Ticks(100)); +Console.WriteLine(report.Failures[0].ToText()); + +public sealed class Graph +{ + private readonly List _nodes = []; + + public int NodeCount => _nodes.Count; + public int MaxChildren => _nodes.Count == 0 ? 0 : _nodes.Max(node => node.Children.Count); + public IReadOnlyList Nodes => _nodes; + + public void Grow(Random random) + { + var parent = _nodes.Count == 0 ? null : _nodes[random.Next(_nodes.Count)]; + var node = new Node(parent); + parent?.Children.Add(node); + _nodes.Add(node); + } +} + +public sealed class Node(Node? parent) +{ + public Node? Parent { get; } = parent; + public List Children { get; } = []; +} ``` -Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81 -[InvariantViolation] seed=4 tick=426 - QueueNonNegative: Pending=-1 +```text +[InvariantViolation] seed=1 tick=6 + AtMostThreeChildren: predicate returned false StateDiff: - $.Completed: 198 -> 200 - $.Pending: 0 -> -1 - Repro: .Seeds(4, 4).Ticks(426) + $.MaxChildren: 3 -> 4 + $.NodeCount: 6 -> 7 + Repro: .Seeds(1, 1).Ticks(6) ``` -In a test, call `report.ThrowIfFailed()` or use [EpochSim.Testing](testing.md). +`Project` cannot be combined with `Serializer`; both decide how the state is serialized. A projection is one way: it is used for fingerprints and diffs, not to restore state. -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`. +The determinism analyzer (rules ESIM001 to ESIM006) treats the lambdas passed to `Step` and `Invariant` as simulation code, like `AddSystem`: `new Random()`, `DateTime.Now` and the like are reported there. ## 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. | +| `Engine(Action>)` | one of `Engine` or `Step` | Registers systems and command handlers on a new engine. Called for every run. | +| `Step(Action)` | one of `Engine` or `Step` | Per-tick logic without writing a system. See above. | | `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. | +| `Invariant(string, Func)` | no | A named invariant. Can be repeated. | +| `Invariants(Func>>)` | no | Invariant classes. A factory, so every run gets its own instances. Checked before the `Invariant` predicates. | | `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. | +| `Project(Func)` | no | Alternative to `Serializer`: serialize a projection of the state. | | `Commands(Action)` | no | Generates input commands for a seed. See below. | +| `Shrink(bool)` | no | Minimize the commands of a failed seed. Default: `true` when `Commands` is set. | +| `OnlyCommands(IReadOnlyList)` | no | Keep only the commands with these indices of the generated plan. | | `CheckDeterminism(bool)` | no | Run every seed twice and compare fingerprints after every tick. Default: `false`. | +| `Name(string)` | no | Stable name of this suite in the failure store. Default: the full name of `TState`. | +| `FailureStore(string? path = null)` | no | Keep failing seeds in a file and replay them first. Default path: `epochsim-failures.json`. | | `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`. +Invalid values throw immediately: a missing required parameter, `Seeds` with `from > to`, `Ticks < 0`, `Parallelism < 1`, an empty `Name`, a negative index in `OnlyCommands`. ## 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 => +using EpochSim; +using EpochSim.Kernel.Messaging; + +var report = Epoch.Fuzz(f => f + .State(() => new Counter()) + .Engine(e => e.OnCommand((counter, command, _) => counter.Total += command.Amount)) + .Commands(plan => + { + for (var i = 0; i < 20; i++) + plan.Enqueue(plan.Rng.NextInt(0, (int)plan.EndTick + 1), new Add(plan.Rng.NextInt(1, 10))); + }) + .Invariant("TotalBelowLimit", counter => counter.Total < 100) + .Seeds(1, 10) + .Ticks(50)); + +Console.WriteLine(report.Passed); + +public sealed class Counter { - for (var i = 0; i < 20; i++) - plan.Enqueue(plan.Rng.NextInt(0, (int)plan.EndTick), new AddPopulation(plan.Rng.NextInt(1, 10))); -}) + public int Total { get; set; } +} + +public sealed record Add(int Amount) : ICommand; ``` -`Enqueue(tick, command)` accepts ticks from `0` to `plan.EndTick`. Commands are delivered through a `ScheduledCommandInbox`. +`Enqueue(tick, command)` accepts ticks from `0` to `plan.EndTick`. Commands are delivered through a `ScheduledCommandInbox`. The generator must be deterministic: it may use only `plan.Rng` and `plan.Seed`. The index of a command is its position in the order of `Enqueue` calls. ## Reading the report -`FuzzReport` has `Passed`, `SeedsRun`, `Duration`, `Failures`, `ToText()` and `ThrowIfFailed()`. `Failures` is always sorted by seed, whatever the `Parallelism`. +`FuzzReport` has `Passed`, `SeedsRun`, `Duration`, `Failures`, `NewFailures`, `KnownFailures`, `FixedSeeds`, `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`. +Every `FuzzFailure` carries the `Seed`, the `Kind`, the `Tick`, a `Summary`, the `StateDiff` for that tick, the `ArtifactsDir` (when `ArtifactsRoot` is set) and `ReproCode`. It also has the `Identity` (the invariant name, or the exception type) and the `Signature`, a 16-character hash of the kind and the identity that is the same for every seed that hits the same bug. `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"]`. @@ -87,12 +243,157 @@ Every `FuzzFailure` carries the `Seed`, the `Kind`, the `Tick`, a `Summary`, the Add the `ReproCode` to your `Epoch.Fuzz` call to narrow it to the failing seed: -```csharp -.Seeds(4, 4).Ticks(426) +```text +.Seeds(18, 18).Ticks(19) ``` 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. +When `Commands` is configured, `ReproCode` keeps the configured `Ticks`, not the failing tick: the command plan is generated for the configured length, and a different length may generate a different plan. It also carries `OnlyCommands` for a shrunk failure. + +## Shrinking + +A seed with `Commands` can carry hundreds of commands, and a failure rarely needs all of them. When a seed fails, EpochSim reduces its command plan to a minimal set that still fails, using delta debugging (ddmin). No maintained .NET library does this, so the algorithm is part of EpochSim. + +The `Account` sample of [src/EpochSim.Samples/Fuzzing](../../src/EpochSim.Samples/Fuzzing/) generates 300 deposits and withdrawals per seed and forgets to check the balance on withdrawal: + +```csharp +using EpochSim; +using EpochSim.Samples.Fuzzing; + +var report = Epoch.Fuzz(f => f + .State(() => new AccountState()) + .Engine(AccountLedger.Register) + .Invariants(() => [new BalanceNonNegativeInvariant()]) + .Commands(AccountLedger.PlanCommands) + .Seeds(1, 3) + .Ticks(500)); + +Console.WriteLine(report.Failures[0].ToText()); +``` + +```text +[InvariantViolation] seed=1 tick=489 + BalanceNonNegative: Balance=-7 + Commands: 300 -> 2 (shrunk in 13 attempts) + #4 tick 489: WithdrawCommand + #5 tick 157: WithdrawCommand + StateDiff: + $.Balance: 44 -> -7 + Repro: .Seeds(1, 1).Ticks(500).OnlyCommands([4, 5]) +``` + +Two of 300 commands are enough. The `StateDiff` belongs to the minimal scenario, and `ReproCode` replays exactly it: `OnlyCommands` keeps the commands with these indices of the generated plan, so the repro is code and needs no serialization of commands. + +How it works: + +- A candidate fails the same way when its `Kind` and its identity (the invariant name or the exception type) are the same. The failing tick may move, and that is fine. +- The search is deterministic: candidates are tried in a fixed order, with no randomness, and one failure is shrunk on one thread. The result does not depend on `Parallelism`. +- The budget is 1000 attempts or 10 seconds per failure. When it runs out, the best scenario found so far is returned; it still fails, and the report says that the budget was exhausted and the result may not be minimal. +- With `OnlyCommands` set by you, the search starts from your selection. + +What is not shrunk: + +- Without `Commands` there is nothing to shrink. The seed and the tick are already minimal, because a run stops at the first failure. `OriginalCommandCount` is `0` and `MinimalCommandIndices` is `null`. +- A `NonDeterminism` failure is not shrunk, because a smaller scenario cannot be checked against replays that disagree. The report says so (`ShrinkSkipReason`). +- Commands are removed, not moved to other ticks, and `Ticks` is not reduced: a repro must be expressible by `OnlyCommands`, and the plan depends on `Ticks`. + +`Shrink(false)` turns shrinking off. In the CLI, use `--no-shrink`. + +## Failure store + +A bug found once should be checked always: on your machine, in CI and on your colleagues' machines. `FailureStore()` keeps failing seeds in `epochsim-failures.json`, a file meant to be committed to git, like `.hypothesis/`: + +```csharp +using EpochSim; + +var report = Epoch.Fuzz(f => f + .Name("inventory") + .State(() => new Inventory()) + .Step((inventory, ctx) => inventory.Tick(ctx.Rng.AsRandom())) + .Invariant("StockNonNegative", inventory => inventory.Stock >= 0) + .Seeds(1, 1000) + .Ticks(500) + .FailureStore()); + +Console.WriteLine(report.ToText()); + +public sealed class Inventory +{ + public int Stock { get; private set; } = 5; + + public void Tick(Random random) + { + if (random.Next(0, 3) == 0) + Stock += 4; + + var demand = random.Next(0, 3); + if (Stock >= demand) + Stock -= demand; + + if (random.Next(0, 400) == 0) + Stock -= 5; + } +} +``` + +The first run writes the file. All 21 failing seeds hit the same bug, so they make one entry: the lowest seed with its tick, the other 20 seeds in `otherSeeds`, and a `signature`. The second run prints the same failures marked as known: + +```text +Fuzz failed: Failures=21 (new=0, known=21), SeedsRun=1000, ElapsedMs=145 + +Known failures: + +[InvariantViolation] seed=18 tick=19 (known) + StockNonNegative: predicate returned false + StateDiff: + $.Stock: 1 -> -2 + Repro: .Seeds(18, 18).Ticks(19) +``` + +How the store behaves: + +- `Name` identifies the suite in the file. The default is the full name of `TState`. Suites with different names do not touch each other's entries. +- The seeds stored for the suite run first, whatever `Seeds` says. A seed that is also in the range runs once. +- Entries are deduplicated by `Signature`: the kind plus the invariant name or exception type. A new seed with a known signature joins `otherSeeds`. +- The report separates new failures from known ones. `ThrowIfFailed` throws in both cases: a known bug is still a bug. +- When every seed of an entry passes, the entry is marked `fixed` and the report says `Previously failing seed 18 now passes.` once. Entries are never deleted automatically. A fixed entry keeps being replayed; if its bug comes back, it is reopened and reported as a new failure. +- A seed that was not run, for instance because of `StopAtFirstFailure`, does not count as passed. +- Writes are atomic (a temporary file, then a move) and serialized between threads and processes, so parallel test runs do not corrupt the file. The file is sorted, so the diffs in git stay small. +- The file has a `version`. A file written by a newer EpochSim is rejected with a message instead of being misread. A file that is not valid JSON is rejected and never overwritten. +- Without `FailureStore`, nothing is read or written. + +The `failures` command works on the file: + +```bash +epochsim failures list +epochsim failures prune +epochsim failures export-test --framework xunit --configure MyApp.InventoryFuzz.Configure --out tests/ +``` + +- `list` prints every entry, `prune` deletes the fixed ones. +- `export-test` writes one regression test per entry, for xunit, nunit or mstest. A configuration of a simulation contains lambdas and cannot be generated, so you point `--configure` at a `public static void Configure(FuzzBuilder)` method that builds the same simulation as your `Epoch.Fuzz` call, and the tests call it. If the store holds several suites, pass `--name`. The state type is read from the store; `--state-type` overrides it. + +For the store above, the generated `InventoryFuzzRegressionTests.cs` is: + +```text +using EpochSim.Testing; +using Xunit; + +namespace MyApp; + +public sealed class InventoryFuzzRegressionTests +{ + [Fact] + public void Seed18_StockNonNegative_AtTick19() + { + SimAssert.Regression(global::MyApp.InventoryFuzz.Configure, 18, 19); + } +} +``` + +The test fails until the bug is fixed and keeps guarding the fix afterwards. `SimAssert.Regression` and `SimAssert.StoredFailuresStayFixed` are described in [Testing](testing.md). + ## 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. @@ -115,24 +416,11 @@ epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500 | `--check-determinism` | off | Run every seed twice | | `--parallel N` | CPU count | Concurrent runs | | `--out dir` | `artifacts` | Artifacts directory for failed seeds | +| `--no-shrink` | off | Keep the full command plan of a failed seed | +| `--store path` | none | Record failures in a failure store, named after the adapter | -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. +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. `epochsim init` writes a starter project that already contains an `Epoch.Fuzz` call. ## 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. +Call `report.ThrowIfFailed()` from a test, or use `SimAssert` from [Testing](testing.md), with a large `Seeds` range and `.ArtifactsRoot("fuzz-artifacts")`. Upload `fuzz-artifacts` as a build artifact when the test fails. Commit `epochsim-failures.json`, so CI replays the seeds that failed on your machine, and the other way round. diff --git a/docs/en/testing.md b/docs/en/testing.md index 9855347..3391c32 100644 --- a/docs/en/testing.md +++ b/docs/en/testing.md @@ -18,6 +18,8 @@ It is a test dependency and is not part of `EpochSim.All`. | `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. | +| `SimAssert.Regression(configure, seed, ticks, commandIndices)` | Replays one recorded failure. Fails while the bug is present. | +| `SimAssert.StoredFailuresStayFixed(configure, storePath)` | Replays every failure of the suite recorded in a failure store. | `configure` is the same builder callback as in `Epoch.Fuzz`. A single seed is `Seeds(s, s)`. @@ -112,3 +114,22 @@ SimAssert.MatchesGolden( ``` 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. + +## Regression tests for found bugs + +A failure found by `Epoch.Fuzz` with `FailureStore()` is kept in `epochsim-failures.json` (see [Fuzzing](fuzzing.md#failure-store)). Two assertions turn it into a test. + +`SimAssert.Regression` replays one seed. It is a thin wrapper over `Epoch.Fuzz`: it applies `configure`, then restricts the run to `Seeds(seed, seed)` and `Ticks(ticks)`, turns shrinking and the failure store off, and applies `OnlyCommands(commandIndices)` when the indices are given. The values to pass are in the `Repro:` line of the report, or generated for you by `epochsim failures export-test`: + +```text +SimAssert.Regression(InventoryFuzz.Configure, 18, 19); +SimAssert.Regression(AccountFuzz.Configure, 1, 500, [4, 5]); +``` + +`SimAssert.StoredFailuresStayFixed` is one test that replays everything the store holds for the suite named by `configure` (`Name(...)`): the recorded scenario of every entry and the other seeds listed in it. It only reads the store and never marks anything as fixed, so it is safe in CI: + +```text +SimAssert.StoredFailuresStayFixed(InventoryFuzz.Configure, "epochsim-failures.json"); +``` + +A missing store file or a suite without entries passes. When a seed still fails, the exception carries the same report text as any other failed check. diff --git a/docs/ru/fuzzing.md b/docs/ru/fuzzing.md index c3c4b00..7cc982f 100644 --- a/docs/ru/fuzzing.md +++ b/docs/ru/fuzzing.md @@ -1,85 +1,241 @@ # Fuzzing -`Epoch.Fuzz` прогоняет симуляцию на диапазоне seed и показывает, какой seed её ломает, на каком тике и какие поля состояния изменились на этом тике. Находит три вида сбоев: +`Epoch.Fuzz` прогоняет ваш код на диапазоне seed и показывает, какой seed его ломает, на каком тике и какие поля состояния изменились на этом тике. Находит три вида сбоев: -- `InvariantViolation`: `IInvariant` вернул `false`. -- `Exception`: исключение из системы или обработчика команды. +- `InvariantViolation`: инвариант вернул `false`. +- `Exception`: исключение из системы, шага или обработчика команды. - `NonDeterminism`: два прогона одного seed дали разное состояние (нужен `CheckDeterminism`). -Любой сбой воспроизводится тем же seed. +Любой сбой воспроизводится тем же seed. Если симуляцию ведут команды, отчёт ещё и сокращает их до минимального сценария ([Шринкинг](#шринкинг)), а сбойные seed можно хранить в файле, чтобы найденный один раз баг проверялся всегда ([Хранилище сбоев](#хранилище-сбоев)). ## Минимальный пример +`Inventory` это обычный класс, который ничего не знает про EpochSim. `Step` вызывает его на каждом тике, `Invariant` говорит, что должно выполняться всегда, `Seeds` и `Ticks` задают объём перебора: + ```csharp using EpochSim; -var report = Epoch.Fuzz(f => f - .State(() => new JobQueueState()) - .Engine(e => e.AddSystem(new JobQueueSystem())) - .Invariants(() => [new QueueNonNegativeInvariant()]) +var report = Epoch.Fuzz(f => f + .State(() => new Inventory()) + .Step((inventory, ctx) => inventory.Tick(ctx.Rng.AsRandom())) + .Invariant("StockNonNegative", inventory => inventory.Stock >= 0) .Seeds(1, 1000) .Ticks(500)); Console.WriteLine(report.ToText()); + +public sealed class Inventory +{ + public int Stock { get; private set; } = 5; + + public void Tick(Random random) + { + if (random.Next(0, 3) == 0) + Stock += 4; + + var demand = random.Next(0, 3); + if (Stock >= demand) + Stock -= demand; + + if (random.Next(0, 400) == 0) + Stock -= 5; + } +} +``` + +Вывод (первый из 21 сбоя; `ElapsedMs` зависит от машины): + +```text +Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150 + +[InvariantViolation] seed=18 tick=19 + StockNonNegative: predicate returned false + StateDiff: + $.Stock: 1 -> -2 + Repro: .Seeds(18, 18).Ticks(19) +``` + +В тесте вызывайте `report.ThrowIfFailed()` или используйте [EpochSim.Testing](testing.md). Этот же класс лежит в [src/EpochSim.Samples/Onboarding](../../src/EpochSim.Samples/Onboarding/), и набор тестов прогоняет на нём вызов выше. + +## Подключение существующего кода + +Переносить код в системы, классы инвариантов и сериализуемое состояние не нужно. + +| Метод | Что делает | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------ | +| `Step(Action)` | Вызывается на каждом тике после систем, добавленных через `Engine`. Несколько шагов идут в порядке регистрации. | +| `Invariant(string, Func)` | Именованный инвариант, проверяется после каждого тика. Имя попадает в отчёт и в `Signature`. | +| `ctx.Rng.AsRandom()` | `System.Random` поверх детерминированного потока, для кода, который уже принимает `Random`. | +| `ctx.TimeProvider` | `TimeProvider` (`FakeTimeProvider`), стартует с `StepContext.ClockStart` и продвигается на `StepContext.TickDuration` (одну секунду) за тик. | +| `ctx.Tick` | Текущий тик. | +| `Project(Func)` | Часть состояния для fingerprint'ов и `StateDiff`, когда само состояние не сериализуется в JSON. | + +`AsRandom()` возвращает один адаптер на поток, так что вызов на каждом тике стоит поиска в таблице. Значения берутся из того же потока, что и `ctx.Rng`: для одного seed они одинаковы и никогда не читают системную энтропию. + +Код, который читает время, принимает `TimeProvider` вместо `DateTime.UtcNow`, и прогон остаётся детерминированным: + +```csharp +using EpochSim; + +var report = Epoch.Fuzz(f => f + .State(() => new Cache(TimeSpan.FromSeconds(5))) + .Step((cache, ctx) => + { + var random = ctx.Rng.AsRandom(); + var now = ctx.TimeProvider.GetUtcNow(); + cache.Get(random.Next(0, 20), now); + cache.Put(random.Next(0, 20), now); + if (cache.Count > 15) + cache.Evict(now); + }) + .Invariant("NeverServesStaleEntries", cache => cache.StaleHits == 0) + .CheckDeterminism() + .Seeds(1, 100) + .Ticks(200)); + +Console.WriteLine(report.Failures.Count > 0 ? report.Failures[0].ToText() : report.ToText()); + +public sealed class Cache(TimeSpan lifetime) +{ + private readonly Dictionary _storedAt = []; + + public int Count => _storedAt.Count; + public int StaleHits { get; private set; } + + public void Put(int key, DateTimeOffset now) => _storedAt[key] = now; + + public void Get(int key, DateTimeOffset now) + { + if (_storedAt.TryGetValue(key, out var storedAt) && now - storedAt > lifetime) + StaleHits++; + } + + public void Evict(DateTimeOffset now) + { + foreach (var key in _storedAt.Where(entry => now - entry.Value > lifetime).Select(entry => entry.Key).ToList()) + _storedAt.Remove(key); + } +} ``` -Вывод: +Состояние, которое не сериализуется в JSON (циклы, словари с ключами-объектами), заставляет сериализатор по умолчанию бросить исключение. `Project` заменяет его проекцией нужных полей: + +```csharp +using EpochSim; + +var report = Epoch.Fuzz(f => f + .State(() => new Graph()) + .Step((graph, ctx) => graph.Grow(ctx.Rng.AsRandom())) + .Project(graph => new { graph.NodeCount, graph.MaxChildren }) + .Invariant("AtMostThreeChildren", graph => graph.MaxChildren <= 3) + .CheckDeterminism() + .Seeds(1, 5) + .Ticks(100)); +Console.WriteLine(report.Failures[0].ToText()); + +public sealed class Graph +{ + private readonly List _nodes = []; + + public int NodeCount => _nodes.Count; + public int MaxChildren => _nodes.Count == 0 ? 0 : _nodes.Max(node => node.Children.Count); + public IReadOnlyList Nodes => _nodes; + + public void Grow(Random random) + { + var parent = _nodes.Count == 0 ? null : _nodes[random.Next(_nodes.Count)]; + var node = new Node(parent); + parent?.Children.Add(node); + _nodes.Add(node); + } +} + +public sealed class Node(Node? parent) +{ + public Node? Parent { get; } = parent; + public List Children { get; } = []; +} ``` -Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81 -[InvariantViolation] seed=4 tick=426 - QueueNonNegative: Pending=-1 +```text +[InvariantViolation] seed=1 tick=6 + AtMostThreeChildren: predicate returned false StateDiff: - $.Completed: 198 -> 200 - $.Pending: 0 -> -1 - Repro: .Seeds(4, 4).Ticks(426) + $.MaxChildren: 3 -> 4 + $.NodeCount: 6 -> 7 + Repro: .Seeds(1, 1).Ticks(6) ``` -В тесте вызывайте `report.ThrowIfFailed()` или используйте [EpochSim.Testing](testing.md). +`Project` нельзя сочетать с `Serializer`: оба определяют, как сериализуется состояние. Проекция односторонняя: она нужна для fingerprint'ов и диффов, а не для восстановления состояния. -Рабочий пример лежит в [src/EpochSim.Samples/Fuzzing](../../src/EpochSim.Samples/Fuzzing/): очередь задач, счётчик которой уходит в минус на редкой последовательности значений `ctx.Rng`, зависящей от seed. +Анализатор детерминизма (правила ESIM001-ESIM006) считает лямбды, переданные в `Step` и `Invariant`, кодом симуляции, как и в `AddSystem`: `new Random()`, `DateTime.Now` и подобное там отмечаются. ## Билдер | Метод | Обязателен | Смысл | | ----------------------------------------- | ---------- | ---------------------------------------------------------------------------------- | | `State(Func)` | да | Фабрика свежего начального состояния. Вызывается для каждого прогона. | -| `Engine(Action>)` | да | Регистрирует системы и обработчики команд на новом движке. Для каждого прогона. | +| `Engine(Action>)` | `Engine` или `Step` | Регистрирует системы и обработчики команд на новом движке. Для каждого прогона. | +| `Step(Action)` | `Engine` или `Step` | Логика на каждый тик без написания системы. См. выше. | | `Ticks(long)` | да | Последний тик каждого прогона, включительно. | | `Seeds(ulong from, ulong to)` | да | Диапазон seed, включительно. | | `Seeds(IEnumerable)` | да | Явный список seed. Используйте любую из двух перегрузок. | +| `Invariant(string, Func)` | нет | Именованный инвариант. Можно вызывать несколько раз. | +| `Invariants(Func>>)` | нет | Классы инвариантов. Фабрика: у каждого прогона свои экземпляры. Проверяются раньше предикатов `Invariant`. | | `Serializer(IStateSerializer)` | нет | Для fingerprint'ов и диффа. По умолчанию `JsonStateSerializer`. | -| `Invariants(Func>>)` | нет | Проверяются после каждого тика. Фабрика: у каждого прогона свои экземпляры. | +| `Project(Func)` | нет | Альтернатива `Serializer`: сериализовать проекцию состояния. | | `Commands(Action)` | нет | Генерирует входные команды для seed. См. ниже. | +| `Shrink(bool)` | нет | Сокращать команды сбойного seed. По умолчанию `true`, если задан `Commands`. | +| `OnlyCommands(IReadOnlyList)` | нет | Оставить только команды с этими индексами сгенерированного плана. | | `CheckDeterminism(bool)` | нет | Прогнать каждый seed дважды и сравнить fingerprint'ы после каждого тика. По умолчанию `false`. | +| `Name(string)` | нет | Стабильное имя набора в хранилище сбоев. По умолчанию полное имя `TState`. | +| `FailureStore(string? path = null)` | нет | Хранить сбойные seed в файле и запускать их первыми. Путь по умолчанию: `epochsim-failures.json`. | | `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`. +Неверные значения бросают исключение сразу: нет обязательного параметра, `Seeds` с `from > to`, `Ticks < 0`, `Parallelism < 1`, пустой `Name`, отрицательный индекс в `OnlyCommands`. ## Генерация команд `Commands` вызывается один раз на seed до начала прогона. `plan.Rng` это детерминированный поток, выведенный из seed. Он отделён от `ctx.Rng`, поэтому генерация команд не сдвигает случайность ваших систем. ```csharp -.Commands(plan => +using EpochSim; +using EpochSim.Kernel.Messaging; + +var report = Epoch.Fuzz(f => f + .State(() => new Counter()) + .Engine(e => e.OnCommand((counter, command, _) => counter.Total += command.Amount)) + .Commands(plan => + { + for (var i = 0; i < 20; i++) + plan.Enqueue(plan.Rng.NextInt(0, (int)plan.EndTick + 1), new Add(plan.Rng.NextInt(1, 10))); + }) + .Invariant("TotalBelowLimit", counter => counter.Total < 100) + .Seeds(1, 10) + .Ticks(50)); + +Console.WriteLine(report.Passed); + +public sealed class Counter { - for (var i = 0; i < 20; i++) - plan.Enqueue(plan.Rng.NextInt(0, (int)plan.EndTick), new AddPopulation(plan.Rng.NextInt(1, 10))); -}) + public int Total { get; set; } +} + +public sealed record Add(int Amount) : ICommand; ``` -`Enqueue(tick, command)` принимает тики от `0` до `plan.EndTick`. Команды доставляются через `ScheduledCommandInbox`. +`Enqueue(tick, command)` принимает тики от `0` до `plan.EndTick`. Команды доставляются через `ScheduledCommandInbox`. Генератор должен быть детерминированным: используйте только `plan.Rng` и `plan.Seed`. Индекс команды это её позиция в порядке вызовов `Enqueue`. ## Чтение отчёта -У `FuzzReport` есть `Passed`, `SeedsRun`, `Duration`, `Failures`, `ToText()` и `ThrowIfFailed()`. `Failures` всегда отсортирован по seed, независимо от `Parallelism`. +У `FuzzReport` есть `Passed`, `SeedsRun`, `Duration`, `Failures`, `NewFailures`, `KnownFailures`, `FixedSeeds`, `ToText()` и `ThrowIfFailed()`. `Failures` всегда отсортирован по seed, независимо от `Parallelism`. -Каждый `FuzzFailure` содержит `Seed`, `Kind`, `Tick`, `Summary`, `StateDiff` этого тика, `ArtifactsDir` (если задан `ArtifactsRoot`) и `ReproCode`. +Каждый `FuzzFailure` содержит `Seed`, `Kind`, `Tick`, `Summary`, `StateDiff` этого тика, `ArtifactsDir` (если задан `ArtifactsRoot`) и `ReproCode`. Также есть `Identity` (имя инварианта или тип исключения) и `Signature`: 16-символьный хэш вида сбоя и `Identity`, одинаковый для всех seed, которые попадают в один и тот же баг. `StateDiff` перечисляет поля, изменившиеся на сбойном тике: от конца предыдущего тика до сбойного состояния. Для `NonDeterminism` это поля, в которых два прогона различаются. Пути выглядят как `$.Population`, `$.Items[3].Count`, `$["a.b"]`. @@ -87,12 +243,157 @@ Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81 Добавьте `ReproCode` в вызов `Epoch.Fuzz`, чтобы сузить его до сбойного seed: -```csharp -.Seeds(4, 4).Ticks(426) +```text +.Seeds(18, 18).Ticks(19) ``` Прогон падает на том же тике. С `ArtifactsRoot` каталог `fuzz-` содержит ещё `manifest.json`, `statefp.jsonl`, отчёт о сбое и, при заданном `EventCodec`, лог событий, так что с ним работают `epochsim verify-run`, `bisect` и `repro`. +Если задан `Commands`, `ReproCode` сохраняет заданный `Ticks`, а не тик сбоя: план команд генерируется под заданную длину прогона, и другая длина может дать другой план. Для сокращённого сбоя в нём также есть `OnlyCommands`. + +## Шринкинг + +У seed с `Commands` могут быть сотни команд, а для сбоя редко нужны все. Когда seed падает, EpochSim сокращает его план команд до минимального набора, который всё ещё падает, методом delta debugging (ddmin). Поддерживаемой .NET-библиотеки для этого нет, поэтому алгоритм входит в EpochSim. + +Пример `Account` из [src/EpochSim.Samples/Fuzzing](../../src/EpochSim.Samples/Fuzzing/) генерирует на seed 300 пополнений и снятий и забывает проверять баланс при снятии: + +```csharp +using EpochSim; +using EpochSim.Samples.Fuzzing; + +var report = Epoch.Fuzz(f => f + .State(() => new AccountState()) + .Engine(AccountLedger.Register) + .Invariants(() => [new BalanceNonNegativeInvariant()]) + .Commands(AccountLedger.PlanCommands) + .Seeds(1, 3) + .Ticks(500)); + +Console.WriteLine(report.Failures[0].ToText()); +``` + +```text +[InvariantViolation] seed=1 tick=489 + BalanceNonNegative: Balance=-7 + Commands: 300 -> 2 (shrunk in 13 attempts) + #4 tick 489: WithdrawCommand + #5 tick 157: WithdrawCommand + StateDiff: + $.Balance: 44 -> -7 + Repro: .Seeds(1, 1).Ticks(500).OnlyCommands([4, 5]) +``` + +Двух команд из 300 достаточно. `StateDiff` относится к минимальному сценарию, а `ReproCode` воспроизводит именно его: `OnlyCommands` оставляет команды с этими индексами сгенерированного плана, поэтому репро это код и сериализация команд не нужна. + +Как это работает: + +- Кандидат падает так же, если совпадают `Kind` и идентичность (имя инварианта или тип исключения). Тик сбоя может сместиться, это нормально. +- Поиск детерминирован: кандидаты перебираются в фиксированном порядке без случайности, один сбой сокращается в одном потоке. Результат не зависит от `Parallelism`. +- Бюджет: 1000 попыток или 10 секунд на один сбой. Когда он исчерпан, возвращается лучший найденный сценарий. Он всё ещё падает, а отчёт сообщает, что бюджет исчерпан и результат может быть не минимальным. +- Если вы задали `OnlyCommands`, поиск начинается с вашей выборки. + +Что не сокращается: + +- Без `Commands` сокращать нечего. Seed и тик уже минимальны, потому что прогон останавливается на первом сбое. `OriginalCommandCount` равен `0`, а `MinimalCommandIndices` равен `null`. +- Сбой `NonDeterminism` не сокращается: меньший сценарий нельзя проверить, когда повторные прогоны расходятся. Отчёт говорит об этом (`ShrinkSkipReason`). +- Команды удаляются, но не переносятся на другие тики, и `Ticks` не уменьшается: репро должно выражаться через `OnlyCommands`, а план зависит от `Ticks`. + +`Shrink(false)` отключает шринкинг. В CLI используйте `--no-shrink`. + +## Хранилище сбоев + +Найденный один раз баг должен проверяться всегда: на вашей машине, в CI и у коллег. `FailureStore()` хранит сбойные seed в `epochsim-failures.json`: этот файл предназначен для коммита в git, как `.hypothesis/`: + +```csharp +using EpochSim; + +var report = Epoch.Fuzz(f => f + .Name("inventory") + .State(() => new Inventory()) + .Step((inventory, ctx) => inventory.Tick(ctx.Rng.AsRandom())) + .Invariant("StockNonNegative", inventory => inventory.Stock >= 0) + .Seeds(1, 1000) + .Ticks(500) + .FailureStore()); + +Console.WriteLine(report.ToText()); + +public sealed class Inventory +{ + public int Stock { get; private set; } = 5; + + public void Tick(Random random) + { + if (random.Next(0, 3) == 0) + Stock += 4; + + var demand = random.Next(0, 3); + if (Stock >= demand) + Stock -= demand; + + if (random.Next(0, 400) == 0) + Stock -= 5; + } +} +``` + +Первый запуск создаёт файл. Все 21 сбойных seed попадают в один баг, поэтому они дают одну запись: наименьший seed с его тиком, остальные 20 seed в `otherSeeds` и `signature`. Второй запуск печатает те же сбои с пометкой «известный»: + +```text +Fuzz failed: Failures=21 (new=0, known=21), SeedsRun=1000, ElapsedMs=145 + +Known failures: + +[InvariantViolation] seed=18 tick=19 (known) + StockNonNegative: predicate returned false + StateDiff: + $.Stock: 1 -> -2 + Repro: .Seeds(18, 18).Ticks(19) +``` + +Как ведёт себя хранилище: + +- `Name` идентифицирует набор в файле. По умолчанию это полное имя `TState`. Наборы с разными именами не трогают записи друг друга. +- Сохранённые seed набора запускаются первыми, что бы ни говорил `Seeds`. Seed, который есть и в диапазоне, запускается один раз. +- Записи дедуплицируются по `Signature`: вид сбоя плюс имя инварианта или тип исключения. Новый seed с известной сигнатурой добавляется в `otherSeeds`. +- Отчёт разделяет новые сбои и известные. `ThrowIfFailed` бросает в обоих случаях: известный баг остаётся багом. +- Когда проходят все seed записи, она помечается `fixed`, а отчёт один раз пишет `Previously failing seed 18 now passes.`. Записи не удаляются автоматически. Исправленная запись продолжает перепроигрываться; если баг вернётся, она откроется заново и сообщится как новый сбой. +- Seed, который не запускался, например из-за `StopAtFirstFailure`, прошедшим не считается. +- Запись атомарна (временный файл, затем перемещение) и сериализована между потоками и процессами, поэтому параллельные прогоны тестов не портят файл. Файл отсортирован, так что диффы в git остаются небольшими. +- У файла есть `version`. Файл, записанный более новым EpochSim, отклоняется с сообщением, а не читается неверно. Файл, который не является корректным JSON, отклоняется и никогда не перезаписывается. +- Без `FailureStore` ничего не читается и не пишется. + +С файлом работает команда `failures`: + +```bash +epochsim failures list +epochsim failures prune +epochsim failures export-test --framework xunit --configure MyApp.InventoryFuzz.Configure --out tests/ +``` + +- `list` печатает все записи, `prune` удаляет исправленные. +- `export-test` пишет по одному регрессионному тесту на запись для xunit, nunit или mstest. Конфигурацию симуляции с лямбдами сгенерировать нельзя, поэтому `--configure` указывает на метод `public static void Configure(FuzzBuilder)`, который строит ту же симуляцию, что и ваш вызов `Epoch.Fuzz`, а тесты вызывают его. Если в хранилище несколько наборов, укажите `--name`. Тип состояния берётся из хранилища; `--state-type` переопределяет его. + +Для хранилища выше сгенерированный `InventoryFuzzRegressionTests.cs` выглядит так: + +```text +using EpochSim.Testing; +using Xunit; + +namespace MyApp; + +public sealed class InventoryFuzzRegressionTests +{ + [Fact] + public void Seed18_StockNonNegative_AtTick19() + { + SimAssert.Regression(global::MyApp.InventoryFuzz.Configure, 18, 19); + } +} +``` + +Тест падает, пока баг не исправлен, и после исправления продолжает его охранять. `SimAssert.Regression` и `SimAssert.StoredFailuresStayFixed` описаны в [Testing](testing.md). + ## Проверка детерминизма `CheckDeterminism(true)` прогоняет каждый seed дважды и сравнивает fingerprint состояния после каждого тика. Ловит `static`-состояние, `DateTime.UtcNow`, `Random`, зависимость от порядка хэш-коллекций и всё остальное, из-за чего два прогона одного seed различаются. Прогоны не делят изменяемое состояние, кроме того, что делит ваш код, например `static`-полей: это и находит проверка. @@ -115,24 +416,11 @@ epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500 | `--check-determinism` | выкл. | Прогнать каждый seed дважды | | `--parallel N` | число CPU | Число одновременных прогонов | | `--out dir` | `artifacts` | Каталог артефактов для сбойных seed | +| `--no-shrink` | выкл. | Оставить полный план команд сбойного seed | +| `--store path` | нет | Записывать сбои в хранилище, имя набора совпадает с адаптером | -Код возврата `0`: сбоев нет. Код `2`: найдены сбои или неверные аргументы. CLI работает с адаптерами из `DomainAdapterRegistry`; в собственном коде основной вход это библиотечный API. +Код возврата `0`: сбоев нет. Код `2`: найдены сбои или неверные аргументы. CLI работает с адаптерами из `DomainAdapterRegistry`; в собственном коде основной вход это библиотечный API. `epochsim init` создаёт стартовый проект, в котором уже есть вызов `Epoch.Fuzz`. ## Запуск в 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` как артефакт сборки. +Вызывайте `report.ThrowIfFailed()` из теста или используйте `SimAssert` из [Testing](testing.md), с большим диапазоном `Seeds` и `.ArtifactsRoot("fuzz-artifacts")`. Если тест упал, загрузите `fuzz-artifacts` как артефакт сборки. Коммитьте `epochsim-failures.json`: тогда CI перепроигрывает seed, упавшие у вас, и наоборот. diff --git a/docs/ru/testing.md b/docs/ru/testing.md index 5c4b139..368945a 100644 --- a/docs/ru/testing.md +++ b/docs/ru/testing.md @@ -18,6 +18,8 @@ dotnet add package EpochSim.Testing | `SimAssert.InvariantsHold(configure)` | Инварианты, исключения и, если `configure` включает, детерминизм. | | `SimAssert.NoFailures(report)` | Бросает исключение, если в `FuzzReport` есть сбои. | | `SimAssert.MatchesGolden(configure, path, seed)` | Сравнивает fingerprint'ы одного seed с сохранённым файлом. | +| `SimAssert.Regression(configure, seed, ticks, commandIndices)` | Перепроигрывает один записанный сбой. Падает, пока баг есть. | +| `SimAssert.StoredFailuresStayFixed(configure, storePath)` | Перепроигрывает все сбои набора, записанные в хранилище сбоев. | `configure` это тот же билдер, что в `Epoch.Fuzz`. Один seed записывается как `Seeds(s, s)`. @@ -112,3 +114,22 @@ SimAssert.MatchesGolden( ``` Первый запуск создаёт файл. В нём fingerprint'ы состояния этого seed на каждом сотом тике и на последнем. Следующие запуски сравниваются с файлом и называют первый тик, на котором есть расхождение. После намеренного изменения запустите тесты один раз с `EPOCHSIM_UPDATE_GOLDEN=1`, чтобы перезаписать файл, и закоммитьте его. + +## Регрессионные тесты для найденных багов + +Сбой, найденный `Epoch.Fuzz` с `FailureStore()`, хранится в `epochsim-failures.json` (см. [Fuzzing](fuzzing.md#хранилище-сбоев)). Две проверки превращают его в тест. + +`SimAssert.Regression` перепроигрывает один seed. Это тонкая обёртка над `Epoch.Fuzz`: она применяет `configure`, затем ограничивает прогон `Seeds(seed, seed)` и `Ticks(ticks)`, отключает шринкинг и хранилище сбоев и применяет `OnlyCommands(commandIndices)`, если индексы заданы. Нужные значения есть в строке `Repro:` отчёта, а `epochsim failures export-test` генерирует вызовы за вас: + +```text +SimAssert.Regression(InventoryFuzz.Configure, 18, 19); +SimAssert.Regression(AccountFuzz.Configure, 1, 500, [4, 5]); +``` + +`SimAssert.StoredFailuresStayFixed` это один тест, который перепроигрывает всё, что хранилище содержит для набора, названного в `configure` (`Name(...)`): записанный сценарий каждой записи и остальные seed из неё. Он только читает хранилище и ничего не помечает исправленным, поэтому безопасен в CI: + +```text +SimAssert.StoredFailuresStayFixed(InventoryFuzz.Configure, "epochsim-failures.json"); +``` + +Если файла хранилища нет или у набора нет записей, тест проходит. Если seed всё ещё падает, исключение содержит тот же текст отчёта, что и любая другая упавшая проверка. diff --git a/tests/EpochSim.Determinism.Tests/DocumentationSnippetTests.cs b/tests/EpochSim.Determinism.Tests/DocumentationSnippetTests.cs new file mode 100644 index 0000000..46441a3 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/DocumentationSnippetTests.cs @@ -0,0 +1,196 @@ +using System.Reflection; +using System.Text.RegularExpressions; +using EpochSim; +using EpochSim.Samples.Fuzzing; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +[CollectionDefinition("Snippets", DisableParallelization = true)] +public sealed class SnippetsCollection; + +[Collection("Snippets")] +public sealed partial class DocumentationSnippetTests : IDisposable +{ + private const string ImplicitUsings = + "global using System; global using System.Collections.Generic; global using System.IO; " + + "global using System.Linq; global using System.Threading; global using System.Threading.Tasks;"; + + private static readonly string[] Documents = + [ + "README.md", + "README.ru.md", + "docs/en/fuzzing.md", + "docs/ru/fuzzing.md" + ]; + + private readonly string _workingDirectory = Path.Combine(Path.GetTempPath(), $"epochsim-snippet-{Guid.NewGuid():N}"); + private readonly string _originalDirectory = Directory.GetCurrentDirectory(); + + public DocumentationSnippetTests() + { + Directory.CreateDirectory(_workingDirectory); + Directory.SetCurrentDirectory(_workingDirectory); + } + + public void Dispose() + { + Directory.SetCurrentDirectory(_originalDirectory); + Directory.Delete(_workingDirectory, recursive: true); + } + + public static TheoryData Snippets() + { + var data = new TheoryData(); + + foreach (var document in Documents) + { + foreach (var snippet in ReadSnippets(document)) + data.Add(document, snippet.Number); + } + + return data; + } + + [Fact] + public void EveryDocumentHasSnippets() + { + foreach (var document in Documents) + Assert.NotEmpty(ReadSnippets(document)); + } + + [Fact] + public void EnglishAndRussianDocumentsHaveTheSameNumberOfSnippets() + { + Assert.Equal(ReadSnippets("README.md").Count, ReadSnippets("README.ru.md").Count); + Assert.Equal(ReadSnippets("docs/en/fuzzing.md").Count, ReadSnippets("docs/ru/fuzzing.md").Count); + } + + [Theory] + [MemberData(nameof(Snippets))] + public void Snippet_CompilesAndRuns(string document, int number) + { + var snippet = ReadSnippets(document).Single(candidate => candidate.Number == number); + var assembly = Compile(snippet, document); + + var entryPoint = assembly.EntryPoint + ?? throw new Xunit.Sdk.XunitException($"{document} snippet #{number} has no top-level statements to run."); + + var originalOut = Console.Out; + Console.SetOut(TextWriter.Null); + + try + { + var outcome = Record.Exception(() => Invoke(entryPoint)); + Assert.True(snippet.ExpectedException == outcome?.GetType().Name, outcome?.ToString()); + } + finally + { + Console.SetOut(originalOut); + } + } + + [Fact] + public void ReadmeFuzzSnippetFindsTheInventoryBugAndReportsTheFailingSeed() + { + var snippet = ReadSnippets("README.md").Single(candidate => candidate.ExpectedException == "FuzzFailedException"); + var assembly = Compile(snippet, "README.md"); + + var failure = Record.Exception(() => Invoke(assembly.EntryPoint!)); + + var exception = Assert.IsType(failure); + Assert.Contains("StockNonNegative", exception.Message, StringComparison.Ordinal); + Assert.Contains("Failures=21, SeedsRun=1000", exception.Message, StringComparison.Ordinal); + Assert.Contains( + "[InvariantViolation] seed=18 tick=19\n StockNonNegative: predicate returned false\n StateDiff:\n $.Stock: 1 -> -2\n Repro: .Seeds(18, 18).Ticks(19)", + exception.Message.ReplaceLineEndings("\n"), + StringComparison.Ordinal); + } + + [Theory] + [InlineData("docs/en/fuzzing.md")] + [InlineData("docs/ru/fuzzing.md")] + public void FuzzingDocument_ShowsTheRealOutputOfTheShrinkingExample(string document) + { + var report = Epoch.Fuzz(f => f + .State(() => new AccountState()) + .Engine(AccountLedger.Register) + .Invariants(() => [new BalanceNonNegativeInvariant()]) + .Commands(AccountLedger.PlanCommands) + .Seeds(1, 3) + .Ticks(500)); + + var documentText = File.ReadAllText(Path.Combine(RepositoryRoot(), document)).ReplaceLineEndings("\n"); + + Assert.Contains(report.Failures[0].ToText().ReplaceLineEndings("\n"), documentText, StringComparison.Ordinal); + } + + private static void Invoke(MethodInfo entryPoint) + { + try + { + entryPoint.Invoke(null, entryPoint.GetParameters().Length == 0 ? null : [Array.Empty()]); + } + catch (TargetInvocationException error) when (error.InnerException is { } inner) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(inner).Throw(); + } + } + + private static Assembly Compile(Snippet snippet, string document) + { + var references = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator) + .Select(path => MetadataReference.CreateFromFile(path)); + + var options = new CSharpParseOptions(LanguageVersion.Latest); + var compilation = CSharpCompilation.Create( + $"Snippet{Guid.NewGuid():N}", + [CSharpSyntaxTree.ParseText(snippet.Code, options), CSharpSyntaxTree.ParseText(ImplicitUsings, options)], + references, + new CSharpCompilationOptions(OutputKind.ConsoleApplication, nullableContextOptions: NullableContextOptions.Enable)); + + using var stream = new MemoryStream(); + var result = compilation.Emit(stream); + var errors = result.Diagnostics.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error).ToArray(); + Assert.True(result.Success, $"{document} snippet #{snippet.Number} does not compile:{Environment.NewLine}{string.Join(Environment.NewLine, errors.Select(error => error.ToString()))}"); + + return Assembly.Load(stream.ToArray()); + } + + private static List ReadSnippets(string relativePath) + { + var lines = File.ReadAllLines(Path.Combine(RepositoryRoot(), relativePath)); + var snippets = new List(); + + for (var i = 0; i < lines.Length; i++) + { + if (lines[i].Trim() != "```csharp") + continue; + + var end = Array.FindIndex(lines, i + 1, line => line.Trim() == "```"); + var marker = i > 0 ? ExpectationMarker().Match(lines[i - 1]) : Match.Empty; + snippets.Add(new Snippet( + snippets.Count + 1, + string.Join(Environment.NewLine, lines[(i + 1)..end]), + marker.Success ? marker.Groups["exception"].Value : null)); + i = end; + } + + return snippets; + } + + private static string RepositoryRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "EpochSim.slnx"))) + directory = directory.Parent; + + return directory?.FullName ?? throw new DirectoryNotFoundException("EpochSim.slnx was not found above the test binaries."); + } + + [GeneratedRegex(@"^$")] + private static partial Regex ExpectationMarker(); + + private sealed record Snippet(int Number, string Code, string? ExpectedException); +} From 8ad5fc5bead5955e099d4900a69a6641f62ee650 Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 12:55:32 +0300 Subject: [PATCH 07/10] chore: release 0.3.1 --- Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index fa9b122..02cc0f2 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 0.3.0 + 0.3.1 14.0 false false From 58cddddc46200446b33ef2a43f0433ce3e98bf56 Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 13:05:31 +0300 Subject: [PATCH 08/10] chore: update readme --- README.md | 300 +++--------------- README.ru.md | 296 +++-------------- docs/en/artifacts.md | 50 +++ docs/en/determinism.md | 1 + docs/en/embedding.md | 66 ++++ docs/en/sessions.md | 12 + docs/en/testing.md | 27 +- docs/ru/artifacts.md | 50 +++ docs/ru/determinism.md | 1 + docs/ru/embedding.md | 66 ++++ docs/ru/sessions.md | 12 + docs/ru/testing.md | 27 +- .../DocumentationFailureStoreTests.cs | 72 +++++ .../DocumentationSnippetTests.cs | 51 ++- .../InventoryFuzz.cs | 16 + 15 files changed, 509 insertions(+), 538 deletions(-) create mode 100644 tests/EpochSim.Determinism.Tests/DocumentationFailureStoreTests.cs create mode 100644 tests/EpochSim.Determinism.Tests/InventoryFuzz.cs diff --git a/README.md b/README.md index 4486bfb..ff31b16 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ # EpochSim -**A deterministic tick simulation engine for .NET 10.** -Run a simulation from a seed, record fingerprints and events, then verify, replay and bisect any run. +**Find the seed that breaks your simulation.** +A deterministic tick engine for .NET 10: fuzz by seed, replay any run, bisect to the first tick that diverges. **English** · [Русский](README.ru.md) @@ -13,64 +13,28 @@ Run a simulation from a seed, record fingerprints and events, then verify, repla -## Why EpochSim +A simulation that cannot be reproduced cannot be debugged. EpochSim fixes the inputs of every tick: the same seed and the same commands always produce the same state, and a divergence is located to a single tick. -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. +- **Seed fuzzing.** `Epoch.Fuzz` runs your code on thousands of seeds, names the failing seed and tick, and shows which state fields changed. Failures shrink to a minimal command scenario. - **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 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. +- **Replay and bisect.** Verify a run against recorded fingerprints and find the first tick where an invariant breaks. +- **Test-framework agnostic.** `SimAssert` works in xUnit, NUnit and MSTest and turns found bugs into regression tests. +- **Roslyn analyzer.** Flags wall-clock time, `Random`, threads and other sources of non-determinism in simulation code. +- **CLI.** Run, inspect, verify, replay, bisect and fuzz from the terminal. ## Installation ```bash dotnet add package EpochSim -``` - -Requires .NET 10. `EpochSim.All` brings the full module graph (`EpochSim`, `Execution`, `Serialization`, `Observability`, `Kernel`) as a single dependency: - -```bash -dotnet add package EpochSim.All -``` - -The command-line tool is installed separately: - -```bash +dotnet add package EpochSim.Testing dotnet tool install --global EpochSim.Cli ``` -## Quick start +Requires .NET 10. `EpochSim.All` brings the whole module graph as a single dependency. -```csharp -using EpochSim; +## Find a bug by seed -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -engine.AddSystem("World", tick: ctx => ctx.State.Population++); - -using var run = Epoch.QuickRun(state, rootDir: "artifacts"); -run.RunTicks(engine, seed: 1, endTickInclusive: 100); - -Console.WriteLine(state.Population); - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` - -Always call `run.RunTicks(engine, ...)` rather than `engine.RunTicks(state, ...)`, so the state passed in is the one the run scope was built with. - -More in [Embedding](docs/en/embedding.md). - -## Find bugs by seed - -`Epoch.Fuzz` runs your code on a range of seeds and checks invariants, exceptions and, optionally, determinism. Existing code needs no rewrite: call it from `Step`, state what must always hold in `Invariant` and pick the seeds. `ctx.Rng.AsRandom()` hands code that takes a `System.Random` a deterministic stream. +`Epoch.Fuzz` needs no rewrite of existing code. Call it from `Step`, state what must always hold in `Invariant`, pick the seeds. ```csharp @@ -104,7 +68,7 @@ public sealed class Inventory } ``` -`Inventory` is an ordinary class with no reference to EpochSim. The run finds the seeds on which its stock goes negative, and names the tick and the state fields that changed: +The run finds the seeds on which the stock goes negative and names the tick and the state fields that changed: ```text Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150 @@ -118,69 +82,10 @@ Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150 ... ``` -Add `.Seeds(18, 18).Ticks(19)` from the `Repro` line to your call to run only that failure. When commands drive the simulation, `Commands(...)` failures are shrunk to a minimal scenario, `FailureStore()` keeps failing seeds in a file you commit, and `epochsim failures export-test` turns them into regression tests. Add `.CheckDeterminism()` to run every seed twice and catch `static` state, wall-clock time and other sources of non-determinism. The same search 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 -using EpochSim.Testing; - -SimAssert.IsDeterministic(f => f - .State(() => new WorldState()) - .Step((world, _) => world.Population++) - .Seeds(1, 50) - .Ticks(200)); - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` - -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 | -| ---------------- | ------------------- | -------------- | ------------------------------ | -| `QuickRun` | every tick | No | First use, CI smoke test | -| `RecommendedRun` | every 50 ticks | No | Production diagnostics | -| `DebugRun` | every tick | Yes | Invariant hunting, strict mode | - -```csharp -using EpochSim; - -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -engine.AddSystem("World", tick: ctx => ctx.State.Population++); - -using var quick = Epoch.QuickRun(state, rootDir: "artifacts"); -quick.RunTicks(engine, seed: 1, endTickInclusive: 100); - -using var recommended = Epoch.RecommendedRun(state, rootDir: "artifacts"); -recommended.RunTicks(engine, seed: 1, endTickInclusive: 1000); - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` +Add `.Seeds(18, 18).Ticks(19)` from the `Repro` line to run only that failure. More in [Fuzzing](docs/en/fuzzing.md). -The mutation guard serializes the state before and after each system and throws `InvalidOperationException` when the fingerprint changes. It finds systems that mutate state outside event handlers, at a significant serialization cost: use it in `DebugRun` only. The system above changes `Population` directly, so `DebugRun` rejects it with the tick and the system name: +## Run a simulation - ```csharp using EpochSim; @@ -188,91 +93,10 @@ var state = new WorldState(); var engine = Epoch.CreateEngine(); engine.AddSystem("World", tick: ctx => ctx.State.Population++); -using var debug = Epoch.DebugRun(state, rootDir: "artifacts"); -debug.RunTicks(engine, seed: 1, endTickInclusive: 200); - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` - -For full control use `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` or `EpochSimRun.For(state)...Build()`. - -## Event log and artifacts - -The event log is optional and required for `verify-run`, `bisect` and `fast-replay`. Artifacts are plain files in the run directory and can be read in-process: - -```csharp -using EpochSim; -using EpochSim.Execution.RunArtifacts; -using EpochSim.Execution.StateFingerprint; -using EpochSim.Kernel.Messaging; -using EpochSim.Serialization.EventLog; - -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -var inbox = new ScheduledCommandInbox(); -engine.AttachScheduledInbox(inbox); -engine.OnCommand((world, command, events) => -{ - world.Population += command.Delta; - events.Emit(new Changed(command.Delta)); -}); -inbox.Enqueue(5, new AddPopulation(3)); - -var codec = Epoch.JsonCodecFromAssembly(type => type == typeof(Changed)); -var serializer = Epoch.JsonStateSerializer(); - -string runDir; -using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts")) -{ - run.RunTicks(engine, seed: 1, endTickInclusive: 100); - runDir = run.Paths.RunDir; -} - -var manifest = RunManifestReader.TryRead(Path.Combine(runDir, "manifest.json")); -var fingerprints = JsonlStateFingerprintWriter.ReadAll(Path.Combine(runDir, "statefp.jsonl")); -var entries = EventLogReader.ReadAll(Path.Combine(runDir, "events.jsonl")); - -Console.WriteLine($"EndTick={manifest?.EndTick}, fingerprints={fingerprints.Count}, events={entries.Count}"); - -[MessageKind("AddPopulation")] -public sealed record AddPopulation(int Delta) : ICommand; - -[MessageKind("Changed")] -public sealed record Changed(int Delta) : IEvent; - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` - -Layout and formats are described in [Artifacts](docs/en/artifacts.md). - -## Sessions and external input - -`RunTicks` fits batch jobs. `SimulationSession` fits long-lived loops: - -```csharp -using EpochSim; -using EpochSim.Kernel.Messaging; - -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -engine.OnCommand((world, command, _) => world.Population += command.Delta); - -var inbox = new CommandInbox(); -engine.AttachInbox(inbox); - -using var session = engine.CreateSession(state, seed: 1, startTick: 0); -inbox.Enqueue(new AddPopulation(5)); -session.TickOnce(); -session.RunUntil(100); +using var run = Epoch.QuickRun(state, rootDir: "artifacts"); +run.RunTicks(engine, seed: 1, endTickInclusive: 100); -[MessageKind("AddPopulation")] -public sealed record AddPopulation(int Delta) : ICommand; +Console.WriteLine(state.Population); public sealed class WorldState { @@ -280,31 +104,18 @@ public sealed class WorldState } ``` -Inboxes feed external commands into the simulation thread deterministically: +Presets, external input, sessions and artifacts are covered in [Embedding](docs/en/embedding.md). -- `CommandInbox`: commands for the next tick. -- `ScheduledCommandInbox`: commands for a specific tick, ordered by tick ascending, then by insertion order. +## Test it ```csharp -using EpochSim; -using EpochSim.Kernel.Messaging; - -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -engine.OnCommand((world, command, _) => world.Population += command.Delta); - -var scheduled = new ScheduledCommandInbox(); -engine.AttachScheduledInbox(scheduled); - -scheduled.Enqueue(10, new AddPopulation(3)); -scheduled.Enqueue(10, new AddPopulation(7)); -scheduled.Enqueue(12, new AddPopulation(1)); - -using var session = engine.CreateSession(state, seed: 1, startTick: 0); -session.RunUntil(100); +using EpochSim.Testing; -[MessageKind("AddPopulation")] -public sealed record AddPopulation(int Delta) : ICommand; +SimAssert.IsDeterministic(f => f + .State(() => new WorldState()) + .Step((world, _) => world.Population++) + .Seeds(1, 50) + .Ticks(200)); public sealed class WorldState { @@ -312,66 +123,31 @@ public sealed class WorldState } ``` -More in [Sessions](docs/en/sessions.md). +A failure names the seed, the tick and the changed state fields. More in [Testing](docs/en/testing.md). ## Command line ```bash -epochsim init . -epochsim run artifacts -epochsim list-runs artifacts -epochsim inspect-run artifacts -``` - -Determinism debugging: - -```bash +epochsim fuzz --adapter fuzzbug --seeds 1..1000 epochsim verify-run artifacts epochsim bisect artifacts -epochsim fuzz --adapter fuzzbug --seeds 1..1000 epochsim failures list ``` -| Command | Purpose | -| -------------------------------------------------- | ------------------------------------------ | -| `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 violation | -| `fuzz`, `failures` | Find the seed that breaks, manage stored failures | -| `event-stats`, `timeline`, `list-adapters` | Analyze events and list available adapters | - -## What is included - -| Area | Highlights | -| ------------- | ----------------------------------------------------------------------------- | -| Engine | Ordered systems, seeded runs, tick and session execution. | -| Presets | `QuickRun`, `RecommendedRun`, `DebugRun`, builder for custom setups. | -| 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, 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, shrinking, failure store, regression tests. | -| CLI | `epochsim` .NET tool covering the whole run lifecycle. | - ## Documentation -| | | -| --------------------------------- | ---------------------------------------------------- | -| [Embedding](docs/en/embedding.md) | Integration recipes: hosts, servers, external input | -| [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 +| Guide | Contents | +| -------------------------------------- | --------------------------------------------------- | +| [Embedding](docs/en/embedding.md) | Presets, hosts, servers, external input | +| [Fuzzing](docs/en/fuzzing.md) | Seeds, shrinking, failure store, CLI, CI | +| [Testing](docs/en/testing.md) | `SimAssert`, golden fingerprints, regression tests | +| [Determinism](docs/en/determinism.md) | Rules and the analyzer ESIM001-ESIM006 | +| [Sessions](docs/en/sessions.md) | Long-lived loops and stepping | +| [Artifacts](docs/en/artifacts.md) | Run directory layout and file formats | -[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. [Onboarding](src/EpochSim.Samples/Onboarding/) holds the `Inventory` class from the fuzzing example. [Fuzzing](src/EpochSim.Samples/Fuzzing/) has rare seed-dependent and command-dependent bugs for `Epoch.Fuzz` to find. +Runnable examples are in [src/EpochSim.Samples](src/EpochSim.Samples). -## Build and test +## Development ```bash dotnet build EpochSim.slnx -m:1 diff --git a/README.ru.md b/README.ru.md index 0ac3447..84992c1 100644 --- a/README.ru.md +++ b/README.ru.md @@ -2,8 +2,8 @@ # EpochSim -**Детерминированный движок тиковых симуляций для .NET 10.** -Запускайте симуляцию по seed, записывайте fingerprint'ы и события, затем проверяйте, воспроизводите и бисектите любой прогон. +**Найдите seed, на котором ломается ваша симуляция.** +Детерминированный движок тиковых симуляций для .NET 10: фаззинг по seed, воспроизведение любого прогона и бисект до первого расходящегося тика. [English](README.md) · **Русский** @@ -13,64 +13,28 @@ -## Зачем нужен EpochSim - Симуляцию, которую нельзя воспроизвести, нельзя отладить. EpochSim фиксирует входы каждого тика: один и тот же seed и те же команды всегда дают то же состояние, а расхождение локализуется до одного тика. -- **Поиск seed, на котором ломается логика.** `Epoch.Fuzz` прогоняет симуляцию на тысячах seed, возвращает сбойный seed и тик и показывает, какие поля состояния изменились. +- **Фаззинг по seed.** `Epoch.Fuzz` прогоняет ваш код на тысячах seed, называет сбойный seed и тик и показывает, какие поля состояния изменились. Сбои сокращаются до минимального сценария команд. - **Детерминизм по построению.** Прогон определяется состоянием, seed и упорядоченным входом. Системы выполняются в фиксированном порядке в одном потоке симуляции. -- **Пресеты запуска.** `QuickRun`, `RecommendedRun` и `DebugRun` закрывают smoke-тесты, диагностику в production и строгий поиск нарушений инвариантов одним вызовом. -- **Артефакты каждого прогона.** Манифест, fingerprint'ы состояния по тикам и необязательный лог событий пишутся на диск и читаются из кода. - **Replay и bisect.** Проверка прогона по записанным fingerprint'ам и поиск первого тика, на котором нарушается инвариант. -- **Детерминированный ввод.** `CommandInbox` и `ScheduledCommandInbox` передают команды из HTTP, UI или очередей в стабильном порядке. -- **Долгоживущие сессии.** `SimulationSession` для игр, серверов и пошагового режима. -- **CLI для всего процесса.** Запуск, список, инспекция, валидация, replay, bisect и воспроизведение прогонов из терминала. +- **Любой тестовый фреймворк.** `SimAssert` работает в xUnit, NUnit и MSTest и превращает найденные баги в регрессионные тесты. +- **Roslyn-анализатор.** Находит в коде симуляции системное время, `Random`, потоки и другие источники недетерминизма. +- **CLI.** Запуск, инспекция, проверка, replay, bisect и фаззинг из терминала. ## Установка ```bash dotnet add package EpochSim -``` - -Требуется .NET 10. `EpochSim.All` приносит весь граф модулей (`EpochSim`, `Execution`, `Serialization`, `Observability`, `Kernel`) одной зависимостью: - -```bash -dotnet add package EpochSim.All -``` - -Утилита командной строки ставится отдельно: - -```bash +dotnet add package EpochSim.Testing dotnet tool install --global EpochSim.Cli ``` -## Быстрый старт +Требуется .NET 10. `EpochSim.All` приносит весь граф модулей одной зависимостью. -```csharp -using EpochSim; +## Найдите баг по seed -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -engine.AddSystem("World", tick: ctx => ctx.State.Population++); - -using var run = Epoch.QuickRun(state, rootDir: "artifacts"); -run.RunTicks(engine, seed: 1, endTickInclusive: 100); - -Console.WriteLine(state.Population); - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` - -Всегда вызывайте `run.RunTicks(engine, ...)`, а не `engine.RunTicks(state, ...)`: так передаётся тот же state, с которым создан run scope. - -Подробнее в [Embedding](docs/ru/embedding.md). - -## Поиск багов по seed - -`Epoch.Fuzz` прогоняет ваш код на диапазоне seed и проверяет инварианты, исключения и, по желанию, детерминизм. Переписывать существующий код не нужно: вызовите его из `Step`, опишите в `Invariant`, что должно выполняться всегда, и задайте seed. `ctx.Rng.AsRandom()` отдаёт коду, принимающему `System.Random`, детерминированный поток. +`Epoch.Fuzz` не требует переписывать существующий код. Вызовите его из `Step`, опишите в `Invariant`, что должно выполняться всегда, и задайте seed. ```csharp @@ -104,7 +68,7 @@ public sealed class Inventory } ``` -`Inventory` это обычный класс без ссылок на EpochSim. Прогон находит seed, на которых остаток уходит в минус, и называет тик и изменившиеся поля состояния: +Прогон находит seed, на которых остаток уходит в минус, и называет тик и изменившиеся поля состояния: ```text Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150 @@ -118,69 +82,10 @@ Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150 ... ``` -Добавьте `.Seeds(18, 18).Ticks(19)` из строки `Repro` в свой вызов, чтобы прогнать только этот сбой. Если симуляцию ведут команды, сбои при `Commands(...)` сокращаются до минимального сценария, `FailureStore()` хранит сбойные seed в файле, который вы коммитите, а `epochsim failures export-test` превращает их в регрессионные тесты. `.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 -using EpochSim.Testing; - -SimAssert.IsDeterministic(f => f - .State(() => new WorldState()) - .Step((world, _) => world.Population++) - .Seeds(1, 50) - .Ticks(200)); - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` - -Сообщение о сбое называет seed, тик и изменившиеся поля состояния. Подробнее в [Testing](docs/ru/testing.md). - -## Пресеты запуска - -| Пресет | Каденция fingerprint | Mutation guard | Когда использовать | -| ---------------- | -------------------- | -------------- | --------------------------------- | -| `QuickRun` | каждый тик | Нет | Первый запуск, CI smoke | -| `RecommendedRun` | каждые 50 тиков | Нет | Диагностика в production | -| `DebugRun` | каждый тик | Да | Поиск инвариантов, строгий режим | - -```csharp -using EpochSim; - -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -engine.AddSystem("World", tick: ctx => ctx.State.Population++); - -using var quick = Epoch.QuickRun(state, rootDir: "artifacts"); -quick.RunTicks(engine, seed: 1, endTickInclusive: 100); - -using var recommended = Epoch.RecommendedRun(state, rootDir: "artifacts"); -recommended.RunTicks(engine, seed: 1, endTickInclusive: 1000); - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` +Добавьте `.Seeds(18, 18).Ticks(19)` из строки `Repro` в свой вызов, чтобы прогнать только этот сбой. Подробнее в [Fuzzing](docs/ru/fuzzing.md). -Mutation guard сериализует state до и после каждой системы и бросает `InvalidOperationException`, если fingerprint изменился. Он находит системы, меняющие state вне обработчиков событий, но заметно замедляет прогон: используйте его только в `DebugRun`. Система выше меняет `Population` напрямую, поэтому `DebugRun` отклоняет её, называя тик и систему: +## Запуск симуляции - ```csharp using EpochSim; @@ -188,91 +93,10 @@ var state = new WorldState(); var engine = Epoch.CreateEngine(); engine.AddSystem("World", tick: ctx => ctx.State.Population++); -using var debug = Epoch.DebugRun(state, rootDir: "artifacts"); -debug.RunTicks(engine, seed: 1, endTickInclusive: 200); - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` - -Для полного контроля: `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` или `EpochSimRun.For(state)...Build()`. - -## Лог событий и артефакты - -Лог событий необязателен и нужен для `verify-run`, `bisect` и `fast-replay`. Артефакты лежат обычными файлами в каталоге прогона и читаются из кода: - -```csharp -using EpochSim; -using EpochSim.Execution.RunArtifacts; -using EpochSim.Execution.StateFingerprint; -using EpochSim.Kernel.Messaging; -using EpochSim.Serialization.EventLog; - -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -var inbox = new ScheduledCommandInbox(); -engine.AttachScheduledInbox(inbox); -engine.OnCommand((world, command, events) => -{ - world.Population += command.Delta; - events.Emit(new Changed(command.Delta)); -}); -inbox.Enqueue(5, new AddPopulation(3)); - -var codec = Epoch.JsonCodecFromAssembly(type => type == typeof(Changed)); -var serializer = Epoch.JsonStateSerializer(); - -string runDir; -using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts")) -{ - run.RunTicks(engine, seed: 1, endTickInclusive: 100); - runDir = run.Paths.RunDir; -} - -var manifest = RunManifestReader.TryRead(Path.Combine(runDir, "manifest.json")); -var fingerprints = JsonlStateFingerprintWriter.ReadAll(Path.Combine(runDir, "statefp.jsonl")); -var entries = EventLogReader.ReadAll(Path.Combine(runDir, "events.jsonl")); - -Console.WriteLine($"EndTick={manifest?.EndTick}, fingerprints={fingerprints.Count}, events={entries.Count}"); - -[MessageKind("AddPopulation")] -public sealed record AddPopulation(int Delta) : ICommand; - -[MessageKind("Changed")] -public sealed record Changed(int Delta) : IEvent; - -public sealed class WorldState -{ - public int Population { get; set; } -} -``` - -Структура и форматы описаны в [Artifacts](docs/ru/artifacts.md). - -## Сессии и внешний ввод - -`RunTicks` подходит для batch-прогонов. `SimulationSession` подходит для долгоживущих циклов: - -```csharp -using EpochSim; -using EpochSim.Kernel.Messaging; - -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -engine.OnCommand((world, command, _) => world.Population += command.Delta); - -var inbox = new CommandInbox(); -engine.AttachInbox(inbox); - -using var session = engine.CreateSession(state, seed: 1, startTick: 0); -inbox.Enqueue(new AddPopulation(5)); -session.TickOnce(); -session.RunUntil(100); +using var run = Epoch.QuickRun(state, rootDir: "artifacts"); +run.RunTicks(engine, seed: 1, endTickInclusive: 100); -[MessageKind("AddPopulation")] -public sealed record AddPopulation(int Delta) : ICommand; +Console.WriteLine(state.Population); public sealed class WorldState { @@ -280,31 +104,18 @@ public sealed class WorldState } ``` -Inbox'ы детерминированно передают внешние команды в поток симуляции: +Пресеты, внешний ввод, сессии и артефакты описаны в [Embedding](docs/ru/embedding.md). -- `CommandInbox`: команды на ближайший тик. -- `ScheduledCommandInbox`: команды на заданный тик, порядок: сначала тик по возрастанию, затем порядок добавления. +## Тесты ```csharp -using EpochSim; -using EpochSim.Kernel.Messaging; - -var state = new WorldState(); -var engine = Epoch.CreateEngine(); -engine.OnCommand((world, command, _) => world.Population += command.Delta); - -var scheduled = new ScheduledCommandInbox(); -engine.AttachScheduledInbox(scheduled); - -scheduled.Enqueue(10, new AddPopulation(3)); -scheduled.Enqueue(10, new AddPopulation(7)); -scheduled.Enqueue(12, new AddPopulation(1)); - -using var session = engine.CreateSession(state, seed: 1, startTick: 0); -session.RunUntil(100); +using EpochSim.Testing; -[MessageKind("AddPopulation")] -public sealed record AddPopulation(int Delta) : ICommand; +SimAssert.IsDeterministic(f => f + .State(() => new WorldState()) + .Step((world, _) => world.Population++) + .Seeds(1, 50) + .Ticks(200)); public sealed class WorldState { @@ -312,66 +123,31 @@ public sealed class WorldState } ``` -Подробнее в [Sessions](docs/ru/sessions.md). +Сообщение о сбое называет seed, тик и изменившиеся поля состояния. Подробнее в [Testing](docs/ru/testing.md). ## Командная строка ```bash -epochsim init . -epochsim run artifacts -epochsim list-runs artifacts -epochsim inspect-run artifacts -``` - -Отладка детерминизма: - -```bash +epochsim fuzz --adapter fuzzbug --seeds 1..1000 epochsim verify-run artifacts epochsim bisect artifacts -epochsim fuzz --adapter fuzzbug --seeds 1..1000 epochsim failures list ``` -| Команда | Назначение | -| -------------------------------------------- | ----------------------------------------------- | -| `init`, `run` | Создать стартовое приложение, запустить его | -| `list-runs`, `inspect-run`, `pretty-inspect` | Просмотр и инспекция записанных прогонов | -| `validate-run`, `verify-run` | Проверка артефактов и fingerprint'ов | -| `fast-replay`, `bisect`, `repro` | Replay прогона, поиск первого нарушения | -| `fuzz`, `failures` | Поиск сбойного seed, сохранённые сбои | -| `event-stats`, `timeline`, `list-adapters` | Анализ событий и список доступных адаптеров | - -## Состав - -| Область | Возможности | -| ------------- | ------------------------------------------------------------------------------ | -| Движок | Упорядоченные системы, прогоны по seed, выполнение по тикам и сессиям. | -| Пресеты | `QuickRun`, `RecommendedRun`, `DebugRun`, builder для своих конфигураций. | -| Ввод | `CommandInbox`, `ScheduledCommandInbox` со стабильным порядком. | -| Артефакты | Манифест, fingerprint'ы состояния, лог событий, артефакты сбоев, профилирование. | -| Сериализация | JSON-сериализатор состояния и кодек сообщений, находимых в сборке. | -| Диагностика | Mutation guard, инварианты, проверка replay, bisect, полевой дифф состояния. | -| Анализатор | Roslyn-правила ESIM001-ESIM006 ловят системное время, `Random`, потоки и другое в коде симуляции. | -| Тестирование | `EpochSim.Testing`: `SimAssert` для любого тестового фреймворка, золотые fingerprint'ы. | -| Fuzzing | `Epoch.Fuzz`: диапазоны seed, инварианты, проверка детерминизма, шринкинг, хранилище сбоев, регрессионные тесты. | -| CLI | .NET-утилита `epochsim` для всего жизненного цикла прогона. | - ## Документация -| | | -| ---------------------------------- | ------------------------------------------------------ | -| [Embedding](docs/ru/embedding.md) | Рецепты интеграции: хосты, серверы, внешний ввод | -| [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 | - -## Примеры +| Руководство | Содержание | +| -------------------------------------- | --------------------------------------------------- | +| [Embedding](docs/ru/embedding.md) | Пресеты, хосты, серверы, внешний ввод | +| [Fuzzing](docs/ru/fuzzing.md) | Seed, шринкинг, хранилище сбоев, CLI, CI | +| [Testing](docs/ru/testing.md) | `SimAssert`, золотые fingerprint'ы, регрессионные тесты | +| [Determinism](docs/ru/determinism.md) | Правила и анализатор ESIM001-ESIM006 | +| [Sessions](docs/ru/sessions.md) | Долгоживущие циклы и пошаговый режим | +| [Artifacts](docs/ru/artifacts.md) | Структура каталога прогона и форматы файлов | -[QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs) — минимальная отправная точка. [Population](src/EpochSim.Samples/Population/) — событийный домен с инвариантами и replay. [Onboarding](src/EpochSim.Samples/Onboarding/) — класс `Inventory` из примера поиска багов. [Fuzzing](src/EpochSim.Samples/Fuzzing/) — редкие баги, зависящие от seed и от команд, для поиска через `Epoch.Fuzz`. +Запускаемые примеры лежат в [src/EpochSim.Samples](src/EpochSim.Samples). -## Сборка и тесты +## Разработка ```bash dotnet build EpochSim.slnx -m:1 diff --git a/docs/en/artifacts.md b/docs/en/artifacts.md index 3126df2..65a3ed0 100644 --- a/docs/en/artifacts.md +++ b/docs/en/artifacts.md @@ -36,3 +36,53 @@ Written when a run fails: ## Finalization `manifest.json` and `meta.txt` are finalized in `EpochSimRunScope.Dispose()`. Dispose the run scope before reading them. + +## Reading artifacts from code + +Artifacts are plain files in the run directory and can be read in-process. The event log is optional and required for `verify-run`, `bisect` and `fast-replay`: + +```csharp +using EpochSim; +using EpochSim.Execution.RunArtifacts; +using EpochSim.Execution.StateFingerprint; +using EpochSim.Kernel.Messaging; +using EpochSim.Serialization.EventLog; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +var inbox = new ScheduledCommandInbox(); +engine.AttachScheduledInbox(inbox); +engine.OnCommand((world, command, events) => +{ + world.Population += command.Delta; + events.Emit(new Changed(command.Delta)); +}); +inbox.Enqueue(5, new AddPopulation(3)); + +var codec = Epoch.JsonCodecFromAssembly(type => type == typeof(Changed)); +var serializer = Epoch.JsonStateSerializer(); + +string runDir; +using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts")) +{ + run.RunTicks(engine, seed: 1, endTickInclusive: 100); + runDir = run.Paths.RunDir; +} + +var manifest = RunManifestReader.TryRead(Path.Combine(runDir, "manifest.json")); +var fingerprints = JsonlStateFingerprintWriter.ReadAll(Path.Combine(runDir, "statefp.jsonl")); +var entries = EventLogReader.ReadAll(Path.Combine(runDir, "events.jsonl")); + +Console.WriteLine($"EndTick={manifest?.EndTick}, fingerprints={fingerprints.Count}, events={entries.Count}"); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +[MessageKind("Changed")] +public sealed record Changed(int Delta) : IEvent; + +public sealed class WorldState +{ + public int Population { get; set; } +} +``` diff --git a/docs/en/determinism.md b/docs/en/determinism.md index e0015d9..c89ac72 100644 --- a/docs/en/determinism.md +++ b/docs/en/determinism.md @@ -23,6 +23,7 @@ EpochSim guarantees deterministic execution for identical inputs: initial state, Calls into other methods are not followed. Mark a helper with `[Deterministic]` to check it too. + ```csharp using EpochSim.Kernel.Determinism; diff --git a/docs/en/embedding.md b/docs/en/embedding.md index 8971215..d4a7992 100644 --- a/docs/en/embedding.md +++ b/docs/en/embedding.md @@ -7,15 +7,37 @@ Integrating EpochSim into an application: execution model, external input and di `RunTicks` executes a bounded batch run: ```csharp +using EpochSim; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + engine.RunTicks(state, seed: 1, endTickInclusive: 10_000); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` `CreateSession` serves long-lived applications such as servers, games and interactive tools: ```csharp +using EpochSim; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + using var session = engine.CreateSession(state, seed: 1, startTick: 0); session.TickOnce(); session.RunUntil(1_000); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` A session keeps random number generator and scheduler continuity across `TickOnce` calls. See [Sessions](sessions.md). @@ -29,12 +51,19 @@ A session keeps random number generator and scheduler continuity across `TickOnc Minimal integration needs no codec and no events: ```csharp +using EpochSim; + var state = new WorldState(); var engine = Epoch.CreateEngine(); engine.AddSystem("World", tick: ctx => ctx.State.Population++); using var run = Epoch.QuickRun(state, rootDir: "artifacts"); run.RunTicks(engine, seed: 1, endTickInclusive: 100); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Run through `run.RunTicks(engine, ...)` so the state is the one the run scope was built with. A different instance attached to the same engine fails with a state mismatch error. @@ -64,6 +93,14 @@ engine.Attach(run); using var session = engine.CreateSession(state, seed: 1, startTick: 0); inbox.Enqueue(new AddPopulation(5)); session.TickOnce(); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ### Server with scheduled input @@ -86,6 +123,14 @@ scheduledInbox.Enqueue(10, new AddPopulation(3)); scheduledInbox.Enqueue(11, new AddPopulation(1)); session.RunUntil(20); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` `ScheduledCommandInbox` order is deterministic: tick ascending, then insertion order within a tick. @@ -110,6 +155,27 @@ session.RunUntil(20); Enable the event log only when replay or bisect is needed. For explicit control over the codec, run identifier and individual artifacts use `Epoch.RecommendedRun(state, codec, serializer, ...)` or `EpochSimRun.For(state)`. +### Mutation guard + +`DebugRun` serializes the state before and after each system and throws `InvalidOperationException` when the fingerprint changes. It finds systems that mutate state outside event handlers, at a significant serialization cost: use it in `DebugRun` only. The system below changes `Population` directly, so `DebugRun` rejects it with the tick and the system name: + + +```csharp +using EpochSim; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + +using var debug = Epoch.DebugRun(state, rootDir: "artifacts"); +debug.RunTicks(engine, seed: 1, endTickInclusive: 200); + +public sealed class WorldState +{ + public int Population { get; set; } +} +``` + ## Debugging determinism Run a simulation: diff --git a/docs/en/sessions.md b/docs/en/sessions.md index e310d86..168f9e8 100644 --- a/docs/en/sessions.md +++ b/docs/en/sessions.md @@ -15,12 +15,24 @@ ## Example ```csharp +using EpochSim; +using EpochSim.Kernel.Time; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + using var session = engine.CreateSession(state, seed: 12345, start: SimTime.Zero); while (session.CurrentTime.Tick <= 10) session.TickOnce(); session.RunUntil(new SimTime(500)); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ## Behavior diff --git a/docs/en/testing.md b/docs/en/testing.md index 3391c32..b01d9e2 100644 --- a/docs/en/testing.md +++ b/docs/en/testing.md @@ -25,6 +25,7 @@ It is a test dependency and is not part of `EpochSim.All`. ## xUnit + ```csharp using EpochSim.Testing; using Xunit; @@ -41,10 +42,16 @@ public sealed class WorldTests .Ticks(200)); } } + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ## NUnit + ```csharp using EpochSim.Testing; using NUnit.Framework; @@ -61,10 +68,16 @@ public sealed class WorldTests .Ticks(200)); } } + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ## MSTest + ```csharp using EpochSim.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -82,6 +95,11 @@ public sealed class WorldTests .Ticks(200)); } } + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ## Reading a failure @@ -104,13 +122,20 @@ The first line is the totals. Each block gives the failure kind, the seed, the t `MatchesGolden` is a regression test for "I changed behavior by accident": ```csharp +using EpochSim.Testing; + SimAssert.MatchesGolden( f => f .State(() => new WorldState()) - .Engine(e => e.AddSystem(new WorldSystem())) + .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++)) .Ticks(1000), goldenPath: "golden/world-seed-7.json", seed: 7); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` 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/artifacts.md b/docs/ru/artifacts.md index fc81c5d..ae0de66 100644 --- a/docs/ru/artifacts.md +++ b/docs/ru/artifacts.md @@ -36,3 +36,53 @@ artifacts// ## Финализация `manifest.json` и `meta.txt` финализируются в `EpochSimRunScope.Dispose()`. Освободите run scope до чтения этих файлов. + +## Чтение артефактов из кода + +Артефакты лежат обычными файлами в каталоге прогона и читаются из кода. Лог событий необязателен и нужен для `verify-run`, `bisect` и `fast-replay`: + +```csharp +using EpochSim; +using EpochSim.Execution.RunArtifacts; +using EpochSim.Execution.StateFingerprint; +using EpochSim.Kernel.Messaging; +using EpochSim.Serialization.EventLog; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +var inbox = new ScheduledCommandInbox(); +engine.AttachScheduledInbox(inbox); +engine.OnCommand((world, command, events) => +{ + world.Population += command.Delta; + events.Emit(new Changed(command.Delta)); +}); +inbox.Enqueue(5, new AddPopulation(3)); + +var codec = Epoch.JsonCodecFromAssembly(type => type == typeof(Changed)); +var serializer = Epoch.JsonStateSerializer(); + +string runDir; +using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts")) +{ + run.RunTicks(engine, seed: 1, endTickInclusive: 100); + runDir = run.Paths.RunDir; +} + +var manifest = RunManifestReader.TryRead(Path.Combine(runDir, "manifest.json")); +var fingerprints = JsonlStateFingerprintWriter.ReadAll(Path.Combine(runDir, "statefp.jsonl")); +var entries = EventLogReader.ReadAll(Path.Combine(runDir, "events.jsonl")); + +Console.WriteLine($"EndTick={manifest?.EndTick}, fingerprints={fingerprints.Count}, events={entries.Count}"); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +[MessageKind("Changed")] +public sealed record Changed(int Delta) : IEvent; + +public sealed class WorldState +{ + public int Population { get; set; } +} +``` diff --git a/docs/ru/determinism.md b/docs/ru/determinism.md index eef6b34..e306dad 100644 --- a/docs/ru/determinism.md +++ b/docs/ru/determinism.md @@ -23,6 +23,7 @@ EpochSim гарантирует детерминированное выполн Вызовы в другие методы не отслеживаются. Пометьте вспомогательный метод `[Deterministic]`, чтобы проверить и его. + ```csharp using EpochSim.Kernel.Determinism; diff --git a/docs/ru/embedding.md b/docs/ru/embedding.md index b178a19..976be4c 100644 --- a/docs/ru/embedding.md +++ b/docs/ru/embedding.md @@ -7,15 +7,37 @@ `RunTicks` выполняет ограниченный batch-прогон: ```csharp +using EpochSim; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + engine.RunTicks(state, seed: 1, endTickInclusive: 10_000); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` `CreateSession` подходит для долгоживущих приложений: серверов, игр и интерактивных инструментов: ```csharp +using EpochSim; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + using var session = engine.CreateSession(state, seed: 1, startTick: 0); session.TickOnce(); session.RunUntil(1_000); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Сессия сохраняет непрерывность генератора случайных чисел и планировщика между вызовами `TickOnce`. См. [Sessions](sessions.md). @@ -29,12 +51,19 @@ session.RunUntil(1_000); Минимальной интеграции не нужны ни кодек, ни события: ```csharp +using EpochSim; + var state = new WorldState(); var engine = Epoch.CreateEngine(); engine.AddSystem("World", tick: ctx => ctx.State.Population++); using var run = Epoch.QuickRun(state, rootDir: "artifacts"); run.RunTicks(engine, seed: 1, endTickInclusive: 100); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Запускайте через `run.RunTicks(engine, ...)`, чтобы использовался тот state, с которым создан run scope. Другой экземпляр, переданный тому же движку, приведёт к ошибке несоответствия state. @@ -64,6 +93,14 @@ engine.Attach(run); using var session = engine.CreateSession(state, seed: 1, startTick: 0); inbox.Enqueue(new AddPopulation(5)); session.TickOnce(); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ### Сервер с отложенным вводом @@ -86,6 +123,14 @@ scheduledInbox.Enqueue(10, new AddPopulation(3)); scheduledInbox.Enqueue(11, new AddPopulation(1)); session.RunUntil(20); + +[MessageKind("AddPopulation")] +public sealed record AddPopulation(int Delta) : ICommand; + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Порядок `ScheduledCommandInbox` детерминирован: сначала тик по возрастанию, затем порядок добавления внутри тика. @@ -110,6 +155,27 @@ session.RunUntil(20); Включайте лог событий только когда нужны replay или bisect. Для явного управления кодеком, идентификатором прогона и отдельными артефактами используйте `Epoch.RecommendedRun(state, codec, serializer, ...)` или `EpochSimRun.For(state)`. +### Mutation guard + +`DebugRun` сериализует state до и после каждой системы и бросает `InvalidOperationException`, если fingerprint изменился. Он находит системы, меняющие state вне обработчиков событий, но заметно замедляет прогон: используйте его только в `DebugRun`. Система ниже меняет `Population` напрямую, поэтому `DebugRun` отклоняет её, называя тик и систему: + + +```csharp +using EpochSim; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + +using var debug = Epoch.DebugRun(state, rootDir: "artifacts"); +debug.RunTicks(engine, seed: 1, endTickInclusive: 200); + +public sealed class WorldState +{ + public int Population { get; set; } +} +``` + ## Отладка детерминизма Запустить симуляцию: diff --git a/docs/ru/sessions.md b/docs/ru/sessions.md index 17636e5..5f43251 100644 --- a/docs/ru/sessions.md +++ b/docs/ru/sessions.md @@ -15,12 +15,24 @@ ## Пример ```csharp +using EpochSim; +using EpochSim.Kernel.Time; + +var state = new WorldState(); +var engine = Epoch.CreateEngine(); +engine.AddSystem("World", tick: ctx => ctx.State.Population++); + using var session = engine.CreateSession(state, seed: 12345, start: SimTime.Zero); while (session.CurrentTime.Tick <= 10) session.TickOnce(); session.RunUntil(new SimTime(500)); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ## Поведение diff --git a/docs/ru/testing.md b/docs/ru/testing.md index 368945a..0dad9f7 100644 --- a/docs/ru/testing.md +++ b/docs/ru/testing.md @@ -25,6 +25,7 @@ dotnet add package EpochSim.Testing ## xUnit + ```csharp using EpochSim.Testing; using Xunit; @@ -41,10 +42,16 @@ public sealed class WorldTests .Ticks(200)); } } + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ## NUnit + ```csharp using EpochSim.Testing; using NUnit.Framework; @@ -61,10 +68,16 @@ public sealed class WorldTests .Ticks(200)); } } + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ## MSTest + ```csharp using EpochSim.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -82,6 +95,11 @@ public sealed class WorldTests .Ticks(200)); } } + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` ## Как читать сообщение об ошибке @@ -104,13 +122,20 @@ Fuzz failed: Failures=1, SeedsRun=50, ElapsedMs=12 `MatchesGolden` это регрессионный тест на случай «я случайно изменил поведение»: ```csharp +using EpochSim.Testing; + SimAssert.MatchesGolden( f => f .State(() => new WorldState()) - .Engine(e => e.AddSystem(new WorldSystem())) + .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++)) .Ticks(1000), goldenPath: "golden/world-seed-7.json", seed: 7); + +public sealed class WorldState +{ + public int Population { get; set; } +} ``` Первый запуск создаёт файл. В нём fingerprint'ы состояния этого seed на каждом сотом тике и на последнем. Следующие запуски сравниваются с файлом и называют первый тик, на котором есть расхождение. После намеренного изменения запустите тесты один раз с `EPOCHSIM_UPDATE_GOLDEN=1`, чтобы перезаписать файл, и закоммитьте его. diff --git a/tests/EpochSim.Determinism.Tests/DocumentationFailureStoreTests.cs b/tests/EpochSim.Determinism.Tests/DocumentationFailureStoreTests.cs new file mode 100644 index 0000000..79ab599 --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/DocumentationFailureStoreTests.cs @@ -0,0 +1,72 @@ +using EpochSim; +using EpochSim.Cli.App; +using EpochSim.Samples.Onboarding; +using MyApp; + +[Collection("Console")] +public sealed class DocumentationFailureStoreTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), $"epochsim-doc-store-{Guid.NewGuid():N}"); + + public DocumentationFailureStoreTests() => Directory.CreateDirectory(_directory); + + public void Dispose() => Directory.Delete(_directory, recursive: true); + + [Theory] + [InlineData("docs/en/fuzzing.md")] + [InlineData("docs/ru/fuzzing.md")] + public async Task FuzzingDocument_ShowsTheRealSecondRunAndTheGeneratedRegressionTest(string document) + { + var storePath = Path.Combine(_directory, "epochsim-failures.json"); + Epoch.Fuzz(fuzz => InventoryFuzz.Configure(fuzz.FailureStore(storePath))); + var secondRun = Epoch.Fuzz(fuzz => InventoryFuzz.Configure(fuzz.FailureStore(storePath))); + + var exitCode = await ExportTest(storePath); + + var documentText = File.ReadAllText(Path.Combine(RepositoryRoot(), document)).ReplaceLineEndings("\n"); + var generated = File.ReadAllText(Path.Combine(_directory, "tests", "InventoryFuzzRegressionTests.cs")).ReplaceLineEndings("\n"); + Assert.Equal(0, exitCode); + Assert.Contains(KnownFailureBlock(secondRun.ToText()), documentText, StringComparison.Ordinal); + Assert.Contains(generated.TrimEnd(), documentText, StringComparison.Ordinal); + } + + private static string KnownFailureBlock(string reportText) + { + var text = reportText.ReplaceLineEndings("\n"); + var start = text.IndexOf("[InvariantViolation]", StringComparison.Ordinal); + var end = text.IndexOf("\n\n", start, StringComparison.Ordinal); + return text[start..end]; + } + + private async Task ExportTest(string storePath) + { + var originalOut = Console.Out; + Console.SetOut(TextWriter.Null); + + try + { + return await new CliApp().RunAsync( + [ + "failures", "export-test", + "--framework", "xunit", + "--configure", "MyApp.InventoryFuzz.Configure", + "--out", Path.Combine(_directory, "tests"), + "--store", storePath + ]); + } + finally + { + Console.SetOut(originalOut); + } + } + + private static string RepositoryRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "EpochSim.slnx"))) + directory = directory.Parent; + + return directory?.FullName ?? throw new DirectoryNotFoundException("EpochSim.slnx was not found above the test binaries."); + } +} diff --git a/tests/EpochSim.Determinism.Tests/DocumentationSnippetTests.cs b/tests/EpochSim.Determinism.Tests/DocumentationSnippetTests.cs index 46441a3..c09cc05 100644 --- a/tests/EpochSim.Determinism.Tests/DocumentationSnippetTests.cs +++ b/tests/EpochSim.Determinism.Tests/DocumentationSnippetTests.cs @@ -15,12 +15,20 @@ public sealed partial class DocumentationSnippetTests : IDisposable "global using System; global using System.Collections.Generic; global using System.IO; " + "global using System.Linq; global using System.Threading; global using System.Threading.Tasks;"; + private static readonly string[] Topics = ["artifacts", "determinism", "embedding", "fuzzing", "sessions", "testing"]; + private static readonly string[] Documents = [ "README.md", "README.ru.md", - "docs/en/fuzzing.md", - "docs/ru/fuzzing.md" + .. Topics.Select(topic => $"docs/en/{topic}.md"), + .. Topics.Select(topic => $"docs/ru/{topic}.md") + ]; + + private static readonly (string English, string Russian)[] Translations = + [ + ("README.md", "README.ru.md"), + .. Topics.Select(topic => ($"docs/en/{topic}.md", $"docs/ru/{topic}.md")) ]; private readonly string _workingDirectory = Path.Combine(Path.GetTempPath(), $"epochsim-snippet-{Guid.NewGuid():N}"); @@ -51,18 +59,27 @@ public static TheoryData Snippets() return data; } - [Fact] - public void EveryDocumentHasSnippets() + public static TheoryData TranslationPairs() { - foreach (var document in Documents) - Assert.NotEmpty(ReadSnippets(document)); + var data = new TheoryData(); + + foreach (var (english, russian) in Translations) + data.Add(english, russian); + + return data; } - [Fact] - public void EnglishAndRussianDocumentsHaveTheSameNumberOfSnippets() + [Theory] + [MemberData(nameof(TranslationPairs))] + public void EnglishAndRussianDocumentsHaveTheSameSnippets(string english, string russian) { - Assert.Equal(ReadSnippets("README.md").Count, ReadSnippets("README.ru.md").Count); - Assert.Equal(ReadSnippets("docs/en/fuzzing.md").Count, ReadSnippets("docs/ru/fuzzing.md").Count); + var englishSnippets = ReadSnippets(english); + var russianSnippets = ReadSnippets(russian); + + Assert.Equal(englishSnippets.Count, russianSnippets.Count); + Assert.Equal( + englishSnippets.Select(snippet => (snippet.ExpectedException, snippet.CompileOnly)), + russianSnippets.Select(snippet => (snippet.ExpectedException, snippet.CompileOnly))); } [Theory] @@ -72,6 +89,9 @@ public void Snippet_CompilesAndRuns(string document, int number) var snippet = ReadSnippets(document).Single(candidate => candidate.Number == number); var assembly = Compile(snippet, document); + if (snippet.CompileOnly) + return; + var entryPoint = assembly.EntryPoint ?? throw new Xunit.Sdk.XunitException($"{document} snippet #{number} has no top-level statements to run."); @@ -147,7 +167,9 @@ private static Assembly Compile(Snippet snippet, string document) $"Snippet{Guid.NewGuid():N}", [CSharpSyntaxTree.ParseText(snippet.Code, options), CSharpSyntaxTree.ParseText(ImplicitUsings, options)], references, - new CSharpCompilationOptions(OutputKind.ConsoleApplication, nullableContextOptions: NullableContextOptions.Enable)); + new CSharpCompilationOptions( + snippet.CompileOnly ? OutputKind.DynamicallyLinkedLibrary : OutputKind.ConsoleApplication, + nullableContextOptions: NullableContextOptions.Enable)); using var stream = new MemoryStream(); var result = compilation.Emit(stream); @@ -172,7 +194,8 @@ private static List ReadSnippets(string relativePath) snippets.Add(new Snippet( snippets.Count + 1, string.Join(Environment.NewLine, lines[(i + 1)..end]), - marker.Success ? marker.Groups["exception"].Value : null)); + marker.Success && marker.Groups["exception"].Success ? marker.Groups["exception"].Value : null, + marker.Success && marker.Groups["compiles"].Success)); i = end; } @@ -189,8 +212,8 @@ private static string RepositoryRoot() return directory?.FullName ?? throw new DirectoryNotFoundException("EpochSim.slnx was not found above the test binaries."); } - [GeneratedRegex(@"^$")] + [GeneratedRegex(@"^$")] private static partial Regex ExpectationMarker(); - private sealed record Snippet(int Number, string Code, string? ExpectedException); + private sealed record Snippet(int Number, string Code, string? ExpectedException, bool CompileOnly); } diff --git a/tests/EpochSim.Determinism.Tests/InventoryFuzz.cs b/tests/EpochSim.Determinism.Tests/InventoryFuzz.cs new file mode 100644 index 0000000..bae24ca --- /dev/null +++ b/tests/EpochSim.Determinism.Tests/InventoryFuzz.cs @@ -0,0 +1,16 @@ +using EpochSim; +using EpochSim.Fuzzing; +using EpochSim.Samples.Onboarding; + +namespace MyApp; + +public static class InventoryFuzz +{ + public static void Configure(FuzzBuilder fuzz) + => fuzz.Name("inventory") + .State(() => new Inventory()) + .Step((inventory, context) => inventory.Tick(context.Rng.AsRandom())) + .Invariant("StockNonNegative", inventory => inventory.Stock >= 0) + .Seeds(1, 1000) + .Ticks(500); +} From df473d46cf29560cb4d74035c57ad44ffaddb359 Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 13:10:35 +0300 Subject: [PATCH 09/10] chore: update ci --- .github/actions/setup/action.yml | 39 ++++ .github/dependabot.yml | 31 +++ .github/scripts/audit_packages.py | 104 ++++++++++ .github/scripts/coverage_gate.py | 106 ++++++++++ .github/scripts/nuget_push.sh | 33 ++++ .github/scripts/nupkg_check.py | 98 ++++++++++ .github/scripts/trx_summary.py | 158 +++++++++++++++ .github/workflows/ci.yml | 183 ++++++++++++++---- .github/workflows/security.yml | 91 +++++++++ .../EpochSim.Benchmarks.csproj | 1 + global.json | 6 + 11 files changed, 807 insertions(+), 43 deletions(-) create mode 100644 .github/actions/setup/action.yml create mode 100644 .github/dependabot.yml create mode 100755 .github/scripts/audit_packages.py create mode 100755 .github/scripts/coverage_gate.py create mode 100755 .github/scripts/nuget_push.sh create mode 100755 .github/scripts/nupkg_check.py create mode 100755 .github/scripts/trx_summary.py create mode 100644 .github/workflows/security.yml create mode 100644 global.json diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml new file mode 100644 index 0000000..0a775d0 --- /dev/null +++ b/.github/actions/setup/action.yml @@ -0,0 +1,39 @@ +name: Setup .NET +description: Install the SDK pinned by global.json, warm the NuGet cache and restore. + +inputs: + solution: + required: false + default: EpochSim.slnx + restore: + required: false + default: 'true' + cache: + required: false + default: 'true' + +runs: + using: composite + steps: + - shell: bash + run: | + { + echo "NUGET_PACKAGES=${GITHUB_WORKSPACE}/.nuget/packages" + echo "DOTNET_NOLOGO=true" + echo "DOTNET_CLI_TELEMETRY_OPTOUT=true" + } >> "$GITHUB_ENV" + + - uses: actions/setup-dotnet@v6 + with: + global-json-file: global.json + + - if: inputs.cache == 'true' + uses: actions/cache@v6 + with: + path: ${{ github.workspace }}/.nuget/packages + key: nuget-${{ runner.os }}-${{ hashFiles('**/packages.lock.json', '**/*.csproj', '**/*.props', 'global.json') }} + restore-keys: nuget-${{ runner.os }}- + + - if: inputs.restore == 'true' + shell: bash + run: dotnet restore "${{ inputs.solution }}" diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..7902f03 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,31 @@ +version: 2 + +updates: + - package-ecosystem: github-actions + directories: [/, /.github/actions/setup] + schedule: + interval: weekly + day: monday + commit-message: + prefix: ci + groups: + actions: + patterns: ['*'] + + - package-ecosystem: nuget + directory: / + schedule: + interval: weekly + day: monday + open-pull-requests-limit: 10 + commit-message: + prefix: deps + groups: + test-tooling: + patterns: ['xunit*', 'MSTest*', 'NUnit*', 'Microsoft.NET.Test.Sdk', 'coverlet*'] + roslyn: + patterns: ['Microsoft.CodeAnalysis*'] + minor-and-patch: + update-types: [minor, patch] + ignore: + - dependency-name: EpochSim* diff --git a/.github/scripts/audit_packages.py b/.github/scripts/audit_packages.py new file mode 100755 index 0000000..6292f6c --- /dev/null +++ b/.github/scripts/audit_packages.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +import argparse +import json +import os +import sys +from pathlib import Path + +SEVERITIES = ["low", "moderate", "high", "critical"] + + +def load(path: str | None) -> dict: + if not path: + return {} + file = Path(path) + if not file.is_file() or not file.stat().st_size: + return {} + try: + return json.loads(file.read_text(encoding="utf-8")) + except json.JSONDecodeError: + return {} + + +def walk(report: dict): + for project in report.get("projects", []): + name = Path(project.get("path", "?")).stem + for framework in project.get("frameworks") or []: + for key in ("topLevelPackages", "transitivePackages"): + for package in framework.get(key) or []: + yield name, package, key == "transitivePackages" + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--vulnerable", help="json from dotnet list package --vulnerable") + parser.add_argument("--deprecated", help="json from dotnet list package --deprecated") + parser.add_argument("--fail-on", choices=SEVERITIES + ["never"], default="moderate") + args = parser.parse_args() + + floor = SEVERITIES.index(args.fail_on) if args.fail_on != "never" else len(SEVERITIES) + + findings = [] + for project, package, transitive in walk(load(args.vulnerable)): + for advisory in package.get("vulnerabilities") or []: + findings.append({ + "project": project, + "id": package.get("id", "?"), + "version": package.get("resolvedVersion") or package.get("requestedVersion", "?"), + "severity": (advisory.get("severity") or "unknown").lower(), + "url": advisory.get("advisoryurl") or advisory.get("advisoryUrl", ""), + "transitive": transitive, + }) + + deprecations = [ + (project, package.get("id", "?"), package.get("resolvedVersion", "?"), + ", ".join(package.get("deprecationReasons") or [])) + for project, package, _ in walk(load(args.deprecated)) + if package.get("deprecationReasons") + ] + + blocking = [f for f in findings + if f["severity"] in SEVERITIES and SEVERITIES.index(f["severity"]) >= floor] + + lines = [f"## Dependency audit: {'failed' if blocking else 'passed'}", ""] + if findings: + lines += [ + f"**{len(findings)} advisory finding(s)**, {len(blocking)} at or above `{args.fail_on}`.", + "", + "| Package | Scope | Version | Severity | Project | Advisory |", + "|---|---|---|---|---|---|", + ] + rank = lambda f: SEVERITIES.index(f["severity"]) if f["severity"] in SEVERITIES else -1 + for finding in sorted(findings, key=rank, reverse=True): + link = f"[details]({finding['url']})" if finding["url"] else "n/a" + lines.append( + f"| `{finding['id']}` | {'transitive' if finding['transitive'] else 'direct'} | " + f"{finding['version']} | {finding['severity']} | " + f"`{finding['project']}` | {link} |" + ) + lines.append("") + else: + lines += ["No known advisories against any direct or transitive package.", ""] + + if deprecations: + lines += ["
Deprecated packages", "", + "| Package | Version | Project | Reason |", "|---|---|---|---|"] + lines += [f"| `{pkg}` | {version} | `{project}` | {reason} |" + for project, pkg, version, reason in deprecations] + lines += ["", "
", ""] + + report = "\n".join(lines) + print(report) + if path := os.environ.get("GITHUB_STEP_SUMMARY"): + with open(path, "a", encoding="utf-8") as handle: + handle.write(report + "\n") + + for finding in blocking: + print(f"::error title=Vulnerable package::{finding['id']} {finding['version']} " + f"({finding['severity']}) in {finding['project']} {finding['url']}") + + return 1 if blocking else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/coverage_gate.py b/.github/scripts/coverage_gate.py new file mode 100755 index 0000000..00e7f1a --- /dev/null +++ b/.github/scripts/coverage_gate.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +import argparse +import os +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + + +def bar(rate: float, width: int = 20) -> str: + filled = round(rate * width) + return "#" * filled + "." * (width - filled) + + +def counters(node: ET.Element) -> tuple[int, int, int, int]: + lines_covered = lines_valid = branches_covered = branches_valid = 0 + for line in node.iter("line"): + lines_valid += 1 + if int(line.get("hits", "0")) > 0: + lines_covered += 1 + coverage = line.get("condition-coverage", "") if line.get("branch") == "True" else "" + if "(" in coverage and "/" in coverage: + covered, valid = coverage.split("(", 1)[1].rstrip(")").split("/") + branches_covered += int(covered) + branches_valid += int(valid) + return lines_covered, lines_valid, branches_covered, branches_valid + + +def gather(paths: list[str]) -> list[Path]: + files: list[Path] = [] + for raw in paths: + path = Path(raw) + if path.is_dir(): + files.extend(sorted(path.rglob("*.cobertura.xml"))) + elif path.is_file(): + files.append(path) + return files + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("paths", nargs="+", help="cobertura files or directories to scan") + parser.add_argument("--min-line", type=float, default=0.0) + parser.add_argument("--min-branch", type=float, default=0.0) + parser.add_argument("--title", default="Coverage") + args = parser.parse_args() + + files = gather(args.paths) + if not files: + emit(f"## {args.title}: no data\n\n> No Cobertura report was produced.\n") + return 1 + + packages: dict[str, list[int]] = {} + total = [0, 0, 0, 0] + for file in files: + for package in ET.parse(file).getroot().iter("package"): + slot = packages.setdefault(package.get("name") or "(unnamed)", [0, 0, 0, 0]) + for index, value in enumerate(counters(package)): + slot[index] += value + total[index] += value + + line_rate = total[0] / total[1] if total[1] else 0.0 + branch_rate = total[2] / total[3] if total[3] else 0.0 + min_line = args.min_line / 100 + min_branch = args.min_branch / 100 + ok = line_rate >= min_line and branch_rate >= min_branch + + lines = [ + f"## {args.title}: {'passed' if ok else 'failed'}", + "", + f"`{bar(line_rate)}` **{line_rate * 100:.1f}%** lines ({total[0]}/{total[1]}), floor {args.min_line:.0f}%", + "", + f"`{bar(branch_rate)}` **{branch_rate * 100:.1f}%** branches ({total[2]}/{total[3]}), floor {args.min_branch:.0f}%", + "", + "| Result | Assembly | Lines | Branches |", + "|---|---|---:|---:|", + ] + for name, (lc, lv, bc, bv) in sorted(packages.items(), key=lambda kv: kv[1][0] / max(kv[1][1], 1)): + rate = lc / lv if lv else 0.0 + lines.append( + f"| {'ok' if rate >= min_line else 'FAIL'} | `{name}` | " + f"{rate * 100:.1f}% {lc}/{lv} | " + f"{(bc / bv * 100) if bv else 0:.1f}% {bc}/{bv} |" + ) + lines.append("") + + if not ok: + lines += [f"> Below the floor: lines {line_rate * 100:.1f}%, branches {branch_rate * 100:.1f}%.", ""] + + emit("\n".join(lines)) + + if path := os.environ.get("GITHUB_OUTPUT"): + with open(path, "a", encoding="utf-8") as handle: + handle.write(f"line-rate={line_rate * 100:.1f}\nbranch-rate={branch_rate * 100:.1f}\n") + + return 0 if ok else 1 + + +def emit(report: str) -> None: + print(report) + if path := os.environ.get("GITHUB_STEP_SUMMARY"): + with open(path, "a", encoding="utf-8") as handle: + handle.write(report + "\n") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/nuget_push.sh b/.github/scripts/nuget_push.sh new file mode 100755 index 0000000..bf23f1d --- /dev/null +++ b/.github/scripts/nuget_push.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail + +: "${NUGET_API_KEY:?NUGET_API_KEY is not set}" + +source=https://api.nuget.org/v3/index.json +failed=0 + +if [ "$#" -eq 0 ]; then + echo "::error::nuget_push.sh got no packages to push" + exit 1 +fi + +for package in "$@"; do + echo "::group::push ${package##*/}" + if output=$(dotnet nuget push "$package" \ + --source "$source" \ + --api-key "$NUGET_API_KEY" \ + --skip-duplicate 2>&1); then + echo "$output" + else + echo "$output" + if grep -qiE 'already exists|conflict|409' <<<"$output"; then + echo "::notice::${package##*/} is already on nuget.org, skipping" + else + echo "::error::failed to push ${package##*/}" + failed=1 + fi + fi + echo "::endgroup::" +done + +exit "$failed" diff --git a/.github/scripts/nupkg_check.py b/.github/scripts/nupkg_check.py new file mode 100755 index 0000000..09ffa07 --- /dev/null +++ b/.github/scripts/nupkg_check.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +import argparse +import os +import sys +import zipfile +from pathlib import Path +from xml.etree import ElementTree as ET + +REQUIRED = ("description", "authors", "repository", "tags") +PAYLOAD_ROOTS = ("lib/", "analyzers/", "build/", "tools/", "runtimes/") + + +def read_nuspec(package: Path) -> tuple[dict[str, str], set[str], bool]: + with zipfile.ZipFile(package) as archive: + names = set(archive.namelist()) + nuspec = next((n for n in names if n.endswith(".nuspec") and "/" not in n), None) + if nuspec is None: + raise ValueError("package contains no .nuspec") + root = ET.fromstring(archive.read(nuspec)) + + metadata_node = next((c for c in root if c.tag.rsplit("}", 1)[-1] == "metadata"), None) + if metadata_node is None: + raise ValueError("nuspec has no ") + + metadata = {} + for child in metadata_node: + key = child.tag.rsplit("}", 1)[-1] + metadata[key] = child.get("url", "") if key == "repository" else (child.text or "").strip() + has_dependencies = any(c.tag.rsplit("}", 1)[-1] == "dependencies" and len(c) for c in metadata_node) + return metadata, names, has_dependencies + + +def check(package: Path, version: str | None, want_symbols: bool) -> tuple[str, list[str]]: + try: + metadata, names, has_dependencies = read_nuspec(package) + except (zipfile.BadZipFile, ValueError, ET.ParseError) as exc: + return "?", [f"cannot read package: {exc}"] + + problems = [] + if version and metadata.get("version") != version: + problems.append(f"version is {metadata.get('version')!r}, expected {version!r}") + + problems += [f"missing <{key}>" for key in REQUIRED if not metadata.get(key)] + + if not (metadata.get("license") or metadata.get("licenseUrl")): + problems.append("missing license expression") + + readme = metadata.get("readme") + if not readme: + problems.append("missing ") + elif readme not in names: + problems.append(f" points at {readme!r}, absent from the package") + + if not has_dependencies and not any(name.startswith(PAYLOAD_ROOTS) for name in names): + problems.append("no dependencies and no lib/, analyzers/, build/, tools/ or runtimes/ content") + + has_library = any(n.startswith("lib/") and n.endswith(".dll") for n in names) + if want_symbols and has_library and not package.with_suffix(".snupkg").exists(): + problems.append(f"no {package.with_suffix('.snupkg').name} beside it") + + return metadata.get("version", "?"), problems + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("directory", help="folder holding the .nupkg files") + parser.add_argument("--version", help="version every package must carry") + parser.add_argument("--no-symbols", action="store_true") + args = parser.parse_args() + + packages = sorted(Path(args.directory).glob("*.nupkg")) + if not packages: + emit(f"## Package validation: failed\n\n> No `.nupkg` files in `{args.directory}`.\n") + return 1 + + lines = ["| Result | Package | Version | Size | Notes |", "|---|---|---|---:|---|"] + failed = False + for package in packages: + version, problems = check(package, args.version, not args.no_symbols) + failed = failed or bool(problems) + lines.append( + f"| {'FAIL' if problems else 'ok'} | `{package.name}` | {version} | " + f"{package.stat().st_size / 1024:.0f} KB | {'
'.join(problems) or 'ok'} |" + ) + + emit("\n".join([f"## Package validation: {'failed' if failed else 'passed'}", "", *lines, ""])) + return 1 if failed else 0 + + +def emit(report: str) -> None: + print(report) + if path := os.environ.get("GITHUB_STEP_SUMMARY"): + with open(path, "a", encoding="utf-8") as handle: + handle.write(report + "\n") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/trx_summary.py b/.github/scripts/trx_summary.py new file mode 100755 index 0000000..3b4973a --- /dev/null +++ b/.github/scripts/trx_summary.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +import argparse +import os +import sys +import xml.etree.ElementTree as ET +from dataclasses import dataclass, field +from pathlib import Path + +NS = {"t": "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"} +SKIPPED = {"notexecuted", "skipped", "pending", "inconclusive"} + + +@dataclass +class Run: + name: str + passed: int = 0 + failed: int = 0 + skipped: int = 0 + duration: float = 0.0 + failures: list[tuple[str, str, str]] = field(default_factory=list) + + @property + def total(self) -> int: + return self.passed + self.failed + self.skipped + + @property + def status(self) -> str: + return "FAIL" if self.failed else "empty" if not self.total else "ok" + + +def parse_duration(value: str | None) -> float: + if not value: + return 0.0 + try: + hours, minutes, seconds = value.split(":") + return int(hours) * 3600 + int(minutes) * 60 + float(seconds) + except ValueError: + return 0.0 + + +def parse_trx(path: Path) -> Run: + run = Run(name=path.stem) + try: + root = ET.parse(path).getroot() + except ET.ParseError as exc: + run.failed = 1 + run.failures.append((path.name, f"unreadable trx file: {exc}", "")) + return run + + method = root.find(".//t:TestDefinitions/t:UnitTest/t:TestMethod", NS) + if method is not None and method.get("codeBase"): + run.name = Path(method.get("codeBase")).stem + + for result in root.findall(".//t:Results/t:UnitTestResult", NS): + outcome = (result.get("outcome") or "").lower() + run.duration += parse_duration(result.get("duration")) + if outcome == "passed": + run.passed += 1 + elif outcome in SKIPPED: + run.skipped += 1 + else: + run.failed += 1 + run.failures.append(( + result.get("testName") or "", + (result.findtext(".//t:Output/t:ErrorInfo/t:Message", "", NS) or "").strip(), + (result.findtext(".//t:Output/t:ErrorInfo/t:StackTrace", "", NS) or "").strip(), + )) + return run + + +def collect(paths: list[str]) -> list[Run]: + files: list[Path] = [] + for raw in paths: + path = Path(raw) + if path.is_dir(): + files.extend(sorted(path.rglob("*.trx"))) + elif path.is_file(): + files.append(path) + + seen: set[Path] = set() + runs = [] + for file in files: + if file.resolve() not in seen: + seen.add(file.resolve()) + runs.append(parse_trx(file)) + return runs + + +def fence(text: str, limit: int) -> str: + text = text or "(no details)" + if len(text) > limit: + text = text[:limit] + "\n... truncated ..." + return f"```\n{text}\n```" + + +def render(runs: list[Run], title: str, max_failures: int) -> str: + if not runs: + return f"## {title}: no data\n\n> No `.trx` files were produced.\n" + + passed = sum(r.passed for r in runs) + failed = sum(r.failed for r in runs) + skipped = sum(r.skipped for r in runs) + duration = sum(r.duration for r in runs) + + lines = [ + f"## {title}: {'failed' if failed else 'passed'}", + "", + f"**{passed} passed, {failed} failed, {skipped} skipped** in {duration:.2f}s", + "", + "| Result | Suite | Passed | Failed | Skipped | Time |", + "|---|---|---:|---:|---:|---:|", + ] + for run in sorted(runs, key=lambda r: (r.failed == 0, r.name)): + lines.append( + f"| {run.status} | `{run.name}` | {run.passed} | {run.failed} | " + f"{run.skipped} | {run.duration:.2f}s |" + ) + lines.append("") + + failures = [(run.name, *failure) for run in runs for failure in run.failures] + if failures: + lines += ["### Failures", ""] + for suite, name, message, stack in failures[:max_failures]: + lines += [ + f"
{name} in {suite}", + "", + fence(message, 1600), + ] + if stack: + lines += ["", fence(stack, 2400)] + lines += ["", "
", ""] + if len(failures) > max_failures: + lines += [f"> {len(failures) - max_failures} more failure(s) in the artifacts.", ""] + + return "\n".join(lines) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("paths", nargs="+", help=".trx files or directories to scan") + parser.add_argument("--title", default="Test results") + parser.add_argument("--max-failures", type=int, default=20) + parser.add_argument("--fail-on-error", action="store_true") + args = parser.parse_args() + + runs = collect(args.paths) + report = render(runs, args.title, args.max_failures) + + print(report) + if path := os.environ.get("GITHUB_STEP_SUMMARY"): + with open(path, "a", encoding="utf-8") as handle: + handle.write(report + "\n") + + return 1 if args.fail_on_error and (not runs or any(r.failed for r in runs)) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f71cf36..bed998d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,62 +2,159 @@ name: CI on: push: - branches: ["main", "master"] + branches: [main] pull_request: + branches: [main] + merge_group: + workflow_dispatch: permissions: contents: read -jobs: - build_lint_test: - name: Build • Lint • Test - runs-on: ubuntu-latest +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + SOLUTION: EpochSim.slnx + CONFIGURATION: Release + COVERAGE_MIN_LINE: '40' + COVERAGE_MIN_BRANCH: '32' + +jobs: + build: + name: Build (${{ matrix.label }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + label: linux + - os: windows-latest + label: windows steps: - - name: Checkout - uses: actions/checkout@v4 + - uses: actions/checkout@v7 + - uses: ./.github/actions/setup - - name: Setup .NET (preview) - uses: actions/setup-dotnet@v4 - with: - dotnet-version: "10.0.x" - dotnet-quality: "preview" - cache: true - cache-dependency-path: | - **/*.csproj - **/*.props - **/*.targets - **/*.sln - **/*.slnx - NuGet.config - - - name: Restore - run: dotnet restore ./EpochSim.slnx - - - name: Build (Release, warnings as errors) - run: dotnet build ./EpochSim.slnx -c Release --no-restore -p:TreatWarningsAsErrors=true - - - name: Lint (dotnet format verify) - run: dotnet format ./EpochSim.slnx --verify-no-changes --no-restore + - name: Build + shell: bash + run: | + dotnet build "$SOLUTION" -c "$CONFIGURATION" --no-restore -warnaserror \ + -p:ContinuousIntegrationBuild=true \ + -bl:artifacts/binlog/build-${{ matrix.label }}.binlog + + - name: Format + if: runner.os == 'Linux' + run: dotnet format "$SOLUTION" --verify-no-changes --no-restore - name: Test - run: dotnet test ./EpochSim.slnx -c Release --no-build --verbosity normal + id: test + shell: bash + run: | + args=( + --no-build -c "$CONFIGURATION" + --logger trx + --results-directory artifacts/test + --blame-hang --blame-hang-timeout 5m --blame-hang-dump-type none + ) + if [ "$RUNNER_OS" = Linux ]; then + args+=(--collect "XPlat Code Coverage") + fi + dotnet test "$SOLUTION" "${args[@]}" -- RunConfiguration.TreatNoTestsAsError=true + + - name: Test summary + if: ${{ !cancelled() && steps.test.outcome != 'skipped' }} + shell: bash + run: | + python3 .github/scripts/trx_summary.py \ + --title "Tests (${{ matrix.label }})" --fail-on-error artifacts/test - - name: Pack (verify packages build) + - name: Coverage gate + if: runner.os == 'Linux' run: | - dotnet pack src/EpochSim.Kernel -c Release --no-build - dotnet pack src/EpochSim -c Release --no-build - 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 + python3 .github/scripts/coverage_gate.py \ + --min-line "$COVERAGE_MIN_LINE" --min-branch "$COVERAGE_MIN_BRANCH" \ + artifacts/test/*/*.cobertura.xml + + - name: Pack + if: runner.os == 'Linux' + run: | + dotnet pack "$SOLUTION" -c "$CONFIGURATION" --no-build \ + -p:ContinuousIntegrationBuild=true \ + -o artifacts/packages + version=$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n1) + python3 .github/scripts/nupkg_check.py --version "$version" artifacts/packages - name: Verify analyzer is packed + if: runner.os == 'Linux' + shell: bash 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 + set -euo pipefail + for pattern in 'EpochSim.[0-9]*.nupkg' 'EpochSim.Analyzers.[0-9]*.nupkg'; do + for package in artifacts/packages/$pattern; do + entries=$(unzip -Z1 "$package") + grep -Fx "analyzers/dotnet/cs/EpochSim.Analyzers.dll" <<<"$entries" > /dev/null + grep -Fx "analyzers/dotnet/cs/EpochSim.Analyzers.CodeFixes.dll" <<<"$entries" > /dev/null + done done - dotnet pack src/EpochSim.Cli -c Release --no-build - dotnet pack src/EpochSim.All -c Release --no-build + + - name: CLI smoke + if: runner.os == 'Linux' + run: | + dotnet run --project src/EpochSim.Cli/EpochSim.Cli.csproj -c "$CONFIGURATION" --no-build -- --help + + - if: ${{ !cancelled() && steps.test.outcome != 'skipped' }} + uses: actions/upload-artifact@v7 + with: + name: test-results-${{ matrix.label }} + path: artifacts/test + retention-days: 14 + if-no-files-found: warn + + - if: runner.os == 'Linux' + uses: actions/upload-artifact@v7 + with: + name: packages + path: artifacts/packages + retention-days: ${{ github.ref_type == 'tag' && 90 || 14 }} + if-no-files-found: error + + - if: failure() + uses: actions/upload-artifact@v7 + with: + name: binlog-${{ matrix.label }} + path: artifacts/binlog + retention-days: 7 + if-no-files-found: ignore + + ci: + name: CI + if: always() + needs: [build] + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - env: + NEEDS: ${{ toJSON(needs) }} + run: | + python3 - <<'PY' + import json, os, sys + + needs = json.loads(os.environ["NEEDS"]) + bad = {n: d["result"] for n, d in needs.items() if d["result"] not in ("success", "skipped")} + + rows = ["## " + ("CI failed" if bad else "CI passed"), "", "| Job | Result |", "|---|---|"] + rows += [f"| `{n}` | {d['result']} |" for n, d in sorted(needs.items())] + report = "\n".join(rows) + "\n" + + print(report) + if path := os.environ.get("GITHUB_STEP_SUMMARY"): + with open(path, "a", encoding="utf-8") as handle: + handle.write(report) + + for name, result in bad.items(): + print(f"::error title=CI::{name} -> {result}") + sys.exit(1 if bad else 0) + PY diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml new file mode 100644 index 0000000..5f7ffad --- /dev/null +++ b/.github/workflows/security.yml @@ -0,0 +1,91 @@ +name: Security + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: '41 5 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: security-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + SOLUTION: EpochSim.slnx + +jobs: + codeql: + name: CodeQL + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + contents: read + security-events: write + actions: read + steps: + - uses: actions/checkout@v7 + - uses: ./.github/actions/setup + + - uses: github/codeql-action/init@v4 + with: + languages: csharp + build-mode: manual + queries: security-and-quality + + - run: dotnet build "$SOLUTION" -c Release --no-restore + + - uses: github/codeql-action/analyze@v4 + with: + category: /language:csharp + + dependency-review: + name: Dependency review + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pull-requests: write + steps: + - uses: actions/checkout@v7 + - uses: actions/dependency-review-action@v5.0.0 + with: + fail-on-severity: high + comment-summary-in-pr: on-failure + + advisories: + name: NuGet advisories + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + - uses: ./.github/actions/setup + + - name: Collect + run: | + mkdir -p artifacts/audit + dotnet list "$SOLUTION" package --vulnerable --include-transitive --format json \ + > artifacts/audit/vulnerable.json + dotnet list "$SOLUTION" package --deprecated --include-transitive --format json \ + > artifacts/audit/deprecated.json + + - name: Evaluate + run: | + python3 .github/scripts/audit_packages.py \ + --vulnerable artifacts/audit/vulnerable.json \ + --deprecated artifacts/audit/deprecated.json \ + --fail-on moderate + + - if: always() + uses: actions/upload-artifact@v7 + with: + name: dependency-audit + path: artifacts/audit + retention-days: 30 + if-no-files-found: warn diff --git a/benchmarks/EpochSim.Benchmarks/EpochSim.Benchmarks.csproj b/benchmarks/EpochSim.Benchmarks/EpochSim.Benchmarks.csproj index 9169966..5e4ca0a 100644 --- a/benchmarks/EpochSim.Benchmarks/EpochSim.Benchmarks.csproj +++ b/benchmarks/EpochSim.Benchmarks/EpochSim.Benchmarks.csproj @@ -2,6 +2,7 @@ Exe + false net10.0 enable enable diff --git a/global.json b/global.json new file mode 100644 index 0000000..694f4f2 --- /dev/null +++ b/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "10.0.111", + "rollForward": "latestPatch" + } +} From 1819c19d2926a73fa8855ee5542dde8514670ada Mon Sep 17 00:00:00 2001 From: Echways Date: Tue, 10 Nov 2026 13:14:39 +0300 Subject: [PATCH 10/10] fix: ci --- src/EpochSim.Cli/App/CliApp.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/EpochSim.Cli/App/CliApp.cs b/src/EpochSim.Cli/App/CliApp.cs index c7114f9..0de0d65 100644 --- a/src/EpochSim.Cli/App/CliApp.cs +++ b/src/EpochSim.Cli/App/CliApp.cs @@ -36,6 +36,12 @@ public CliApp() public Task RunAsync(string[] args) { + if (args.Length > 0 && IsHelpFlag(args[0])) + { + PrintUsage(); + return Task.FromResult(0); + } + var commandName = args.Length > 0 ? args[0] : "run"; var root = args.Length > 1 ? args[1] : "artifacts"; var commandArgs = args.Length > 2 ? args.Skip(2).ToArray() : Array.Empty(); @@ -70,8 +76,7 @@ public Task RunAsync(string[] args) return Task.FromResult(2); } - if (commandArgs.Any(a => string.Equals(a, "--help", StringComparison.OrdinalIgnoreCase) - || string.Equals(a, "-h", StringComparison.OrdinalIgnoreCase))) + if (commandArgs.Any(IsHelpFlag)) { Console.WriteLine(command.Help); return Task.FromResult(0); @@ -89,6 +94,10 @@ public Task RunAsync(string[] args) } } + private static bool IsHelpFlag(string arg) => + string.Equals(arg, "--help", StringComparison.OrdinalIgnoreCase) + || string.Equals(arg, "-h", StringComparison.OrdinalIgnoreCase); + private static void PrintUsage() { Console.WriteLine("Usage:");