Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

Skip the preliminary full update for exact-pinned targets - #9952

Draft
jeffwidman wants to merge 1 commit into
ruby:masterfrom
jeffwidman:perf/skip-exact-pin-preliminary-resolution
Draft

jeffwidman wants to merge 1 commit into
ruby:masterfrom
jeffwidman:perf/skip-exact-pin-preliminary-resolution

Conversation

@jeffwidman

@jeffwidman jeffwidman commented Oct 14, 2026 •

Copy link
Copy Markdown

WIP - please ignore while this is in Draft.

Thanks!
-Jeff

What was the end-user or developer problem that led to this PR?

For a targeted update, Bundler can resolve the dependency graph twice: first
as a full update to discover the versions of the explicitly unlocked gems,
then with those versions pinned while retaining the other update constraints.

The first resolution is useful when Bundler must choose a target version.
However, when every explicit target already has an applicable exact requirement,
its version is known before that resolution starts. Solving the graph to discover
those same versions repeats work without providing new target-version information.
The final constrained resolution is still needed to check whether the complete
dependency graph can satisfy the request.

This occurs with ordinary bundle update GEM and bundle lock --update GEM
requests after changing exact requirements, as well as automated updates.
For example, Dependabot's public lockfile updater pins the chosen versions
before resolving
.
Repeating a full resolution in each eligible invocation adds up on larger graphs.

What is your fix for the problem, implemented in this PR?

Derive the exact base requirements directly when all explicit update targets
have exactly one applicable, exact, source-less requirement, and skip only the
preliminary full-update resolution.

The change adds 21 lines in Definition, with no cache, serialization, new
configuration, or concurrency. It retains the existing path for nonexact or
mixed requests, indirect-only targets, explicit source targets, active overrides,
and explicitly unlocked Bundler self-updates.

Two details are important for correctness:

  • Read Resolver::Base#requirements, which has already filtered out declarations
    for excluded platforms. An inactive exact declaration must not restrict a gem
    that is needed transitively on the active platform.
  • Install the exact base requirements, rather than simply returning early.
    Otherwise an existing downgrade-prevention floor can reject a valid exact
    downgrade. This also matters when a caller changes requirements after building
    the definition.

The final constrained resolver and its existing conflict-relaxation behavior
remain in place. This preserves necessary indirect downgrades without
unnecessarily updating unrelated direct dependencies.

Benchmarks

Isolated native patch on current master

An offline synthetic fixture has 20 direct dependencies, 120 locked gem names,
and 12 available versions per name. All gems start locked at 1.0.0; the first
direct dependency is changed to = 1.11.0 and explicitly unlocked. Each gem
depends on the gems 20 and 21 positions later, where present, with >= 1.0.0
requirements.

The actual baseline and patched libraries were compared in seven alternating
pairs, after one discarded warmup per library. Every sample used a fresh Ruby
process and the same unchanged input lockfile. Timing covers Definition.build,
resolve_with_cache!, and to_lock, including archive metadata reads, but
excludes fixture generation and Ruby startup. These runs were performed after
the test suite finished.

Metric Baseline This patch
Median process CPU 1.786 s 1.670 s
Median elapsed time 1.786 s 1.670 s
Resolver starts per invocation 2 1
HTTP requests 0 0

This is 6.5% less median CPU and elapsed time on this synthetic workload.
All 14 measured runs produced the same lockfile SHA-256. It is a small repeated
local benchmark, not a confidence interval or a prediction for other graphs.

Standalone synthetic reproduction

Save the following as exact-pin-benchmark.rb. With unmodified and patched
checkouts at the same base revision, run:

ruby -I/path/to/baseline/lib exact-pin-benchmark.rb /path/to/baseline/lib /path/to/patched/lib 7

The command passed locally with the results above. It generates only synthetic
gems in a temporary directory, uses cached resolution without a registry, and
fails if either library fails or the lockfile hashes differ.

# frozen_string_literal: true

require "bundler"
require "digest"
require "fileutils"
require "json"
require "open3"
require "rubygems/package"
require "rubygems/user_interaction"
require "tmpdir"

if ARGV.first == "--case"
  module CountResolutions
    def start
      $resolution_count += 1
      super
    end
  end

  Bundler::Resolver.prepend(CountResolutions)
  Bundler.ui = Bundler::UI::Silent.new
  $resolution_count = 0
  Dir.chdir(ARGV.fetch(1))
  cpu = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID)
  wall = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  definition = Bundler::Definition.build("Gemfile", "Gemfile.lock", gems: ["fixture000"])
  definition.resolve_with_cache!
  output = definition.to_lock
  puts JSON.generate(
    cpu: Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) - cpu,
    wall: Process.clock_gettime(Process::CLOCK_MONOTONIC) - wall,
    resolutions: $resolution_count,
    lock_sha256: Digest::SHA256.hexdigest(output),
    bundler: Bundler::VERSION, rubygems: Gem::VERSION, ruby: RUBY_VERSION
  )
  exit
end

baseline, patched, repetitions = ARGV
abort "Usage: ruby -I<baseline>/lib exact-pin-benchmark.rb <baseline>/lib <patched>/lib [repetitions]" unless baseline && patched
libraries = { "baseline" => File.expand_path(baseline), "patched" => File.expand_path(patched) }
repetitions = Integer(repetitions || "7")
abort "Repetitions must be positive" unless repetitions.positive?
Gem::DefaultUserInteraction.ui = Gem::SilentUI.new
names = Array.new(120) {|i| format("fixture%03d", i) }
direct = names.first(20)
versions = Array.new(12) {|i| "1.#{i}.0" }
children = names.each_with_index.to_h do |name, i|
  [name, [names[i + 20], names[i + 21]].compact]
end
results = []

Dir.mktmpdir("exact-pin-benchmark-") do |directory|
  cache = File.join(directory, "vendor", "cache")
  FileUtils.mkdir_p(cache)
  Dir.chdir(cache) do
    names.product(versions).each do |name, version|
      spec = Gem::Specification.new do |s|
        s.name = name
        s.version = version
        s.summary = "Synthetic exact-pin benchmark"
        s.authors = ["Fixture"]
        s.license = "MIT"
        children.fetch(name).each {|child| s.add_dependency(child, ">= 1.0.0") }
      end
      Gem::Package.build(spec)
    end
  end
  File.write(File.join(directory, "Gemfile"),
    "source 'https://example.invalid'\n" +
    direct.map {|name| "gem '#{name}', '#{name == names.first ? '= 1.11.0' : '>= 1.0.0'}'\n" }.join)
  locked_specs = names.map do |name|
    "    #{name} (1.0.0)\n" + children.fetch(name).map {|child| "      #{child} (>= 1.0.0)\n" }.join
  end.join
  File.write(File.join(directory, "Gemfile.lock"), <<~LOCK)
    GEM
      remote: https://example.invalid/
      specs:
    #{locked_specs}
    PLATFORMS
      ruby

    DEPENDENCIES
    #{direct.map {|name| "  #{name} (>= 1.0.0)\n" }.join}
    BUNDLED WITH
       #{Bundler::VERSION}
  LOCK

  # Discard one warmup per library, then alternate which library runs first.
  (0..repetitions).each do |iteration|
    order = iteration.odd? ? libraries.to_a.reverse : libraries.to_a
    order.each do |label, library|
      stdout, stderr, status = Open3.capture3(
        { "BUNDLE_IGNORE_CONFIG" => "true", "HOME" => directory },
        RbConfig.ruby, "-I", library, __FILE__, "--case", directory
      )
      abort "#{label} failed (#{status}): #{stderr}\n#{stdout}" unless status.success?
      result = JSON.parse(stdout).merge("library" => label, "iteration" => iteration)
      results << result unless iteration.zero?
      warn "#{label} iteration #{iteration}: #{result.fetch("cpu").round(3)} CPU seconds, #{result.fetch("resolutions")} resolutions"
    end
  end
end

abort "Lockfiles differ" unless results.map {|r| r.fetch("lock_sha256") }.uniq.one?
median = lambda do |values|
  sorted = values.sort
  (sorted[(sorted.size - 1) / 2] + sorted[sorted.size / 2]) / 2.0
end
summary = results.group_by {|r| r.fetch("library") }.transform_values do |runs|
  {
    cpu_median: median.call(runs.map {|r| r.fetch("cpu") }),
    wall_median: median.call(runs.map {|r| r.fetch("wall") }),
    resolution_counts: runs.map {|r| r.fetch("resolutions") }.uniq
  }
end
puts JSON.pretty_generate(
  direct_dependencies: direct.size, locked_names: names.size, versions_per_name: versions.size,
  repetitions: repetitions, identical_lockfiles: true, summary: summary, runs: results
)

Existing standalone Dependabot measurements

These measurements tested only this exact-pin optimization, using a runtime
prototype of the same eligibility checks and exact-base-requirement replacement.
They are not measurements of the other performance changes being investigated.

The local jobs used Ruby 4.0.5, Bundler 4.0.22, and RubyGems 4.0.14. CPU is the sum
of native helper process CPU measured with Process::CLOCK_PROCESS_CPUTIME_ID,
not total updater/container CPU. All proposed dependency records and all proposed
text/binary file contents matched between each baseline and optimized pair.

Workload Direct dependencies / unique locked gem names Native CPU before Native CPU after Reduction
Three-update sample from an internal GitHub repository 463 / 663 186.40 s 151.75 s 18.6%
Complete root update job for another internal GitHub repository 84 / 296 914.97 s 868.42 s 5.1%
Complete root update job for the public dependabot/dependabot-core repository 52 / 138 237.94 s 211.17 s 11.3%

Eligible lockfile-writer invocations went from two solver passes to one.
The update checkers were not optimized. There was no observed HTTP-request
reduction from this shortcut; the demonstrated saving is repeated native CPU work.

These were individual paired local jobs on a shared development host, with live
network access. The two complete-job comparisons overlapped with other runs, so
they are not controlled wall-time trials or statistical estimates. The large
repository sample was not a complete update job. These numbers demonstrate the
opportunity, not a universal percentage or a benchmark of this patch on current
master.

Validation

Current branch base: a099e068a86c0a912d558b2c107c6c263cb5b4ff.
Local validation uses Linux MRI Ruby 4.0.5 and the checked-out Bundler/RubyGems
4.1.0.beta2.

  • Before changes:
    ruby bin/rspec spec/bundler/definition_spec.rb spec/commands/update_spec.rb --format progress --seed 45123
    • Passed: 55 examples, 0 failures.
  • With this patch, the same command:
    • Passed: 64 examples, 0 failures.
    • Nine added examples cover the shortcut, all-exact multiple targets,
      conservative fallbacks, indirect downgrades, unrelated direct dependencies,
      and excluded-platform requirements.
  • ruby bin/rubocop lib/bundler/definition.rb spec/bundler/definition_spec.rb spec/commands/update_spec.rb
    • Passed: 3 files inspected, no offenses.
  • A separate seeded differential harness compared the actual unmodified and
    patched libraries at the same base revision, without replacing the
    implementation with a runtime prototype:
    • Passed: 535 cases; 385 byte-identical successful lockfiles and 150 identical
      error classes/messages.
    • Includes 500 small acyclic graphs (seed 470013), strict/conservative update
      policies, exact downgrades, missing versions, conflicts, prereleases,
      platforms, runtime requirements, source-scoped targets, overrides, and
      requirements changed after definition construction.
  • ruby bin/parallel_rspec -n 4 spec --seed 45123
    • Passed: 4,163 examples, 0 failures, 29 pending.

The network-dependent realworld suite, RubyGems test-unit suite, and the
Windows/JRuby/TruffleRuby matrix have not been run locally.

Make sure the following tasks are checked

Derive exact base requirements from applicable explicit targets instead of resolving the complete graph to rediscover those versions. Keep the constrained resolution and fall back for nonexact targets, explicit sources, overrides, and Bundler self-updates.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants