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
50 changes: 41 additions & 9 deletions .github/workflows/benchmark-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,60 @@ 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
with:
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() }}
Expand All @@ -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
126 changes: 42 additions & 84 deletions benchmarks/registry.py
Original file line number Diff line number Diff line change
@@ -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']
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Execute a single benchmark profile in a fresh interpreter."""

from __future__ import annotations

import json
import os
import sys
from pathlib import Path

from .artifacts import _jsonable
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(_jsonable(measurement)), encoding='utf-8')


if __name__ == '__main__':
main()
Original file line number Diff line number Diff line change
@@ -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 *
Expand All @@ -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,
*,
Expand Down Expand Up @@ -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)
Expand Down
20 changes: 19 additions & 1 deletion tests/perf/test_driver_checks.py
Original file line number Diff line number Diff line change
@@ -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]

Expand Down Expand Up @@ -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', 'content_coding_under_load'],
establish_baseline=True,
)

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) == summary.total
assert os.getpid() not in worker_pids
assert all(record['worker_peak_before_workload_kib'] >= 0 for record in metadata)
4 changes: 2 additions & 2 deletions tests/test_open_loop_benchmark_matrices.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
10 changes: 9 additions & 1 deletion tools/fmt_benchmark_comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -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())
Expand All @@ -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]
Expand Down
Loading