Skip to content

Commit ce384b6

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 ce384b6

15 files changed

Lines changed: 943 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: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
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. It runs once the Perf workflow has, with this
7+
# repository's own workflow and a token that can write, so a pull request
8+
# from a fork gets a comment too. It checks nothing out and runs none of
9+
# the pull request's code, and of what the Duel job kept (where that code
10+
# ran), it trusts only what that job could have said: the pull request's
11+
# number, if it names the pull request the run compared, and the comment
12+
# and the status, if they're ones Duel says. A fork's report, which the
13+
# fork's code wrote, is shown as text.
14+
#
15+
# (The workflow must be on the default branch before it runs at all.)
16+
on:
17+
workflow_run:
18+
workflows: ["Perf"]
19+
types: [completed]
20+
21+
permissions: {}
22+
23+
jobs:
24+
comment:
25+
name: Comment
26+
if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion != 'cancelled' }}
27+
runs-on: ubuntu-latest
28+
permissions:
29+
actions: read # to get the report from the Perf run
30+
pull-requests: write # to comment on the pull request with the report
31+
steps:
32+
- name: Get the report
33+
id: report
34+
continue-on-error: true # there's none when the Duel job failed before comparing
35+
uses: actions/download-artifact@v8
36+
with:
37+
name: duel-report
38+
path: ${{ runner.temp }}/report
39+
run-id: ${{ github.event.workflow_run.id }}
40+
github-token: ${{ github.token }}
41+
- name: Comment on the pull request
42+
if: steps.report.outcome == 'success'
43+
env:
44+
GH_TOKEN: ${{ github.token }}
45+
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
46+
run: |
47+
said() { grep -xE "$1=($2)" "$RUNNER_TEMP/report/comment.env" | tail -n 1 | cut -d= -f2; }
48+
PR=$(said pr '[0-9]+')
49+
COMMENT=$(said comment 'post|change')
50+
STATUS=$(said status 'passed|failed|neutral')
51+
[ -n "$PR" ] && [ -n "$COMMENT" ] && [ -n "$STATUS" ] || exit 0
52+
# (The pull request's head commit, and the repository it's from.)
53+
head=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR" --jq '"\(.head.sha) \(.head.repo.full_name)"')
54+
[ "${head%% *}" = "$HEAD_SHA" ] || exit 0
55+
# The report, as Markdown for a branch of this repository (whose
56+
# author can push here anyway), but for a fork's, as text: its run
57+
# ran the fork's code, which could have written anything in it. In
58+
# a code block, fenced with more backticks than any run of them in
59+
# the report, it can't mention anyone, link anywhere or show an
60+
# image. It's cut short where a comment couldn't hold it, and loses
61+
# any NUL bytes, which GitHub wouldn't take, and grep reads it as
62+
# text whatever's in it, so it finds every run of backticks.
63+
report() {
64+
if [ "${head#* }" = "$GITHUB_REPOSITORY" ]; then cat "$RUNNER_TEMP/report/duel.md" && return; fi
65+
text="$RUNNER_TEMP/report.txt"
66+
LC_ALL=C tr -d '\000' < "$RUNNER_TEMP/report/duel.md" | head -c 60000 > "$text"
67+
fence=$(LC_ALL=C grep -ao '``*' "$text" | awk '{ if (length > n) n = length } END { n = (n < 3) ? 3 : n + 1; while (n-- > 0) printf "`" }')
68+
printf 'From a fork, so shown as text:\n\n%s\n' "$fence"
69+
cat "$text"
70+
printf '\n%s\n' "$fence"
71+
}
72+
marker="<!-- duel"
73+
# The first line of the last comment Duel posted here: its marker,
74+
# with its status (none in Duel 0.1.0's, which counts as another).
75+
last=$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$PR/comments" \
76+
--jq ".[] | select(.user.login == \"github-actions[bot]\") | .body | split(\"\n\")[0] | rtrimstr(\"\r\") | select(startswith(\"$marker status=\") or . == \"$marker -->\")" | tail -n 1)
77+
if [ "$COMMENT" = post ] || { [ -n "$last" ] && [ "$last" != "$marker status=$STATUS -->" ]; }; then
78+
{ echo "$marker status=$STATUS -->"; report; } > "$RUNNER_TEMP/comment.md"
79+
gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$PR/comments" -F body=@"$RUNNER_TEMP/comment.md" > /dev/null
80+
fi

‎.github/workflows/perf.yml‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
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+
- name: Find the pull request's labels
48+
id: labels
49+
if: github.event_name == 'pull_request' || github.event_name == 'merge_group' || github.event_name == 'push'
50+
continue-on-error: true # (without them, nothing's accepted)
51+
env:
52+
GH_TOKEN: ${{ github.token }}
53+
PR: ${{ github.event.pull_request.number }}
54+
QUEUED: ${{ github.event.merge_group.head_ref }}
55+
run: |
56+
# (In a merge queue, the last pull request queued, which the queue's
57+
# branch names: gh-readonly-queue/master/pr-123-<sha>.)
58+
if [ -n "$QUEUED" ]; then
59+
PR=${QUEUED##*/pr-}
60+
PR=${PR%%-*}
61+
fi
62+
if [ -n "$PR" ]; then
63+
labels=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/labels" --jq '[.[].name]')
64+
else
65+
labels=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" --jq '[.[0].labels[]?.name]')
66+
fi
67+
echo "labels=$labels" >> "$GITHUB_OUTPUT"
68+
- uses: ruby/setup-ruby@v1
69+
with:
70+
ruby-version: "4.0" # the newest Ruby, which those who care most about speed run
71+
bundler-cache: true
72+
# Against the branch it targets for a pull request, the queue's base
73+
# for a merge queue, what was there before for a push (or as
74+
# c.push_base in .duel.rb says, the last commit Duel passed), and the
75+
# last release on a schedule (slow creep). Duel adds its report to
76+
# the job's summary, writes it to duel.md for the comment, and sets
77+
# the step's outputs to say whether to comment, as c.comment in
78+
# .duel.rb says, whatever the outcome.
79+
- name: Compare
80+
id: compare
81+
env:
82+
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 || '' }}
83+
# (Run by hand, it compares anyway: with nothing changed, the code
84+
# with itself, which checks the setup.)
85+
DUEL_FORCE: ${{ github.event_name == 'workflow_dispatch' && '1' || '' }}
86+
DUEL_LABELS: ${{ steps.labels.outputs.labels }}
87+
run: bundle exec duel --markdown "$RUNNER_TEMP/duel/duel.md"
88+
# For a pull request, what Duel said, for the Perf comment workflow,
89+
# which can't see this job's outputs.
90+
- name: Say whether to comment
91+
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
92+
env:
93+
PR: ${{ github.event.pull_request.number }}
94+
COMMENT: ${{ steps.compare.outputs.comment }}
95+
STATUS: ${{ steps.compare.outputs.status }}
96+
run: |
97+
mkdir -p "$RUNNER_TEMP/duel"
98+
printf 'pr=%s\ncomment=%s\nstatus=%s\n' "$PR" "$COMMENT" "$STATUS" > "$RUNNER_TEMP/duel/comment.env"
99+
# The report, for the comments.
100+
- name: Keep the report
101+
if: ${{ !cancelled() && (github.event_name == 'pull_request' || github.event_name == 'push') }}
102+
uses: actions/upload-artifact@v7
103+
with:
104+
name: duel-report
105+
path: ${{ runner.temp }}/duel/
106+
if-no-files-found: ignore # none when Duel didn't get to compare
107+
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.7' 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: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,10 @@ require('rubocop/rake_task')
2525
RuboCop::RakeTask.new
2626

2727
task(default: %i[rubocop spec])
28+
29+
begin
30+
require('duel/rake_task')
31+
Duel::RakeTask.new
32+
rescue LoadError
33+
# Duel requires Ruby 3.4 or later
34+
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)