Skip to content

Commit 04afd23

Browse files
committed
Add Duel performance regression guards
Duel (https://github.com/sferik/duel-ruby) runs the benchmarks in duel/ on the branch a pull request targets and on the pull request, side by side, and fails the Perf workflow when the pull request is slower or allocates more. The 39 benchmarks send requests through an API's Rack interface in memory: routing among 200 routes, nested namespaces, requirements and wildcards, 404 and 405, params coercion and validation (query string, form, JSON body, nested arrays, a custom validator, a 400), declared, JSON formatting, present, content negotiation, error! and rescue_from, callbacks and helpers, path, header and param versioning, mounting, and compiling an API. Comparing master with itself passed three times in a row. An extra dup in Router#process_route failed 17 benchmarks on allocations, and reading the attribute three times in CoerceValidator#validate_param! failed 11 on instructions and CPU time.
1 parent 0521ea5 commit 04afd23

15 files changed

Lines changed: 969 additions & 0 deletions

‎.duel.rb‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# frozen_string_literal: true
2+
3+
# Duel's configuration: https://github.com/sferik/duel-ruby/blob/main/docs/configuration.md
4+
#
5+
# Duel follows conventions, so set only what differs: benchmarks are in
6+
# duel/**/*_duel.rb, each version's lib/ is first on the load path, a
7+
# change is compared when it touches lib/ or ext/ (or the benchmarks, or
8+
# this file), and releases are tagged v*.
9+
Duel.configure do |c|
10+
# The library each version's workers require (from the gemspec, unless
11+
# this says otherwise).
12+
# c.library = 'grape'
13+
14+
# When the workflow comments on a pull request with the report: :always,
15+
# :results (passed or failed), :failures (failed, or couldn't compare),
16+
# or :never.
17+
# c.comment = :failures
18+
19+
# Which runs a regression fails: :every_run, or :pull_requests, for a
20+
# project where people push to master directly (on GitHub Actions, another
21+
# run warns and passes, and a pushed commit gets the comment instead, from
22+
# a workflow job written only where this is set: see docs/ci.md).
23+
# c.fail_on = :every_run
24+
25+
# A label that accepts a regression in a pull request, for a change
26+
# that's slower on purpose (nil for none).
27+
c.accept_label = 'duel: accept'
28+
29+
# What the workflow compares a push with: :before (the commit before it),
30+
# or :last_passed (the last commit Duel passed, which a branch,
31+
# duel/passed/master, marks), so small slowdowns add up until they fail.
32+
# (A workflow job moves the branch, written only where this is set: see
33+
# docs/ci.md.)
34+
# c.push_base = :before
35+
end

‎.github/workflows/perf-comment.yml‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
name: Perf comment
2+
3+
# Duel's report, as a new comment on the pull request, when Duel says to:
4+
# always (post), or only when its last comment's status differs from the
5+
# run's (change), so the latest comment is never stale. It never edits or
6+
# deletes a comment, but hides Duel's earlier ones as outdated, so the
7+
# newest is the one in view. It runs once the Perf workflow has, with
8+
# this repository's own workflow and a token that can write, so a pull
9+
# request from a fork gets a comment too. It checks nothing out and runs
10+
# none of the pull request's code, only `duel comment` (see Duel's
11+
# docs/ci.md), which trusts only what the Duel job could have said in
12+
# what it kept: the pull request's number, if it names the pull request
13+
# the run compared, and the comment and the status, if they're ones Duel
14+
# says. Its report, a fork's too, is the comment, as Markdown.
15+
#
16+
# And when the label that accepts a regression (c.accept_label in
17+
# .duel.rb) is added to a pull request, or taken off, it runs the Duel
18+
# job again, which reads the labels as it runs: a run that failed, once
19+
# the label's added, or one that passed, once it's taken off.
20+
#
21+
# (The workflow must be on the default branch before it runs at all.)
22+
on:
23+
workflow_run:
24+
workflows: ["Perf"]
25+
types: [completed]
26+
# (This repository's own workflow, as for the comment, with a token
27+
# that can run a workflow again: it checks nothing out, and runs none
28+
# of the pull request's code.)
29+
pull_request_target:
30+
types: [labeled, unlabeled]
31+
32+
permissions: {}
33+
34+
jobs:
35+
comment:
36+
name: Comment
37+
if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion != 'cancelled' }}
38+
runs-on: ubuntu-latest
39+
permissions:
40+
actions: read # to get the report from the Perf run
41+
pull-requests: write # to comment on the pull request with the report
42+
steps:
43+
- name: Get the report
44+
id: report
45+
continue-on-error: true # there's none when the Duel job failed before comparing
46+
uses: actions/download-artifact@v8
47+
with:
48+
name: duel-report
49+
path: ${{ runner.temp }}/report
50+
run-id: ${{ github.event.workflow_run.id }}
51+
github-token: ${{ github.token }}
52+
- uses: ruby/setup-ruby@v1
53+
if: steps.report.outcome == 'success'
54+
with:
55+
ruby-version: ruby
56+
# Duel's own code, from RubyGems (none of the pull request's), so a
57+
# fix to how it comments comes with a release of Duel.
58+
- name: Comment on the pull request
59+
if: steps.report.outcome == 'success'
60+
env:
61+
GH_TOKEN: ${{ github.token }}
62+
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
63+
run: |
64+
gem install duel --version '~> 0.1.8' --no-document
65+
duel comment --report "$RUNNER_TEMP/report" --head "$HEAD_SHA" --marker 'duel'
66+
67+
again:
68+
name: Run Duel again
69+
if: >-
70+
github.event_name == 'pull_request_target' && github.event.label.name == 'duel: accept'
71+
runs-on: ubuntu-latest
72+
permissions:
73+
actions: write # to run the Perf workflow's jobs again
74+
steps:
75+
- name: Run Duel again
76+
env:
77+
GH_TOKEN: ${{ github.token }}
78+
GH_REPO: ${{ github.repository }}
79+
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
80+
ACTION: ${{ github.event.action }}
81+
run: |
82+
# The newest Perf run of the pull request's head commit, once it's
83+
# done (one that's running may have read the labels already).
84+
id=$(gh run list --workflow "Perf" --event pull_request --commit "$HEAD_SHA" --limit 1 \
85+
--json databaseId --jq '.[0].databaseId // empty')
86+
[ -n "$id" ] || exit 0
87+
gh run watch "$id" --interval 30 > /dev/null || true
88+
conclusion=$(gh run view "$id" --json conclusion --jq .conclusion)
89+
case "$ACTION:$conclusion" in
90+
labeled:failure) gh run rerun "$id" --failed ;;
91+
unlabeled:success) gh run rerun "$id" ;;
92+
esac

‎.github/workflows/perf.yml‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
name: Perf
2+
3+
on:
4+
pull_request:
5+
merge_group: # (a merge queue's)
6+
push:
7+
branches: [master] # (and any other branch to guard, a stable one, say)
8+
schedule:
9+
- cron: "0 4 * * *"
10+
workflow_dispatch:
11+
12+
# A pull request's newer push cancels its run, if that's still going, as
13+
# only its newest commit's result counts. Every other run (a push's, say)
14+
# runs to the end, so that each push is compared.
15+
concurrency:
16+
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.run_id }}
17+
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
18+
19+
# The Duel job runs the branch's code (its benchmarks too), so it only
20+
# reads. Commenting on a commit is the Comment on the commit job's, which
21+
# runs none of it, and commenting on a pull request is the Perf comment
22+
# workflow's.
23+
permissions:
24+
contents: read
25+
pull-requests: read # for the pull request's labels (see c.accept_label)
26+
27+
jobs:
28+
duel:
29+
name: Duel
30+
runs-on: ubuntu-latest
31+
# Whether to comment (post, change or none), the run's status (passed,
32+
# failed or neutral), and whether to mark a push passed (true, or
33+
# nothing), from Duel.
34+
outputs:
35+
comment: ${{ steps.compare.outputs.comment }}
36+
status: ${{ steps.compare.outputs.status }}
37+
passed: ${{ steps.compare.outputs.passed }}
38+
steps:
39+
- uses: actions/checkout@v7
40+
with:
41+
fetch-depth: 0 # the baseline comes from history, tags included
42+
persist-credentials: false
43+
# The labels of the pull request (or for a push, of the one that
44+
# merged it), for c.accept_label in .duel.rb, as a JSON array. They're
45+
# read as the job runs, and adding the label (or taking it off) runs
46+
# the job again: see the Perf comment workflow.
47+
# On a schedule, the last commit since the last release that merged a
48+
# pull request with the label (ACCEPT_LABEL, as .duel.rb names it):
49+
# what that slowed down was accepted, so it's compared with instead.
50+
- name: Find the pull request's labels
51+
id: labels
52+
if: github.event_name == 'pull_request' || github.event_name == 'merge_group' || github.event_name == 'push' || github.event_name == 'schedule'
53+
continue-on-error: true # (without them, nothing's accepted)
54+
env:
55+
GH_TOKEN: ${{ github.token }}
56+
PR: ${{ github.event.pull_request.number }}
57+
QUEUED: ${{ github.event.merge_group.head_ref }}
58+
ACCEPT_LABEL: 'duel: accept'
59+
RELEASE_TAGS: "v*"
60+
run: |
61+
if [ "$GITHUB_EVENT_NAME" = schedule ]; then
62+
tag=$(git describe --tags --abbrev=0 --match "$RELEASE_TAGS" HEAD^ 2>/dev/null) || exit 0
63+
since=$(TZ=UTC git log -1 --date=format-local:%Y-%m-%dT%H:%M:%SZ --format=%cd "$tag")
64+
merged=$(gh pr list --repo "$GITHUB_REPOSITORY" --state merged --label "$ACCEPT_LABEL" --search "merged:>=$since" --limit 1000 \
65+
--json mergeCommit --jq '.[].mergeCommit.oid')
66+
accepted=$(git rev-list "$tag..HEAD" | grep -Fx -m 1 -f <(echo "$merged")) || accepted=
67+
echo "accepted=$accepted" >> "$GITHUB_OUTPUT"
68+
exit 0
69+
fi
70+
# (In a merge queue, the last pull request queued, which the queue's
71+
# branch names: gh-readonly-queue/master/pr-123-<sha>.)
72+
if [ -n "$QUEUED" ]; then
73+
PR=${QUEUED##*/pr-}
74+
PR=${PR%%-*}
75+
fi
76+
if [ -n "$PR" ]; then
77+
labels=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/labels" --jq '[.[].name]')
78+
else
79+
labels=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" --jq '[.[0].labels[]?.name]')
80+
fi
81+
echo "labels=$labels" >> "$GITHUB_OUTPUT"
82+
- uses: ruby/setup-ruby@v1
83+
with:
84+
ruby-version: "4.0" # the newest Ruby, which those who care most about speed run
85+
bundler-cache: true
86+
# Against the branch it targets for a pull request, the queue's base
87+
# for a merge queue, what was there before for a push (or as
88+
# c.push_base in .duel.rb says, the last commit Duel passed), and the
89+
# last release on a schedule (slow creep). Duel adds its report to
90+
# the job's summary, writes it to duel.md for the comment, and sets
91+
# the step's outputs to say whether to comment, as c.comment in
92+
# .duel.rb says, whatever the outcome.
93+
- name: Compare
94+
id: compare
95+
env:
96+
DUEL_BASE: ${{ github.event_name == 'schedule' && 'last-release' || github.event_name == 'push' && github.event.before || github.event_name == 'merge_group' && github.event.merge_group.base_sha || '' }}
97+
# (Run by hand, it compares anyway: with nothing changed, the code
98+
# with itself, which checks the setup.)
99+
DUEL_FORCE: ${{ github.event_name == 'workflow_dispatch' && '1' || '' }}
100+
DUEL_LABELS: ${{ steps.labels.outputs.labels }}
101+
DUEL_ACCEPTED: ${{ steps.labels.outputs.accepted }}
102+
run: bundle exec duel --markdown "$RUNNER_TEMP/duel/duel.md"
103+
# For a pull request, what Duel said, for the Perf comment workflow,
104+
# which can't see this job's outputs.
105+
- name: Say whether to comment
106+
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
107+
env:
108+
PR: ${{ github.event.pull_request.number }}
109+
COMMENT: ${{ steps.compare.outputs.comment }}
110+
STATUS: ${{ steps.compare.outputs.status }}
111+
run: |
112+
mkdir -p "$RUNNER_TEMP/duel"
113+
printf 'pr=%s\ncomment=%s\nstatus=%s\n' "$PR" "$COMMENT" "$STATUS" > "$RUNNER_TEMP/duel/comment.env"
114+
# The report, for the comments.
115+
- name: Keep the report
116+
if: ${{ !cancelled() && (github.event_name == 'pull_request' || github.event_name == 'push') }}
117+
uses: actions/upload-artifact@v7
118+
with:
119+
name: duel-report
120+
path: ${{ runner.temp }}/duel/
121+
if-no-files-found: ignore # none when Duel didn't get to compare
122+
retention-days: 1

‎.rubocop.yml‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,18 @@ AllCops:
22
NewCops: enable
33
TargetRubyVersion: 3.3
44
SuggestExtensions: false
5+
Include:
6+
- .duel.rb
57
Exclude:
68
- vendor/**/*
79
- bin/**/*
810
- benchmark/**/*
911
- tmp/**/*
1012

13+
inherit_mode:
14+
merge:
15+
- Include
16+
1117
plugins:
1218
- rubocop-exception_messages
1319
- rubocop-performance
@@ -32,6 +38,10 @@ Style/MultilineIfModifier:
3238
Style/MutableConstant:
3339
Recursive: true
3440

41+
Style/OneClassPerFile:
42+
Exclude:
43+
- duel/**/*.rb
44+
3545
Style/RaiseArgs:
3646
Enabled: false
3747

‎Gemfile‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@ end
1717
group :development do
1818
gem 'benchmark-ips'
1919
gem 'benchmark-memory'
20+
# Duel requires Ruby 3.4 or later
21+
gem 'duel', '~> 0.1.8' if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.4')
2022
gem 'irb'
23+
gem 'stackprof', platforms: :mri
2124
end
2225

2326
group :test do

‎Rakefile‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,9 @@ require('rubocop/rake_task')
2525
RuboCop::RakeTask.new
2626

2727
task(default: %i[rubocop spec])
28+
29+
# Duel requires Ruby 3.4 or later
30+
if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.4')
31+
require('duel/rake_task')
32+
Duel::RakeTask.new
33+
end

‎duel/callbacks_duel.rb‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# frozen_string_literal: true
2+
3+
require_relative 'duel_helper'
4+
5+
# Callbacks and helpers: an endpoint runs the before, validation, after
6+
# and finally callbacks of every namespace it's in, and its block calls
7+
# helpers, reads headers, and sets the status, headers and cookies.
8+
9+
module AuthHelpers
10+
def current_user
11+
@current_user ||= { id: 1, name: 'Ada', token: headers['Authorization'].to_s.delete_prefix('Bearer ') }
12+
end
13+
14+
def authenticate!
15+
error!('Unauthorized', 401) unless current_user[:token] == 's3cret'
16+
end
17+
end
18+
19+
class CallbacksAPI < Grape::API
20+
format :json
21+
helpers AuthHelpers
22+
23+
helpers do
24+
def request_id
25+
headers['X-Request-Id'] || 'none'
26+
end
27+
28+
params :pagination do
29+
optional :page, type: Integer, default: 1
30+
optional :per_page, type: Integer, default: 25
31+
end
32+
end
33+
34+
before { header 'X-Request-Id', request_id }
35+
before { authenticate! }
36+
after { header 'X-Runtime', '0.001' }
37+
finally { @finished = true }
38+
39+
namespace :admin do
40+
before { header 'X-Admin', 'true' }
41+
before_validation { @validating = true }
42+
after_validation { @validated = true }
43+
after { header 'Cache-Control', 'no-store' }
44+
45+
params do
46+
use :pagination
47+
end
48+
get :reports do
49+
status 200
50+
header 'X-Total-Count', '3'
51+
cookies[:last_seen] = { value: 'reports', path: '/admin', httponly: true }
52+
{ user: current_user[:name], page: params[:page], request_id: }
53+
end
54+
end
55+
end
56+
57+
AUTHORIZED = { 'Authorization' => 'Bearer s3cret', 'X-Request-Id' => '0f8fad5b-d9cb-469f-a165-70867728950e' }.freeze
58+
59+
duel 'callbacks: before, validation, after and finally callbacks, with helpers' do |n|
60+
once { prepare(CallbacksAPI, rack_env('/admin/reports?page=2', headers: AUTHORIZED), 200, 'Ada') }
61+
serve(@app, @env, n)
62+
end
63+
64+
duel 'callbacks: a before callback that halts with error!' do |n|
65+
once { prepare(CallbacksAPI, rack_env('/admin/reports', headers: { 'Authorization' => 'Bearer wrong' }), 401, 'Unauthorized') }
66+
serve(@app, @env, n)
67+
end

0 commit comments

Comments
 (0)