Skip to content

Commit 953f969

Browse files
authored
fix: make buildpack position updates concurrency-safe (#5497)
1 parent 7f5afb0 commit 953f969

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎app/actions/buildpack_update.rb‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ def update(buildpack, message)
1313
Buildpack.db.transaction do
1414
Locking[name: 'buildpacks'].lock!
1515

16+
# The buildpack was loaded before this lock, so its in-memory position may be stale.
17+
# Re-read under the lock so move_to's shift range is correct; removing this reintroduces
18+
# duplicate/missing positions.
19+
buildpack.refresh
1620
MetadataUpdate.update(buildpack, message)
1721

1822
buildpack.move_to(message.position) if message.requested?(:position)

‎spec/unit/actions/buildpack_update_spec.rb‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,26 @@ module VCAP::CloudController
3939

4040
expect(buildpack1.reload.position).to eq(1)
4141
end
42+
43+
context 'when the in-memory position is stale because of a concurrent reorder' do
44+
let!(:buildpack4) { create(:buildpack, position: 4) }
45+
46+
it 'recomputes the shift from the committed state and keeps positions contiguous' do
47+
# buildpack2 was loaded (position 2) before the lock. Simulate a concurrent request
48+
# that reorders the list in the meantime: buildpack2 drifts from 2 -> 3 in the DB,
49+
# but the in-memory object still thinks it is at 2.
50+
buildpack4.move_to(1)
51+
expect(buildpack2.position).to eq(2) # stale in-memory value
52+
expect(Buildpack.first(guid: buildpack2.guid).position).to eq(3) # committed DB truth
53+
54+
message = BuildpackUpdateMessage.new(position: 1)
55+
BuildpackUpdate.new(user_audit_info).update(buildpack2, message)
56+
57+
positions = Buildpack.order(:position).all.map(&:position)
58+
expect(positions).to eq([1, 2, 3, 4]), "expected contiguous positions, got #{positions.inspect}"
59+
expect(buildpack2.reload.position).to eq(1)
60+
end
61+
end
4262
end
4363

4464
context 'when enabled is changed' do

0 commit comments

Comments
 (0)