From dc5281172d20f539a6dc8a9b3e2fd4199a16815f Mon Sep 17 00:00:00 2001 From: Lars Kanis Date: Sat, 7 Nov 2026 18:14:39 +0100 Subject: [PATCH 1/9] Undefine PG::Tuple.new since it has no use at all --- ext/pg_tuple.c | 1 + spec/pg/tuple_spec.rb | 18 ++++++------------ 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/ext/pg_tuple.c b/ext/pg_tuple.c index 07ddd2fb5..278faa2c3 100644 --- a/ext/pg_tuple.c +++ b/ext/pg_tuple.c @@ -552,6 +552,7 @@ init_pg_tuple(void) { rb_cPG_Tuple = rb_define_class_under( rb_mPG, "Tuple", rb_cObject ); rb_define_alloc_func( rb_cPG_Tuple, pg_tuple_s_allocate ); + rb_undef_method(rb_singleton_class(rb_cPG_Tuple), "new"); rb_include_module(rb_cPG_Tuple, rb_mEnumerable); rb_define_method(rb_cPG_Tuple, "fetch", pg_tuple_fetch, -1); diff --git a/spec/pg/tuple_spec.rb b/spec/pg/tuple_spec.rb index 12ddaf50a..ffa2ca0a4 100644 --- a/spec/pg/tuple_spec.rb +++ b/spec/pg/tuple_spec.rb @@ -26,7 +26,12 @@ let!(:tuple2) { result2x3cast.tuple(0).freeze } let!(:tuple2sym) { result2x3symcast.tuple(0).freeze } let!(:tuple3) { str = Marshal.dump(result2x3cast.tuple(1).freeze); Marshal.load(str) } - let!(:tuple_empty) { PG::Tuple.new.freeze } + + describe "new" do + it "is not defined" do + expect { PG::Tuple.new }.to raise_error(NoMethodError) + end + end describe "[]" do it "returns nil for invalid keys" do @@ -35,7 +40,6 @@ expect( tuple0[2] ).to be_nil expect( tuple0[-3] ).to be_nil expect( tuple2[-4] ).to be_nil - expect{ tuple_empty[0] }.to raise_error(TypeError) end it "supports array like access" do @@ -114,7 +118,6 @@ expect{ tuple0.fetch(-3) }.to raise_error(IndexError) expect{ tuple0.fetch(-3) }.to raise_error(IndexError) expect{ tuple2.fetch(-4) }.to raise_error(IndexError) - expect{ tuple_empty[0] }.to raise_error(TypeError) end it "supports array like access" do @@ -158,7 +161,6 @@ expect( tuple1.each.to_a ).to eq( [["column1", "2"], ["column2", "b"]] ) expect( tuple2.each.to_a ).to eq( [["a", 1], ["b", true], ["b", "3"]] ) expect( tuple3.each.to_a ).to eq( [["a", 2], ["b", false], ["b", "4"]] ) - expect{ tuple_empty.each }.to raise_error(TypeError) end it "can be used as an enumerator with symbols" do @@ -183,7 +185,6 @@ expect( tuple1.each_value.to_a ).to eq( ["2", "b"] ) expect( tuple2.each_value.to_a ).to eq( [1, true, "3"] ) expect( tuple3.each_value.to_a ).to eq( [2, false, "4"] ) - expect{ tuple_empty.each_value }.to raise_error(TypeError) end it "can be used with block" do @@ -198,7 +199,6 @@ it "responds to values" do expect( tuple0.values ).to eq( ["1", "a"] ) expect( tuple3.values ).to eq( [2, false, "4"] ) - expect{ tuple_empty.values }.to raise_error(TypeError) end it "responds to key?" do @@ -294,10 +294,6 @@ expect( t2.instance_variable_get("@a") ).to eq( 4711 ) end - it "can't be marshaled when empty" do - expect{ Marshal.dump(tuple_empty) }.to raise_error(TypeError) - end - it "should be shareable for Ractor", :ractor do res = @conn.exec("SELECT 1").tuple(0) Ractor.make_shareable(res) @@ -322,14 +318,12 @@ it "should give account about memory usage" do expect( ObjectSpace.memsize_of(tuple0) ).to be > DATA_OBJ_MEMSIZE - expect( ObjectSpace.memsize_of(tuple_empty) ).to be > 0 end it "should override #inspect" do expect( tuple1.inspect ).to eq('#') expect( tuple2.inspect ).to eq('#') expect( tuple2sym.inspect ).to eq('#') - expect{ tuple_empty.inspect }.to raise_error(TypeError) end context "with cleared result" do From 6dfc948efdfd706e06ec9d269b1a06447f158dcb Mon Sep 17 00:00:00 2001 From: Lars Kanis Date: Sat, 7 Nov 2026 18:16:09 +0100 Subject: [PATCH 2/9] Materialize PG::Tuple objects when freezing Otherwise a race condition could happen, like so: ``` /home/runner/work/ruby-pg/ruby-pg/spec/pg/tuple_spec.rb:316: [BUG] Segmentation fault at 0x0000000000000028 ruby 3.1.7p261 (2025-03-26 revision 0a3704f218) [x86_64-linux] -- Control frame information ----------------------------------------------- c:0004 p:---- s:0014 e:000013 CFUNC :each c:0003 p:---- s:0011 e:000010 CFUNC :to_h c:0002 p:0004 s:0007 e:000006 BLOCK /home/runner/work/ruby-pg/ruby-pg/spec/pg/tuple_spec.rb:316 [FINISH] c:0001 p:---- s:0003 e:000002 (none) [FINISH] ``` --- ext/pg_tuple.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/ext/pg_tuple.c b/ext/pg_tuple.c index 278faa2c3..d0edff439 100644 --- a/ext/pg_tuple.c +++ b/ext/pg_tuple.c @@ -547,6 +547,20 @@ pg_tuple_load(VALUE self, VALUE a) return self; } +/* + * call-seq: + * res.freeze + * + * Freeze the PG::Tuple object and materialize all fields, so that it can be safely shared across ractors. + * + */ +static VALUE +pg_tuple_freeze(VALUE self) +{ + pg_tuple_materialize(self); + return rb_call_super(0, NULL); +} + void init_pg_tuple(void) { @@ -556,6 +570,7 @@ init_pg_tuple(void) rb_include_module(rb_cPG_Tuple, rb_mEnumerable); rb_define_method(rb_cPG_Tuple, "fetch", pg_tuple_fetch, -1); + rb_define_method(rb_cPG_Tuple, "freeze", pg_tuple_freeze, 0 ); rb_define_method(rb_cPG_Tuple, "[]", pg_tuple_aref, 1); rb_define_method(rb_cPG_Tuple, "each", pg_tuple_each, 0); rb_define_method(rb_cPG_Tuple, "each_value", pg_tuple_each_value, 0); From fec1205f49de74d358426009981765855a079864 Mon Sep 17 00:00:00 2001 From: Matt Larraz Date: Thu, 12 Nov 2026 12:37:22 -0500 Subject: [PATCH 3/9] Decode IPv4-mapped IPv6 addresses in TextDecoder::Inet PostgreSQL prints IPv4-mapped and IPv4-compatible IPv6 addresses in dotted form, like ::ffff:1.2.3.4. The decoder chose AF_INET whenever the text contained a dot, so inet_pton() rejected these values and decoding raised TypeError. Choose AF_INET6 when the text contains a colon instead. --- ext/pg_text_decoder.c | 2 +- spec/pg/basic_type_map_for_results_spec.rb | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/ext/pg_text_decoder.c b/ext/pg_text_decoder.c index cc2d42d64..65c5c19f0 100644 --- a/ext/pg_text_decoder.c +++ b/ext/pg_text_decoder.c @@ -823,7 +823,7 @@ pg_text_dec_inet(t_pg_coder *conv, const char *val, int len, int tuple, int fiel VALUE vmasks; char dst[16]; char buf[64]; - int af = strchr(val, '.') ? AF_INET : AF_INET6; + int af = strchr(val, ':') ? AF_INET6 : AF_INET; int mask = -1; if (len >= 64) { diff --git a/spec/pg/basic_type_map_for_results_spec.rb b/spec/pg/basic_type_map_for_results_spec.rb index 99d19c48c..2b7bed82a 100644 --- a/spec/pg/basic_type_map_for_results_spec.rb +++ b/spec/pg/basic_type_map_for_results_spec.rb @@ -351,6 +351,9 @@ '1234:3456:5678:789a:9abc:bced:edf0:f012/32', '1234:3456:5678:789a:9abc:bced:edf0:f012/64', '1234:3456:5678:789a:9abc:bced:edf0:f012/96', + '::ffff:1.2.3.4', + '::ffff:1.2.3.4/120', + '::1.2.3.4', ] sql_vals = vals.map{|v| "CAST('#{v}' AS inet)"} res = @conn.exec_params(("SELECT " + sql_vals.join(', ')), [], format ) @@ -374,6 +377,7 @@ '1234:3456:5678:789a::/64', '1234:3456:5678:789a:9abc:bced::/96', '1234:3456:5678:789a:9abc:bced:edf0:f012/128', + '::ffff:1.2.3.0/120', ] sql_vals = vals.map { |v| "CAST('#{v}' AS cidr)" } res = @conn.exec_params(("SELECT " + sql_vals.join(', ')), [], format ) From 583aa836a2e67633d3d2e20c413cb1298161333b Mon Sep 17 00:00:00 2001 From: Erik Berlin Date: Tue, 3 Nov 2026 11:12:36 -0800 Subject: [PATCH 4/9] Add Duel performance regression guards Duel (https://github.com/sferik/duel-ruby) runs the benchmarks in duel/ on the branch and on master side by side, and fails a pull request that is slower or allocates more. The 44 benchmarks cover queries over a socket to a PostgreSQL server of each worker's own (exec, exec_params, exec_prepared, COPY in and out), reading results in memory (values, getvalue, each, each_row, tuples, field names), the type maps, the text and binary coders on their own, escaping, and parsing connection parameters. Each version compiles its own extension (c.build). The duel-postgresql plugin needs a released pg, so Duel is in an optional Gemfile group. Checked by comparing master with itself three times, and with planted regressions: the Integer decoder without its fast path failed 6 benchmarks on instructions, and an extra rb_str_dup in the String decoder failed 13 on allocations. --- .duel.rb | 43 ++++++++++ .github/workflows/perf-comment.yml | 92 ++++++++++++++++++++ .github/workflows/perf.yml | 129 +++++++++++++++++++++++++++++ Gemfile | 16 ++++ Rakefile | 7 ++ duel/coder_duel.rb | 105 +++++++++++++++++++++++ duel/connect_duel.rb | 26 ++++++ duel/copy_duel.rb | 59 +++++++++++++ duel/duel_helper.rb | 47 +++++++++++ duel/escape_duel.rb | 31 +++++++ duel/query_duel.rb | 42 ++++++++++ duel/result_duel.rb | 64 ++++++++++++++ duel/type_map_duel.rb | 53 ++++++++++++ 13 files changed, 714 insertions(+) create mode 100644 .duel.rb create mode 100644 .github/workflows/perf-comment.yml create mode 100644 .github/workflows/perf.yml create mode 100644 duel/coder_duel.rb create mode 100644 duel/connect_duel.rb create mode 100644 duel/copy_duel.rb create mode 100644 duel/duel_helper.rb create mode 100644 duel/escape_duel.rb create mode 100644 duel/query_duel.rb create mode 100644 duel/result_duel.rb create mode 100644 duel/type_map_duel.rb diff --git a/.duel.rb b/.duel.rb new file mode 100644 index 000000000..2ddcf166c --- /dev/null +++ b/.duel.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +# Duel's configuration: https://github.com/sferik/duel-ruby/blob/main/docs/configuration.md +# +# Duel follows conventions, so set only what differs: benchmarks are in +# duel/**/*_duel.rb, each version's lib/ is first on the load path, a +# change is compared when it touches lib/ or ext/ (or the benchmarks, or +# this file), and releases are tagged v*. +Duel.configure do |c| + # The library each version's workers require (from the gemspec, unless + # this says otherwise). + # c.library = "pg" + + # Builds each version's C extension, so that each is measured with its + # own build. + c.build = "bundle exec rake compile" + + # A PostgreSQL server of each worker's own, and the queries, rows and + # server time that each benchmark took of it. + c.use :postgresql + + # When the workflow comments on a pull request with the report: :always, + # :results (passed or failed), :failures (failed, or couldn't compare), + # or :never. + # c.comment = :failures + + # Which runs a regression fails: :every_run, or :pull_requests, for a + # project where people push to master directly (on GitHub Actions, another + # run warns and passes, and a pushed commit gets the comment instead, from + # a workflow job written only where this is set: see docs/ci.md). + # c.fail_on = :every_run + + # A label that accepts a regression in a pull request, for a change + # that's slower on purpose (nil for none). + c.accept_label = "duel: accept" + + # What the workflow compares a push with: :before (the commit before it), + # or :last_passed (the last commit Duel passed, which a branch, + # duel/passed/master, marks), so small slowdowns add up until they fail. + # (A workflow job moves the branch, written only where this is set: see + # docs/ci.md.) + # c.push_base = :before +end diff --git a/.github/workflows/perf-comment.yml b/.github/workflows/perf-comment.yml new file mode 100644 index 000000000..dfc0e9027 --- /dev/null +++ b/.github/workflows/perf-comment.yml @@ -0,0 +1,92 @@ +name: Perf comment + +# Duel's report, as a new comment on the pull request, when Duel says to: +# always (post), or only when its last comment's status differs from the +# run's (change), so the latest comment is never stale. It never edits or +# deletes a comment, but hides Duel's earlier ones as outdated, so the +# newest is the one in view. It runs once the Perf workflow has, with +# this repository's own workflow and a token that can write, so a pull +# request from a fork gets a comment too. It checks nothing out and runs +# none of the pull request's code, only `duel comment` (see Duel's +# docs/ci.md), which trusts only what the Duel job could have said in +# what it kept: the pull request's number, if it names the pull request +# the run compared, and the comment and the status, if they're ones Duel +# says. Its report, a fork's too, is the comment, as Markdown. +# +# And when the label that accepts a regression (c.accept_label in +# .duel.rb) is added to a pull request, or taken off, it runs the Duel +# job again, which reads the labels as it runs: a run that failed, once +# the label's added, or one that passed, once it's taken off. +# +# (The workflow must be on the default branch before it runs at all.) +on: + workflow_run: + workflows: ["Perf"] + types: [completed] + # (This repository's own workflow, as for the comment, with a token + # that can run a workflow again: it checks nothing out, and runs none + # of the pull request's code.) + pull_request_target: + types: [labeled, unlabeled] + +permissions: {} + +jobs: + comment: + name: Comment + if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion != 'cancelled' }} + runs-on: ubuntu-latest + permissions: + actions: read # to get the report from the Perf run + pull-requests: write # to comment on the pull request with the report + steps: + - name: Get the report + id: report + continue-on-error: true # there's none when the Duel job failed before comparing + uses: actions/download-artifact@v8 + with: + name: duel-report + path: ${{ runner.temp }}/report + run-id: ${{ github.event.workflow_run.id }} + github-token: ${{ github.token }} + - uses: ruby/setup-ruby@v1 + if: steps.report.outcome == 'success' + with: + ruby-version: ruby + # Duel's own code, from RubyGems (none of the pull request's), so a + # fix to how it comments comes with a release of Duel. + - name: Comment on the pull request + if: steps.report.outcome == 'success' + env: + GH_TOKEN: ${{ github.token }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + run: | + gem install duel --version '~> 0.1.8' --no-document + duel comment --report "$RUNNER_TEMP/report" --head "$HEAD_SHA" --marker 'duel' + + again: + name: Run Duel again + if: >- + github.event_name == 'pull_request_target' && github.event.label.name == 'duel: accept' + runs-on: ubuntu-latest + permissions: + actions: write # to run the Perf workflow's jobs again + steps: + - name: Run Duel again + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + ACTION: ${{ github.event.action }} + run: | + # The newest Perf run of the pull request's head commit, once it's + # done (one that's running may have read the labels already). + id=$(gh run list --workflow "Perf" --event pull_request --commit "$HEAD_SHA" --limit 1 \ + --json databaseId --jq '.[0].databaseId // empty') + [ -n "$id" ] || exit 0 + gh run watch "$id" --interval 30 > /dev/null || true + conclusion=$(gh run view "$id" --json conclusion --jq .conclusion) + case "$ACTION:$conclusion" in + labeled:failure) gh run rerun "$id" --failed ;; + unlabeled:success) gh run rerun "$id" ;; + esac diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml new file mode 100644 index 000000000..a4738b5da --- /dev/null +++ b/.github/workflows/perf.yml @@ -0,0 +1,129 @@ +name: Perf + +on: + pull_request: + merge_group: # (a merge queue's) + push: + branches: [master] + schedule: + - cron: "0 4 * * *" + workflow_dispatch: + +# A pull request's newer push cancels its run, if that's still going, as +# only its newest commit's result counts. Every other run (a push's, say) +# runs to the end, so that each push is compared. +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +# The Duel job runs the branch's code (its benchmarks too), so it only +# reads. Commenting on a commit is the Comment on the commit job's, which +# runs none of it, and commenting on a pull request is the Perf comment +# workflow's. +permissions: + contents: read + pull-requests: read # for the pull request's labels (see c.accept_label) + +jobs: + duel: + name: Duel + runs-on: ubuntu-latest + # Whether to comment (post, change or none), the run's status (passed, + # failed or neutral), and whether to mark a push passed (true, or + # nothing), from Duel. + outputs: + comment: ${{ steps.compare.outputs.comment }} + status: ${{ steps.compare.outputs.status }} + passed: ${{ steps.compare.outputs.passed }} + env: + BUNDLE_WITH: duel # the Gemfile's optional group, with Duel and its PostgreSQL plugin + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 # the baseline comes from history, tags included + persist-credentials: false + # The labels of the pull request (or for a push, of the one that + # merged it), for c.accept_label in .duel.rb, as a JSON array. They're + # read as the job runs, and adding the label (or taking it off) runs + # the job again: see the Perf comment workflow. + # On a schedule, the last commit since the last release that merged a + # pull request with the label (ACCEPT_LABEL, as .duel.rb names it): + # what that slowed down was accepted, so it's compared with instead. + - name: Find the pull request's labels + id: labels + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' || github.event_name == 'push' || github.event_name == 'schedule' + continue-on-error: true # (without them, nothing's accepted) + env: + GH_TOKEN: ${{ github.token }} + PR: ${{ github.event.pull_request.number }} + QUEUED: ${{ github.event.merge_group.head_ref }} + ACCEPT_LABEL: 'duel: accept' + RELEASE_TAGS: "v*" + run: | + if [ "$GITHUB_EVENT_NAME" = schedule ]; then + tag=$(git describe --tags --abbrev=0 --match "$RELEASE_TAGS" HEAD^ 2>/dev/null) || exit 0 + since=$(TZ=UTC git log -1 --date=format-local:%Y-%m-%dT%H:%M:%SZ --format=%cd "$tag") + merged=$(gh pr list --repo "$GITHUB_REPOSITORY" --state merged --label "$ACCEPT_LABEL" --search "merged:>=$since" --limit 1000 \ + --json mergeCommit --jq '.[].mergeCommit.oid') + accepted=$(git rev-list "$tag..HEAD" | grep -Fx -m 1 -f <(echo "$merged")) || accepted= + echo "accepted=$accepted" >> "$GITHUB_OUTPUT" + exit 0 + fi + # (In a merge queue, the last pull request queued, which the queue's + # branch names: gh-readonly-queue/master/pr-123-.) + if [ -n "$QUEUED" ]; then + PR=${QUEUED##*/pr-} + PR=${PR%%-*} + fi + if [ -n "$PR" ]; then + labels=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/labels" --jq '[.[].name]') + else + labels=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" --jq '[.[0].labels[]?.name]') + fi + echo "labels=$labels" >> "$GITHUB_OUTPUT" + # PostgreSQL, for the server each Duel worker starts (its programs in + # /usr/lib/postgresql/*/bin, where duel-postgresql looks, with + # pg_stat_statements), and libpq's headers, to build each version's + # C extension (c.build in .duel.rb). + - run: sudo apt-get install -y postgresql libpq-dev + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "4.0" # the newest Ruby, which those who care most about speed run + bundler-cache: true + # Against the branch it targets for a pull request, the queue's base + # for a merge queue, what was there before for a push (or as + # c.push_base in .duel.rb says, the last commit Duel passed), and the + # last release on a schedule (slow creep). Duel adds its report to + # the job's summary, writes it to duel.md for the comment, and sets + # the step's outputs to say whether to comment, as c.comment in + # .duel.rb says, whatever the outcome. + - name: Compare + id: compare + env: + 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 || '' }} + # (Run by hand, it compares anyway: with nothing changed, the code + # with itself, which checks the setup.) + DUEL_FORCE: ${{ github.event_name == 'workflow_dispatch' && '1' || '' }} + DUEL_LABELS: ${{ steps.labels.outputs.labels }} + DUEL_ACCEPTED: ${{ steps.labels.outputs.accepted }} + run: bundle exec duel --markdown "$RUNNER_TEMP/duel/duel.md" + # For a pull request, what Duel said, for the Perf comment workflow, + # which can't see this job's outputs. + - name: Say whether to comment + if: ${{ !cancelled() && github.event_name == 'pull_request' }} + env: + PR: ${{ github.event.pull_request.number }} + COMMENT: ${{ steps.compare.outputs.comment }} + STATUS: ${{ steps.compare.outputs.status }} + run: | + mkdir -p "$RUNNER_TEMP/duel" + printf 'pr=%s\ncomment=%s\nstatus=%s\n' "$PR" "$COMMENT" "$STATUS" > "$RUNNER_TEMP/duel/comment.env" + # The report, for the comments. + - name: Keep the report + if: ${{ !cancelled() && (github.event_name == 'pull_request' || github.event_name == 'push') }} + uses: actions/upload-artifact@v7 + with: + name: duel-report + path: ${{ runner.temp }}/duel/ + if-no-files-found: ignore # none when Duel didn't get to compare + retention-days: 1 diff --git a/Gemfile b/Gemfile index a0f069130..e4b1ad16b 100644 --- a/Gemfile +++ b/Gemfile @@ -10,6 +10,22 @@ group :development do gem "mini_portile2", "~> 2.1" end +# Duel, for the performance regression guards in duel/: install it with +# `bundle config set --local with duel`, and run them with `rake duel`. +# Its PostgreSQL plugin needs a released pg, which would load its own +# pg_ext in the specs and in Duel's workers, so the group is optional, +# and the released pg is the source gem, whose lib/ has no pg_ext of the +# Ruby's version (lib/3.4/pg_ext) for pg.rb to load ahead of this tree's. +group :duel, optional: true do + # Duel requires Ruby 3.4 or later + if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("3.4") + gem "duel", "~> 0.1.8" + gem "duel-postgresql", "~> 0.1.5" + gem "pg", force_ruby_platform: true + end + gem "stackprof", platforms: :mri +end + group :test do gem "bundler", ">= 1.16", "< 5.0" gem "rake-compiler", "~> 1.0" diff --git a/Rakefile b/Rakefile index b19472d08..7711df0e4 100644 --- a/Rakefile +++ b/Rakefile @@ -181,3 +181,10 @@ task :translate do sh "po4a po4a.cfg" end end + +begin + require "duel/rake_task" + Duel::RakeTask.new +rescue LoadError + # Duel requires Ruby 3.4 or later, and the Gemfile's optional duel group +end diff --git a/duel/coder_duel.rb b/duel/coder_duel.rb new file mode 100644 index 000000000..7c8dcc2ae --- /dev/null +++ b/duel/coder_duel.rb @@ -0,0 +1,105 @@ +# frozen_string_literal: true + +require_relative "duel_helper" + +# Encoders and decoders on their own, 100 fixed values a call, as a type +# map runs them on a column: the text format, which results come in by +# default, and the binary one. + +duel "text decoder: Integer" do + once { @decoder = PG::TextDecoder::Integer.new } + TEXT_VALUES[:integers].each { |value| @decoder.decode(value) } +end + +duel "text decoder: Float" do + once { @decoder = PG::TextDecoder::Float.new } + TEXT_VALUES[:floats].each { |value| @decoder.decode(value) } +end + +duel "text decoder: TimestampWithoutTimeZone" do + once { @decoder = PG::TextDecoder::TimestampWithoutTimeZone.new } + TEXT_VALUES[:timestamps].each { |value| @decoder.decode(value) } +end + +duel "text decoder: TimestampWithTimeZone" do + once { @decoder = PG::TextDecoder::TimestampWithTimeZone.new } + TEXT_VALUES[:timestamptzs].each { |value| @decoder.decode(value) } +end + +duel "text decoder: Date" do + once { @decoder = PG::TextDecoder::Date.new } + TEXT_VALUES[:dates].each { |value| @decoder.decode(value) } +end + +duel "text decoder: an Array of 100 integers" do + once do + @decoder = PG::TextDecoder::Array.new(elements_type: PG::TextDecoder::Integer.new) + @array = "{#{TEXT_VALUES[:integers].join(',')}}" + end + @decoder.decode(@array) +end + +duel "text decoder: an Array of quoted strings, nested" do + once do + @decoder = PG::TextDecoder::Array.new(elements_type: PG::TextDecoder::String.new) + row = Array.new(10) { |i| %("name \\"#{i}\\", with, commas") }.join(",") + @array = "{#{Array.new(10) { "{#{row}}" }.join(',')}}" + end + @decoder.decode(@array) +end + +duel "text decoder: Bytea of 4 KB" do + once do + @decoder = PG::TextDecoder::Bytea.new + @hex = "\\x#{(0...4096).map { |i| format('%02x', i % 256) }.join}" + end + @decoder.decode(@hex) +end + +duel "text encoder: Integer" do + once do + @encoder = PG::TextEncoder::Integer.new + @integers = TEXT_VALUES[:integers].map(&:to_i) + end + @integers.each { |value| @encoder.encode(value) } +end + +duel "text encoder: TimestampWithTimeZone" do + once { @encoder = PG::TextEncoder::TimestampWithTimeZone.new } + TIMES.each { |value| @encoder.encode(value) } +end + +duel "text encoder: an Array of strings that need quoting" do + once do + @encoder = PG::TextEncoder::Array.new(elements_type: PG::TextEncoder::String.new) + @array = Array.new(10) { |i| Array.new(10) { |j| %(name "#{i}-#{j}", with {braces}) } } + end + @encoder.encode(@array) +end + +duel "binary decoder: Integer, Float and TimestampUtc" do + once do + @integer = PG::BinaryDecoder::Integer.new + @float = PG::BinaryDecoder::Float.new + @timestamp = PG::BinaryDecoder::TimestampUtc.new + @int8s = TEXT_VALUES[:integers].map { |value| [value.to_i].pack("q>") } + @float8s = TEXT_VALUES[:floats].map { |value| [value.to_f].pack("G") } + @times = TIMES.map { |time| PG::BinaryEncoder::TimestampUtc.new.encode(time) } + end + @int8s.each { |value| @integer.decode(value) } + @float8s.each { |value| @float.decode(value) } + @times.each { |value| @timestamp.decode(value) } +end + +duel "binary encoder: Int8, Float8 and TimestampUtc" do + once do + @int8 = PG::BinaryEncoder::Int8.new + @float8 = PG::BinaryEncoder::Float8.new + @timestamp = PG::BinaryEncoder::TimestampUtc.new + @integers = TEXT_VALUES[:integers].map(&:to_i) + @floats = TEXT_VALUES[:floats].map(&:to_f) + end + @integers.each { |value| @int8.encode(value) } + @floats.each { |value| @float8.encode(value) } + TIMES.each { |value| @timestamp.encode(value) } +end diff --git a/duel/connect_duel.rb b/duel/connect_duel.rb new file mode 100644 index 000000000..0dbeb5fff --- /dev/null +++ b/duel/connect_duel.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +require_relative "duel_helper" + +# What happens to the connection parameters before libpq connects: every +# PG.connect parses them, and a pool or an ORM builds them from a URL or a +# Hash. No connection is made. + +duel "connect: parse_connect_args of a URL" do + PG::Connection.parse_connect_args( + "postgres://jane:secret@db.example.com:5433/app_production?sslmode=require&connect_timeout=5" + ) +end + +duel "connect: parse_connect_args of a keyword string" do + PG::Connection.parse_connect_args("host=db.example.com port=5433 dbname=app_production user=jane sslmode=require") +end + +duel "connect: parse_connect_args of a Hash" do + PG::Connection.parse_connect_args(host: "db.example.com", port: 5433, dbname: "app_production", user: "jane", + password: "it's secret", sslmode: "require", application_name: "web") +end + +duel "connect: conninfo_hash of a connection", setup: -> { @conn = pg_connection }, teardown: -> { @conn.close } do + @conn.conninfo_hash +end diff --git a/duel/copy_duel.rb b/duel/copy_duel.rb new file mode 100644 index 000000000..a2d665deb --- /dev/null +++ b/duel/copy_duel.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +require_relative "duel_helper" + +# COPY, the fast way in and out of a table, with the CopyRow coders: an +# encoder that turns each row (an Array) into a line, and a decoder that +# turns each line back. On their own first, then through the worker's +# server. + +ROWS = Array.new(100) do |i| + [i, "user #{i}", "line\twith a tab", i.even? ? nil : "O'Brien \\ #{i}", (i * 1.5).to_s] +end.freeze + +duel "copy: encode 100 rows with TextEncoder::CopyRow" do + once { @encoder = PG::TextEncoder::CopyRow.new } + ROWS.each { |row| @encoder.encode(row) } +end + +duel "copy: decode 100 lines with TextDecoder::CopyRow" do + once do + @decoder = PG::TextDecoder::CopyRow.new + encoder = PG::TextEncoder::CopyRow.new + @lines = ROWS.map { |row| encoder.encode(row) } + end + @lines.each { |line| @decoder.decode(line) } +end + +copy_table = lambda do + @conn = pg_connection + @conn.exec("CREATE TEMP TABLE copied (id int, name text, note text, other text, score text)") + columns = PG::TypeMapByColumn.new([PG::TextEncoder::Integer.new, nil, nil, nil, nil]) + @encoder = PG::TextEncoder::CopyRow.new(type_map: columns) +end + +# Each iteration's rows are rolled back, so the table never grows. +rolled_back = lambda do |iteration| + @conn.exec("BEGIN") + iteration.call + @conn.exec("ROLLBACK") +end + +duel "copy: COPY 100 rows in with an encoder", + setup: copy_table, teardown: -> { @conn.close }, around_iteration: rolled_back do + @conn.copy_data("COPY copied FROM STDIN", @encoder) do + ROWS.each { |row| @conn.put_copy_data(row) } + end +end + +copy_out = lambda do + @conn = pg_connection + columns = PG::TypeMapByColumn.new([PG::TextDecoder::Integer.new, nil, PG::TextDecoder::Float.new]) + @decoder = PG::TextDecoder::CopyRow.new(type_map: columns) +end + +duel "copy: COPY 100 rows out with a decoder", setup: copy_out, teardown: -> { @conn.close } do + @conn.copy_data("COPY (SELECT g, 'user ' || g, g * 1.5 FROM generate_series(1, 100) g) TO STDOUT", @decoder) do + while @conn.get_copy_data; end + end +end diff --git a/duel/duel_helper.rb b/duel/duel_helper.rb new file mode 100644 index 000000000..163de8fd6 --- /dev/null +++ b/duel/duel_helper.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +# What several files of benchmarks share: a connection to the worker's +# own PostgreSQL server (see .duel.rb), and results and values fetched +# once, so that what's timed is the driver's work on them. + +# A new connection to the worker's server. A benchmark keeps one for all +# its samples. +def pg_connection + PG.connect(Duel::PostgreSQL.url) +end + +# A typical result's columns: an id, a name, a score, a flag, a +# timestamp, a date, and a small integer array, in 100 rows. +ROWS_SQL = <<~SQL + SELECT g AS id, 'user' || g AS name, g * 1.5::float8 AS score, g % 2 = 0 AS active, + timestamp '2026-01-01 12:00:00' + g * interval '1 minute 1.5 seconds' AS created_at, + date '2026-01-01' + g AS day, ARRAY[g, g + 1, g + 2] AS tags + FROM generate_series(1, 100) g +SQL + +# ROWS_SQL's result, in text format (or with +format+ 1, binary), over +# +conn+. It stays in memory after +conn+ moves on, so reading it makes +# no round trip. +def rows_result(conn, format = 0) + conn.exec_params(ROWS_SQL, [], format) +end + +# The +i+th of the timestamps below, as the server sends it, with +# +suffix+ (a zone, say). +def timestamp_text(i, suffix = "") + format("2026-%02d-%02d %02d:%02d:%02d.%06d%s", + (i % 12) + 1, (i % 28) + 1, i % 24, i % 60, (i * 7) % 60, i * 1234, suffix) +end + +# 100 fixed values of each kind that a text decoder takes, as the server +# sends them. +TEXT_VALUES = { + integers: Array.new(100) { |i| (i * 7919).to_s }, + floats: Array.new(100) { |i| (i * 3.14159).to_s }, + timestamps: Array.new(100) { |i| timestamp_text(i) }, + timestamptzs: Array.new(100) { |i| timestamp_text(i, "+02") }, + dates: Array.new(100) { |i| format("2026-%02d-%02d", (i % 12) + 1, (i % 28) + 1) }, +}.freeze + +# Times to encode, fixed. +TIMES = Array.new(100) { |i| Time.utc(2026, (i % 12) + 1, (i % 28) + 1, i % 24, i % 60, (i * 7) % 60, i * 1234) }.freeze diff --git a/duel/escape_duel.rb b/duel/escape_duel.rb new file mode 100644 index 000000000..e9369a603 --- /dev/null +++ b/duel/escape_duel.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require_relative "duel_helper" + +# Quoting and escaping for SQL, which libpq does by the connection's +# encoding, and pg wraps: no round trip. Each escapes 20 fixed strings, +# some with quotes and backslashes in them. + +setup do + @conn = pg_connection + @strings = Array.new(20) { |i| i.even? ? "jane#{i}@example.com" : "O'Brien \\ \"#{i}\" it's" } +end +teardown { @conn.close } + +duel "escape: escape_string" do + @strings.each { |string| @conn.escape_string(string) } +end + +duel "escape: escape_literal" do + @strings.each { |string| @conn.escape_literal(string) } +end + +duel "escape: quote_ident of a schema-qualified name" do + PG::Connection.quote_ident(%w[public users]) + PG::Connection.quote_ident("Order Items") +end + +duel "escape: escape_bytea and unescape_bytea of 4 KB" do + once { @bytes = (0...4096).map { |i| (i % 256).chr }.join.b } + PG::Connection.unescape_bytea(@conn.escape_bytea(@bytes)) +end diff --git a/duel/query_duel.rb b/duel/query_duel.rb new file mode 100644 index 000000000..747983c67 --- /dev/null +++ b/duel/query_duel.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +require_relative "duel_helper" + +# Queries, over a Unix socket to the worker's own server: sending each +# one, waiting for its result and reading it. What the server does for +# them is in its own process, not this one's CPU time, so these are +# judged on what the driver does, and on the plugin's counts of the +# queries and rows the server ran. + +setup { @conn = pg_connection } +teardown { @conn.close } + +duel "query: exec a small SELECT" do + @conn.exec("SELECT 1") +end + +duel "query: exec_params with three parameters" do + @conn.exec_params("SELECT $1::int, $2::text, $3::bool", [42, "jane@example.com", true]) +end + +duel "query: exec_prepared a statement" do + once { @conn.prepare("user_by_id", "SELECT $1::int AS id, 'user' || $1 AS name") } + @conn.exec_prepared("user_by_id", [42]) +end + +duel "query: exec 100 rows and read their values" do + @conn.exec(ROWS_SQL).values +end + +duel "query: exec_params with a BasicTypeMapForQueries" do + once do + @conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(@conn) + @params = [42, "jane@example.com", 3.5, true, Time.utc(2026, 1, 2, 3, 4, 5), [1, 2, 3]] + end + @conn.exec_params("SELECT $1, $2, $3, $4, $5, $6", @params) +end + +duel "query: 100 rows decoded by a BasicTypeMapForResults" do + once { @conn.type_map_for_results = PG::BasicTypeMapForResults.new(@conn) } + @conn.exec(ROWS_SQL).values +end diff --git a/duel/result_duel.rb b/duel/result_duel.rb new file mode 100644 index 000000000..268b1d00b --- /dev/null +++ b/duel/result_duel.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +require_relative "duel_helper" + +# Reading a result that's in memory already, 100 rows of 7 columns (see +# ROWS_SQL): what an application does with every result, once its query +# has come back. + +setup do + conn = pg_connection + @result = rows_result(conn) + @symbols = rows_result(conn).field_names_as(:symbol) + conn.close +end + +duel "result: values" do + @result.values +end + +duel "result: getvalue of every field" do + result = @result + 100.times do |row| + 7.times { |field| result.getvalue(row, field) } + end +end + +duel "result: each, a Hash a row" do + @result.each { |_row| nil } +end + +duel "result: each_row, an Array a row" do + @result.each_row { |_row| nil } +end + +duel "result: column_values of two columns" do + @result.column_values(0) + @result.column_values(1) +end + +duel "result: tuple, and fields by name" do + result = @result + 100.times do |row| + tuple = result.tuple(row) + tuple["id"] + tuple["name"] + tuple[6] + end +end + +duel "result: each, a Hash a row with Symbol keys" do + @symbols.each { |_row| nil } +end + +duel "result: field names, numbers and types" do + result = @result + result.fields + 7.times do |field| + result.fname(field) + result.ftype(field) + result.fmod(field) + end + result.fnumber("created_at") + result.fnumber("tags") +end diff --git a/duel/type_map_duel.rb b/duel/type_map_duel.rb new file mode 100644 index 000000000..ed8c7928d --- /dev/null +++ b/duel/type_map_duel.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +require_relative "duel_helper" + +# The type maps that decode a result's values into Ruby objects: the +# basic ones, which pick a decoder by the column's type OID, and one of +# explicit decoders by column. Each decodes a result that's in memory +# already (see ROWS_SQL), so no round trip is timed. + +setup do + @conn = pg_connection + @text = rows_result(@conn) + @binary = rows_result(@conn, 1) +end +teardown { @conn.close } + +duel "type map: BasicTypeMapForResults, text format" do + once { @map = PG::BasicTypeMapForResults.new(@conn) } + @text.map_types!(@map).values +end + +duel "type map: BasicTypeMapForResults, binary format" do + once { @map = PG::BasicTypeMapForResults.new(@conn) } + @binary.map_types!(@map).values +end + +duel "type map: TypeMapByColumn of text decoders" do + once do + @map = PG::TypeMapByColumn.new([ + PG::TextDecoder::Integer.new, nil, PG::TextDecoder::Float.new, PG::TextDecoder::Boolean.new, + PG::TextDecoder::TimestampWithoutTimeZone.new, PG::TextDecoder::Date.new, + PG::TextDecoder::Array.new(elements_type: PG::TextDecoder::Integer.new), + ]) + end + @text.map_types!(@map).values +end + +duel "type map: BasicTypeMapForQueries picks encoders for parameters" do + once do + @map = PG::BasicTypeMapForQueries.new(@conn) + @params = [42, "jane@example.com", 3.5, true, nil, Time.utc(2026, 1, 2, 3, 4, 5), [1, 2, 3], %w[a b], 2**40] + end + @map.query_param_encoders(@params) +end + +duel "type map: embed_params with a BasicTypeMapForQueries" do + once do + @map = PG::BasicTypeMapForQueries.new(@conn) + @params = [42, "O'Brien", 3.5, true, nil, Time.utc(2026, 1, 2, 3, 4, 5), [1, 2, 3]] + end + @conn.embed_params("SELECT * FROM users WHERE id = $1 AND name = $2 AND score > $3 AND active = $4 " \ + "AND deleted_at IS $5 AND created_at < $6 AND group_id = ANY($7)", @params, type_map: @map) +end From 55e479e68588fbb2fed5273e1b2395963a0d7900 Mon Sep 17 00:00:00 2001 From: Erik Berlin Date: Mon, 16 Nov 2026 11:01:23 -0800 Subject: [PATCH 5/9] Measure on macOS and Windows too, with Duel 0.2.0 pg's code paths differ by system, and Linux's was the only one Duel measured. The Perf workflow runs on Linux, macOS and Windows now, each saying what it found in a report of its own, and the Perf comment workflow comments with all three. On Linux and macOS, it calls Duel 0.2.0's reusable workflow, so the copy of its steps is gone. It grants contents: write, which GitHub checks every job of the reusable workflow against, though none of the jobs that write is turned on here, and the Duel job still only reads. The reusable workflow's steps are Unix shell's, so the Windows job runs the same ones itself, in bash, with what pg's build needs there as source-gem.yml has it (MSYS2's gcc, and PostgreSQL's binaries, for libpq). Its servers are the runner's own PostgreSQL's, whose initdb drops the rights of the runner's user, an administrator, as postgres needs: the binaries' doesn't. The Perf comment workflow calls Duel's reusable one too. --- .github/workflows/perf-comment.yml | 82 +++--------------- .github/workflows/perf.yml | 133 ++++++++++++++++++++--------- Gemfile | 4 +- 3 files changed, 105 insertions(+), 114 deletions(-) diff --git a/.github/workflows/perf-comment.yml b/.github/workflows/perf-comment.yml index dfc0e9027..aee89c224 100644 --- a/.github/workflows/perf-comment.yml +++ b/.github/workflows/perf-comment.yml @@ -1,31 +1,20 @@ name: Perf comment -# Duel's report, as a new comment on the pull request, when Duel says to: -# always (post), or only when its last comment's status differs from the -# run's (change), so the latest comment is never stale. It never edits or -# deletes a comment, but hides Duel's earlier ones as outdated, so the -# newest is the one in view. It runs once the Perf workflow has, with -# this repository's own workflow and a token that can write, so a pull -# request from a fork gets a comment too. It checks nothing out and runs -# none of the pull request's code, only `duel comment` (see Duel's -# docs/ci.md), which trusts only what the Duel job could have said in -# what it kept: the pull request's number, if it names the pull request -# the run compared, and the comment and the status, if they're ones Duel -# says. Its report, a fork's too, is the comment, as Markdown. +# Duel's report, as a new comment on the pull request, when Duel says +# to, by Duel's reusable workflow (see Duel's docs/ci.md), which this +# one calls once the Perf workflow has run, with a token that can write, +# so a pull request from a fork gets a comment too. It checks nothing +# out and runs none of the pull request's code, only `duel comment`. # # And when the label that accepts a regression (c.accept_label in # .duel.rb) is added to a pull request, or taken off, it runs the Duel -# job again, which reads the labels as it runs: a run that failed, once -# the label's added, or one that passed, once it's taken off. +# job again. # # (The workflow must be on the default branch before it runs at all.) on: workflow_run: workflows: ["Perf"] types: [completed] - # (This repository's own workflow, as for the comment, with a token - # that can run a workflow again: it checks nothing out, and runs none - # of the pull request's code.) pull_request_target: types: [labeled, unlabeled] @@ -33,60 +22,9 @@ permissions: {} jobs: comment: - name: Comment - if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion != 'cancelled' }} - runs-on: ubuntu-latest + uses: sferik/duel-ruby/.github/workflows/duel-comment.yml@v0.2.0 permissions: - actions: read # to get the report from the Perf run + actions: write # to get the report from the Perf run, and run its Duel job again pull-requests: write # to comment on the pull request with the report - steps: - - name: Get the report - id: report - continue-on-error: true # there's none when the Duel job failed before comparing - uses: actions/download-artifact@v8 - with: - name: duel-report - path: ${{ runner.temp }}/report - run-id: ${{ github.event.workflow_run.id }} - github-token: ${{ github.token }} - - uses: ruby/setup-ruby@v1 - if: steps.report.outcome == 'success' - with: - ruby-version: ruby - # Duel's own code, from RubyGems (none of the pull request's), so a - # fix to how it comments comes with a release of Duel. - - name: Comment on the pull request - if: steps.report.outcome == 'success' - env: - GH_TOKEN: ${{ github.token }} - HEAD_SHA: ${{ github.event.workflow_run.head_sha }} - run: | - gem install duel --version '~> 0.1.8' --no-document - duel comment --report "$RUNNER_TEMP/report" --head "$HEAD_SHA" --marker 'duel' - - again: - name: Run Duel again - if: >- - github.event_name == 'pull_request_target' && github.event.label.name == 'duel: accept' - runs-on: ubuntu-latest - permissions: - actions: write # to run the Perf workflow's jobs again - steps: - - name: Run Duel again - env: - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - ACTION: ${{ github.event.action }} - run: | - # The newest Perf run of the pull request's head commit, once it's - # done (one that's running may have read the labels already). - id=$(gh run list --workflow "Perf" --event pull_request --commit "$HEAD_SHA" --limit 1 \ - --json databaseId --jq '.[0].databaseId // empty') - [ -n "$id" ] || exit 0 - gh run watch "$id" --interval 30 > /dev/null || true - conclusion=$(gh run view "$id" --json conclusion --jq .conclusion) - case "$ACTION:$conclusion" in - labeled:failure) gh run rerun "$id" --failed ;; - unlabeled:success) gh run rerun "$id" ;; - esac + with: + accept-label: "duel: accept" diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index a4738b5da..c663acbc8 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -1,5 +1,14 @@ name: Perf +# Duel's performance regression guards (see Duel's docs/ci.md), on +# Linux, macOS and Windows, as pg's code paths differ on each. On Linux +# and macOS, Duel's reusable workflow runs them, which this one calls +# with what .duel.rb sets that it needs. Its steps are Unix shell's, so +# the Windows job does the same steps itself, in bash. Each says what it +# found in a report of its own, and the Perf comment workflow comments +# with all three. Each compares a pull request with the branch it +# targets, a merge queue's group with the queue's base, a push with what +# was there before, and on a schedule, the last release (slow creep). on: pull_request: merge_group: # (a merge queue's) @@ -16,39 +25,79 @@ concurrency: group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} -# The Duel job runs the branch's code (its benchmarks too), so it only -# reads. Commenting on a commit is the Comment on the commit job's, which -# runs none of it, and commenting on a pull request is the Perf comment -# workflow's. -permissions: - contents: read - pull-requests: read # for the pull request's labels (see c.accept_label) +permissions: {} jobs: - duel: - name: Duel - runs-on: ubuntu-latest - # Whether to comment (post, change or none), the run's status (passed, - # failed or neutral), and whether to mark a push passed (true, or - # nothing), from Duel. - outputs: - comment: ${{ steps.compare.outputs.comment }} - status: ${{ steps.compare.outputs.status }} - passed: ${{ steps.compare.outputs.passed }} + # PostgreSQL, for the server each Duel worker starts (its programs in + # /usr/lib/postgresql/*/bin, where duel-postgresql looks, with + # pg_stat_statements), and libpq's headers, to build each version's C + # extension (c.build in .duel.rb). The Gemfile's optional group has + # Duel and its PostgreSQL plugin. + linux: + uses: sferik/duel-ruby/.github/workflows/duel.yml@v0.2.0 + # (Its Duel job, which runs the branch's code, only reads: the + # workflow keeps it to contents: read. GitHub checks what each of its + # jobs asks for against what's granted here, run or not, and those + # that comment on a pushed commit, mark a push passed or keep a badge, + # none of which this workflow turns on, ask for contents: write.) + permissions: + contents: write + pull-requests: read # for the pull request's labels (see c.accept_label) + with: + report: linux + ruby-version: "4.0" # the newest Ruby, which those who care most about speed run + setup: | + sudo apt-get install -y postgresql libpq-dev + echo "BUNDLE_WITH=duel" >> "$GITHUB_ENV" + accept-label: "duel: accept" + + # Homebrew's PostgreSQL, on the PATH (where duel-postgresql looks for + # its programs, and pg's build for pg_config), which Homebrew doesn't + # link it onto. + macos: + uses: sferik/duel-ruby/.github/workflows/duel.yml@v0.2.0 + permissions: + contents: write # (as Linux's) + pull-requests: read + with: + report: macos + runs-on: macos-latest + ruby-version: "4.0" + setup: | + brew install postgresql@17 + echo "$(brew --prefix postgresql@17)/bin" >> "$GITHUB_PATH" + echo "BUNDLE_WITH=duel" >> "$GITHUB_ENV" + accept-label: "duel: accept" + + # The reusable workflow's Duel job's steps, in bash, with what pg's + # build needs on Windows, as source-gem.yml has it: MSYS2's gcc, and + # PostgreSQL's binaries (for libpq), on the PATH. The server each + # worker starts (with pg_ctl, there) is the runner's own PostgreSQL's, + # in PGBIN, whose initdb drops the rights of the runner's user, an + # administrator, as postgres needs: the binaries' doesn't. + windows: + name: Duel (windows) + runs-on: windows-latest + timeout-minutes: 60 + permissions: + contents: read + pull-requests: read # for the pull request's labels (see c.accept_label) env: BUNDLE_WITH: duel # the Gemfile's optional group, with Duel and its PostgreSQL plugin + PGVERSION: 18.0-1-windows-x64 + defaults: + run: + shell: bash steps: - uses: actions/checkout@v7 with: fetch-depth: 0 # the baseline comes from history, tags included persist-credentials: false # The labels of the pull request (or for a push, of the one that - # merged it), for c.accept_label in .duel.rb, as a JSON array. They're - # read as the job runs, and adding the label (or taking it off) runs - # the job again: see the Perf comment workflow. - # On a schedule, the last commit since the last release that merged a - # pull request with the label (ACCEPT_LABEL, as .duel.rb names it): - # what that slowed down was accepted, so it's compared with instead. + # merged it), for c.accept_label in .duel.rb, as a JSON array. On a + # schedule, the last commit since the last release that merged a + # pull request with the label: what that slowed down was accepted, + # so it's compared with instead. - name: Find the pull request's labels id: labels if: github.event_name == 'pull_request' || github.event_name == 'merge_group' || github.event_name == 'push' || github.event_name == 'schedule' @@ -57,7 +106,7 @@ jobs: GH_TOKEN: ${{ github.token }} PR: ${{ github.event.pull_request.number }} QUEUED: ${{ github.event.merge_group.head_ref }} - ACCEPT_LABEL: 'duel: accept' + ACCEPT_LABEL: "duel: accept" RELEASE_TAGS: "v*" run: | if [ "$GITHUB_EVENT_NAME" = schedule ]; then @@ -81,22 +130,26 @@ jobs: labels=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" --jq '[.[0].labels[]?.name]') fi echo "labels=$labels" >> "$GITHUB_OUTPUT" - # PostgreSQL, for the server each Duel worker starts (its programs in - # /usr/lib/postgresql/*/bin, where duel-postgresql looks, with - # pg_stat_statements), and libpq's headers, to build each version's - # C extension (c.build in .duel.rb). - - run: sudo apt-get install -y postgresql libpq-dev + # (The bundle once gcc and libpq are there, below.) - uses: ruby/setup-ruby@v1 with: - ruby-version: "4.0" # the newest Ruby, which those who care most about speed run - bundler-cache: true - # Against the branch it targets for a pull request, the queue's base - # for a merge queue, what was there before for a push (or as - # c.push_base in .duel.rb says, the last commit Duel passed), and the - # last release on a schedule (slow creep). Duel adds its report to - # the job's summary, writes it to duel.md for the comment, and sets - # the step's outputs to say whether to comment, as c.comment in - # .duel.rb says, whatever the outcome. + ruby-version: "4.0" + - name: Install MSYS2's gcc + shell: cmd + run: ridk exec sh -c "pacman --sync --needed --noconfirm ${MINGW_PACKAGE_PREFIX}-gcc" + - name: Download PostgreSQL + shell: pwsh + run: | + Add-Type -AssemblyName System.IO.Compression.FileSystem + $(new-object net.webclient).DownloadFile("https://get.enterprisedb.com/postgresql/postgresql-$env:PGVERSION-binaries.zip", "$env:RUNNER_TEMP/postgresql-binaries.zip") + [System.IO.Compression.ZipFile]::ExtractToDirectory("$env:RUNNER_TEMP/postgresql-binaries.zip", "$env:RUNNER_TEMP") + echo "$env:RI_DEVKIT$env:MINGW_PREFIX/bin;$env:RI_DEVKIT/usr/bin;$env:RUNNER_TEMP/pgsql/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + - name: Use the runner's PostgreSQL for the servers + run: echo "DUEL_POSTGRESQL_BIN=$PGBIN" >> "$GITHUB_ENV" + - run: bundle install + # As on Linux and macOS: Duel adds its report to the job's summary, + # writes it to duel.md for the comment, and sets the step's outputs + # to say whether to comment, as c.comment in .duel.rb says. - name: Compare id: compare env: @@ -118,12 +171,12 @@ jobs: run: | mkdir -p "$RUNNER_TEMP/duel" printf 'pr=%s\ncomment=%s\nstatus=%s\n' "$PR" "$COMMENT" "$STATUS" > "$RUNNER_TEMP/duel/comment.env" - # The report, for the comments. + # The report, for the comments, beside Linux's and macOS's. - name: Keep the report if: ${{ !cancelled() && (github.event_name == 'pull_request' || github.event_name == 'push') }} uses: actions/upload-artifact@v7 with: - name: duel-report + name: duel-report-windows path: ${{ runner.temp }}/duel/ if-no-files-found: ignore # none when Duel didn't get to compare retention-days: 1 diff --git a/Gemfile b/Gemfile index e4b1ad16b..ddb627167 100644 --- a/Gemfile +++ b/Gemfile @@ -19,8 +19,8 @@ end group :duel, optional: true do # Duel requires Ruby 3.4 or later if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("3.4") - gem "duel", "~> 0.1.8" - gem "duel-postgresql", "~> 0.1.5" + gem "duel", "~> 0.2.0" + gem "duel-postgresql", "~> 0.2.0" gem "pg", force_ruby_platform: true end gem "stackprof", platforms: :mri From bca6908d5bd3035d97afc481af0362da6e1c7b00 Mon Sep 17 00:00:00 2001 From: Erik Berlin Date: Mon, 16 Nov 2026 14:00:01 -0800 Subject: [PATCH 6/9] Test: Windows through Duel's reusable workflow, at main --- .github/workflows/perf.yml | 127 ++++++------------------------------- 1 file changed, 20 insertions(+), 107 deletions(-) diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index c663acbc8..dc45d927b 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -69,114 +69,27 @@ jobs: echo "BUNDLE_WITH=duel" >> "$GITHUB_ENV" accept-label: "duel: accept" - # The reusable workflow's Duel job's steps, in bash, with what pg's - # build needs on Windows, as source-gem.yml has it: MSYS2's gcc, and + # On Windows, what pg's build needs, as source-gem.yml has it: + # MSYS2's gcc (from Ruby's devkit, so once Ruby is set up) and # PostgreSQL's binaries (for libpq), on the PATH. The server each - # worker starts (with pg_ctl, there) is the runner's own PostgreSQL's, - # in PGBIN, whose initdb drops the rights of the runner's user, an - # administrator, as postgres needs: the binaries' doesn't. + # worker starts is the runner's own PostgreSQL's, in PGBIN, whose + # initdb drops the rights of the runner's user, an administrator, as + # postgres needs: the binaries' doesn't. windows: - name: Duel (windows) - runs-on: windows-latest - timeout-minutes: 60 + uses: sferik/duel-ruby/.github/workflows/duel.yml@main permissions: - contents: read + contents: write pull-requests: read # for the pull request's labels (see c.accept_label) - env: - BUNDLE_WITH: duel # the Gemfile's optional group, with Duel and its PostgreSQL plugin - PGVERSION: 18.0-1-windows-x64 - defaults: - run: - shell: bash - steps: - - uses: actions/checkout@v7 - with: - fetch-depth: 0 # the baseline comes from history, tags included - persist-credentials: false - # The labels of the pull request (or for a push, of the one that - # merged it), for c.accept_label in .duel.rb, as a JSON array. On a - # schedule, the last commit since the last release that merged a - # pull request with the label: what that slowed down was accepted, - # so it's compared with instead. - - name: Find the pull request's labels - id: labels - if: github.event_name == 'pull_request' || github.event_name == 'merge_group' || github.event_name == 'push' || github.event_name == 'schedule' - continue-on-error: true # (without them, nothing's accepted) - env: - GH_TOKEN: ${{ github.token }} - PR: ${{ github.event.pull_request.number }} - QUEUED: ${{ github.event.merge_group.head_ref }} - ACCEPT_LABEL: "duel: accept" - RELEASE_TAGS: "v*" - run: | - if [ "$GITHUB_EVENT_NAME" = schedule ]; then - tag=$(git describe --tags --abbrev=0 --match "$RELEASE_TAGS" HEAD^ 2>/dev/null) || exit 0 - since=$(TZ=UTC git log -1 --date=format-local:%Y-%m-%dT%H:%M:%SZ --format=%cd "$tag") - merged=$(gh pr list --repo "$GITHUB_REPOSITORY" --state merged --label "$ACCEPT_LABEL" --search "merged:>=$since" --limit 1000 \ - --json mergeCommit --jq '.[].mergeCommit.oid') - accepted=$(git rev-list "$tag..HEAD" | grep -Fx -m 1 -f <(echo "$merged")) || accepted= - echo "accepted=$accepted" >> "$GITHUB_OUTPUT" - exit 0 - fi - # (In a merge queue, the last pull request queued, which the queue's - # branch names: gh-readonly-queue/master/pr-123-.) - if [ -n "$QUEUED" ]; then - PR=${QUEUED##*/pr-} - PR=${PR%%-*} - fi - if [ -n "$PR" ]; then - labels=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/labels" --jq '[.[].name]') - else - labels=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" --jq '[.[0].labels[]?.name]') - fi - echo "labels=$labels" >> "$GITHUB_OUTPUT" - # (The bundle once gcc and libpq are there, below.) - - uses: ruby/setup-ruby@v1 - with: - ruby-version: "4.0" - - name: Install MSYS2's gcc - shell: cmd - run: ridk exec sh -c "pacman --sync --needed --noconfirm ${MINGW_PACKAGE_PREFIX}-gcc" - - name: Download PostgreSQL - shell: pwsh - run: | - Add-Type -AssemblyName System.IO.Compression.FileSystem - $(new-object net.webclient).DownloadFile("https://get.enterprisedb.com/postgresql/postgresql-$env:PGVERSION-binaries.zip", "$env:RUNNER_TEMP/postgresql-binaries.zip") - [System.IO.Compression.ZipFile]::ExtractToDirectory("$env:RUNNER_TEMP/postgresql-binaries.zip", "$env:RUNNER_TEMP") - echo "$env:RI_DEVKIT$env:MINGW_PREFIX/bin;$env:RI_DEVKIT/usr/bin;$env:RUNNER_TEMP/pgsql/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - - name: Use the runner's PostgreSQL for the servers - run: echo "DUEL_POSTGRESQL_BIN=$PGBIN" >> "$GITHUB_ENV" - - run: bundle install - # As on Linux and macOS: Duel adds its report to the job's summary, - # writes it to duel.md for the comment, and sets the step's outputs - # to say whether to comment, as c.comment in .duel.rb says. - - name: Compare - id: compare - env: - 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 || '' }} - # (Run by hand, it compares anyway: with nothing changed, the code - # with itself, which checks the setup.) - DUEL_FORCE: ${{ github.event_name == 'workflow_dispatch' && '1' || '' }} - DUEL_LABELS: ${{ steps.labels.outputs.labels }} - DUEL_ACCEPTED: ${{ steps.labels.outputs.accepted }} - run: bundle exec duel --markdown "$RUNNER_TEMP/duel/duel.md" - # For a pull request, what Duel said, for the Perf comment workflow, - # which can't see this job's outputs. - - name: Say whether to comment - if: ${{ !cancelled() && github.event_name == 'pull_request' }} - env: - PR: ${{ github.event.pull_request.number }} - COMMENT: ${{ steps.compare.outputs.comment }} - STATUS: ${{ steps.compare.outputs.status }} - run: | - mkdir -p "$RUNNER_TEMP/duel" - printf 'pr=%s\ncomment=%s\nstatus=%s\n' "$PR" "$COMMENT" "$STATUS" > "$RUNNER_TEMP/duel/comment.env" - # The report, for the comments, beside Linux's and macOS's. - - name: Keep the report - if: ${{ !cancelled() && (github.event_name == 'pull_request' || github.event_name == 'push') }} - uses: actions/upload-artifact@v7 - with: - name: duel-report-windows - path: ${{ runner.temp }}/duel/ - if-no-files-found: ignore # none when Duel didn't get to compare - retention-days: 1 + with: + report: windows + runs-on: windows-latest + ruby-version: "4.0" + setup: | + echo "BUNDLE_WITH=duel" >> "$GITHUB_ENV" + echo "DUEL_POSTGRESQL_BIN=$PGBIN" >> "$GITHUB_ENV" + setup-after-ruby: | + ridk exec pacman --sync --needed --noconfirm "${MINGW_PACKAGE_PREFIX}-gcc" + curl -fsSL -o "$RUNNER_TEMP/postgresql.zip" https://get.enterprisedb.com/postgresql/postgresql-18.0-1-windows-x64-binaries.zip + 7z x -y -o"$RUNNER_TEMP" "$RUNNER_TEMP/postgresql.zip" > /dev/null + { echo "$RI_DEVKIT$MINGW_PREFIX/bin"; echo "$RI_DEVKIT/usr/bin"; echo "$RUNNER_TEMP/pgsql/bin"; } >> "$GITHUB_PATH" + accept-label: "duel: accept" From bd7c0e681e7134374e3efafa69b45b78c0294f41 Mon Sep 17 00:00:00 2001 From: Erik Berlin Date: Mon, 16 Nov 2026 14:04:02 -0800 Subject: [PATCH 7/9] Test: what Git's bash finds of MSYS2's, and ridk.cmd --- .github/workflows/perf.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index dc45d927b..d45f84638 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -88,7 +88,10 @@ jobs: echo "BUNDLE_WITH=duel" >> "$GITHUB_ENV" echo "DUEL_POSTGRESQL_BIN=$PGBIN" >> "$GITHUB_ENV" setup-after-ruby: | - ridk exec pacman --sync --needed --noconfirm "${MINGW_PACKAGE_PREFIX}-gcc" + type -a ridk ridk.cmd pacman || true + env | grep -E '^(RI_DEVKIT|MSYSTEM|MINGW_|MSYS)' || true + ls "$RI_DEVKIT/usr/bin/pacman.exe" || true + ridk.cmd exec pacman --sync --needed --noconfirm "${MINGW_PACKAGE_PREFIX}-gcc" curl -fsSL -o "$RUNNER_TEMP/postgresql.zip" https://get.enterprisedb.com/postgresql/postgresql-18.0-1-windows-x64-binaries.zip 7z x -y -o"$RUNNER_TEMP" "$RUNNER_TEMP/postgresql.zip" > /dev/null { echo "$RI_DEVKIT$MINGW_PREFIX/bin"; echo "$RI_DEVKIT/usr/bin"; echo "$RUNNER_TEMP/pgsql/bin"; } >> "$GITHUB_PATH" From 941fdaeba1cd5c7029c8e2c9c9acd2e2fa37e732 Mon Sep 17 00:00:00 2001 From: Erik Berlin Date: Mon, 16 Nov 2026 14:07:59 -0800 Subject: [PATCH 8/9] Test: pacman directly, and 7z from the temp directory --- .github/workflows/perf.yml | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index d45f84638..279af0ae0 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -88,11 +88,8 @@ jobs: echo "BUNDLE_WITH=duel" >> "$GITHUB_ENV" echo "DUEL_POSTGRESQL_BIN=$PGBIN" >> "$GITHUB_ENV" setup-after-ruby: | - type -a ridk ridk.cmd pacman || true - env | grep -E '^(RI_DEVKIT|MSYSTEM|MINGW_|MSYS)' || true - ls "$RI_DEVKIT/usr/bin/pacman.exe" || true - ridk.cmd exec pacman --sync --needed --noconfirm "${MINGW_PACKAGE_PREFIX}-gcc" - curl -fsSL -o "$RUNNER_TEMP/postgresql.zip" https://get.enterprisedb.com/postgresql/postgresql-18.0-1-windows-x64-binaries.zip - 7z x -y -o"$RUNNER_TEMP" "$RUNNER_TEMP/postgresql.zip" > /dev/null + pacman --sync --needed --noconfirm "${MINGW_PACKAGE_PREFIX}-gcc" + (cd "$RUNNER_TEMP" && curl -fsSL -o postgresql.zip https://get.enterprisedb.com/postgresql/postgresql-18.0-1-windows-x64-binaries.zip && + 7z x -y postgresql.zip > /dev/null) { echo "$RI_DEVKIT$MINGW_PREFIX/bin"; echo "$RI_DEVKIT/usr/bin"; echo "$RUNNER_TEMP/pgsql/bin"; } >> "$GITHUB_PATH" accept-label: "duel: accept" From 8ba81fb2bb5685bc18ca5204cfdabfd5f1433a4c Mon Sep 17 00:00:00 2001 From: Erik Berlin Date: Mon, 16 Nov 2026 14:11:47 -0800 Subject: [PATCH 9/9] Test: the PATH as one line, the devkit's first --- .github/workflows/perf.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index 279af0ae0..26fad8b4c 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -91,5 +91,7 @@ jobs: pacman --sync --needed --noconfirm "${MINGW_PACKAGE_PREFIX}-gcc" (cd "$RUNNER_TEMP" && curl -fsSL -o postgresql.zip https://get.enterprisedb.com/postgresql/postgresql-18.0-1-windows-x64-binaries.zip && 7z x -y postgresql.zip > /dev/null) - { echo "$RI_DEVKIT$MINGW_PREFIX/bin"; echo "$RI_DEVKIT/usr/bin"; echo "$RUNNER_TEMP/pgsql/bin"; } >> "$GITHUB_PATH" + # (One line, in this order: each line goes before the last, and + # PostgreSQL's DLLs mustn't come before the devkit's, which gcc runs.) + echo "$RI_DEVKIT$MINGW_PREFIX/bin;$RI_DEVKIT/usr/bin;$RUNNER_TEMP/pgsql/bin" >> "$GITHUB_PATH" accept-label: "duel: accept"