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/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
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 455f893..bf4d043 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -7,6 +7,10 @@
+
+
+
+
@@ -17,13 +21,15 @@
-
-
+
+
+
+
-
+
-
+
diff --git a/README.md b/README.md
index 0e0b355..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,270 +13,141 @@ 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
+dotnet add package EpochSim.Testing
+dotnet tool install --global EpochSim.Cli
```
-Requires .NET 10. `EpochSim.All` brings the full module graph (`EpochSim`, `Execution`, `Serialization`, `Observability`, `Kernel`) as a single dependency:
+Requires .NET 10. `EpochSim.All` brings the whole module graph as a single dependency.
-```bash
-dotnet add package EpochSim.All
-```
+## Find a bug by seed
-The command-line tool is installed separately:
-
-```bash
-dotnet tool install --global EpochSim.Cli
-```
-
-## Quick start
+`Epoch.Fuzz` needs no rewrite of existing code. Call it from `Step`, state what must always hold in `Invariant`, pick the seeds.
+
```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);
-
-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 the simulation on a range of seeds and checks invariants, exceptions and, optionally, determinism. Every failure comes with a seed that reproduces it and the state fields that changed on the failing tick.
-
-```csharp
-var report = Epoch.Fuzz(f => f
- .State(() => new JobQueueState())
- .Engine(e => e.AddSystem(new JobQueueSystem()))
- .Invariants(() => [new QueueNonNegativeInvariant()])
+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();
-```
-
-```
-Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81
-
-[InvariantViolation] seed=4 tick=426
- QueueNonNegative: Pending=-1
- StateDiff:
- $.Completed: 198 -> 200
- $.Pending: 0 -> -1
- Repro: .Seeds(4, 4).Ticks(426)
-```
-
-Add `.CheckDeterminism()` to run every seed twice and catch `static` state, wall-clock time and other sources of non-determinism. The same run from the terminal:
-```bash
-epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500
-```
-
-More in [Fuzzing](docs/en/fuzzing.md).
-
-## Testing
+public sealed class Inventory
+{
+ public int Stock { get; private set; } = 5;
-`EpochSim.Testing` brings the same checks to xUnit, NUnit and MSTest without depending on any of them:
+ public void Tick(Random random)
+ {
+ if (random.Next(0, 3) == 0)
+ Stock += 4;
-```bash
-dotnet add package EpochSim.Testing
-```
+ var demand = random.Next(0, 3);
+ if (Stock >= demand)
+ Stock -= demand;
-```csharp
-SimAssert.IsDeterministic(f => f
- .State(() => new WorldState())
- .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
- .Seeds(1, 50)
- .Ticks(200));
+ if (random.Next(0, 400) == 0)
+ Stock -= 5;
+ }
+}
```
-A failure names the seed, the tick and the changed state fields. More in [Testing](docs/en/testing.md).
-
-## Run presets
+The run finds the seeds on which the stock goes negative and names the tick and the state fields that changed:
-| 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 |
-
-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 var quick = Epoch.QuickRun(state, rootDir: "artifacts");
-quick.RunTicks(engine, seed: 1, endTickInclusive: 100);
+```text
+Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150
-using var recommended = Epoch.RecommendedRun(state, rootDir: "artifacts");
-recommended.RunTicks(engine, seed: 1, endTickInclusive: 1000);
+[InvariantViolation] seed=18 tick=19
+ StockNonNegative: predicate returned false
+ StateDiff:
+ $.Stock: 1 -> -2
+ Repro: .Seeds(18, 18).Ticks(19)
-var serializer = Epoch.JsonStateSerializer();
-using var debug = Epoch.DebugRun(state, serializer, rootDir: "artifacts");
-debug.RunTicks(engine, seed: 1, endTickInclusive: 200);
+...
```
-For full control use `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` or `EpochSimRun.For(state)...Build()`.
-
-## Event log and replay
+Add `.Seeds(18, 18).Ticks(19)` from the `Repro` line to run only that failure. More in [Fuzzing](docs/en/fuzzing.md).
-The event log is optional and required for `verify-run`, `bisect` and `fast-replay`.
+## Run a simulation
```csharp
using EpochSim;
-using EpochSim.Kernel.Messaging;
-
-var codec = Epoch.JsonCodecFromAssembly(t => t == typeof(Changed));
-var serializer = Epoch.JsonStateSerializer();
-
-using var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts");
-
-[MessageKind("Changed")]
-public sealed record Changed(int Delta) : IEvent;
-```
-## Reading artifacts
+var state = new WorldState();
+var engine = Epoch.CreateEngine();
+engine.AddSystem("World", tick: ctx => ctx.State.Population++);
-Artifacts are plain files in the run directory and can be read in-process:
+using var run = Epoch.QuickRun(state, rootDir: "artifacts");
+run.RunTicks(engine, seed: 1, endTickInclusive: 100);
-```csharp
-using EpochSim;
-using EpochSim.Execution.RunArtifacts;
-using EpochSim.Execution.StateFingerprint;
-using EpochSim.Serialization.EventLog;
+Console.WriteLine(state.Population);
-string runDir;
-using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts"))
+public sealed class WorldState
{
- run.RunTicks(engine, seed: 1, endTickInclusive: 100);
- runDir = run.Paths.RunDir;
+ public int Population { get; set; }
}
-
-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}");
```
-Layout and formats are described in [Artifacts](docs/en/artifacts.md).
+Presets, external input, sessions and artifacts are covered in [Embedding](docs/en/embedding.md).
-## Sessions and external input
-
-`RunTicks` fits batch jobs. `SimulationSession` fits long-lived loops:
+## Test it
```csharp
-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);
-
-[MessageKind("AddPopulation")]
-public sealed record AddPopulation(int Delta) : ICommand;
-```
-
-Inboxes feed external commands into the simulation thread deterministically:
-
-- `CommandInbox`: commands for the next tick.
-- `ScheduledCommandInbox`: commands for a specific tick, ordered by tick ascending, then by insertion order.
+using EpochSim.Testing;
-```csharp
-var scheduled = new ScheduledCommandInbox();
-engine.AttachScheduledInbox(scheduled);
+SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Step((world, _) => world.Population++)
+ .Seeds(1, 50)
+ .Ticks(200));
-scheduled.Enqueue(10, new AddPopulation(3));
-scheduled.Enqueue(10, new AddPopulation(7));
-scheduled.Enqueue(12, new AddPopulation(1));
+public sealed class WorldState
+{
+ public int Population { get; set; }
+}
```
-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` | Run many seeds, find the one that breaks |
-| `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, reproducible failures. |
-| 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. [Fuzzing](src/EpochSim.Samples/Fuzzing/) has a rare seed-dependent bug 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 8d42cb1..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,270 +13,141 @@
-## Зачем нужен 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
+dotnet add package EpochSim.Testing
+dotnet tool install --global EpochSim.Cli
```
-Требуется .NET 10. `EpochSim.All` приносит весь граф модулей (`EpochSim`, `Execution`, `Serialization`, `Observability`, `Kernel`) одной зависимостью:
+Требуется .NET 10. `EpochSim.All` приносит весь граф модулей одной зависимостью.
-```bash
-dotnet add package EpochSim.All
-```
+## Найдите баг по seed
-Утилита командной строки ставится отдельно:
-
-```bash
-dotnet tool install --global EpochSim.Cli
-```
-
-## Быстрый старт
+`Epoch.Fuzz` не требует переписывать существующий код. Вызовите его из `Step`, опишите в `Invariant`, что должно выполняться всегда, и задайте seed.
+
```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);
-
-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 и проверяет инварианты, исключения и, по желанию, детерминизм. Каждый сбой приходит с seed, который его воспроизводит, и полями состояния, изменившимися на сбойном тике.
-
-```csharp
-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));
report.ThrowIfFailed();
-```
-
-```
-Fuzz failed: Failures=14, SeedsRun=1000, ElapsedMs=81
-
-[InvariantViolation] seed=4 tick=426
- QueueNonNegative: Pending=-1
- StateDiff:
- $.Completed: 198 -> 200
- $.Pending: 0 -> -1
- Repro: .Seeds(4, 4).Ticks(426)
-```
-
-Добавьте `.CheckDeterminism()`, чтобы прогонять каждый seed дважды и ловить `static`-состояние, системное время и другие источники недетерминизма. Тот же прогон из терминала:
-```bash
-epochsim fuzz --adapter fuzzbug --seeds 1..1000 --ticks 500
-```
-
-Подробнее в [Fuzzing](docs/ru/fuzzing.md).
-
-## Тестирование
+public sealed class Inventory
+{
+ public int Stock { get; private set; } = 5;
-`EpochSim.Testing` даёт те же проверки в xUnit, NUnit и MSTest, не завися ни от одного из них:
+ public void Tick(Random random)
+ {
+ if (random.Next(0, 3) == 0)
+ Stock += 4;
-```bash
-dotnet add package EpochSim.Testing
-```
+ var demand = random.Next(0, 3);
+ if (Stock >= demand)
+ Stock -= demand;
-```csharp
-SimAssert.IsDeterministic(f => f
- .State(() => new WorldState())
- .Engine(e => e.AddSystem("World", tick: ctx => ctx.State.Population++))
- .Seeds(1, 50)
- .Ticks(200));
+ if (random.Next(0, 400) == 0)
+ Stock -= 5;
+ }
+}
```
-Сообщение о сбое называет seed, тик и изменившиеся поля состояния. Подробнее в [Testing](docs/ru/testing.md).
-
-## Пресеты запуска
+Прогон находит seed, на которых остаток уходит в минус, и называет тик и изменившиеся поля состояния:
-| Пресет | Каденция fingerprint | Mutation guard | Когда использовать |
-| ---------------- | -------------------- | -------------- | --------------------------------- |
-| `QuickRun` | каждый тик | Нет | Первый запуск, CI smoke |
-| `RecommendedRun` | каждые 50 тиков | Нет | Диагностика в production |
-| `DebugRun` | каждый тик | Да | Поиск инвариантов, строгий режим |
-
-Mutation guard сериализует state до и после каждой системы и бросает `InvalidOperationException`, если fingerprint изменился. Он находит системы, меняющие state вне обработчиков событий, но заметно замедляет прогон: используйте его только в `DebugRun`.
-
-```csharp
-using var quick = Epoch.QuickRun(state, rootDir: "artifacts");
-quick.RunTicks(engine, seed: 1, endTickInclusive: 100);
+```text
+Fuzz failed: Failures=21, SeedsRun=1000, ElapsedMs=150
-using var recommended = Epoch.RecommendedRun(state, rootDir: "artifacts");
-recommended.RunTicks(engine, seed: 1, endTickInclusive: 1000);
+[InvariantViolation] seed=18 tick=19
+ StockNonNegative: predicate returned false
+ StateDiff:
+ $.Stock: 1 -> -2
+ Repro: .Seeds(18, 18).Ticks(19)
-var serializer = Epoch.JsonStateSerializer();
-using var debug = Epoch.DebugRun(state, serializer, rootDir: "artifacts");
-debug.RunTicks(engine, seed: 1, endTickInclusive: 200);
+...
```
-Для полного контроля: `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` или `EpochSimRun.For(state)...Build()`.
-
-## Лог событий и replay
+Добавьте `.Seeds(18, 18).Ticks(19)` из строки `Repro` в свой вызов, чтобы прогнать только этот сбой. Подробнее в [Fuzzing](docs/ru/fuzzing.md).
-Лог событий необязателен и нужен для `verify-run`, `bisect` и `fast-replay`.
+## Запуск симуляции
```csharp
using EpochSim;
-using EpochSim.Kernel.Messaging;
-
-var codec = Epoch.JsonCodecFromAssembly(t => t == typeof(Changed));
-var serializer = Epoch.JsonStateSerializer();
-
-using var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts");
-
-[MessageKind("Changed")]
-public sealed record Changed(int Delta) : IEvent;
-```
-## Чтение артефактов
+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);
-```csharp
-using EpochSim;
-using EpochSim.Execution.RunArtifacts;
-using EpochSim.Execution.StateFingerprint;
-using EpochSim.Serialization.EventLog;
+Console.WriteLine(state.Population);
-string runDir;
-using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts"))
+public sealed class WorldState
{
- run.RunTicks(engine, seed: 1, endTickInclusive: 100);
- runDir = run.Paths.RunDir;
+ public int Population { get; set; }
}
-
-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}");
```
-Структура и форматы описаны в [Artifacts](docs/ru/artifacts.md).
+Пресеты, внешний ввод, сессии и артефакты описаны в [Embedding](docs/ru/embedding.md).
-## Сессии и внешний ввод
-
-`RunTicks` подходит для batch-прогонов. `SimulationSession` подходит для долгоживущих циклов:
+## Тесты
```csharp
-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);
-
-[MessageKind("AddPopulation")]
-public sealed record AddPopulation(int Delta) : ICommand;
-```
-
-Inbox'ы детерминированно передают внешние команды в поток симуляции:
-
-- `CommandInbox`: команды на ближайший тик.
-- `ScheduledCommandInbox`: команды на заданный тик, порядок: сначала тик по возрастанию, затем порядок добавления.
+using EpochSim.Testing;
-```csharp
-var scheduled = new ScheduledCommandInbox();
-engine.AttachScheduledInbox(scheduled);
+SimAssert.IsDeterministic(f => f
+ .State(() => new WorldState())
+ .Step((world, _) => world.Population++)
+ .Seeds(1, 50)
+ .Ticks(200));
-scheduled.Enqueue(10, new AddPopulation(3));
-scheduled.Enqueue(10, new AddPopulation(7));
-scheduled.Enqueue(12, new AddPopulation(1));
+public sealed class WorldState
+{
+ public int Population { get; set; }
+}
```
-Подробнее в [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` | Прогон многих 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. [Fuzzing](src/EpochSim.Samples/Fuzzing/) — редкий баг, зависящий от seed, для поиска через `Epoch.Fuzz`.
+Запускаемые примеры лежат в [src/EpochSim.Samples](src/EpochSim.Samples).
-## Сборка и тесты
+## Разработка
```bash
dotnet build EpochSim.slnx -m:1
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/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/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/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 9855347..b01d9e2 100644
--- a/docs/en/testing.md
+++ b/docs/en/testing.md
@@ -18,11 +18,14 @@ 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)`.
## xUnit
+
```csharp
using EpochSim.Testing;
using Xunit;
@@ -39,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;
@@ -59,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;
@@ -80,6 +95,11 @@ public sealed class WorldTests
.Ticks(200));
}
}
+
+public sealed class WorldState
+{
+ public int Population { get; set; }
+}
```
## Reading a failure
@@ -102,13 +122,39 @@ 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.
+
+## 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/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/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/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 5c4b139..0dad9f7 100644
--- a/docs/ru/testing.md
+++ b/docs/ru/testing.md
@@ -18,11 +18,14 @@ 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)`.
## xUnit
+
```csharp
using EpochSim.Testing;
using Xunit;
@@ -39,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;
@@ -59,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;
@@ -80,6 +95,11 @@ public sealed class WorldTests
.Ticks(200));
}
}
+
+public sealed class WorldState
+{
+ public int Population { get; set; }
+}
```
## Как читать сообщение об ошибке
@@ -102,13 +122,39 @@ 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`, чтобы перезаписать файл, и закоммитьте его.
+
+## Регрессионные тесты для найденных багов
+
+Сбой, найденный `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/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"
+ }
+}
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/src/EpochSim.Cli/App/CliApp.cs b/src/EpochSim.Cli/App/CliApp.cs
index 035ba17..0de0d65 100644
--- a/src/EpochSim.Cli/App/CliApp.cs
+++ b/src/EpochSim.Cli/App/CliApp.cs
@@ -29,17 +29,25 @@ public CliApp()
["bisect"] = new BisectCommand(),
["repro"] = new ReproCommand(),
["fuzz"] = new FuzzCommand(),
+ ["failures"] = new FailuresCommand(),
["list-adapters"] = new ListAdaptersCommand()
};
}
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();
- 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();
}
@@ -68,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);
@@ -87,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:");
@@ -106,7 +117,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]");
+ 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 ff4c5a1..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]
+ 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.
@@ -21,6 +21,8 @@ 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
+ --store path Record failures in a failure store and replay its seeds first (see failures --help)
""";
public int Execute(CommandContext ctx, string[] args)
@@ -42,14 +44,21 @@ 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);
+
+ 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 e33b312..fd6d923 100644
--- a/src/EpochSim.Cli/Commands/FuzzOptions.cs
+++ b/src/EpochSim.Cli/Commands/FuzzOptions.cs
@@ -9,7 +9,9 @@ internal sealed record FuzzOptions(
long Ticks,
bool CheckDeterminism,
int? Parallelism,
- string OutputDirectory)
+ string OutputDirectory,
+ bool Shrink,
+ string? StorePath)
{
private const ulong DefaultFromSeed = 1;
private const ulong DefaultToSeed = 1000;
@@ -18,7 +20,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, null);
for (var i = 0; i < args.Length; i++)
{
@@ -32,6 +34,8 @@ 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 },
+ "--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/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/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.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.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.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/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/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/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/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 8c035ef..ca6c4ea 100644
--- a/src/EpochSim/Fuzzing/FuzzBuilder.cs
+++ b/src/EpochSim/Fuzzing/FuzzBuilder.cs
@@ -20,6 +20,14 @@ public sealed class FuzzBuilder
private string? _artifactsRoot;
private IEventCodecV2? _eventCodec;
private IProgress? _progress;
+ private bool? _shrink;
+ private IReadOnlyList? _onlyCommands;
+ 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()
{
@@ -37,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);
@@ -113,21 +142,113 @@ 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;
+ }
+
+ 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);
+ ArgumentOutOfRangeException.ThrowIfLessThan(timeLimit, TimeSpan.Zero);
+ _shrinkBudget = new FuzzShrinkBudget(maxAttempts, timeLimit);
+ return this;
+ }
+
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,
_stopAtFirstFailure,
_artifactsRoot,
_eventCodec,
- _progress);
+ _progress,
+ _shrink ?? _commands is not null,
+ _onlyCommands,
+ _shrinkBudget,
+ _name ?? typeof(TState).FullName ?? typeof(TState).Name,
+ 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/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..300b469 100644
--- a/src/EpochSim/Fuzzing/FuzzFailure.cs
+++ b/src/EpochSim/Fuzzing/FuzzFailure.cs
@@ -12,12 +12,25 @@ 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 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);
+
if (StateDiff.Count > 0)
{
text.AppendLine(" StateDiff:");
@@ -25,10 +38,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/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