Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ All notable changes to BenchmarkGate are documented here.
policy-free comparison. No pass/fail vocabulary in any of the three.
- `Reporting.MarkdownBuilder.CodeSpan` — CommonMark-safe backtick-delimited
code spans.
- `benchmark-gate compare` command — reports what changed between a
baseline and a set of results (matching, deltas, direction) without
requiring a `policy.json` or producing a pass/fail verdict. Supports
`console` (default), `json`, and `markdown` output via `--format`;
`--output <path>` writes to a file instead of stdout (required for
`json`/`markdown`, since those reporters only write to a path). Always
exits `Passed` (0) once it successfully produces a comparison — an
added/removed benchmark or a slower metric is a comparison result, not
a process failure.

### Changed
- `Core.Comparison.MetricValue.Unit` is now `string?` rather than `string`.
Expand All @@ -42,6 +51,10 @@ All notable changes to BenchmarkGate are documented here.
then `RegressionEvaluator.Evaluate(comparison, policy)`, replacing the deleted
`Evaluate(observations, baseline, policy)` overload. Minimal compile-fix only —
`CheckCommand`'s full rewrite into pure orchestration is still #29's scope.
- `Tool.Commands.CheckCommand` documentation updated to reflect its actual
orchestration (`BenchmarkComparisonEngine.Compare` then
`RegressionEvaluator.Evaluate`) — no behavior change; the real
refactor happened during #27's compile-fix.

## [0.3.0-alpha.1] - 03/08/2026

Expand Down
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,38 @@ Useful flags on `check`:
| `--fail-on-warning` | Make a Warning-only suite exit non-zero |
| `--quiet` | Suppress console output (reports/exit code still work) |

## Comparing without a policy

`benchmark-gate compare` reports what changed between a baseline and a set
of results — matching, deltas, direction — without requiring a
`policy.json` or producing a pass/fail verdict. Useful for a quick "what
moved" check, a PR comment, or feeding a dashboard, when you don't want
`check`'s policy machinery in the loop.

```bash
benchmark-gate compare --results ./BenchmarkDotNet.Artifacts/results --baseline ./benchmarks/baseline.json
```

Write a report to a file instead of stdout with `--format` and `--output`:

```bash
benchmark-gate compare --results ./BenchmarkDotNet.Artifacts/results --baseline ./benchmarks/baseline.json --format json --output ./compare.json
benchmark-gate compare --results ./BenchmarkDotNet.Artifacts/results --baseline ./benchmarks/baseline.json --format markdown --output ./compare.md
```

`compare` always exits `0` once it successfully produces a comparison — an
added benchmark, a removed benchmark, or a metric that got slower are
comparison *results*, not process failures. Use `check` when you need a
build to fail on regression.

Useful flags on `compare`:

| Flag | Purpose |
|---|---|
| `--format <console\|json\|markdown>` | Output format (default: `console`) |
| `--output <path>` | Write the report to a file instead of stdout. Required for `--format json`/`--format markdown` |
| `--quiet` | Suppress console output (an explicit `--output` file still gets written) |

## Validating inputs

`benchmark-gate validate` checks a policy, baseline, and/or BenchmarkDotNet
Expand Down Expand Up @@ -118,6 +150,7 @@ independent of `check`'s exit codes, since `validate` answers a different
question (“is this file correct?”) than `check` does (“do these results
pass the policy?”).


## What this is not

- Not a benchmark execution service — BenchmarkDotNet remains the
Expand Down
18 changes: 13 additions & 5 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ BenchmarkDotNet, (later: Crank, custom JSON/CSV)
▼
Compare
│
▼
Check
│
▼
Report
┌─────────┴─────────┐
▼ ▼
`compare` reports Check (policy)
│
▼
`check` reports
```

The permanent boundaries, one job each:
Expand All @@ -50,6 +51,13 @@ exists so the gate's pass/fail contract never depends on best-effort
correlation logic — a build fails or doesn't based on Check alone, and
Explain adds understanding without ever changing that decision.

Compare and Check are split for the same reason Explain is split from
Check: `compare` describes what changed without requiring a policy;
`check` applies a policy on top of the *same* comparison. Both commands
call the identical Compare step — there is one implementation of "what
changed," consumed two ways, never two implementations that happen to
agree. See ADR-0005 (comparison facts vs. evaluation verdicts)

## Solution layout

```
Expand Down
20 changes: 14 additions & 6 deletions docs/EXIT-CODES.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@ change without a major version bump.

| Code | Name | Meaning | Returned by |
|---|---|---|---|
| 0 | `Passed` | The command completed successfully with no failures. | `check`, `capture`, `validate` |
| 0 | `Passed` | The command completed successfully with no failures. | `check`, `compare`, `capture`, `validate` |
| 1 | `Regressed` | At least one benchmark regressed past its policy's failure threshold. | `check` |
| 2 | `InvalidArguments` | The command's arguments were invalid or incomplete — e.g. an empty `--suite`, an output path that already exists without `--overwrite`, or `validate` invoked with none of `--policy`/`--baseline`/`--results`. | `check`, `capture`, `validate` |
| 3 | `InvalidBaselineOrPolicy` | The baseline or policy file failed to load — missing, malformed, or fails semantic validation. | `check` |
| 2 | `InvalidArguments` | The command's arguments were invalid or incomplete — e.g. an empty `--suite`, an output path that already exists without `--overwrite`, `compare` invoked with `--format json`/`--format markdown` and no `--output`, or `validate` invoked with none of `--policy`/`--baseline`/`--results`. | `check`, `compare`, `capture`, `validate` |
| 3 | `InvalidBaselineOrPolicy` | The baseline or policy file failed to load — missing, malformed, or fails semantic validation. | `check`, `compare` |
| 4 | `IncompleteResultSet` | The baseline contains a benchmark not present in the current results (`Missing` status). | `check` |
| 5 | `IncompatibleEnvironment` | Reserved for future functionality — an environment-compatibility evaluator (deferred past v0.1, see ROADMAP.md). Verified: not currently returned by `SuiteDecision.GetExitCode` or any command. | — |
| 6 | `UnstableResults` | At least one benchmark failed the stability gate (too few measurements, or coefficient of variation above the policy's threshold). | `check` |
| 7 | `UnapprovedNewBenchmarks` | Reserved for future functionality — a `--reject-new`-style gate on benchmarks with no baseline entry. Verified: not currently returned by `SuiteDecision.GetExitCode` or any command. | — |
| 8 | `UnsupportedSchema` | The BenchmarkDotNet results file/directory failed to parse — missing, malformed, unsupported schema, or (for `capture`) parsed to zero observations. | `check`, `capture` |
| 8 | `UnsupportedSchema` | The BenchmarkDotNet results file/directory failed to parse — missing, malformed, unsupported schema, or (for `capture`) parsed to zero observations. | `check`, `compare`, `capture` |
| 9 | `Warning` | A Warning-only suite (no Regressed, Missing, or Unstable benchmarks) evaluated with `--fail-on-warning`. | `check` |
| 10 | `InternalError` | An unexpected, unhandled exception reached the process boundary — a bug, not an expected failure mode. See `Program.cs`'s top-level catch. | any command |
| 11 | `OutputWriteFailure` | A requested report (Markdown/JSON/JUnit) or baseline candidate could not be written to disk. | `check`, `capture`, `validate` |
| 11 | `OutputWriteFailure` | A requested report (Markdown/JSON/JUnit) or baseline candidate could not be written to disk. | `check`, `compare`, `capture`, `validate` |
| 12 | `ValidationFailed` | At least one artifact requested via `validate` has error-level diagnostics, or could not be read/parsed at all. Used uniformly regardless of whether the artifact was a policy, baseline, or results file, and regardless of whether the cause was semantic (a validation rule failed) or syntactic (malformed JSON) — `validate` answers "is this file valid", not "which parser phase rejected it". | `validate` |

## Notes
Expand All @@ -40,4 +40,12 @@ change without a major version bump.
(`IncompleteResultSet`) > `Unstable` (`UnstableResults`) >
`Warning`-if-`--fail-on-warning` > `Passed`. A regression always wins
over a missing or unstable benchmark, so CI surfaces the most
actionable failure first.
actionable failure first.
- **`compare` has no severity verdict at all.** Unlike `check`, `compare`
always returns `Passed` (0) once it successfully produces a comparison —
a regression, an added/removed benchmark, or a missing metric are
comparison *results*, not process failures. `compare` never returns
`Regressed`, `IncompleteResultSet`, `UnstableResults`, `Warning`, or
`ValidationFailed`; those are `check`-only (or, for `ValidationFailed`,
`validate`-only) outcomes that require a policy or validation rules
`compare` doesn't have.
16 changes: 11 additions & 5 deletions src/BenchmarkGate.Tool/Commands/CheckCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,24 @@ namespace Bijecta.BenchmarkGate.Tool.Commands;
/// <summary>
/// Implements <c>benchmark-gate check</c>. Argument acquisition lives in
/// Program.cs (System.CommandLine, per ADR-0002). This type orchestrates:
/// parse -> load baseline -> load policy -> evaluate -> report -> exit code.
/// parse -> load baseline -> load policy -> BenchmarkComparisonEngine.Compare
/// -> RegressionEvaluator.Evaluate -> report -> exit code.
/// </summary>
/// <remarks>
/// <para>
/// Report files are written independently (Markdown, JSON, JUnit are not a
/// transaction) — if a later report fails, earlier ones may already exist
/// on disk. That's deliberate: these are separate artifacts, not a single
/// atomic output, and best-effort sequential writing is the right model
/// here rather than a cross-file rollback.
/// </para>
/// <para>
/// This type must not itself match benchmarks, match metrics, check units,
/// calculate deltas, or derive direction — all of that is
/// <c>BenchmarkComparisonEngine</c>'s job, called once, from one place, same
/// as <c>CompareCommand</c>. It only calls <c>RegressionEvaluator.Evaluate</c>
/// on top of that shared comparison to apply policy — see ADR-0004.
/// </para>
/// </remarks>
internal static class CheckCommand
{
Expand Down Expand Up @@ -68,10 +78,6 @@ public static int Run(
return ExitCodes.InvalidBaselineOrPolicy;
}

// Minimal #27 compile-fix only: Compare then Evaluate, replacing the
// deleted Evaluate(observations, baseline, policy) overload. This is
// NOT #29's CheckCommand rewrite — no compare subcommand wiring, no
// reporter changes, no docs. That work stays scoped to #29.
var comparison = BenchmarkComparisonEngine.Compare(baseline, observations);
var decision = RegressionEvaluator.Evaluate(comparison, policy);

Expand Down
149 changes: 149 additions & 0 deletions src/BenchmarkGate.Tool/Commands/CompareCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
using Bijecta.BenchmarkGate.BenchmarkDotNet.Parsing;
using Bijecta.BenchmarkGate.Core.Baseline;
using Bijecta.BenchmarkGate.Core.Comparison;
using Bijecta.BenchmarkGate.Core.Evaluation;
using Bijecta.BenchmarkGate.Core.Model;
using Bijecta.BenchmarkGate.Reporting;
using Bijecta.BenchmarkGate.Storage.FileSystem;
using Bijecta.BenchmarkGate.Tool.Baseline;

namespace Bijecta.BenchmarkGate.Tool.Commands;

/// <summary>
/// Implements <c>benchmark-gate compare</c>. Argument acquisition lives in
/// Program.cs (System.CommandLine, per ADR-0002). This type orchestrates:
/// parse -> load baseline -> BenchmarkComparisonEngine.Compare -> report ->
/// exit code.
/// </summary>
/// <remarks>
/// No policy acquisition anywhere in this path — compare is deliberately
/// policy-free. This type must not itself match benchmarks, match metrics,
/// check units, calculate deltas, or derive direction — all of that is
/// <c>BenchmarkComparisonEngine</c>'s job, called once, from one place,
/// same as <c>CheckCommand</c>.
/// </remarks>
internal static class CompareCommand
{
public static int Run(
string resultsPath,
string baselinePath,
string format,
string? outputPath,
bool quiet,
TextWriter stdout,
TextWriter stderr)
{
if (format is not ("console" or "json" or "markdown"))
{
stderr.WriteLine($"Invalid --format value '{format}'. Expected console, json, or markdown.");
return ExitCodes.InvalidArguments;
}

// console can go to stdout with no --output; json/markdown
// reporters only know how to write to a path (see #28), so
// --output is required for those two. Validated here, before any
// I/O — nothing has been attempted yet, so this is InvalidArguments,
// not a write failure. This is a conditional requirement
// System.CommandLine's per-option Required flag can't express on
// its own.
if (format is "json" or "markdown" && string.IsNullOrWhiteSpace(outputPath))
{
stderr.WriteLine($"--output is required when --format is '{format}'.");
return ExitCodes.InvalidArguments;
}

IReadOnlyList<BenchmarkObservation> observations;
try
{
observations = BenchmarkDotNetResultParser.ParsePath(resultsPath);
}
catch (BenchmarkResultParseException ex)
{
stderr.WriteLine($"Failed to parse results: {ex.Message}");
return ExitCodes.UnsupportedSchema;
}

BenchmarkBaseline baseline;
try
{
baseline = BaselineFile.Load(baselinePath);
}
catch (BaselineFileException ex)
{
stderr.WriteLine($"Failed to load baseline: {ex.Message}");
return ExitCodes.InvalidBaselineOrPolicy;
}

var comparison = BenchmarkComparisonEngine.Compare(baseline, observations);

try
{
WriteReport(comparison, format, outputPath, quiet, stdout);
}
catch (ReportWriteException ex)
{
stderr.WriteLine($"Failed to write report: {ex.Message}");
return ExitCodes.OutputWriteFailure;
}

// Comparison completed, regardless of what it found — compare has
// no severity verdict. A regression, an added/removed benchmark, a
// missing metric: none of these are process failures, they're
// comparison results.
return ExitCodes.Passed;
}

/// <summary>
/// --quiet controls terminal output only — it must never suppress an
/// explicitly requested output artifact (a file the user asked for via
/// --output still gets written even under --quiet).
/// </summary>
internal static void WriteReport(
ComparisonResult comparison, string format, string? outputPath, bool quiet, TextWriter stdout)
{
switch (format)
{
case "console" when outputPath is not null:
WriteConsoleReportToFile(comparison, outputPath);
break;

case "console":
if (!quiet)
{
ConsoleComparisonReporter.Write(stdout, comparison);
}
break;

case "json":
JsonComparisonReporter.Write(outputPath!, comparison);
break;

case "markdown":
MarkdownComparisonReporter.Write(outputPath!, comparison);
break;
}
}

/// <summary>
/// Renders console-format output to a string first, then writes it via
/// <see cref="AtomicFileWriter"/> — matching <c>JsonComparisonReporter</c>/
/// <c>MarkdownComparisonReporter</c>'s atomicity guarantee (and
/// <c>MarkdownReporter</c>/<c>JunitReporter</c>'s established pattern for
/// a text-rendered report) rather than a one-off raw <see cref="StreamWriter"/>
/// that could leave a partially-written file on a mid-write failure.
/// </summary>
private static void WriteConsoleReportToFile(ComparisonResult comparison, string outputPath)
{
using var stringWriter = new StringWriter();
ConsoleComparisonReporter.Write(stringWriter, comparison);

try
{
AtomicFileWriter.Write(outputPath, stringWriter.ToString());
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
throw new ReportWriteException(outputPath, "Failed to write console-format comparison report.", ex);
}
}
}
21 changes: 21 additions & 0 deletions src/BenchmarkGate.Tool/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,31 @@
Console.Out,
Console.Error));

var compareResultsOption = new Option<string>("--results") { Required = true };
var compareBaselineOption = new Option<string>("--baseline") { Required = true };
var compareFormatOption = new Option<string>("--format") { DefaultValueFactory = _ => "console" };
var compareOutputOption = new Option<string?>("--output");
var compareQuietOption = new Option<bool>("--quiet");

var compareCommand = new Command("compare", "Compare BenchmarkDotNet results against a baseline. Policy-free — no pass/fail verdict.")
{
compareResultsOption, compareBaselineOption, compareFormatOption, compareOutputOption, compareQuietOption,
};

compareCommand.SetAction(parseResult => CompareCommand.Run(
parseResult.GetValue(compareResultsOption)!,
parseResult.GetValue(compareBaselineOption)!,
parseResult.GetValue(compareFormatOption)!,
parseResult.GetValue(compareOutputOption),
parseResult.GetValue(compareQuietOption),
Console.Out,
Console.Error));


var rootCommand = new RootCommand("BenchmarkGate — a local-first performance regression gate for BenchmarkDotNet.")
{
checkCommand,
compareCommand,
captureCommand,
validateCommand,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@
<PackageReference Include="xunit.v3" />
</ItemGroup>

<ItemGroup>
<None Include="Fixtures\sample-results.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\BenchmarkGate.Tool\BenchmarkGate.Tool.csproj" />
</ItemGroup>
Expand Down
Loading
Loading