From 3494cdfecb7748cca558e46c805b636b3383c299 Mon Sep 17 00:00:00 2001 From: Shinya Maeda Date: Tue, 12 Dec 2017 16:17:45 +0900 Subject: [PATCH] ActiveRecord::StaleObjectError: Attempted to update a stale object: Ci::Build --- app/services/ci/register_job_service.rb | 15 ++++++++------- spec/services/ci/register_job_service_spec.rb | 13 +++++++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/app/services/ci/register_job_service.rb b/app/services/ci/register_job_service.rb index c8b6450c9b5..f832b79ef21 100644 --- a/app/services/ci/register_job_service.rb +++ b/app/services/ci/register_job_service.rb @@ -38,11 +38,15 @@ module Ci begin # In case when 2 runners try to assign the same build, second runner will be declined # with StateMachines::InvalidTransition or StaleObjectError when doing run! or save method. - build.runner_id = runner.id - build.run! - register_success(build) + begin + build.runner_id = runner.id + build.run! + register_success(build) - return Result.new(build, true) + return Result.new(build, true) + rescue Ci::Build::MissingDependenciesError + build.drop!(:missing_dependency_failure) + end rescue StateMachines::InvalidTransition, ActiveRecord::StaleObjectError # We are looping to find another build that is not conflicting # It also indicates that this build can be picked and passed to runner. @@ -54,9 +58,6 @@ module Ci # we still have to return 409 in the end, # to make sure that this is properly handled by runner. valid = false - rescue Ci::Build::MissingDependenciesError - build.drop!(:missing_dependency_failure) - valid = false end end diff --git a/spec/services/ci/register_job_service_spec.rb b/spec/services/ci/register_job_service_spec.rb index 3ee59014b5b..22fb7ed7215 100644 --- a/spec/services/ci/register_job_service_spec.rb +++ b/spec/services/ci/register_job_service_spec.rb @@ -307,6 +307,19 @@ module Ci it_behaves_like 'not pick' end + + context 'when job object is staled' do + let!(:pre_stage_job) { create(:ci_build, :running, pipeline: pipeline, name: 'test', stage_idx: 0) } + + before do + allow_any_instance_of(Ci::Build).to receive(:drop!) + .and_raise(ActiveRecord::StaleObjectError.new(pending_job, :drop!)) + end + + it 'does not drop nor pick' do + expect(subject).to be_nil + end + end end shared_examples 'validation is not active' do