From e4bdf33ff35e311e9f077db39ac9172a44fddd28 Mon Sep 17 00:00:00 2001 From: Jacob Stewart <25079070+cobycloud@users.noreply.github.com> Date: Mon, 9 Nov 2026 01:58:28 -0600 Subject: [PATCH 1/2] Isolate benchmark profiles and compare against the PR base Signed-off-by: Jacob Stewart <25079070+cobycloud@users.noreply.github.com> --- .github/workflows/benchmark-pr.yml | 50 +++++-- benchmarks/registry.py | 126 ++++++------------ .../perf_runner/artifacts.py | 1 + .../perf_runner/profile_worker.py | 31 +++++ .../perf_runner/runner.py | 24 +++- tests/perf/test_driver_checks.py | 20 ++- tests/test_open_loop_benchmark_matrices.py | 4 +- tools/fmt_benchmark_comment.py | 10 +- 8 files changed, 165 insertions(+), 101 deletions(-) create mode 100644 pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/profile_worker.py diff --git a/.github/workflows/benchmark-pr.yml b/.github/workflows/benchmark-pr.yml index 924bbed9..3fd04af0 100644 --- a/.github/workflows/benchmark-pr.yml +++ b/.github/workflows/benchmark-pr.yml @@ -15,9 +15,19 @@ jobs: benchmark: runs-on: ubuntu-24.04 timeout-minutes: 30 + defaults: + run: + shell: bash steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: + path: candidate + persist-credentials: false + + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: baseline persist-credentials: false - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 @@ -25,17 +35,40 @@ jobs: python-version: '3.12' - name: Install workspace packages - run: bash scripts/ci/install-workspace.sh + run: | + for tree in baseline candidate; do + venv="$RUNNER_TEMP/benchmark-$tree" + python -m venv "$venv" + (cd "$tree" && PATH="$venv/bin:$PATH" bash scripts/ci/install-workspace.sh) + done + + - name: Measure the base revision + working-directory: baseline + run: | + baseline_root="$RUNNER_TEMP/benchmark-results/baseline" + python="$RUNNER_TEMP/benchmark-baseline/bin/python" + profile_list=$("$python" tools/run_perf_matrix.py --list-profiles) + test -n "$profile_list" + while IFS=$'\t' read -r profile _; do + # One invocation per profile also isolates older base revisions. + rm -f "$baseline_root/summary.json" "$baseline_root/index.json" + "$python" tools/run_perf_matrix.py --establish-baseline \ + --profile "$profile" --artifact-root "$baseline_root" || test -s "$baseline_root/summary.json" + done <<< "$profile_list" + rm -f "$baseline_root/summary.json" "$baseline_root/index.json" - - name: Run benchmark measurements + - name: Compare the PR against the same runner baseline + working-directory: candidate run: | artifact_root="$RUNNER_TEMP/benchmark-results" - mkdir -p "$artifact_root" - if python tools/run_perf_matrix.py --establish-baseline --shuffle --artifact-root "$artifact_root"; then - exit 0 + python="$RUNNER_TEMP/benchmark-candidate/bin/python" + if ! "$python" tools/run_perf_matrix.py --seed 3470812123 \ + --baseline-root "$artifact_root/baseline" --artifact-root "$artifact_root/candidate"; then + test -s "$artifact_root/candidate/summary.json" + echo "::warning::Some benchmark profiles missed their configured checks. See the measurement artifacts." fi - test -s "$artifact_root/summary.json" - echo "::warning::Some benchmark profiles missed their thresholds. See the measurement artifacts." + "$python" tools/fmt_benchmark_comment.py "$artifact_root/candidate/summary.json" \ + "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" >> "$GITHUB_STEP_SUMMARY" - name: Upload measurements if: ${{ !cancelled() }} @@ -46,12 +79,11 @@ jobs: if-no-files-found: ignore retention-days: 7 - - name: Upload comment summary if: ${{ !cancelled() }} uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: benchmark-summary - path: ${{ runner.temp }}/benchmark-results/summary.json + path: ${{ runner.temp }}/benchmark-results/candidate/summary.json if-no-files-found: ignore retention-days: 7 diff --git a/benchmarks/registry.py b/benchmarks/registry.py index eae1fe7f..a158ddaa 100644 --- a/benchmarks/registry.py +++ b/benchmarks/registry.py @@ -1,98 +1,56 @@ from __future__ import annotations -from typing import Callable +from importlib import import_module -from .drivers_http import ( - http11_baseline_driver, - http11_chunked_driver, - http11_keepalive_driver, - http2_multiplex_driver, - http2_tls_driver, - http3_clean_driver, - http3_loss_driver, -) -from .drivers_vegeta import ( - vegeta_http11_constant_rate_driver, - vegeta_http11_recovery_pattern_driver, - vegeta_http11_step_rate_driver, -) -from .drivers_wrk2 import ( - wrk2_http11_constant_rate_driver, - wrk2_http11_step_rate_driver, -) -from .drivers_operator import ( - graceful_drain_driver, - logging_off_driver, - logging_on_driver, - metrics_off_driver, - metrics_on_driver, - proxy_headers_off_driver, - proxy_headers_on_driver, - reload_overhead_driver, - worker_scaleout_driver, -) -from .drivers_peer import http3_peer_prepare_driver -from .drivers_runtime import runtime_scheduler_driver -from .drivers_semantic import connect_relay_driver, content_coding_driver, trailers_driver -from .drivers_tls import alpn_negotiation_driver, mtls_handshake_driver, ocsp_strict_driver, tls_handshake_driver -from .drivers_ws_peer import websocket_peer_frame_driver -from .drivers_websocket import ( - ws_fanout_driver, - ws_http11_deflate_driver, - ws_http11_driver, - ws_http2_deflate_driver, - ws_http2_driver, - ws_http3_deflate_driver, - ws_http3_driver, -) -_DRIVER_REGISTRY: dict[str, Callable[..., dict]] = { - 'http11_baseline': http11_baseline_driver, - 'http11_keepalive': http11_keepalive_driver, - 'http11_chunked_upload_download': http11_chunked_driver, - 'http2_multiplex': http2_multiplex_driver, - 'http2_tls': http2_tls_driver, - 'http3_clean_network': http3_clean_driver, - 'http3_loss_jitter': http3_loss_driver, - 'ws_http11': ws_http11_driver, - 'ws_http11_permessage_deflate': ws_http11_deflate_driver, - 'ws_http2': ws_http2_driver, - 'ws_http2_permessage_deflate': ws_http2_deflate_driver, - 'ws_http3': ws_http3_driver, - 'ws_http3_permessage_deflate': ws_http3_deflate_driver, - 'ws_fanout_broadcast': ws_fanout_driver, - 'tls_handshake': tls_handshake_driver, - 'mtls_handshake': mtls_handshake_driver, - 'ocsp_strict_mode': ocsp_strict_driver, - 'alpn_negotiation_cost': alpn_negotiation_driver, - 'connect_relay_throughput': connect_relay_driver, - 'trailers_under_load': trailers_driver, - 'content_coding_under_load': content_coding_driver, - 'logging_off': logging_off_driver, - 'logging_on': logging_on_driver, - 'metrics_off': metrics_off_driver, - 'metrics_on': metrics_on_driver, - 'proxy_headers_off': proxy_headers_off_driver, - 'proxy_headers_on': proxy_headers_on_driver, - 'worker_scaleout': worker_scaleout_driver, - 'graceful_drain': graceful_drain_driver, - 'reload_overhead': reload_overhead_driver, - 'runtime_scheduler': runtime_scheduler_driver, - 'http3_peer_prepare': http3_peer_prepare_driver, - 'websocket_peer_frame': websocket_peer_frame_driver, - 'wrk2_http11_constant_rate': wrk2_http11_constant_rate_driver, - 'wrk2_http11_step_rate': wrk2_http11_step_rate_driver, - 'vegeta_http11_constant_rate': vegeta_http11_constant_rate_driver, - 'vegeta_http11_step_rate': vegeta_http11_step_rate_driver, - 'vegeta_http11_recovery_pattern': vegeta_http11_recovery_pattern_driver, +_DRIVER_REGISTRY: dict[str, tuple[str, str]] = { + 'http11_baseline': ('drivers_http', 'http11_baseline_driver'), + 'http11_keepalive': ('drivers_http', 'http11_keepalive_driver'), + 'http11_chunked_upload_download': ('drivers_http', 'http11_chunked_driver'), + 'http2_multiplex': ('drivers_http', 'http2_multiplex_driver'), + 'http2_tls': ('drivers_http', 'http2_tls_driver'), + 'http3_clean_network': ('drivers_http', 'http3_clean_driver'), + 'http3_loss_jitter': ('drivers_http', 'http3_loss_driver'), + 'ws_http11': ('drivers_websocket', 'ws_http11_driver'), + 'ws_http11_permessage_deflate': ('drivers_websocket', 'ws_http11_deflate_driver'), + 'ws_http2': ('drivers_websocket', 'ws_http2_driver'), + 'ws_http2_permessage_deflate': ('drivers_websocket', 'ws_http2_deflate_driver'), + 'ws_http3': ('drivers_websocket', 'ws_http3_driver'), + 'ws_http3_permessage_deflate': ('drivers_websocket', 'ws_http3_deflate_driver'), + 'ws_fanout_broadcast': ('drivers_websocket', 'ws_fanout_driver'), + 'tls_handshake': ('drivers_tls', 'tls_handshake_driver'), + 'mtls_handshake': ('drivers_tls', 'mtls_handshake_driver'), + 'ocsp_strict_mode': ('drivers_tls', 'ocsp_strict_driver'), + 'alpn_negotiation_cost': ('drivers_tls', 'alpn_negotiation_driver'), + 'connect_relay_throughput': ('drivers_semantic', 'connect_relay_driver'), + 'trailers_under_load': ('drivers_semantic', 'trailers_driver'), + 'content_coding_under_load': ('drivers_semantic', 'content_coding_driver'), + 'logging_off': ('drivers_operator', 'logging_off_driver'), + 'logging_on': ('drivers_operator', 'logging_on_driver'), + 'metrics_off': ('drivers_operator', 'metrics_off_driver'), + 'metrics_on': ('drivers_operator', 'metrics_on_driver'), + 'proxy_headers_off': ('drivers_operator', 'proxy_headers_off_driver'), + 'proxy_headers_on': ('drivers_operator', 'proxy_headers_on_driver'), + 'worker_scaleout': ('drivers_operator', 'worker_scaleout_driver'), + 'graceful_drain': ('drivers_operator', 'graceful_drain_driver'), + 'reload_overhead': ('drivers_operator', 'reload_overhead_driver'), + 'runtime_scheduler': ('drivers_runtime', 'runtime_scheduler_driver'), + 'http3_peer_prepare': ('drivers_peer', 'http3_peer_prepare_driver'), + 'websocket_peer_frame': ('drivers_ws_peer', 'websocket_peer_frame_driver'), + 'wrk2_http11_constant_rate': ('drivers_wrk2', 'wrk2_http11_constant_rate_driver'), + 'wrk2_http11_step_rate': ('drivers_wrk2', 'wrk2_http11_step_rate_driver'), + 'vegeta_http11_constant_rate': ('drivers_vegeta', 'vegeta_http11_constant_rate_driver'), + 'vegeta_http11_step_rate': ('drivers_vegeta', 'vegeta_http11_step_rate_driver'), + 'vegeta_http11_recovery_pattern': ('drivers_vegeta', 'vegeta_http11_recovery_pattern_driver'), } def get_driver(name: str): try: - return _DRIVER_REGISTRY[name] + module, attribute = _DRIVER_REGISTRY[name] except KeyError as exc: raise KeyError(f'unknown benchmark driver: {name}') from exc + return getattr(import_module(f'.{module}', __package__), attribute) __all__ = ['get_driver'] diff --git a/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/artifacts.py b/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/artifacts.py index ed3d1010..4d25c235 100644 --- a/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/artifacts.py +++ b/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/artifacts.py @@ -145,6 +145,7 @@ def _write_run_summary( { 'profile_id': result.profile_id, 'passed': result.passed, + 'baseline_evaluated': bool(result.relative_regression.get('evaluated')), 'artifact_dir': result.artifact_dir, 'failure_reasons': result.failure_reasons, } diff --git a/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/profile_worker.py b/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/profile_worker.py new file mode 100644 index 00000000..3782f777 --- /dev/null +++ b/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/profile_worker.py @@ -0,0 +1,31 @@ +"""Execute a single benchmark profile in a fresh interpreter.""" + +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path + +from .models import PerfProfile + + +def main() -> None: + from benchmarks.common import _rss_kib + from benchmarks.registry import get_driver + + output = Path(sys.argv[1]) + profile = PerfProfile(**json.load(sys.stdin)) + driver = get_driver(profile.driver) + peak_before = _rss_kib() + measurement = driver(profile, source_root=Path.cwd()) + measurement['metadata'] = { + **measurement.get('metadata', {}), + 'worker_pid': os.getpid(), + 'worker_peak_before_workload_kib': peak_before, + } + output.write_text(json.dumps(measurement), encoding='utf-8') + + +if __name__ == '__main__': + main() diff --git a/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/runner.py b/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/runner.py index 9ef2e931..04483f0b 100644 --- a/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/runner.py +++ b/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/runner.py @@ -1,5 +1,8 @@ from __future__ import annotations +from dataclasses import asdict +from tempfile import TemporaryDirectory + from .imports import * from .models import * from .stats import * @@ -15,6 +18,22 @@ _summarize_measurement, ) +def _measure_profile(profile: PerfProfile, source_root: Path) -> dict[str, Any]: + with TemporaryDirectory(prefix='tigrcorn-profile-') as temp: + output = Path(temp) / 'measurement.json' + try: + subprocess.run( + [sys.executable, '-m', 'tigrcorn_certification.perf_runner.profile_worker', str(output)], + input=json.dumps(asdict(profile)), + text=True, + cwd=source_root, + check=True, + ) + except subprocess.CalledProcessError as exc: + raise PerfRunnerError(f'benchmark worker failed for {profile.profile_id}') from exc + return json.loads(output.read_text(encoding='utf-8')) + + def run_performance_matrix( source_root: str | Path, *, @@ -55,12 +74,9 @@ def run_performance_matrix( commit_hash = _resolve_commit_hash(source_root) environment = _environment_snapshot(matrix=matrix, command=sys.argv) - from benchmarks.registry import get_driver - results: list[PerfProfileResult] = [] for profile in selected_profiles: - driver = get_driver(profile.driver) - measurement = driver(profile, source_root=source_root) + measurement = _measure_profile(profile, source_root) profile_dir = artifact_root / profile.profile_id profile_dir.mkdir(parents=True, exist_ok=True) metrics = _summarize_measurement(measurement, profile=profile) diff --git a/tests/perf/test_driver_checks.py b/tests/perf/test_driver_checks.py index e8ed73c2..89c13c5e 100644 --- a/tests/perf/test_driver_checks.py +++ b/tests/perf/test_driver_checks.py @@ -1,9 +1,10 @@ from __future__ import annotations +import os from pathlib import Path from benchmarks.registry import get_driver -from tigrcorn.compat.perf_runner import PerfProfile +from tigrcorn.compat.perf_runner import PerfProfile, run_performance_matrix ROOT = Path(__file__).resolve().parents[2] @@ -78,3 +79,20 @@ def test_content_coding_correctness(): driver_config={'policy': 'allowlist', 'codings': ['gzip', 'deflate']}, ) _assert_correctness_keys(measurement, ['status_ok', 'selection_valid', 'body_nonempty']) + + + +def test_matrix_runs_each_profile_in_a_fresh_process(tmp_path): + summary = run_performance_matrix( + ROOT, + artifact_root=tmp_path, + profile_ids=['http11_baseline', 'http11_keepalive'], + establish_baseline=True, + ) + + assert summary.total == 2 + metadata = [result.metrics['profile_metadata'] for result in summary.profiles] + worker_pids = {record['worker_pid'] for record in metadata} + assert len(worker_pids) == 2 + assert os.getpid() not in worker_pids + assert all(record['worker_peak_before_workload_kib'] >= 0 for record in metadata) diff --git a/tests/test_open_loop_benchmark_matrices.py b/tests/test_open_loop_benchmark_matrices.py index 0370cad0..bd797ac0 100644 --- a/tests/test_open_loop_benchmark_matrices.py +++ b/tests/test_open_loop_benchmark_matrices.py @@ -145,7 +145,7 @@ def test_vegeta_json_parser_handles_representative_report(self) -> None: def test_runner_can_write_wrk2_artifacts_with_mocked_driver(self) -> None: with tempfile.TemporaryDirectory() as tmp: - with patch("benchmarks.drivers_wrk2._run_wrk2_http11", return_value=_mock_measurement()): + with patch("tigrcorn_certification.perf_runner.runner._measure_profile", return_value=_mock_measurement()): summary = run_performance_matrix( ROOT, matrix_path=WRK2_MATRIX, @@ -161,7 +161,7 @@ def test_runner_can_write_wrk2_artifacts_with_mocked_driver(self) -> None: def test_runner_can_write_vegeta_artifacts_with_mocked_driver(self) -> None: with tempfile.TemporaryDirectory() as tmp: - with patch("benchmarks.drivers_vegeta._run_vegeta_http11", return_value=_mock_measurement()): + with patch("tigrcorn_certification.perf_runner.runner._measure_profile", return_value=_mock_measurement()): summary = run_performance_matrix( ROOT, matrix_path=VEGETA_MATRIX, diff --git a/tools/fmt_benchmark_comment.py b/tools/fmt_benchmark_comment.py index 2b223280..10f78a57 100644 --- a/tools/fmt_benchmark_comment.py +++ b/tools/fmt_benchmark_comment.py @@ -18,6 +18,7 @@ def format_comment(summary: object, run_url: str) -> str: if not isinstance(profiles, list) or not 1 <= len(profiles) <= 100: raise ValueError('expected 1 to 100 benchmark profiles') results: dict[str, bool] = {} + compared = 0 for profile in profiles: if not isinstance(profile, dict): raise ValueError('expected a benchmark profile object') @@ -27,6 +28,10 @@ def format_comment(summary: object, run_url: str) -> str: raise ValueError('invalid or repeated benchmark profile ID') if type(passed) is not bool: raise ValueError('invalid benchmark profile verdict') + baseline_evaluated = profile.get('baseline_evaluated', False) + if type(baseline_evaluated) is not bool: + raise ValueError('invalid benchmark baseline verdict') + compared += baseline_evaluated results[name] = passed passed_count = sum(results.values()) @@ -35,7 +40,10 @@ def format_comment(summary: object, run_url: str) -> str: '## Benchmark measurements', '', f'{passed_count}/{len(results)} profiles passed their configured checks.', - 'This run used absolute thresholds and did not compare against a reference baseline.', + ( + f'{compared}/{len(results)} profiles were also compared with the reference baseline.' + if compared else 'This run used absolute thresholds without a reference baseline comparison.' + ), f'[Workflow run and full measurement artifacts]({run_url})', ] failed_profiles = [name for name, passed in results.items() if not passed] From ad04b2ad27b4520af35ba4f93efcf7dce541626f Mon Sep 17 00:00:00 2001 From: Jacob Stewart <25079070+cobycloud@users.noreply.github.com> Date: Mon, 9 Nov 2026 02:01:27 -0600 Subject: [PATCH 2/2] Normalize worker measurements before serialization Signed-off-by: Jacob Stewart <25079070+cobycloud@users.noreply.github.com> --- .../tigrcorn_certification/perf_runner/profile_worker.py | 3 ++- tests/perf/test_driver_checks.py | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/profile_worker.py b/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/profile_worker.py index 3782f777..8b34fbc5 100644 --- a/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/profile_worker.py +++ b/pkgs/tigrcorn-certification/src/tigrcorn_certification/perf_runner/profile_worker.py @@ -7,6 +7,7 @@ import sys from pathlib import Path +from .artifacts import _jsonable from .models import PerfProfile @@ -24,7 +25,7 @@ def main() -> None: 'worker_pid': os.getpid(), 'worker_peak_before_workload_kib': peak_before, } - output.write_text(json.dumps(measurement), encoding='utf-8') + output.write_text(json.dumps(_jsonable(measurement)), encoding='utf-8') if __name__ == '__main__': diff --git a/tests/perf/test_driver_checks.py b/tests/perf/test_driver_checks.py index 89c13c5e..6979c300 100644 --- a/tests/perf/test_driver_checks.py +++ b/tests/perf/test_driver_checks.py @@ -86,13 +86,13 @@ def test_matrix_runs_each_profile_in_a_fresh_process(tmp_path): summary = run_performance_matrix( ROOT, artifact_root=tmp_path, - profile_ids=['http11_baseline', 'http11_keepalive'], + profile_ids=['http11_baseline', 'http11_keepalive', 'content_coding_under_load'], establish_baseline=True, ) - assert summary.total == 2 + assert summary.total == 3 metadata = [result.metrics['profile_metadata'] for result in summary.profiles] worker_pids = {record['worker_pid'] for record in metadata} - assert len(worker_pids) == 2 + assert len(worker_pids) == summary.total assert os.getpid() not in worker_pids assert all(record['worker_peak_before_workload_kib'] >= 0 for record in metadata)