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
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,26 @@ All notable changes to BenchmarkGate are documented here.

## [Unreleased]

### Fixed
- `BdnParameterStringParser` no longer silently discards malformed BenchmarkDotNet
parameter fragments (e.g. `N1000000` missing its `=`, or `=1000000` with an empty
key). Parsing now returns both successfully parsed parameters and structured
parse issues via the new `ParameterParseResult`/`ParameterParseIssue` types.
- Added diagnostic `BGV306` (Error) — malformed BenchmarkDotNet parameter fragment,
reported at `/Benchmarks/{index}/Parameters`. A malformed fragment can silently
drop from a benchmark's identity, which was confirmed (via fixture testing) able
to collapse two otherwise-distinct benchmarks into the same canonical identity —
so this blocks observation compilation rather than being a cosmetic warning.

### Changed
- `IdentityFactory.TryCreate` renamed to `IdentityFactory.Create` and now returns
`IdentityCreationResult(BenchmarkIdentity? Identity, IReadOnlyList<ParameterParseIssue> ParameterIssues)`
instead of a bare `BenchmarkIdentity?`, so parameter-string interpretation happens
in exactly one place and both `ObservationValidator` and
`BenchmarkDotNetResultParser` consume the same result. All call sites
(`ObservationValidator`, `ObservationSetValidator`, `BenchmarkDotNetResultParser`)
updated accordingly. Pre-1.0 breaking change, no external consumers.

## [0.4.0-alpha.1] - 06/08/2026

### Added
Expand Down
102 changes: 84 additions & 18 deletions src/BenchmarkGate.BenchmarkDotNet/Parsing/BdnParameterStringParser.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,103 @@
namespace Bijecta.BenchmarkGate.BenchmarkDotNet.Parsing;

/// <summary>
/// The categories of malformed parameter fragment that
/// <see cref="BdnParameterStringParser"/> can encounter. Each corresponds
/// to a distinct malformed input shape — see <see cref="ParameterParseIssue"/>.
/// No broader taxonomy is introduced until a concrete BenchmarkDotNet
/// output shape requires it (see Issue #16).
/// </summary>
internal enum ParameterParseIssueKind
{
/// <summary>The fragment contains no '=' separator at all, e.g. "N1000000".</summary>
MissingSeparator,

/// <summary>
/// The fragment contains a '=' separator, but the key portion before it
/// is empty, e.g. "=1000000".
/// </summary>
EmptyKey
}

/// <summary>
/// One malformed fragment encountered while parsing a BenchmarkDotNet
/// parameter display string. Preserved rather than discarded so callers
/// can report a precise diagnostic instead of silently losing the
/// fragment.
/// </summary>
/// <param name="FragmentIndex">
/// The position of this fragment among the non-empty, comma-separated
/// fragments of the display string (empty fragments, e.g. from a trailing
/// comma, are skipped before indexing — matching this parser's prior
/// behavior — so this is not a raw character offset).
/// </param>
/// <param name="Fragment">
/// The raw, untrimmed fragment text exactly as it appeared in the display
/// string.
/// </param>
/// <param name="Kind">The specific way this fragment is malformed.</param>
internal sealed record ParameterParseIssue(
int FragmentIndex,
string Fragment,
ParameterParseIssueKind Kind);

/// <summary>
/// The outcome of parsing a BenchmarkDotNet parameter display string:
/// every successfully parsed key/value pair, plus every malformed
/// fragment encountered along the way. Both are preserved in full so
/// downstream diagnostics never need to reparse or guess — see Issue #16.
/// </summary>
/// <param name="Parameters">Successfully parsed key/value pairs, keyed by parameter name.</param>
/// <param name="Issues">
/// Malformed fragments encountered during parsing, in the order they were
/// found. Empty when every fragment parsed successfully.
/// </param>
internal sealed record ParameterParseResult(
IReadOnlyDictionary<string, string> Parameters,
IReadOnlyList<ParameterParseIssue> Issues);

/// <summary>
/// Parses BenchmarkDotNet's single-string parameter display format
/// ("N=1000000,Distribution=Canonical") into a key/value dictionary.
/// Key ordering and invariant-culture value normalization are handled by
/// <see cref="Core.Identity.BenchmarkIdentity"/> itself; this class only
/// splits the display string.
/// ("N=1000000,Distribution=Canonical") into a key/value dictionary,
/// preserving any malformed fragments encountered rather than discarding
/// them. Key ordering and invariant-culture value normalization are
/// handled by <see cref="Core.Identity.BenchmarkIdentity"/> itself; this
/// class only splits the display string.
/// </summary>
internal static class BdnParameterStringParser
{
public static Dictionary<string, string> Parse(string? parametersDisplayString)
public static ParameterParseResult Parse(string? parametersDisplayString)
{
var result = new Dictionary<string, string>(StringComparer.Ordinal);
var parameters = new Dictionary<string, string>(StringComparer.Ordinal);
var issues = new List<ParameterParseIssue>();

if (string.IsNullOrWhiteSpace(parametersDisplayString))
return result;
return new ParameterParseResult(parameters, issues);

var fragments = parametersDisplayString.Split(',', StringSplitOptions.RemoveEmptyEntries);

foreach (var pair in parametersDisplayString.Split(',', StringSplitOptions.RemoveEmptyEntries))
for (var fragmentIndex = 0; fragmentIndex < fragments.Length; fragmentIndex++)
{
var separatorIndex = pair.IndexOf('=');
if (separatorIndex <= 0)
var fragment = fragments[fragmentIndex];
var separatorIndex = fragment.IndexOf('=');

if (separatorIndex < 0)
{
// Malformed pair without '=' — skip rather than throw here;
// the identity will simply not include this fragment.
// A future version could surface this as a diagnostic.
issues.Add(new ParameterParseIssue(fragmentIndex, fragment, ParameterParseIssueKind.MissingSeparator));
continue;
}

var key = pair[..separatorIndex].Trim();
var value = pair[(separatorIndex + 1)..].Trim();
result[key] = value;
if (separatorIndex == 0)
{
issues.Add(new ParameterParseIssue(fragmentIndex, fragment, ParameterParseIssueKind.EmptyKey));
continue;
}

var key = fragment[..separatorIndex].Trim();
var value = fragment[(separatorIndex + 1)..].Trim();
parameters[key] = value;
}

return result;
return new ParameterParseResult(parameters, issues);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,11 @@ private static List<BenchmarkObservation> CompileObservations(BdnReportRootDto d
private static BenchmarkObservation CompileObservation(BdnBenchmarkDto benchmark)
{
// Trusts ObservationValidator has already confirmed Type, Method,
// and Statistics.Mean are present — this method does not re-check
// them, matching PolicyCompiler/BaselineCompiler's CompileValidated
// pattern (one implementation of each rule, not two).
var identity = IdentityFactory.TryCreate(benchmark)
// Statistics.Mean, and parameter-fragment well-formedness (BGV306)
// — this method does not re-check them, matching
// PolicyCompiler/BaselineCompiler's CompileValidated pattern (one
// implementation of each rule, not two).
var identity = IdentityFactory.Create(benchmark).Identity
?? throw new InvalidOperationException(
"CompileObservation called with an entry that did not pass ObservationValidator.");

Expand Down
36 changes: 28 additions & 8 deletions src/BenchmarkGate.BenchmarkDotNet/Validation/IdentityFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,31 @@

namespace Bijecta.BenchmarkGate.BenchmarkDotNet.Validation;

/// <summary>
/// The outcome of interpreting one BdnBenchmarkDto as a BenchmarkIdentity:
/// the identity itself, plus any malformed parameter fragments
/// encountered while parsing. Identity is absent only when Type or Method
/// is missing — the caller is responsible for having already reported
/// that via BGV301/BGV302.
/// </summary>
/// <param name="Identity">The constructed identity, or null if Type or Method was missing.</param>
/// <param name="ParameterIssues">
/// Malformed parameter fragments encountered while parsing, in the order
/// they were found. Empty when parsing succeeded cleanly or was not
/// attempted (Identity is null).
/// </param>
internal sealed record IdentityCreationResult(
BenchmarkIdentity? Identity,
IReadOnlyList<ParameterParseIssue> ParameterIssues);

/// <summary>
/// Builds a BenchmarkIdentity from a raw BdnBenchmarkDto, shared by
/// ObservationValidator (duplicate detection) and
/// BenchmarkDotNetResultParser (final BenchmarkObservation compilation)
/// so identity composition exists in exactly one place. Returns null only
/// when Type or Method is missing — the caller is responsible for having
/// already reported that via BGV301/BGV302.
/// BenchmarkDotNetResultParser (final BenchmarkObservation compilation) so
/// identity composition — and parameter-string parsing — exists in
/// exactly one place. ObservationValidator must never call
/// BdnParameterStringParser directly; all interpretation of a benchmark's
/// raw parameter string goes through this class (see Issue #16).
/// </summary>
internal static class IdentityFactory
{
Expand All @@ -18,14 +36,16 @@ internal static class IdentityFactory
private static readonly System.Text.RegularExpressions.Regex JobTokenPattern =
new(@": (?<job>[^\s(]+)", System.Text.RegularExpressions.RegexOptions.Compiled);

internal static BenchmarkIdentity? TryCreate(BdnBenchmarkDto benchmark)
internal static IdentityCreationResult Create(BdnBenchmarkDto benchmark)
{
if (string.IsNullOrWhiteSpace(benchmark.Type) || string.IsNullOrWhiteSpace(benchmark.Method))
return null;
return new IdentityCreationResult(Identity: null, ParameterIssues: []);

var job = ExtractJob(benchmark.DisplayInfo);
var parameters = BdnParameterStringParser.Parse(benchmark.Parameters);
return new BenchmarkIdentity(benchmark.Type, benchmark.Method, job, parameters);
var parameterResult = BdnParameterStringParser.Parse(benchmark.Parameters);
var identity = new BenchmarkIdentity(benchmark.Type, benchmark.Method, job, parameterResult.Parameters);

return new IdentityCreationResult(identity, parameterResult.Issues);
}

private static string ExtractJob(string? displayInfo)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ internal static IReadOnlyList<SourceValidationDiagnostic> ValidateWithSources(

foreach (var benchmark in parsed.Document.Benchmarks ?? [])
{
var identity = IdentityFactory.TryCreate(benchmark);
var identity = IdentityFactory.Create(benchmark).Identity;
if (identity is null || !identitiesInThisFile.Add(identity))
continue;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ namespace Bijecta.BenchmarkGate.BenchmarkDotNet.Validation;
/// Validates one deserialized BenchmarkDotNet report document, collecting
/// every finding in one pass rather than failing fast. Adapter-owned per
/// ADR-0003 — Core has no knowledge of BenchmarkDotNet's document shape or
/// these BGV3xx codes.
/// these BGV3xx codes. Parameter-string parsing is never performed here
/// directly — all identity/parameter interpretation goes through
/// IdentityFactory (see Issue #16).
/// </summary>
internal static class ObservationValidator
{
Expand Down Expand Up @@ -61,8 +63,17 @@ internal static ValidationResult Validate(BdnReportRootDto document)
// constructible identity — an entry already missing Type/Method
// has no trustworthy identity to compare, and would otherwise
// produce a spurious duplicate alongside its real BGV301/302.
var identity = IdentityFactory.TryCreate(benchmark);
if (identity is not null && !seenIdentities.Add(identity))
var identityResult = IdentityFactory.Create(benchmark);

foreach (var issue in identityResult.ParameterIssues)
{
diagnostics.Add(new ValidationDiagnostic(
ObservationValidatorDiagnostics.MalformedParameterFragment,
$"{path}/Parameters",
DescribeParameterIssue(issue)));
}

if (identityResult.Identity is { } identity && !seenIdentities.Add(identity))
{
diagnostics.Add(new ValidationDiagnostic(
ObservationValidatorDiagnostics.DuplicateIdentityWithinFile, path,
Expand All @@ -72,4 +83,15 @@ internal static ValidationResult Validate(BdnReportRootDto document)

return new ValidationResult(diagnostics);
}

private static string DescribeParameterIssue(ParameterParseIssue issue) => issue.Kind switch
{
ParameterParseIssueKind.MissingSeparator =>
$"Malformed BenchmarkDotNet parameter fragment at position {issue.FragmentIndex}: " +
$"'{issue.Fragment}' does not contain a '=' separator.",
ParameterParseIssueKind.EmptyKey =>
$"Malformed BenchmarkDotNet parameter fragment at position {issue.FragmentIndex}: " +
$"'{issue.Fragment}' has an empty parameter name.",
_ => $"Malformed BenchmarkDotNet parameter fragment at position {issue.FragmentIndex}: '{issue.Fragment}'.",
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,13 @@ internal static class ObservationValidatorDiagnostics
new("BGV304", "Duplicate benchmark identity within one file", Core.Validation.DiagnosticSeverity.Error);
internal static readonly Core.Validation.DiagnosticDescriptor DuplicateIdentityAcrossFiles =
new("BGV305", "Duplicate benchmark identity across result files", Core.Validation.DiagnosticSeverity.Error);
internal static readonly Core.Validation.DiagnosticDescriptor MalformedParameterFragment =
new("BGV306", "Malformed BenchmarkDotNet parameter fragment", Core.Validation.DiagnosticSeverity.Error);

internal static IReadOnlyList<Core.Validation.DiagnosticDescriptor> All { get; } =
[
MissingBenchmarks, MissingType, MissingMethod, MissingMean,
DuplicateIdentityWithinFile, DuplicateIdentityAcrossFiles,
MalformedParameterFragment,
];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"Title": "ValidMultiFile-a",
"Benchmarks": [
{
"Type": "Ns.MultiFile",
"Method": "MethodA",
"Parameters": "N=1",
"Statistics": { "Mean": 100.0 }
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"Title": "ValidMultiFile-b",
"Benchmarks": [
{
"Type": "Ns.MultiFile",
"Method": "MethodB",
"Parameters": "N=1",
"Statistics": { "Mean": 200.0 }
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"Title": "MalformedParameter-report-full",
"HostEnvironmentInfo": {
"BenchmarkDotNetCaption": "BenchmarkDotNet",
"BenchmarkDotNetVersion": "0.14.0",
"OsVersion": "Linux",
"ProcessorName": "Unknown",
"RuntimeVersion": ".NET 10.0.0"
},
"Benchmarks": [
{
"DisplayInfo": "MalformedParam: DefaultJob [N1000000]",
"Namespace": "Recon.Benchmarks",
"Type": "Recon.Benchmarks.ClassificationBenchmarks",
"Method": "MalformedParam",
"MethodTitle": "MalformedParam",
"Parameters": "N1000000",
"FullName": "Recon.Benchmarks.ClassificationBenchmarks.MalformedParam(N1000000)",
"Statistics": {
"N": 15,
"Min": 4400000.0,
"Mean": 4540000.0,
"Median": 4510000.0,
"Max": 4700000.0,
"StandardDeviation": 85000.0,
"StandardError": 22000.0
},
"Memory": {
"Gen0Collections": 0,
"Gen1Collections": 0,
"Gen2Collections": 0,
"TotalOperations": 15,
"BytesAllocatedPerOperation": 0
}
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
null
Loading
Loading