Commit d9fe8a45 authored by Dmytro Zaporozhets (DZ)'s avatar Dmytro Zaporozhets (DZ)

Merge branch '21098-reducing-cancel-sql-queries' into 'master'

Preload associations in Ci::Pipeline#cancel_running

See merge request gitlab-org/gitlab!58484
parents 89daf3d6 789c4376
......@@ -584,10 +584,18 @@ module Ci
end
def cancel_running(retries: nil)
retry_optimistic_lock(cancelable_statuses, retries, name: 'ci_pipeline_cancel_running') do |cancelable|
cancelable.find_each do |job|
yield(job) if block_given?
job.cancel
commit_status_relations = [:project, :pipeline]
ci_build_relations = [:deployment, :taggings]
retry_optimistic_lock(cancelable_statuses, retries, name: 'ci_pipeline_cancel_running') do |cancelables|
cancelables.find_in_batches do |batch|
ActiveRecord::Associations::Preloader.new.preload(batch, commit_status_relations)
ActiveRecord::Associations::Preloader.new.preload(batch.select { |job| job.is_a?(Ci::Build) }, ci_build_relations)
batch.each do |job|
yield(job) if block_given?
job.cancel
end
end
end
end
......
---
title: Preload associations in Ci::Pipeline#cancel_running
merge_request: 58484
author:
type: performance
......@@ -2635,6 +2635,37 @@ RSpec.describe Ci::Pipeline, :mailer, factory_default: :keep do
expect(latest_status).to eq %w(canceled canceled)
end
end
context 'preloading relations' do
let(:pipeline1) { create(:ci_empty_pipeline, :created) }
let(:pipeline2) { create(:ci_empty_pipeline, :created) }
before do
create(:ci_build, :pending, pipeline: pipeline1)
create(:generic_commit_status, :pending, pipeline: pipeline1)
create(:ci_build, :pending, pipeline: pipeline2)
create(:ci_build, :pending, pipeline: pipeline2)
create(:generic_commit_status, :pending, pipeline: pipeline2)
create(:generic_commit_status, :pending, pipeline: pipeline2)
create(:generic_commit_status, :pending, pipeline: pipeline2)
end
it 'preloads relations for each build to avoid N+1 queries' do
control1 = ActiveRecord::QueryRecorder.new do
pipeline1.cancel_running
end
control2 = ActiveRecord::QueryRecorder.new do
pipeline2.cancel_running
end
extra_update_queries = 3 # transition ... => :canceled
extra_generic_commit_status_validation_queries = 2 # name_uniqueness_across_types
expect(control2.count).to eq(control1.count + extra_update_queries + extra_generic_commit_status_validation_queries)
end
end
end
describe '#retry_failed' do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment