From 2f549e897274e58515e01a10ecc15bfad8741d84 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:20:01 +0000 Subject: [PATCH 1/4] fix: report allocation baseline drift as inconclusive (#144) --- .github/scripts/benchmark_gate.py | 11 +++++-- .github/scripts/test_benchmark_gate.py | 37 ++++++++++++++++++++++-- docs/design.md | 9 ++++-- website/docs/contributing/performance.md | 7 +++-- 4 files changed, 54 insertions(+), 10 deletions(-) diff --git a/.github/scripts/benchmark_gate.py b/.github/scripts/benchmark_gate.py index f36935af4..264284959 100644 --- a/.github/scripts/benchmark_gate.py +++ b/.github/scripts/benchmark_gate.py @@ -118,9 +118,9 @@ def compare(baseline, candidate, *, baseline_after=None, enforce_startup_budget= raise GateError(f"{identity}: repeated baseline metadata differs") throughput = before.mean_ns / after.mean_ns - 1 # A fixed baseline-candidate-baseline sequence exposes drift between processes. - # Throughput must regress against both references; allocations must satisfy both. + # Confirm regressions against both references; report baseline drift explicitly. upper = max(before.upper_ns, repeated.upper_ns) - allocated = min(before.allocated_bytes, repeated.allocated_bytes) + allocated = max(before.allocated_bytes, repeated.allocated_bytes) throughput_failure = max(0, after.lower_ns) > upper / (1 - MAX_THROUGHPUT_LOSS) startup = (after.type_name, after.method) == ("StartupBenchmarks", "Build100Handlers") reasons = [] @@ -132,6 +132,11 @@ def compare(baseline, candidate, *, baseline_after=None, enforce_startup_budget= reasons.append("100-handler startup is not under 50 ms") inconclusive = after.mean_ns > min(before.mean_ns, repeated.mean_ns) / (1 - MAX_THROUGHPUT_LOSS) and not throughput_failure statuses = reasons + (["INCONCLUSIVE: observed throughput loss exceeds 5%; confidence bounds or baseline drift prevent confirmation"] if inconclusive else []) + allocation_inconclusive = (not startup + and after.allocated_bytes > min(before.allocated_bytes, repeated.allocated_bytes) + ALLOCATION_TOLERANCE_BYTES + and after.allocated_bytes <= allocated + ALLOCATION_TOLERANCE_BYTES) + if allocation_inconclusive: + statuses.append("INCONCLUSIVE: observed allocation increase exceeds 0.5 B/op; baseline drift prevents confirmation") if startup: statuses.append("startup allocations are informational") status = "; ".join(statuses) if statuses else "PASS" @@ -143,7 +148,7 @@ def compare(baseline, candidate, *, baseline_after=None, enforce_startup_budget= "", "This gate measures regressions against main, not proof of the raw-client 5% budget.", "Throughput fails only when the candidate lower confidence bound exceeds each baseline upper bound / 0.95. Overlapping bounds or drift with an observed loss are inconclusive, not proof of unchanged performance.", - "Per-message allocations must stay within 0.5 B/op of both baselines; startup allocations are informational and the candidate startup budget remains under 50 ms.", + "Per-message allocations fail only when the candidate exceeds both baselines by more than 0.5 B/op. An increase against only the lower baseline is inconclusive, not proof of unchanged allocations. Startup allocations are informational and the candidate startup budget remains under 50 ms.", "Total receive allocations include fresh DI scopes. Equal scoped baselines establish only zero incremental composition allocations.", "D18 still requires zero pipeline allocations, excluding serializer/native-client allocations; existing positive totals remain visible above.", ]) diff --git a/.github/scripts/test_benchmark_gate.py b/.github/scripts/test_benchmark_gate.py index bee27fd2f..700c82398 100644 --- a/.github/scripts/test_benchmark_gate.py +++ b/.github/scripts/test_benchmark_gate.py @@ -89,10 +89,43 @@ def test_baseline_drift_is_inconclusive_but_sustained_regression_fails(self): failures, _ = gate.compare(first, current, baseline_after=first) self.assertTrue(any("throughput loss" in failure for failure in failures)) - def test_baseline_repeat_cannot_hide_allocation_or_startup_failure(self): + def test_allocation_drift_is_inconclusive_in_both_baseline_orders(self): before, candidate, after = report(), report(), report() - candidate["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] += 1 + for data, allocated in ((before, 1025), (candidate, 1020), (after, 1006)): + data["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] = allocated + first = gate.load_reports(self.write("before", before)) + current = gate.load_reports(self.write("candidate", candidate)) + last = gate.load_reports(self.write("after", after)) + for initial, repeat in ((first, last), (last, first)): + failures, summary = gate.compare(initial, current, baseline_after=repeat) + self.assertEqual([], failures) + self.assertIn("INCONCLUSIVE: observed allocation increase exceeds 0.5 B/op; baseline drift prevents confirmation", summary) + self.assertIn("1020", summary) + self.assertIn("1025", summary) + self.assertIn("1006", summary) + + def test_bracketed_allocations_keep_sub_byte_tolerance_and_confirm_increases(self): + before, after = report(), report() after["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] += 64 + first = gate.load_reports(self.write("before", before)) + last = gate.load_reports(self.write("after", after)) + identity = next(iter(first)) + for repeat in (first, last): + largest = max(first[identity].allocated_bytes, repeat[identity].allocated_bytes) + for excess, should_fail in ((0.5, False), (0.501, True), (1, True)): + candidate = report() + candidate["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] = largest + excess + current = gate.load_reports(self.write("candidate", candidate)) + for initial, repeated in ((first, repeat), (repeat, first)): + with self.subTest(repeated_bytes=repeat[identity].allocated_bytes, excess=excess): + failures, summary = gate.compare(initial, current, baseline_after=repeated) + self.assertEqual(should_fail, any("allocations increased" in failure for failure in failures)) + self.assertEqual(repeat != first and not should_fail, "INCONCLUSIVE: observed allocation" in summary) + + def test_baseline_repeat_cannot_hide_confirmed_allocation_or_startup_failure(self): + before, candidate, after = report(), report(), report() + candidate["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] += 1 + after["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] += 0.25 measurement(next(case for case in candidate["Benchmarks"] if case["Type"] == "StartupBenchmarks"), gate.STARTUP_LIMIT_NS) first = gate.load_reports(self.write("before", before)) current = gate.load_reports(self.write("candidate", candidate)) diff --git a/docs/design.md b/docs/design.md index a725402df..8d02ee47e 100644 --- a/docs/design.md +++ b/docs/design.md @@ -739,9 +739,12 @@ raw-client benchmark pattern. The in-memory gate does not establish real-broker overhead compliance. Fresh receive DI scope costs remain in the reported totals; zero incremental composition allocations do not establish zero total pipeline allocations. CI brackets the candidate with two fixed baseline executions to expose runner -drift. A throughput regression must exceed 5% against both; allocation increases -on the per-message path must stay within 0.5 B/op of each baseline, and candidate -startup stays under 50 ms. Startup allocation totals are informational: randomized +drift. A throughput regression must exceed 5% against both. An allocation +regression on the per-message path must exceed both baselines by more than +0.5 B/op; an increase against only the lower baseline is inconclusive because +unchanged asynchronous executions can allocate different totals. Inconclusive +results remain visible and do not prove unchanged performance. Candidate startup +stays under 50 ms. Startup allocation totals are informational: randomized hashes can change frozen dispatch-table layouts across unchanged processes. --- diff --git a/website/docs/contributing/performance.md b/website/docs/contributing/performance.md index ea6e581ee..dc59b844c 100644 --- a/website/docs/contributing/performance.md +++ b/website/docs/contributing/performance.md @@ -126,8 +126,11 @@ The gate fails when any case: performance or eliminate all runner noise; - increases **per-message** allocations by more than **0.5 B/op**, a sub-byte allowance for amortization and rounding, not an extra allocation budget. The candidate must - satisfy this limit against **each** baseline, so a noisier repeat cannot hide - an allocation increase; + exceed **both** baselines by more than this limit before the gate declares an + allocation regression. An increase against only the lower baseline is reported + as **inconclusive**, not proof of unchanged allocations. Concurrent asynchronous + work includes driver and scheduler allocations that can vary between unchanged + process runs. Both baseline totals and the candidate total remain visible; - takes **50 ms or more** to compose 100 handlers. Startup allocation totals remain visible but are informational. D18 sets an From 976d021f967f2632e1b40740a410e89ec1eed640 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:50:04 +0000 Subject: [PATCH 2/4] fix: verify identical benchmark inputs before classifying allocation drift (#144) --- .github/scripts/benchmark_gate.py | 79 ++++++++++++++++++-- .github/scripts/pin_benchmark_version.py | 6 ++ .github/scripts/test_benchmark_gate.py | 91 ++++++++++++++++++++++++ .github/workflows/performance.yml | 3 + docs/design.md | 9 ++- website/docs/contributing/performance.md | 28 +++++++- 6 files changed, 206 insertions(+), 10 deletions(-) diff --git a/.github/scripts/benchmark_gate.py b/.github/scripts/benchmark_gate.py index 264284959..68506bcfa 100644 --- a/.github/scripts/benchmark_gate.py +++ b/.github/scripts/benchmark_gate.py @@ -3,9 +3,11 @@ import argparse from dataclasses import dataclass, replace +import hashlib import json import math from pathlib import Path +import subprocess import sys @@ -27,11 +29,58 @@ ("InMemoryTransportBenchmarks", "ComposedRoundTrip"), } +# These files do not enter either measured build. The candidate CI driver and +# detector control both executions. Keep every other file, including unknown +# root inputs, tests, scripts, generators, dependencies and the overlaid harness. +NON_BUILD_FILES = { + ".github/scripts/benchmark_gate.py", + ".github/scripts/test_benchmark_gate.py", + ".github/scripts/pin_benchmark_version.py", + ".github/workflows/ci.yml", + ".github/workflows/performance.yml", +} +REQUIRED_INPUTS = { + "global.json", "Directory.Build.props", "Directory.Packages.props", + "src/Relayer/Relayer.csproj", + "src/Relayer.SourceGenerators/Relayer.SourceGenerators.csproj", + "benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj", +} + class GateError(ValueError): """Missing or unusable input; never turn an incomplete run into a pass.""" +def input_manifest(checkout): + """Hash actual checkout inputs after CI overlays the common harness and SDK.""" + checkout = Path(checkout).resolve() + try: + def git(*arguments): + return subprocess.run(["git", "-C", str(checkout), *arguments], check=True, + capture_output=True, text=True, encoding="utf-8").stdout + + if Path(git("rev-parse", "--show-toplevel").strip()).resolve() != checkout: + raise GateError(f"Not a checkout root: {checkout}") + paths = git("ls-files", "--cached", "--others", "--exclude-standard", "-z").split("\0") + manifest = {} + for name in sorted(set(paths)): + if not name or name in NON_BUILD_FILES or name.startswith(("docs/", "website/")): + continue + path = checkout / name + if path.is_symlink(): + raise GateError(f"Cannot verify symlink input: {path}") + if path.is_dir(): + raise GateError(f"Cannot verify directory or submodule input: {path}") + # The common harness overlay can delete a baseline's tracked file. + if path.is_file(): + manifest[name] = hashlib.sha256(path.read_bytes()).hexdigest() + if not REQUIRED_INPUTS <= manifest.keys(): + raise GateError(f"Required comparison inputs missing under {checkout}") + return manifest + except (OSError, subprocess.CalledProcessError) as error: + raise GateError(f"Cannot verify comparison inputs under {checkout}: {error}") from error + + @dataclass(frozen=True) class Measurement: mean_ns: float @@ -97,7 +146,7 @@ def load_reports(directory): return cases -def compare(baseline, candidate, *, baseline_after=None, enforce_startup_budget=True): +def compare(baseline, candidate, *, baseline_after=None, enforce_startup_budget=True, identical_inputs=False): if baseline.keys() != candidate.keys(): missing = sorted(baseline.keys() - candidate.keys()) added = sorted(candidate.keys() - baseline.keys()) @@ -126,7 +175,8 @@ def compare(baseline, candidate, *, baseline_after=None, enforce_startup_budget= reasons = [] if throughput_failure: reasons.append("throughput loss exceeds 5%") - if not startup and after.allocated_bytes > allocated + ALLOCATION_TOLERANCE_BYTES: + allocation_increase = not startup and after.allocated_bytes > allocated + ALLOCATION_TOLERANCE_BYTES + if allocation_increase and not identical_inputs: reasons.append("allocations increased by more than 0.5 B/op") if enforce_startup_budget and startup and after.mean_ns >= STARTUP_LIMIT_NS: reasons.append("100-handler startup is not under 50 ms") @@ -135,7 +185,9 @@ def compare(baseline, candidate, *, baseline_after=None, enforce_startup_budget= allocation_inconclusive = (not startup and after.allocated_bytes > min(before.allocated_bytes, repeated.allocated_bytes) + ALLOCATION_TOLERANCE_BYTES and after.allocated_bytes <= allocated + ALLOCATION_TOLERANCE_BYTES) - if allocation_inconclusive: + if identical_inputs and (allocation_increase or allocation_inconclusive): + statuses.append("INCONCLUSIVE: allocation variation with byte-identical comparison inputs") + elif allocation_inconclusive: statuses.append("INCONCLUSIVE: observed allocation increase exceeds 0.5 B/op; baseline drift prevents confirmation") if startup: statuses.append("startup allocations are informational") @@ -148,10 +200,12 @@ def compare(baseline, candidate, *, baseline_after=None, enforce_startup_budget= "", "This gate measures regressions against main, not proof of the raw-client 5% budget.", "Throughput fails only when the candidate lower confidence bound exceeds each baseline upper bound / 0.95. Overlapping bounds or drift with an observed loss are inconclusive, not proof of unchanged performance.", - "Per-message allocations fail only when the candidate exceeds both baselines by more than 0.5 B/op. An increase against only the lower baseline is inconclusive, not proof of unchanged allocations. Startup allocations are informational and the candidate startup budget remains under 50 ms.", + "Per-message allocations fail only when the candidate exceeds both baselines by more than 0.5 B/op, unless comparison inputs are verified byte-identical. An increase against only the lower baseline is inconclusive, not proof of unchanged allocations. Startup allocations are informational and the candidate startup budget remains under 50 ms.", "Total receive allocations include fresh DI scopes. Equal scoped baselines establish only zero incremental composition allocations.", "D18 still requires zero pipeline allocations, excluding serializer/native-client allocations; existing positive totals remain visible above.", ]) + if identical_inputs: + lines.append("Verified byte-identical comparison inputs: allocation differences are execution variation, not evidence of a source-change regression. Totals remain visible; throughput, startup and input validation still apply.") return failures, "\n".join(lines) @@ -187,6 +241,9 @@ def main(argv=None): compare_parser.add_argument("candidate") compare_parser.add_argument("--baseline-after", type=Path, help="Fixed baseline repeat measured after the candidate") compare_parser.add_argument("--summary", type=Path) + compare_parser.add_argument("--baseline-source", type=Path) + compare_parser.add_argument("--candidate-source", type=Path) + compare_parser.add_argument("--input-manifest", type=Path, help="Retain SHA-256 inventories of both source checkouts") test_parser = commands.add_parser("self-test") test_parser.add_argument("baseline") args = parser.parse_args(argv) @@ -196,7 +253,19 @@ def main(argv=None): self_test(baseline) return 0 baseline_after = None if args.baseline_after is None else load_reports(args.baseline_after) - failures, summary = compare(baseline, load_reports(args.candidate), baseline_after=baseline_after) + identical_inputs = False + source_arguments = (args.baseline_source, args.candidate_source, args.input_manifest) + if any(source_arguments): + if not all(source_arguments): + raise GateError("Source verification requires --baseline-source, --candidate-source and --input-manifest together") + if args.baseline_source.resolve() == args.candidate_source.resolve(): + raise GateError("Source verification requires separate checkouts") + original, current = input_manifest(args.baseline_source), input_manifest(args.candidate_source) + identical_inputs = original == current + args.input_manifest.write_text(json.dumps({"baseline": original, "candidate": current, + "identical": identical_inputs}, indent=2) + "\n", encoding="utf-8") + failures, summary = compare(baseline, load_reports(args.candidate), baseline_after=baseline_after, + identical_inputs=identical_inputs) print(summary) if args.summary: args.summary.write_text(summary + "\n", encoding="utf-8") diff --git a/.github/scripts/pin_benchmark_version.py b/.github/scripts/pin_benchmark_version.py index afc0bf098..2fef3efad 100644 --- a/.github/scripts/pin_benchmark_version.py +++ b/.github/scripts/pin_benchmark_version.py @@ -33,6 +33,12 @@ def pin_version(candidate, baseline): parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)) tree = ET.parse(baseline / PROJECT, parser=parser) reference = package_element(tree.getroot(), "PackageReference") + baseline_version = reference.get("VersionOverride") + if not baseline_version: + central = ET.parse(baseline / "Directory.Packages.props").getroot() + baseline_version = package_element(central, "PackageVersion").get("Version") + if baseline_version == version: + return version reference.set("VersionOverride", version) tree.write(baseline / PROJECT, encoding="utf-8", xml_declaration=False) return version diff --git a/.github/scripts/test_benchmark_gate.py b/.github/scripts/test_benchmark_gate.py index 700c82398..8516f64e4 100644 --- a/.github/scripts/test_benchmark_gate.py +++ b/.github/scripts/test_benchmark_gate.py @@ -3,6 +3,7 @@ import io import json from pathlib import Path +import subprocess import tempfile import unittest import xml.etree.ElementTree as ET @@ -191,6 +192,27 @@ def test_one_byte_allocation_increase_fails(self): after["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] += 1 self.assertIn("allocations increased", self.compare(report(), after)[0]) + def test_verified_identical_inputs_report_allocation_variation_but_keep_other_gates(self): + before, candidate = report(), report() + candidate["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] += 64 + first = gate.load_reports(self.write("before", before)) + current = gate.load_reports(self.write("candidate", candidate)) + failures, summary = gate.compare(first, current, baseline_after=first, identical_inputs=True) + self.assertEqual([], failures) + self.assertIn("INCONCLUSIVE: allocation variation with byte-identical comparison inputs", summary) + self.assertIn("216", summary) + measurement(candidate["Benchmarks"][0], 2000) + measurement(next(case for case in candidate["Benchmarks"] if case["Type"] == "StartupBenchmarks"), gate.STARTUP_LIMIT_NS) + current = gate.load_reports(self.write("candidate", candidate)) + failures, _ = gate.compare(first, current, identical_inputs=True) + self.assertTrue(any("throughput loss" in failure for failure in failures)) + self.assertTrue(any("not under 50 ms" in failure for failure in failures)) + + def test_identical_inputs_do_not_accept_mismatched_reports(self): + cases = gate.load_reports(self.write("before", report())) + with self.assertRaisesRegex(gate.GateError, "case sets differ"): + gate.compare(cases, {}, identical_inputs=True) + def test_fractional_allocation_rounding_passes(self): after = report() after["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] += 0.5 @@ -288,6 +310,69 @@ def test_cli_proves_unchanged_passes_and_real_regression_exits_one(self): self.assertEqual(0, gate.main(["self-test", str(before)])) +class ComparisonInputTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + self.baseline, self.candidate = self.root / "baseline", self.root / "candidate" + for checkout in (self.baseline, self.candidate): + checkout.mkdir() + subprocess.run(["git", "init", "--quiet", str(checkout)], check=True) + for name in gate.REQUIRED_INPUTS: + self.write(checkout, name, "same content") + subprocess.run(["git", "-C", str(checkout), "add", "."], check=True) + + def write(self, checkout, name, content): + path = checkout / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + return path + + def test_only_documentation_and_detector_changes_preserve_identity(self): + for name in ("docs/design.md", "website/docs/contributing/performance.md", + ".github/scripts/benchmark_gate.py", ".github/scripts/test_benchmark_gate.py", + ".github/scripts/pin_benchmark_version.py", + ".github/workflows/ci.yml", ".github/workflows/performance.yml"): + self.write(self.candidate, name, "changed") + self.assertEqual(gate.input_manifest(self.baseline), gate.input_manifest(self.candidate)) + + def test_source_generator_dependencies_sdk_harness_and_unknown_inputs_disable_identity(self): + for name in (*gate.REQUIRED_INPUTS, "src/Relayer/Changed.cs", "new-build-input.targets"): + with self.subTest(name=name): + path = self.candidate / name + original = path.read_bytes() if path.exists() else None + self.write(self.candidate, name, "changed") + self.assertNotEqual(gate.input_manifest(self.baseline), gate.input_manifest(self.candidate)) + if original is None: + path.unlink() + else: + path.write_bytes(original) + + def test_missing_inputs_or_non_checkout_root_fail_closed(self): + (self.candidate / "global.json").unlink() + with self.assertRaises(gate.GateError): + gate.input_manifest(self.candidate) + with self.assertRaises(gate.GateError): + gate.input_manifest(self.baseline / "src") + + def test_cli_verifies_identity_and_retains_manifest(self): + before, candidate = report(), report() + candidate["Benchmarks"][0]["Memory"]["BytesAllocatedPerOperation"] += 1 + first = self.write(self.root, "first/benchmarks-report-full.json", json.dumps(before)).parent + current = self.write(self.root, "current/benchmarks-report-full.json", json.dumps(candidate)).parent + manifest = self.root / "inputs.json" + arguments = ["compare", str(first), str(current), "--baseline-source", str(self.baseline), + "--candidate-source", str(self.candidate), "--input-manifest", str(manifest)] + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(0, gate.main(arguments)) + self.assertTrue(json.loads(manifest.read_text())["identical"]) + self.write(self.candidate, "Directory.Build.props", "changed") + self.assertEqual(1, gate.main(arguments)) + self.assertFalse(json.loads(manifest.read_text())["identical"]) + self.assertEqual(1, gate.main(["compare", str(first), str(current), "--baseline-source", str(self.baseline)])) + + class BenchmarkVersionTests(unittest.TestCase): def setUp(self): self.directory = tempfile.TemporaryDirectory() @@ -318,6 +403,12 @@ def test_explicit_candidate_override_wins_over_central_version(self): project.write_text(project.read_text().replace('Include="BenchmarkDotNet"', 'Include="BenchmarkDotNet" VersionOverride="0.16.0"')) self.assertEqual("0.16.0", pin_benchmark_version.pin_version(self.candidate, self.baseline)) + def test_equal_versions_preserve_byte_identical_harness(self): + (self.baseline / "Directory.Packages.props").write_bytes((self.candidate / "Directory.Packages.props").read_bytes()) + original = (self.baseline / pin_benchmark_version.PROJECT).read_bytes() + self.assertEqual("0.15.8", pin_benchmark_version.pin_version(self.candidate, self.baseline)) + self.assertEqual(original, (self.baseline / pin_benchmark_version.PROJECT).read_bytes()) + def test_missing_or_unresolved_candidate_version_fails_without_baseline_change(self): original = (self.baseline / pin_benchmark_version.PROJECT).read_bytes() for attribute in ('', ' Version="$(BenchmarkVersion)"'): diff --git a/.github/workflows/performance.yml b/.github/workflows/performance.yml index ca2fd4a91..79576b9d4 100644 --- a/.github/workflows/performance.yml +++ b/.github/workflows/performance.yml @@ -164,6 +164,8 @@ jobs: python3 candidate/.github/scripts/benchmark_gate.py compare performance-results/baseline performance-results/candidate --baseline-after performance-results/baseline-after + --baseline-source baseline --candidate-source candidate + --input-manifest performance-inputs.json --summary performance-summary.md - name: Publish comparison summary @@ -183,4 +185,5 @@ jobs: performance-*.log performance-commits.txt performance-harness.sha256 + performance-inputs.json performance-summary.md diff --git a/docs/design.md b/docs/design.md index 8d02ee47e..06748271b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -743,8 +743,13 @@ drift. A throughput regression must exceed 5% against both. An allocation regression on the per-message path must exceed both baselines by more than 0.5 B/op; an increase against only the lower baseline is inconclusive because unchanged asynchronous executions can allocate different totals. Inconclusive -results remain visible and do not prove unchanged performance. Candidate startup -stays under 50 ms. Startup allocation totals are informational: randomized +results remain visible and do not prove unchanged performance. CI hashes actual +comparison inputs after the common harness/SDK overlay. Byte-identical inventories +make allocation differences inconclusive execution variation, even above both +baselines; changed inputs retain the strict threshold. The site documents the +inventory and excluded tooling/documentation. Throughput and input validation +remain active. Candidate startup stays under 50 ms. Startup allocation totals +are informational: randomized hashes can change frozen dispatch-table layouts across unchanged processes. --- diff --git a/website/docs/contributing/performance.md b/website/docs/contributing/performance.md index dc59b844c..ac29e4ff8 100644 --- a/website/docs/contributing/performance.md +++ b/website/docs/contributing/performance.md @@ -133,6 +133,28 @@ The gate fails when any case: process runs. Both baseline totals and the candidate total remain visible; - takes **50 ms or more** to compose 100 handlers. +CI also hashes the actual comparison inputs after overlaying the common harness +and SDK. When the inventories are byte-identical, allocation increases are +reported as **inconclusive execution variation**, even above both baselines: +there is no implementation change to attribute them to. This is not evidence +that the allocation goal is met. The inventory includes production source, +generators, the benchmark harness, SDK selection, dependency versions and build +configuration. Only `docs/`, `website/`, the CI workflow, the detector and its +tests, and the common benchmark-version pinning script are excluded; those do +not enter the measured builds. Every other tracked or unignored file is hashed, +including unknown files. Different inventories retain the strict 0.5 B/op rule. +Throughput, startup and invalid-input checks remain active in both cases. + +To use this check locally, add all three options to the comparison command: + +```powershell +python .github/scripts/benchmark_gate.py compare C:/benchmark-results/baseline C:/benchmark-results/candidate --baseline-source C:/checkouts/baseline --candidate-source C:/checkouts/candidate --input-manifest C:/benchmark-results/performance-inputs.json +``` + +Use the separate checkouts that produced the reports, with their harness and SDK +overlay still in place. CI retains `performance-inputs.json` with the raw reports. +Comparisons without source verification keep the strict allocation rule. + Startup allocation totals remain visible but are informational. D18 sets an allocation budget per message and a time budget for startup. Building frozen dispatch tables can allocate different bucket layouts across processes because @@ -146,9 +168,9 @@ without `--baseline-after` retain the single-baseline rule. The CI detector self-test shows that unchanged measurements pass and injected regressions fail. The comparison prints mean timings as throughput changes and allocation totals in the job summary. When a benchmark run fails, the job -prints the end of its log. The job uploads raw reports, logs, -comparison commits and harness hashes for investigation. Inspect BenchmarkDotNet -error and variation columns when timings are noisy; do not rerun until a noisy +prints the end of its log. The job uploads raw reports, logs, comparison +commits, input inventories and harness hashes for investigation. Inspect +BenchmarkDotNet error and variation columns when timings are noisy; do not rerun until a noisy failure happens to pass. Local numbers are diagnostic only. Do not commit benchmark reports, logs or evidence Markdown. From 0c99e6ac0a7b99e99f342724f8c3eb79e95b699a Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:40:34 +0000 Subject: [PATCH 3/4] fix: exclude agent aliases from benchmark inputs (#144) --- .github/scripts/benchmark_gate.py | 3 ++ .github/scripts/test_benchmark_gate.py | 35 ++++++++++++++++++++++++ website/docs/contributing/performance.md | 7 +++-- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/.github/scripts/benchmark_gate.py b/.github/scripts/benchmark_gate.py index 68506bcfa..c01d51e8c 100644 --- a/.github/scripts/benchmark_gate.py +++ b/.github/scripts/benchmark_gate.py @@ -33,6 +33,9 @@ # detector control both executions. Keep every other file, including unknown # root inputs, tests, scripts, generators, dependencies and the overlaid harness. NON_BUILD_FILES = { + # Agent instruction aliases are symlinks on Linux, placeholders on Windows. + ".claude/skills/issue-pr-loop/SKILL.md", + ".claude/skills/issue-pr-loop/references", ".github/scripts/benchmark_gate.py", ".github/scripts/test_benchmark_gate.py", ".github/scripts/pin_benchmark_version.py", diff --git a/.github/scripts/test_benchmark_gate.py b/.github/scripts/test_benchmark_gate.py index 8516f64e4..0e66583a7 100644 --- a/.github/scripts/test_benchmark_gate.py +++ b/.github/scripts/test_benchmark_gate.py @@ -349,6 +349,41 @@ def test_source_generator_dependencies_sdk_harness_and_unknown_inputs_disable_id else: path.write_bytes(original) + def test_agent_workflow_aliases_do_not_enter_measured_builds(self): + for name in (".claude/skills/issue-pr-loop/SKILL.md", + ".claude/skills/issue-pr-loop/references"): + self.write(self.candidate, name, "agent instruction alias") + self.assertEqual(gate.input_manifest(self.baseline), gate.input_manifest(self.candidate)) + + def symlink(self, name, target, *, directory=False): + path = self.candidate / name + path.parent.mkdir(parents=True, exist_ok=True) + try: + path.symlink_to(target, target_is_directory=directory) + except OSError as error: + self.skipTest(f"Cannot create symlinks: {error}") + return path + + def test_agent_workflow_file_and_directory_symlinks_are_excluded(self): + for checkout in (self.baseline, self.candidate): + self.write(checkout, ".agents/skills/issue-pr-loop/SKILL.md", "instructions") + self.write(checkout, ".agents/skills/issue-pr-loop/references/repository.md", "guidance") + self.symlink(".claude/skills/issue-pr-loop/SKILL.md", + "../../../.agents/skills/issue-pr-loop/SKILL.md") + self.symlink(".claude/skills/issue-pr-loop/references", + "../../../.agents/skills/issue-pr-loop/references", directory=True) + self.assertEqual(gate.input_manifest(self.baseline), gate.input_manifest(self.candidate)) + + def test_other_file_directory_and_broken_symlinks_fail_closed(self): + for target, directory in (("global.json", False), ("src", True), ("missing", False)): + with self.subTest(target=target): + path = self.symlink("unknown-link", target, directory=directory) + try: + with self.assertRaisesRegex(gate.GateError, "Cannot verify symlink input"): + gate.input_manifest(self.candidate) + finally: + path.unlink() + def test_missing_inputs_or_non_checkout_root_fail_closed(self): (self.candidate / "global.json").unlink() with self.assertRaises(gate.GateError): diff --git a/website/docs/contributing/performance.md b/website/docs/contributing/performance.md index ac29e4ff8..44e1f5a4e 100644 --- a/website/docs/contributing/performance.md +++ b/website/docs/contributing/performance.md @@ -140,8 +140,11 @@ there is no implementation change to attribute them to. This is not evidence that the allocation goal is met. The inventory includes production source, generators, the benchmark harness, SDK selection, dependency versions and build configuration. Only `docs/`, `website/`, the CI workflow, the detector and its -tests, and the common benchmark-version pinning script are excluded; those do -not enter the measured builds. Every other tracked or unignored file is hashed, +tests, the common benchmark-version pinning script, and the two agent instruction +aliases (`.claude/skills/issue-pr-loop/SKILL.md` and +`.claude/skills/issue-pr-loop/references`) are excluded; those do not enter the +measured builds. These aliases are symlinks on Linux and can be plain files on +Windows. Other symlinks still fail verification. Every other tracked or unignored file is hashed, including unknown files. Different inventories retain the strict 0.5 B/op rule. Throughput, startup and invalid-input checks remain active in both cases. From 1f98e486b9cc5df12c2a07d0d0af6e637be9ec9a Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:27:16 +0000 Subject: [PATCH 4/4] fix: honor advisory performance checks in merge guards (#144) --- .../issue-pr-loop/references/repository.md | 2 ++ scripts/Assert-PrGreen.ps1 | 24 +++++++++---------- scripts/AssertPrGreenChecks.ps1 | 20 ++++++++++++++++ scripts/Enable-AutoMerge.ps1 | 2 +- scripts/Test-AssertPrGreenChecks.ps1 | 22 +++++++++++++++++ website/docs/contributing/performance.md | 6 +++++ 6 files changed, 63 insertions(+), 13 deletions(-) diff --git a/.agents/skills/issue-pr-loop/references/repository.md b/.agents/skills/issue-pr-loop/references/repository.md index 7cb248c26..96f16b108 100644 --- a/.agents/skills/issue-pr-loop/references/repository.md +++ b/.agents/skills/issue-pr-loop/references/repository.md @@ -22,3 +22,5 @@ Automated review rounds (rework budget): count Claude review comments with `gh a Draft CI: `ci.yml` skips its jobs on draft PR events before renting a build runner. `ready_for_review` starts it on the approved head; `converted_to_draft` cancels an in-flight run through workflow concurrency. The Claude review runs on drafts and is not repeated on `ready_for_review`. `Assert-PrGreen.ps1` denies drafts. Auto-merge: the `main` ruleset requires `CI Passed`, and GitHub's auto-merge waits only for it. The `CI Passed` job name is a `${{ }}` expression that a job skipped by `if:` never evaluates, so a draft run reports the expression text, never the required name, and cannot satisfy it; auto-merge armed right after `gh pr ready` waits for the ready run. Every `CI` job feeds `CI Passed` (`Test-AssertPrGreenChecks.ps1` pins this). `Enable-AutoMerge.ps1` (with `-MarkReady` for the promotion) waits for the ready run's `Detect Changes` job to register, then runs `Assert-PrGreen.ps1 -ForAutoMerge`, which lets only `CI` checks be pending and requires a Claude review comment for the head. On any push to a PR with auto-merge armed, `ci.yml`'s `disarm-auto-merge` job disarms it, and `CI Passed` fails if disarming fails. + +The `Performance` workflow is advisory under D18, including failed, cancelled and pending runs. It is excluded from merge and arming check requirements; `UNSTABLE` permits an immediate merge only when an advisory check explains it and every other check passes. Required CI, review and conflict gates remain enforced. Investigate and disposition advisory failures without retrying for green. diff --git a/scripts/Assert-PrGreen.ps1 b/scripts/Assert-PrGreen.ps1 index 3fa4d3c79..6da5c2c1b 100644 --- a/scripts/Assert-PrGreen.ps1 +++ b/scripts/Assert-PrGreen.ps1 @@ -4,9 +4,10 @@ # Exits 0 ONLY when PR # is provably safe to merge: # - state OPEN and not a draft # - mergeable == MERGEABLE -# - mergeStateStatus == CLEAN -# - every current status check is terminal AND passing (CheckRun: status=COMPLETED and -# conclusion in SUCCESS/SKIPPED/NEUTRAL; StatusContext: state=SUCCESS). Only the newest +# - mergeStateStatus == CLEAN, or UNSTABLE explained by advisory Performance checks +# - every non-advisory current status check is terminal AND passing (CheckRun: status=COMPLETED and +# conclusion in SUCCESS/SKIPPED/NEUTRAL; StatusContext: state=SUCCESS). +# Performance is advisory under D18 and never blocks merging or arming. Only the newest # execution of each check counts, so a run superseded on the same head (a skipped draft # run, or one cancelled by `converted_to_draft`) does not deny forever. # - no current-head top-level review has actionable finding headings @@ -14,13 +15,13 @@ # # -ForAutoMerge is the gate for arming native auto-merge (Enable-AutoMerge.ps1). GitHub's # auto-merge waits only for the `Main` ruleset's required checks, so this mode lets checks of -# the workflow those aggregate (CI) still be pending, and nothing else: +# the workflow those aggregate (CI) still be pending, plus advisory Performance: # - mergeStateStatus may be BLOCKED or UNSTABLE while required checks run -# - every other check is terminal and passing, and no check has failed +# - every other non-advisory check is terminal and passing, and none has failed # - the Claude review workflow has posted its review of the current head # - no actionable top-level review and no unresolved review threads # -# Any other state — pending/queued/in-progress checks, an empty rollup, a failed +# Any other state — blocking pending checks, an empty rollup, a failed non-advisory # check, an unresolved thread, or an API hiccup — exits 1 so the caller MUST NOT # merge. The default on uncertainty is DENY. The caller still judges review content. # @@ -68,10 +69,6 @@ catch { if ($view.state -ne 'OPEN') { Deny "state=$($view.state) (need OPEN)" } if ($view.isDraft) { Deny "PR is a draft; mark it ready only after the draft review lifecycle approves its head" } if ($view.mergeable -ne 'MERGEABLE') { Deny "mergeable=$($view.mergeable) (need MERGEABLE)" } -$allowedMergeStates = if ($ForAutoMerge) { @('CLEAN', 'BLOCKED', 'UNSTABLE', 'HAS_HOOKS') } else { @('CLEAN') } -if ($allowedMergeStates -notcontains $view.mergeStateStatus) { - Deny "mergeStateStatus=$($view.mergeStateStatus) (need $($allowedMergeStates -join '/'))" -} $head = [string]$view.headRefOid if (-not $head) { Deny "PR state omitted headRefOid" } @@ -79,6 +76,9 @@ $checks = @(Select-CurrentCheck @($view.statusCheckRollup)) if ($checks.Count -eq 0) { Deny "statusCheckRollup is empty -- no checks registered yet; refusing to merge blind" } +if (-not (Test-MergeStateAllowed -State $view.mergeStateStatus -Checks $checks -ForAutoMerge:$ForAutoMerge)) { + Deny "mergeStateStatus=$($view.mergeStateStatus) is not allowed by the merge policy" +} $bad = @(Get-CheckDenial -Checks $checks -ForAutoMerge:$ForAutoMerge) if ($bad.Count -gt 0) { @@ -164,9 +164,9 @@ $unresolved = @($reviewThreads | Where-Object { -not $_.isResolved }).Count if ($unresolved -gt 0) { Deny "$unresolved unresolved review thread(s)" } if ($ForAutoMerge) { - Write-Host "OK #${Pr} -- MERGEABLE, no failed or unawaited checks, Claude reviewed $head, no unresolved threads. Safe to arm auto-merge." + Write-Host "OK #${Pr} -- MERGEABLE, no blocking checks, Claude reviewed $head, no unresolved threads. Safe to arm auto-merge." } else { - Write-Host "OK #${Pr} -- MERGEABLE, CLEAN, $($checks.Count) check(s) green, no unresolved threads. Safe to merge." + Write-Host "OK #${Pr} -- MERGEABLE, $($view.mergeStateStatus), all non-advisory checks green, no unresolved threads. Safe to merge." } exit 0 diff --git a/scripts/AssertPrGreenChecks.ps1 b/scripts/AssertPrGreenChecks.ps1 index 06a9d8e7b..be1153fa2 100644 --- a/scripts/AssertPrGreenChecks.ps1 +++ b/scripts/AssertPrGreenChecks.ps1 @@ -52,6 +52,25 @@ function Get-CheckState($Check) { return [string]$Check.state } +function Test-AdvisoryCheck($Check) { + (Test-IsCheckRun $Check) -and [string]$Check.workflowName -ceq 'Performance' +} + +function Test-MergeStateAllowed { + param([string]$State, [object[]]$Checks, [switch]$ForAutoMerge) + + if ($ForAutoMerge) { return $State -in @('CLEAN', 'BLOCKED', 'UNSTABLE', 'HAS_HOOKS') } + if ($State -eq 'CLEAN') { return $true } + # GitHub reports UNSTABLE even when only the advisory workflow is red or pending. + # Get-CheckDenial still enforces every other check before a merge can proceed. + if ($State -eq 'UNSTABLE') { + return @($Checks | Where-Object { + (Test-AdvisoryCheck $_) -and $PassingConclusions -notcontains (Get-CheckState $_) + }).Count -gt 0 + } + return $false +} + # Returns one denial per check that blocks a merge (or, with -ForAutoMerge, arming). function Get-CheckDenial { [CmdletBinding()] @@ -67,6 +86,7 @@ function Get-CheckDenial { "unrecognized check entry: $($check | ConvertTo-Json -Compress)" continue } + if (Test-AdvisoryCheck $check) { continue } $passing = if (Test-IsCheckRun $check) { $PassingConclusions -contains $state } else { $state -eq 'SUCCESS' } if ($passing) { continue } if ($ForAutoMerge -and $PendingStates -contains $state -and diff --git a/scripts/Enable-AutoMerge.ps1 b/scripts/Enable-AutoMerge.ps1 index 3ff921ef2..3dc880052 100644 --- a/scripts/Enable-AutoMerge.ps1 +++ b/scripts/Enable-AutoMerge.ps1 @@ -5,7 +5,7 @@ # the head moved, and waits for the ready CI run to register # (first verifies an active, non-bypassable CI Passed ruleset on the target branch) # 1. captures the head, then runs Assert-PrGreen.ps1 -ForAutoMerge (ready, no failed -# check, nothing pending outside the required CI workflow, +# non-advisory check, nothing pending outside CI except advisory Performance, # finished verdicts from the non-required path-filtered workflows the PR triggers, a # Claude review of this head, no unresolved threads) and stops on any denial # 2. arms gh pr merge --auto --squash --match-head-commit diff --git a/scripts/Test-AssertPrGreenChecks.ps1 b/scripts/Test-AssertPrGreenChecks.ps1 index 3b5bcb285..b4ef141f1 100644 --- a/scripts/Test-AssertPrGreenChecks.ps1 +++ b/scripts/Test-AssertPrGreenChecks.ps1 @@ -40,6 +40,26 @@ Assert-Equal @(Get-CheckDenial @(New-Check 'Unit Tests' 'CI' 'COMPLETED' 'FAILUR Assert-Equal @(Get-CheckDenial @(New-Check 'Lint' 'Other' 'IN_PROGRESS') -ForAutoMerge) @('Lint: state=IN_PROGRESS') 'A pending check of a non-required workflow denies arming' Assert-Equal @(Get-CheckDenial @(New-Check 'Greptile Review' '' 'IN_PROGRESS') -ForAutoMerge) @('Greptile Review: state=IN_PROGRESS') 'A pending app check denies arming' +# The Performance workflow is advisory (D18); it must not become a local merge requirement. +foreach ($mode in @($false, $true)) { + foreach ($state in @('FAILURE', 'CANCELLED', 'TIMED_OUT', 'IN_PROGRESS', 'QUEUED')) { + $check = if ($state -in @('IN_PROGRESS', 'QUEUED')) { + New-Check 'Performance regression gate' 'Performance' $state + } else { New-Check 'Performance regression gate' 'Performance' 'COMPLETED' $state } + Assert-Equal @(Get-CheckDenial @($green + $check) -ForAutoMerge:$mode).Count 0 "Advisory $state does not block (auto=$mode)" + } + $requiredFailure = New-Check 'Performance regression gate' 'CI' 'COMPLETED' 'FAILURE' + Assert-Equal @(Get-CheckDenial @($requiredFailure) -ForAutoMerge:$mode) @('Performance regression gate: state=FAILURE') 'A matching job name in CI is still required' +} +$advisoryFailure = New-Check 'Performance regression gate' 'Performance' 'COMPLETED' 'FAILURE' +Assert-Equal (Test-MergeStateAllowed 'UNSTABLE' @($green + $advisoryFailure)) $true 'Advisory failure can explain UNSTABLE' +Assert-Equal (Test-MergeStateAllowed 'UNSTABLE' $green) $false 'Unexplained UNSTABLE still denies merging' +Assert-Equal (Test-MergeStateAllowed 'BLOCKED' @($green + $advisoryFailure)) $false 'Advisory failure cannot explain blocked protection' +Assert-Equal (Test-MergeStateAllowed 'DIRTY' @($green + $advisoryFailure) -ForAutoMerge) $false 'Conflicts still deny arming' +Assert-Equal @(Get-CheckDenial @($green + $advisoryFailure + $pendingCi)) @('Build & Pack: state=IN_PROGRESS') 'Advisory failure does not hide pending CI' +Assert-Equal @(Get-CheckDenial @($advisoryFailure, $requiredFailure) -ForAutoMerge) @('Performance regression gate: state=FAILURE') 'Advisory failure does not hide failed CI' +Assert-Equal @(Get-CheckDenial @([pscustomobject]@{ context = 'Performance'; state = 'FAILURE' })) @('Performance: state=FAILURE') 'A legacy status cannot impersonate the advisory workflow' + # Claude review of the current head. $review = [pscustomobject]@{ user = [pscustomobject]@{ login = 'github-actions[bot]' }; body = "`nLooks good." } Assert-Equal (Test-ClaudeReviewForHead -Comments @($review) -Head 'abc') $true 'A review comment for the head counts' @@ -51,6 +71,8 @@ Assert-Equal (Test-ClaudeReviewForHead -Comments @($forged) -Head 'abc') $false $ci = Get-Content -Raw (Join-Path $workflows 'ci.yml') Assert-Equal ([regex]::Match($ci, '(?m)^name:\s*(.+)$').Groups[1].Value.Trim()) 'CI' 'ci.yml is the awaited CI workflow' Assert-Equal (@($AutoMergeAwaitedWorkflows) -join ',') 'CI' 'Only required-check workflows are awaited' +$performance = Get-Content -Raw (Join-Path $workflows 'performance.yml') +Assert-Equal ([regex]::Match($performance, '(?m)^name:\s*(.+)$').Groups[1].Value.Trim()) 'Performance' 'The advisory workflow identity matches the gate' $aggregator = [regex]::Match($ci, '(?ms)^ ci-passed:\r?\n(.*?)(?=^ \S|\z)').Groups[1].Value if (-not $aggregator) { throw 'ci.yml has no ci-passed job' } if ($aggregator -notmatch "(?m)^ name: \$\{\{ needs\.changes\.result == 'success' && 'CI Passed' \|\| 'CI Passed \(incomplete\)' \}\}\s*$") { diff --git a/website/docs/contributing/performance.md b/website/docs/contributing/performance.md index 44e1f5a4e..0a42595a5 100644 --- a/website/docs/contributing/performance.md +++ b/website/docs/contributing/performance.md @@ -26,6 +26,12 @@ blocks a merge. It runs: A red `Performance` run on `main` is a regression to investigate, not a reason to rerun. +The merge and auto-merge scripts also treat this workflow as advisory, including +failed, cancelled and pending runs. They still enforce required CI, reviews and +conflict checks. A failure in another workflow remains blocking even if its job +has the same name as the performance job. Keep the reports and investigate the +measurement; an advisory result does not establish compliance with D18. + ## Run locally Use a Release build with no debugger or telemetry listener attached: