Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
# Base and head are measured from identical checkouts so that only their code and dependencies differ.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
path: tmp/head
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
Expand All @@ -112,15 +117,33 @@ jobs:
with:
ruby-version: 4.0
bundler-cache: true
- name: Install base and head dependencies
shell: bash
run: |
for side in base head; do
gemfile="$GITHUB_WORKSPACE/tmp/$side/$BUNDLE_GEMFILE"
if [ ! -f "$gemfile" ]; then
echo "::warning::Base has no $BUNDLE_GEMFILE; measuring base with head dependencies"
gemfile="$GITHUB_WORKSPACE/tmp/head/$BUNDLE_GEMFILE"
fi
BUNDLE_GEMFILE="$gemfile" bundle config set --local path "$GITHUB_WORKSPACE/vendor/bundle"
BUNDLE_GEMFILE="$gemfile" bundle config set --local deployment true
BUNDLE_GEMFILE="$gemfile" bundle install --jobs 4
echo "$(echo "$side" | tr '[:lower:]' '[:upper:]')_BUNDLE_GEMFILE=$gemfile" >> "$GITHUB_ENV"
done
- name: Compare performance against base
shell: bash
env:
PASSES: 5
# Timings shift more between processes than between passes, so favor more processes.
ROUNDS: 6
PASSES: 3
BASE_REF: ${{ steps.release.outputs.tag || github.event.pull_request.base.sha }}
run: |
for round in 1 2 3; do
VIEW_COMPONENT_LIB=tmp/base/lib bundle exec ruby performance/measure.rb "tmp/performance/base/$round.json"
bundle exec ruby performance/measure.rb "tmp/performance/head/$round.json"
for round in $(seq "$ROUNDS"); do
BUNDLE_GEMFILE="$BASE_BUNDLE_GEMFILE" VIEW_COMPONENT_LIB=tmp/base/lib \
bundle exec ruby performance/measure.rb "tmp/performance/base/$round.json"
BUNDLE_GEMFILE="$HEAD_BUNDLE_GEMFILE" VIEW_COMPONENT_LIB=tmp/head/lib \
bundle exec ruby performance/measure.rb "tmp/performance/head/$round.json"
done
{
printf 'Base: `%s`; head: `%s` (pull request merge commit).\n\n' "$BASE_REF" "$GITHUB_SHA"
Expand Down
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ nav_order: 6

## main

* Benchmark pull requests against the base branch's dependencies and compare absolute component times to catch performance regressions from dependency updates, and run more benchmark processes to reduce noise.

*Joel Hawksley*

* Enable all Herb lint rules, template formatting, Tailwind class sorting, and editor support for development.

*Joel Hawksley*
Expand Down
7 changes: 4 additions & 3 deletions docs/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ bundle exec appraisal rails-8.0 rake

### Performance

CI compares each pull request against its base branch on Rails 8.1 and Rails main. For each rendering scenario in `performance/measure.rb`, it divides the component render time by the render time of an equivalent partial. It also measures cold component digests relative to cold partial digests, clearing Action View's digest caches and using a new lookup context for every call.
CI compares each pull request against its base branch on Rails 8.1 and Rails main, measuring the base with its own dependencies so dependency updates are compared too. The report lists any dependency changes. For each rendering scenario in `performance/measure.rb`, it divides the component render time by the render time of an equivalent partial. It also measures cold component digests relative to cold partial digests, clearing Action View's digest caches and using a new lookup context for every call.

The digest and boot scenarios use 300 generated ERB components and 300 generated Slim components. Each renders another component and includes a shared helper that references multiple components, exercising overlapping and cyclic dependencies. The boot scenario divides the time spent in ViewComponent (requiring it, loading components, compiling them, and precomputing digests) by the rest of boot. CI fails if any scenario's ratio is more than 5% higher than the baseline's ratio.
The digest and boot scenarios use 300 generated ERB components and 300 generated Slim components. Each renders another component and includes a shared helper that references multiple components, exercising overlapping and cyclic dependencies. The boot scenario divides the time spent in ViewComponent (requiring it, loading components, compiling them, and precomputing digests) by the rest of boot. CI fails if any scenario's ratio is more than 5% higher than the baseline's ratio. Ratios cancel out runner noise but miss changes, such as dependency updates, that slow components and partials alike, so CI also fails if any scenario's absolute component time, measured on the same runner, is more than 10% higher than the baseline's.

The executor scenario runs empty `app.executor.wrap` jobs on four threads in development with template caching disabled and the polling file watcher. It uses the generated components plus 600 model directories and compares against Rails without ViewComponent, catching template scans on executor-only paths such as Action Cable broadcasts.

Expand All @@ -122,7 +122,8 @@ To run the comparison locally:

```command
git worktree add tmp/base main
VIEW_COMPONENT_LIB=tmp/base/lib bundle exec ruby performance/measure.rb tmp/performance/base.json
BUNDLE_GEMFILE=tmp/base/Gemfile bundle install
BUNDLE_GEMFILE=tmp/base/Gemfile VIEW_COMPONENT_LIB=tmp/base/lib bundle exec ruby performance/measure.rb tmp/performance/base.json
bundle exec ruby performance/measure.rb tmp/performance/head.json
bundle exec ruby performance/compare.rb tmp/performance/base.json tmp/performance/head.json
```
Expand Down
75 changes: 61 additions & 14 deletions performance/compare.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@

# Compares performance/measure.rb runs and fails when any scenario's
# render, cold digest, boot, or development executor ratio regresses by
# more than THRESHOLD (default 0.05).
# more than THRESHOLD (default 0.05), or its absolute component time regresses
# by more than TIME_THRESHOLD (default 0.10). Ratios cancel out machine noise,
# while absolute times catch dependency changes that slow components and
# partials alike.
#
# ruby performance/compare.rb base.json head.json
# ruby performance/compare.rb base/ head/
Expand All @@ -25,50 +28,94 @@
runs.first.merge(
"scenarios" => runs.first["scenarios"].to_h do |name, scenario|
ratios = runs.flat_map { |run| run.dig("scenarios", name, "ratios") || [] }
[name, scenario.merge("ratio" => median.call(ratios), "ratios" => ratios)]
times = runs.flat_map { |run| run.dig("scenarios", name, "component_times_ms") || [] }
scenario = scenario.merge("ratio" => median.call(ratios), "ratios" => ratios)
scenario = scenario.merge("component_ms" => median.call(times), "component_times_ms" => times) if times.any?
[name, scenario]
end
)
end

threshold = Float(ENV.fetch("THRESHOLD", 0.05))
time_threshold = Float(ENV.fetch("TIME_THRESHOLD", 0.10))
percent = -> (value) { "#{(value * 100).round(1)}%" }

puts("### ViewComponent performance (Rails #{head["rails"]}, #{head["ruby"].split.first(2).join(" ")})")
puts
puts(
"Ratios are component render time / equivalent partial render time; for `cold_digest`, cold component digest time / cold partial digest time; for `boot`, time spent in ViewComponent during boot / the rest of boot; and for `executor`, development executor time with ViewComponent / Rails alone. Lower is faster."
"Ratios are component render time / equivalent partial render time; for `cold_digest`, cold component digest time / cold partial digest time; for `boot`, time spent in ViewComponent during boot / the rest of boot; and for `executor`, development executor time with ViewComponent / Rails alone. Lower is faster. Times are median absolute component times, measured on the same runner."
)
puts
puts("| Scenario | Base ratio | Head ratio | Change | Allocations (base → head) | |")
puts("| --- | ---: | ---: | ---: | ---: | --- |")
base_gems = base.fetch("gems", {}).except("view_component")
head_gems = head.fetch("gems", {}).except("view_component")
dependency_changes = (base_gems.keys | head_gems.keys).sort.filter_map do |name|
next if base_gems[name] == head_gems[name]

regressions = head["scenarios"].filter_map do |name, current|
"`#{name}` #{base_gems[name] || "—"} → #{head_gems[name] || "—"}"
end

if dependency_changes.empty?
puts("Dependencies are unchanged.")
else
puts("Dependency changes: #{dependency_changes.join(", ")}.")
end

puts
puts("| Scenario | Base ratio | Head ratio | Change | Time (base → head) | Change | Allocations (base → head) | |")
puts("| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |")

ratio_regressions = []
time_regressions = []
head["scenarios"].each do |name, current|
previous = base["scenarios"][name]
unless previous
puts("| #{name} | — | #{format("%.3f", current["ratio"])} | new | #{current["component_allocations"]} | |")
puts(
"| #{name} | — | #{format("%.3f", current["ratio"])} | new | — | | #{current["component_allocations"]} | |"
)
next
end

change = current["ratio"] / previous["ratio"] - 1
regressed = current["ratio"] > previous["ratio"] * (1 + threshold)
ratio_regressions << name if change > threshold

time = "—"
time_change = ""
if previous["component_ms"] && current["component_ms"]
time = format("%.3fms → %.3fms", previous["component_ms"], current["component_ms"])
time_change = current["component_ms"] / previous["component_ms"] - 1
time_regressions << name if time_change > time_threshold
time_change = format("%+.1f%%", time_change * 100)
end

puts(
format(
"| %s | %.3f | %.3f | %+.1f%% | %d → %d | %s |",
"| %s | %.3f | %.3f | %+.1f%% | %s | %s | %d → %d | %s |",
name,
previous["ratio"],
current["ratio"],
change * 100,
time,
time_change,
previous["component_allocations"],
current["component_allocations"],
regressed ? "❌" : "✅"
(ratio_regressions.include?(name) || time_regressions.include?(name)) ? "❌" : "✅"
)
)
name if regressed
end

puts
if regressions.empty?
puts("No scenario regressed by more than #{(threshold * 100).round(1)}%.")
if ratio_regressions.empty? && time_regressions.empty?
puts(
"No ratio regressed by more than #{percent.call(threshold)} and no time by more than #{percent.call(time_threshold)}."
)
else
puts("Regressed by more than #{(threshold * 100).round(1)}%: #{regressions.join(", ")}.")
if ratio_regressions.any?
puts("Ratio regressed by more than #{percent.call(threshold)}: #{ratio_regressions.join(", ")}.")
end

if time_regressions.any?
puts("Time regressed by more than #{percent.call(time_threshold)}: #{time_regressions.join(", ")}.")
end

exit(1)
end
10 changes: 9 additions & 1 deletion performance/measure.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
# bundle exec ruby performance/measure.rb [OUTPUT_JSON]
#
# Set VIEW_COMPONENT_LIB to the `lib` directory of another checkout to measure
# that version of ViewComponent with this checkout's dependencies and scenarios.
# that version of ViewComponent with this checkout's scenarios. Also set
# BUNDLE_GEMFILE to that checkout's Gemfile to use its dependencies.
# PASSES (default 15), SAMPLE_SECONDS (default 0.1), and BOOT_COMPONENTS
# (default 300) tune the run length.

Expand Down Expand Up @@ -116,6 +117,7 @@ class BenchmarksController < ActionController::Base
"iterations" => {"reference" => reference_iterations, "component" => scenario_iterations},
"reference_ms" => median.call(samples.map(&:first)) * 1000,
"component_ms" => median.call(samples.map(&:last)) * 1000,
"component_times_ms" => samples.map { |_reference_time, scenario_time| scenario_time * 1000 },
"reference_allocations" => allocations.call(reference),
"component_allocations" => allocations.call(scenario)
}
Expand Down Expand Up @@ -276,6 +278,7 @@ def initialize(name:)
"ratios" => ratios,
"reference_ms" => median.call(samples.map { |sample| sample["rest"]["seconds"] }) * 1000,
"component_ms" => median.call(samples.map { |sample| sample["view_component"]["seconds"] }) * 1000,
"component_times_ms" => samples.map { |sample| sample["view_component"]["seconds"] * 1000 },
"reference_allocations" => median.call(samples.map { |sample| sample["rest"]["allocations"] }),
"component_allocations" => median.call(samples.map { |sample| sample["view_component"]["allocations"] })
}
Expand Down Expand Up @@ -314,6 +317,7 @@ def initialize(name:)
"iterations" => {"reference" => reference_run["iterations"], "component" => component_run["iterations"]},
"reference_ms" => median.call(reference_samples.map { |sample| sample["seconds"] }) * 1000,
"component_ms" => median.call(component_samples.map { |sample| sample["seconds"] }) * 1000,
"component_times_ms" => component_samples.map { |sample| sample["seconds"] * 1000 },
"reference_allocations" => median.call(reference_samples.map { |sample| sample["allocations"] }),
"component_allocations" => median.call(component_samples.map { |sample| sample["allocations"] })
}
Expand All @@ -336,6 +340,10 @@ def initialize(name:)
"view_component" => ViewComponent::VERSION::STRING,
"view_component_lib" => view_component_lib,
"git_sha" => git_sha.empty? ? nil : git_sha,
"gems" => Gem.loaded_specs.sort.to_h { |name, spec|
revision = spec.source.revision if spec.respond_to?(:source) && spec.source.respond_to?(:revision)
[name, revision ? "#{spec.version} (#{revision[0, 12]})" : spec.version.to_s]
},
"passes" => passes,
"scenarios" => results
}
Expand Down
67 changes: 59 additions & 8 deletions test/script/benchmark_workflow_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,41 @@ def test_missing_release_tag_fails_instead_of_comparing_against_main
refute(File.exist?(File.join(@directory, "output")))
end

def test_base_and_head_dependencies_are_installed_from_their_own_gemfiles
write("tmp/base/gemfiles/rails_8.1.gemfile", "")
write("tmp/head/gemfiles/rails_8.1.gemfile", "")
stdout, stderr, status = run_dependency_install

assert(status.success?, "#{stdout}\n#{stderr}")
base_gemfile, head_gemfile = %w[base head].map { |side|
File.join(@directory, "tmp/#{side}/gemfiles/rails_8.1.gemfile")
}
assert_equal("BASE_BUNDLE_GEMFILE=#{base_gemfile}\nHEAD_BUNDLE_GEMFILE=#{head_gemfile}\n", read("env"))
[base_gemfile, head_gemfile].each do |gemfile|
assert_includes(read("commands.log"), "#{gemfile} install --jobs 4")
assert_includes(read("commands.log"), "#{gemfile} config set --local path #{@directory}/vendor/bundle")
end
end

def test_base_without_the_gemfile_falls_back_to_head_dependencies
write("tmp/head/gemfiles/rails_8.1.gemfile", "")
stdout, stderr, status = run_dependency_install

assert(status.success?, "#{stdout}\n#{stderr}")
assert_includes(stdout, "::warning::Base has no gemfiles/rails_8.1.gemfile")
assert_includes(
read("env"),
"BASE_BUNDLE_GEMFILE=#{File.join(@directory, "tmp/head/gemfiles/rails_8.1.gemfile")}\n"
)
end

def test_successful_comparisons_are_saved_for_the_comment
assert_comparison_report(head_ratio: 1.0, exitstatus: 0)
end

def test_regressions_still_fail_and_are_saved_for_the_comment
assert_comparison_report(head_ratio: 2.0, exitstatus: 1)
assert_includes(read("tmp/performance/report.md"), "Regressed by more than 5.0%: component.")
assert_includes(read("tmp/performance/report.md"), "Ratio regressed by more than 5.0%: component.")
end

def test_comments_include_both_rails_results_and_are_updated_on_reruns
Expand Down Expand Up @@ -204,6 +232,26 @@ def test_only_same_repository_release_prs_use_release_reporting

private

def run_dependency_install
@environment["COMMAND_LOG"] = File.join(@directory, "commands.log")
mock_commands(
<<~BASH
bundle() {
printf '%s %s\\n' "$BUNDLE_GEMFILE" "$*" >> "$COMMAND_LOG"
}
BASH
)
run_step(
"benchmark-rails",
"Install base and head dependencies",
env: {
"GITHUB_WORKSPACE" => @directory,
"GITHUB_ENV" => File.join(@directory, "env"),
"BUNDLE_GEMFILE" => "gemfiles/rails_8.1.gemfile"
}
)
end

def assert_comparison_report(head_ratio:, exitstatus:)
results = lambda do |ratio|
JSON.generate(
Expand All @@ -219,11 +267,11 @@ def assert_comparison_report(head_ratio:, exitstatus:)
case "$3" in
performance/measure.rb)
mkdir -p "$(dirname "$4")"
if [ -n "${VIEW_COMPONENT_LIB:-}" ]; then
printf '%s\\n' "$BASE_RESULT" > "$4"
else
printf '%s\\n' "$HEAD_RESULT" > "$4"
fi
case "$VIEW_COMPONENT_LIB:$BUNDLE_GEMFILE" in
"tmp/base/lib:$BASE_BUNDLE_GEMFILE") printf '%s\\n' "$BASE_RESULT" > "$4" ;;
"tmp/head/lib:$HEAD_BUNDLE_GEMFILE") printf '%s\\n' "$HEAD_RESULT" > "$4" ;;
*) return 78 ;;
esac
;;
performance/compare.rb) "$RUBY_EXECUTABLE" "$COMPARE_SCRIPT" "$4" "$5" ;;
*) return 77 ;;
Expand All @@ -238,6 +286,8 @@ def assert_comparison_report(head_ratio:, exitstatus:)
env: {
"BASE_RESULT" => results.call(1.0),
"HEAD_RESULT" => results.call(head_ratio),
"BASE_BUNDLE_GEMFILE" => "/base/gemfiles/rails_8.1.gemfile",
"HEAD_BUNDLE_GEMFILE" => "/head/gemfiles/rails_8.1.gemfile",
"RUBY_EXECUTABLE" => RbConfig.ruby,
"COMPARE_SCRIPT" => File.join(ROOT, "performance/compare.rb"),
"BASE_REF" => "v4.21.0",
Expand All @@ -246,7 +296,7 @@ def assert_comparison_report(head_ratio:, exitstatus:)
)

assert_equal(exitstatus, status.exitstatus, "#{stdout}\n#{stderr}")
assert_equal(6, Dir[File.join(@directory, "tmp/performance/{base,head}/*.json")].size)
assert_equal(12, Dir[File.join(@directory, "tmp/performance/{base,head}/*.json")].size)
assert_equal(read("summary.md"), read("tmp/performance/report.md"))
assert_includes(read("tmp/performance/report.md"), "Base: `v4.21.0`; head: `merge-sha`")
assert_includes(read("tmp/performance/report.md"), "| Scenario | Base ratio | Head ratio |")
Expand Down Expand Up @@ -312,8 +362,9 @@ def step(job, name)

def run_step(job, name, env: {})
configuration = step(job, name)
step_env = configuration.fetch("env", {}).to_h { |key, value| [key, value.to_s] }
Open3.capture3(
@environment.merge(env),
@environment.merge(step_env.reject { |_key, value| value.include?("${{") }, env),
"bash",
"-e",
"-o",
Expand Down
Loading
Loading