name: benchmark "on": push: branches: - main - dev - deps pull_request: branches: - main workflow_dispatch: inputs: ref: description: (optional) ref to benchmark env: FORCE_COLOR: "1" PYTHONHASHSEED: "42" BASELINE_RELEASE_TAG: microbenchmarks # Cachegrind counts instructions rather than measuring time, so comparing them is # reproducible and can be held to a tight bound. A change of more than this much in # either direction is called out. # # There is deliberately no wall-clock threshold. The timings pytest-benchmark reports # here are measured *under* Cachegrind, and vary far more between runs of identical code # than any change worth catching: revisions whose bidict/ was byte-identical have been # seen to differ by tens of percent, in both directions. They are still compared in the # run output, which is archived below for eyeballing, but nothing keys off them. INSTRUCTION_CHANGE_PCT: "1.0" jobs: benchmark: runs-on: ubuntu-24.04 steps: - name: install valgrind uses: awalsh128/cache-apt-pkgs-action@553a35bb8ebd9fcabcb1c9451aa4c98e1b4ca8a9 with: packages: valgrind - name: check out source uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 with: fetch-depth: 0 - name: install Nix uses: DeterminateSystems/nix-installer-action@ef8a148080ab6020fd15196c2084a2eea5ff2d25 - name: resolve benchmark metadata id: metadata run: | mapfile -t python_info < <(nix develop .#benchmark --command bash -c "python - <<'PY' import platform print(platform.python_version()) print(platform.python_implementation()) PY") python_version=${python_info[0]} python_impl=${python_info[1]} python_series=${python_version%.*} arch=$(uname -m) baseline_asset_name="GHA-linux-cachegrind-${arch}-${python_impl}-${python_series}-baseline.json" baseline_url="https://github.com/${GITHUB_REPOSITORY}/releases/download/${BASELINE_RELEASE_TAG}/${baseline_asset_name}" instr_asset_name="GHA-linux-cachegrind-${arch}-${python_impl}-${python_series}-instructions.txt" instr_url="https://github.com/${GITHUB_REPOSITORY}/releases/download/${BASELINE_RELEASE_TAG}/${instr_asset_name}" { echo "python_version=$python_version" echo "python_series=$python_series" echo "baseline_asset_name=$baseline_asset_name" echo "baseline_url=$baseline_url" echo "instr_asset_name=$instr_asset_name" echo "instr_url=$instr_url" } >> "$GITHUB_OUTPUT" - name: benchmark and compare to baseline id: benchmark run: | set +e nix develop .#benchmark --command bash -c ' set -euo pipefail git checkout ${{ github.event.inputs.ref || github.sha }} # install a non-editable version of bidict at the revision under test uv pip install --python "$VIRTUAL_ENV/bin/python" --no-deps . # restore the current revision so we use its version of tests/microbenchmarks.py git checkout ${{ github.sha }} # move aside the '"'"'bidict'"'"' subdirectory to make sure we always import the installed version mv -v bidict src curl -L -s -o baseline.json "${{ steps.metadata.outputs.baseline_url }}" line1=$(head -n1 baseline.json) [ "$line1" = "{" ] ./cachegrind.py pytest -c /dev/null -n0 \ --benchmark-autosave \ --benchmark-columns=min,rounds,iterations \ --benchmark-disable-gc \ --benchmark-group-by=name \ --benchmark-compare=baseline.json \ microbenchmarks.py ' 2>&1 | tee benchmark-output.txt benchmark_status=${PIPESTATUS[0]} # Nothing here is allowed to fail the job except the run itself failing, which # means pytest could not benchmark the revision at all. if [ "$benchmark_status" -eq 0 ]; then result_state=ok result_message='benchmarks ran' else result_state=failed result_message='benchmark execution failed' fi { echo "exit_code=$benchmark_status" echo "result_state=$result_state" echo "result_message=$result_message" } >> "$GITHUB_OUTPUT" exit "$benchmark_status" env: CACHEGRIND_ESTIMATE_OUT: ${{ github.workspace }}/instructions.txt - name: compare instruction estimate to baseline id: instructions if: always() env: INSTR_URL: ${{ steps.metadata.outputs.instr_url }} run: | # This comparison is reproducible where a wall-clock one is not: two runs of the # same revision have been measured 0.13% apart, against swings of tens of percent # for the per-benchmark timings. state=unavailable delta= now= baseline= if [ ! -s instructions.txt ]; then # Distinct from a missing baseline: this means cachegrind.py did not honor # CACHEGRIND_ESTIMATE_OUT, i.e. something here is broken rather than unpublished. summary='cachegrind.py recorded no instruction estimate' elif ! curl -fL -s -o instructions-baseline.txt "$INSTR_URL" || [ ! -s instructions-baseline.txt ]; then summary="no instruction baseline published yet (${INSTR_URL##*/})" else now=$(cat instructions.txt) baseline=$(cat instructions-baseline.txt) delta=$(python -c "print(f'{($now - $baseline) / $baseline * 100:+.2f}')") state=$(python -c "d = $delta; p = $INSTRUCTION_CHANGE_PCT; print('regression' if d > p else 'improved' if d < -p else 'ok')") if [ "$state" = regression ]; then summary="${delta}% vs baseline, over the ${INSTRUCTION_CHANGE_PCT}% threshold" else summary="${delta}% vs baseline" fi fi { echo "state=$state" echo "summary=$summary" echo "delta=$delta" echo "now=$now" echo "baseline=$baseline" } >> "$GITHUB_OUTPUT" # Warn only on pull requests, matching the timing check: on a push the baseline is # whatever was last published, so drift since then is expected rather than notable. if [ "$state" = regression ] && [ "${{ github.event_name }}" = "pull_request" ]; then echo "::warning::Instruction count regressed by ${delta}% vs the baseline (threshold ${INSTRUCTION_CHANGE_PCT}%)." fi - name: summarize benchmark result if: always() run: | { echo '## Benchmark result' echo echo "- Baseline asset: \`${{ steps.metadata.outputs.baseline_asset_name }}\`" echo "- Benchmark run: [${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID})" echo "- Instruction threshold: \`${INSTRUCTION_CHANGE_PCT}%\`" echo "- Result: ${{ steps.benchmark.outputs.result_message }}" echo "- Instruction count: ${{ steps.instructions.outputs.summary }}" } >> "$GITHUB_STEP_SUMMARY" - name: prepare PR benchmark comment if: always() && github.event_name == 'pull_request' env: BASELINE_ASSET_NAME: ${{ steps.metadata.outputs.baseline_asset_name }} PR_NUMBER: ${{ github.event.pull_request.number }} RESULT_MESSAGE: ${{ steps.benchmark.outputs.result_message }} RESULT_STATE: ${{ steps.benchmark.outputs.result_state }} INSTR_STATE: ${{ steps.instructions.outputs.state }} INSTR_SUMMARY: ${{ steps.instructions.outputs.summary }} INSTR_DELTA: ${{ steps.instructions.outputs.delta }} run: | mkdir -p benchmark-pr-comment run_url="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" case "$INSTR_STATE" in improved) headline=":zap: Instruction count improved: ${INSTR_SUMMARY}." ;; regression) headline=":warning: Instruction count regressed: ${INSTR_SUMMARY}." ;; ok) headline=":white_check_mark: Instruction count within threshold: ${INSTR_SUMMARY}." ;; *) headline=":grey_question: Instruction count: ${INSTR_SUMMARY}." ;; esac if [ "$RESULT_STATE" != ok ]; then headline=":x: Benchmark execution failed, so there is nothing to compare." fi cat > benchmark-pr-comment/comment.md < ## Benchmark report ${headline} - Baseline asset: \`${BASELINE_ASSET_NAME}\` - Instruction threshold: \`${INSTRUCTION_CHANGE_PCT}%\` - Run: [benchmark workflow run](${run_url}) _Instruction counts are reported for information and do not block merging. Wall-clock timings are compared in the run output too, but they are measured under Cachegrind and vary too much between runs to report on._ EOF python - <<'PY' import json import os from pathlib import Path payload = { 'pr_number': os.environ['PR_NUMBER'], 'result_state': os.environ['RESULT_STATE'], 'result_message': os.environ['RESULT_MESSAGE'], 'baseline_asset_name': os.environ['BASELINE_ASSET_NAME'], 'instruction_threshold_pct': os.environ['INSTRUCTION_CHANGE_PCT'], 'instruction_state': os.environ['INSTR_STATE'], 'instruction_summary': os.environ['INSTR_SUMMARY'], 'instruction_delta_pct': os.environ['INSTR_DELTA'], 'run_url': f"{os.environ['GITHUB_SERVER_URL']}/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}", } Path('benchmark-pr-comment/result.json').write_text(json.dumps(payload, indent=2) + '\n') PY - name: archive PR benchmark comment if: always() && github.event_name == 'pull_request' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a with: name: benchmark-pr-comment path: benchmark-pr-comment if-no-files-found: error - name: archive benchmark results if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a with: name: microbenchmark results (CPython ${{ steps.metadata.outputs.python_version }}) path: | .benchmarks benchmark-output.txt instructions.txt include-hidden-files: true if-no-files-found: error permissions: contents: read