Skip to content

Commit 263461c

Browse files
committed
ruby: Stage initializer chunks in bounded transactions
1 parent 9d7fb11 commit 263461c

5 files changed

Lines changed: 122 additions & 55 deletions

File tree

‎ruby/lib/ci/queue/redis/worker.rb‎

Lines changed: 43 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
require 'ci/queue/static'
44
require 'concurrent/set'
5+
require 'securerandom'
56

67
module CI
78
module Queue
@@ -442,12 +443,22 @@ def initialize_queue
442443

443444
executables = reorder_tests(index.values, random: @random)
444445
chunks, individual_tests = executables.partition { |e| e.is_a?(CI::Queue::TestChunk) }
445-
push(chunks.map(&:id) + individual_tests.map(&:id), chunks: chunks)
446+
# An initializer may outlive its setup marker. Give its chunks unique
447+
# IDs so staging metadata cannot overwrite another initializer's data.
448+
initialization_id = SecureRandom.hex(8)
449+
chunks = chunks.map do |chunk|
450+
CI::Queue::TestChunk.new(
451+
"#{chunk.id}:#{initialization_id}", chunk.suite_name,
452+
chunk.test_ids, chunk.estimated_duration, test_count: chunk.test_count
453+
)
454+
end
455+
store_chunk_metadata(chunks)
456+
push(chunks.map(&:id) + individual_tests.map(&:id))
446457
end
447458

448459
# The setup marker can expire under a slow master, so only the first
449460
# master to finish publishes.
450-
def push(tests, chunks: [])
461+
def push(tests)
451462
@total = tests.size
452463
return unless @master
453464

@@ -457,7 +468,6 @@ def push(tests, chunks: [])
457468
nil
458469
else
459470
redis.multi do |transaction|
460-
store_chunk_metadata(transaction, chunks)
461471
transaction.lpush(key('queue'), tests) unless tests.empty?
462472
transaction.set(key('total'), @total)
463473
transaction.set(key('master-status'), 'ready')
@@ -510,32 +520,37 @@ def register_worker_presence
510520
raise if master?
511521
end
512522

513-
def store_chunk_metadata(transaction, chunks)
514-
return if chunks.empty?
515-
516-
chunks.each do |chunk|
517-
# Store chunk metadata with TTL
518-
transaction.set(
519-
key('chunk', chunk.id),
520-
chunk.to_json
521-
)
522-
transaction.expire(key('chunk', chunk.id), config.redis_ttl)
523-
524-
# Track all chunks for cleanup
525-
transaction.sadd(key('chunks'), chunk.id)
526-
527-
# Store dynamic timeout for this chunk
528-
# Timeout = estimated_duration (in ms) converted to seconds + buffer
529-
# estimated_duration is in milliseconds, convert to seconds and add 10% buffer
530-
buffer_percent = 10
531-
estimated_duration_seconds = chunk.estimated_duration / 1000.0
532-
chunk_timeout = (estimated_duration_seconds * (1 + buffer_percent / 100.0)).round(2)
533-
# Format to string to avoid floating point precision issues in Redis
534-
# Use %g to remove trailing zeros
535-
transaction.hset(key('test-group-timeout'), chunk.id, format('%g', chunk_timeout))
523+
def store_chunk_metadata(chunks)
524+
# Four commands per chunk, plus two expiry commands: at most 22.
525+
batch_size = 5
526+
527+
chunks.each_slice(batch_size) do |chunk_batch|
528+
redis.multi do |transaction|
529+
chunk_batch.each do |chunk|
530+
# Store chunk metadata with TTL
531+
transaction.set(
532+
key('chunk', chunk.id),
533+
chunk.to_json
534+
)
535+
transaction.expire(key('chunk', chunk.id), config.redis_ttl)
536+
537+
# Track all chunks for cleanup
538+
transaction.sadd(key('chunks'), chunk.id)
539+
540+
# Store dynamic timeout for this chunk
541+
# Timeout = estimated_duration (in ms) converted to seconds + buffer
542+
# estimated_duration is in milliseconds, convert to seconds and add 10% buffer
543+
buffer_percent = 10
544+
estimated_duration_seconds = chunk.estimated_duration / 1000.0
545+
chunk_timeout = (estimated_duration_seconds * (1 + buffer_percent / 100.0)).round(2)
546+
# Format to string to avoid floating point precision issues in Redis
547+
# Use %g to remove trailing zeros
548+
transaction.hset(key('test-group-timeout'), chunk.id, format('%g', chunk_timeout))
549+
end
550+
transaction.expire(key('chunks'), config.redis_ttl)
551+
transaction.expire(key('test-group-timeout'), config.redis_ttl)
552+
end
536553
end
537-
transaction.expire(key('chunks'), config.redis_ttl)
538-
transaction.expire(key('test-group-timeout'), config.redis_ttl)
539554
end
540555

541556
def chunk_id?(id)

‎ruby/test/ci/queue/redis/dynamic_timeout_test.rb‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def test_chunk_timeout_stored_in_redis_hash
3838

3939
# Verify timeout was stored in test-group-timeout hash
4040
# Timeout should be: estimated_duration (5000ms = 5s) * 1.1 buffer = 5.5s
41-
chunk_timeout = @redis.hget('build:42:test-group-timeout', 'TestA:chunk_0')
41+
chunk_timeout = @redis.hget('build:42:test-group-timeout', stored_chunk_id('TestA:chunk_0'))
4242
refute_nil chunk_timeout
4343
assert_equal '5.5', chunk_timeout
4444
end
@@ -54,7 +54,7 @@ def test_chunk_timeout_scales_with_test_count
5454
worker.populate(small_tests)
5555
end
5656

57-
small_timeout = @redis.hget('build:42:test-group-timeout', 'SmallSuite:chunk_0')
57+
small_timeout = @redis.hget('build:42:test-group-timeout', stored_chunk_id('SmallSuite:chunk_0'))
5858
assert_equal '1.1', small_timeout # 1000ms = 1s * 1.1 buffer = 1.1s
5959

6060
@redis.flushdb
@@ -69,7 +69,7 @@ def test_chunk_timeout_scales_with_test_count
6969
worker.populate(large_tests)
7070
end
7171

72-
large_timeout = @redis.hget('build:42:test-group-timeout', 'LargeSuite:chunk_0')
72+
large_timeout = @redis.hget('build:42:test-group-timeout', stored_chunk_id('LargeSuite:chunk_0'))
7373
assert_equal '5.5', large_timeout # 5000ms = 5s * 1.1 buffer = 5.5s
7474
end
7575

@@ -92,9 +92,9 @@ def test_multiple_chunks_stored_with_different_timeouts
9292
end
9393

9494
# Verify each chunk has correct timeout
95-
assert_equal '2.2', @redis.hget('build:42:test-group-timeout', 'TestA:chunk_0') # 2000ms = 2s * 1.1 buffer = 2.2s
96-
assert_equal '3.3', @redis.hget('build:42:test-group-timeout', 'TestB:chunk_0') # 3000ms = 3s * 1.1 buffer = 3.3s
97-
assert_equal '1.1', @redis.hget('build:42:test-group-timeout', 'TestC:chunk_0') # 1000ms = 1s * 1.1 buffer = 1.1s
95+
assert_equal '2.2', @redis.hget('build:42:test-group-timeout', stored_chunk_id('TestA:chunk_0')) # 2000ms = 2s * 1.1 buffer = 2.2s
96+
assert_equal '3.3', @redis.hget('build:42:test-group-timeout', stored_chunk_id('TestB:chunk_0')) # 3000ms = 3s * 1.1 buffer = 3.3s
97+
assert_equal '1.1', @redis.hget('build:42:test-group-timeout', stored_chunk_id('TestC:chunk_0')) # 1000ms = 1s * 1.1 buffer = 1.1s
9898
end
9999

100100
def test_timeout_hash_has_ttl
@@ -145,8 +145,8 @@ def test_mixed_chunks_and_tests_only_chunks_have_timeouts
145145
end
146146

147147
# Chunks should have timeouts
148-
assert_equal '2.2', @redis.hget('build:42:test-group-timeout', 'TestA:chunk_0') # 2000ms = 2s * 1.1 buffer = 2.2s
149-
assert_equal '3.3', @redis.hget('build:42:test-group-timeout', 'TestC:chunk_0') # 3000ms = 3s * 1.1 buffer = 3.3s
148+
assert_equal '2.2', @redis.hget('build:42:test-group-timeout', stored_chunk_id('TestA:chunk_0')) # 2000ms = 2s * 1.1 buffer = 2.2s
149+
assert_equal '3.3', @redis.hget('build:42:test-group-timeout', stored_chunk_id('TestC:chunk_0')) # 3000ms = 3s * 1.1 buffer = 3.3s
150150

151151
# Individual test should not
152152
assert_nil @redis.hget('build:42:test-group-timeout', 'TestB#test_1')
@@ -235,7 +235,7 @@ def test_chunk_not_marked_lost_before_dynamic_timeout
235235

236236
# Reserve the chunk with worker1
237237
reserved_id = worker1.send(:try_to_reserve_test)
238-
assert_equal 'TestSuite:chunk_0', reserved_id
238+
assert_match /\ATestSuite:chunk_0:[0-9a-f]{16}\z/, reserved_id
239239

240240
# Wait 1 second (less than 2.5s timeout)
241241
sleep 1
@@ -296,14 +296,18 @@ def test_batching_with_many_chunks
296296

297297
# Verify all chunks have timeouts stored despite batching
298298
chunks.each do |chunk|
299-
timeout = @redis.hget('build:42:test-group-timeout', chunk.id)
299+
timeout = @redis.hget('build:42:test-group-timeout', stored_chunk_id(chunk.id))
300300
refute_nil timeout, "Chunk #{chunk.id} should have timeout stored"
301301
assert_equal '1.1', timeout # 1000ms = 1s * 1.1 buffer = 1.1s
302302
end
303303
end
304304

305305
private
306306

307+
def stored_chunk_id(original_id)
308+
@redis.smembers('build:42:chunks').find { |id| id.start_with?("#{original_id}:") }
309+
end
310+
307311
def create_mock_tests(test_ids)
308312
test_ids.map { |id| MockTest.new(id) }
309313
end

‎ruby/test/ci/queue/redis/worker_chunk_test.rb‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def test_populate_stores_chunk_metadata_in_redis
3636
end
3737

3838
# Verify chunk metadata was stored
39-
chunk_data = @redis.get('build:42:chunk:TestA:chunk_0')
39+
chunk_data = @redis.get("build:42:chunk:#{stored_chunk_id('TestA:chunk_0')}")
4040
refute_nil chunk_data
4141

4242
parsed = JSON.parse(chunk_data)
@@ -100,10 +100,10 @@ def test_resolve_chunk
100100
end
101101

102102
# Manually store and resolve chunk
103-
resolved = @worker.send(:resolve_chunk, 'TestA:chunk_0')
103+
resolved = @worker.send(:resolve_chunk, stored_chunk_id('TestA:chunk_0'))
104104

105105
assert_instance_of CI::Queue::Redis::Worker::ResolvedChunk, resolved
106-
assert_equal 'TestA:chunk_0', resolved.id
106+
assert_match /\ATestA:chunk_0(?::[0-9a-f]{16})?\z/, resolved.id
107107
assert_equal 'TestA', resolved.suite_name
108108
assert_equal 3, resolved.tests.size
109109
assert_equal test_ids, resolved.tests.map(&:id)
@@ -120,10 +120,10 @@ def test_resolve_chunk_with_subset_of_tests
120120
@worker.populate(tests)
121121
end
122122

123-
resolved = @worker.send(:resolve_chunk, 'TestA:chunk_0')
123+
resolved = @worker.send(:resolve_chunk, stored_chunk_id('TestA:chunk_0'))
124124

125125
assert_instance_of CI::Queue::Redis::Worker::ResolvedChunk, resolved
126-
assert_equal 'TestA:chunk_0', resolved.id
126+
assert_match /\ATestA:chunk_0(?::[0-9a-f]{16})?\z/, resolved.id
127127
assert_equal 2, resolved.tests.size
128128
assert_equal ['TestA#test_1', 'TestA#test_3'], resolved.tests.map(&:id)
129129
end
@@ -140,7 +140,7 @@ def test_resolved_chunk_interface
140140

141141
resolved = CI::Queue::Redis::Worker::ResolvedChunk.new(chunk, tests)
142142

143-
assert_equal 'TestA:chunk_0', resolved.id
143+
assert_match /\ATestA:chunk_0(?::[0-9a-f]{16})?\z/, resolved.id
144144
assert_equal 'TestA', resolved.suite_name
145145
assert_equal 2, resolved.size
146146
assert resolved.chunk?
@@ -195,7 +195,7 @@ def test_populate_with_mixed_chunks_and_tests
195195

196196
# Check that both chunk and individual test IDs are in queue
197197
queue_items = @redis.lrange('build:42:queue', 0, -1)
198-
assert_includes queue_items, 'TestA:chunk_0'
198+
assert_includes queue_items, stored_chunk_id('TestA:chunk_0')
199199
assert_includes queue_items, 'TestB#test_1'
200200
end
201201

@@ -210,12 +210,12 @@ def test_chunk_metadata_has_ttl
210210
@worker.populate(tests)
211211
end
212212

213-
ttl = @redis.ttl('build:42:chunk:TestA:chunk_0')
213+
ttl = @redis.ttl("build:42:chunk:#{stored_chunk_id('TestA:chunk_0')}")
214214
assert ttl > 0, 'Chunk metadata should have TTL set'
215215
end
216216

217217
def test_populate_with_many_chunks_uses_batching
218-
# Create 20 test chunks to verify batching works (batch size is 7)
218+
# Create 20 test chunks to verify batching works (batch size is 5)
219219
tests = (1..20).map { |i| MockTest.new("TestSuite#{i}#test_1") }
220220
chunks = (1..20).map do |i|
221221
test_ids = ["TestSuite#{i}#test_1"]
@@ -228,7 +228,7 @@ def test_populate_with_many_chunks_uses_batching
228228

229229
# Verify all chunks were stored despite batching
230230
chunks.each do |chunk|
231-
chunk_data = @redis.get("build:42:chunk:#{chunk.id}")
231+
chunk_data = @redis.get("build:42:chunk:#{stored_chunk_id(chunk.id)}")
232232
refute_nil chunk_data, "Chunk #{chunk.id} should be stored"
233233

234234
parsed = JSON.parse(chunk_data)
@@ -239,7 +239,7 @@ def test_populate_with_many_chunks_uses_batching
239239
# Verify all chunk IDs are in the chunks set
240240
stored_chunks = @redis.smembers('build:42:chunks')
241241
chunks.each do |chunk|
242-
assert_includes stored_chunks, chunk.id
242+
assert_includes stored_chunks, stored_chunk_id(chunk.id)
243243
end
244244
end
245245

@@ -257,7 +257,7 @@ def test_worker_history_retry_expands_chunks_and_deduplicates_tests
257257
end
258258

259259
history_key = 'build:42:worker:1:queue'
260-
[chunk.id, tests.last.id, chunk.id, tests[1].id].each do |id|
260+
[stored_chunk_id(chunk.id), tests.last.id, stored_chunk_id(chunk.id), tests[1].id].each do |id|
261261
@redis.lpush(history_key, id)
262262
end
263263

@@ -304,6 +304,10 @@ def test_worker_history_retry_rejects_invalid_chunk_metadata
304304

305305
private
306306

307+
def stored_chunk_id(original_id)
308+
@redis.smembers('build:42:chunks').find { |id| id.start_with?("#{original_id}:") }
309+
end
310+
307311
def create_mock_tests(test_ids)
308312
test_ids.map { |id| MockTest.new(id) }
309313
end

‎ruby/test/ci/queue/redis_initialization_test.rb‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,11 +71,13 @@ def test_late_initializer_cannot_overwrite_chunk_metadata
7171
replacement = worker(1, strategy: :suite_bin_packing)
7272
redis = @redis
7373
status_key = key('master-status')
74-
chunk_key = key('chunk:ATest:chunk_0')
74+
chunk_key = nil
7575
published_metadata = nil
7676
initializer.define_singleton_method(:reorder_tests) do |input, **|
7777
redis.del(status_key)
7878
replacement.populate(input)
79+
chunk_id = redis.lrange(key('queue'), 0, -1).find { |id| id.start_with?('ATest:chunk_0:') }
80+
chunk_key = key("chunk:#{chunk_id}")
7981
published_metadata = redis.get(chunk_key)
8082
[CI::Queue::TestChunk.new('ATest:chunk_0', 'ATest', [input.first.id], 9999)]
8183
end
@@ -114,6 +116,48 @@ def test_waiting_worker_does_not_take_over_a_live_setup
114116
thread&.join
115117
end
116118

119+
def test_chunk_initialization_keeps_transactions_bounded
120+
initializer = worker(0, strategy: :suite_bin_packing)
121+
client = initializer.send(:redis)
122+
original_multi = client.method(:multi)
123+
transaction_sizes = []
124+
client.define_singleton_method(:multi) do |*args, &block|
125+
original_multi.call(*args) do |transaction|
126+
count = 0
127+
proxy = Object.new
128+
%i[set expire sadd hset lpush llen zcard].each do |command|
129+
proxy.define_singleton_method(command) do |*command_args|
130+
count += 1
131+
transaction.public_send(command, *command_args)
132+
end
133+
end
134+
result = block.call(proxy)
135+
raise ArgumentError, 'Maximum cardinality of 25 exceeded' if count > 25
136+
137+
transaction_sizes << count
138+
result
139+
end
140+
end
141+
input = 20.times.map { |i| SharedTestCases::TestCase.new("Suite#{i}#test") }
142+
143+
initializer.populate(input)
144+
assert_equal input.sort, poll(initializer).flat_map(&:tests).sort
145+
assert_equal [22, 22, 22, 22, 6], transaction_sizes.take(5)
146+
end
147+
148+
def test_recovery_after_partial_chunk_staging
149+
initializer = worker(0, strategy: :suite_bin_packing)
150+
initializer.define_singleton_method(:store_chunk_metadata) do |chunks|
151+
super(chunks.first(1))
152+
raise 'staging failed'
153+
end
154+
assert_raises(RuntimeError) { initializer.populate(tests) }
155+
156+
replacement = worker(0, strategy: :suite_bin_packing).populate(tests)
157+
assert_equal tests.sort, poll(replacement).flat_map(&:tests).sort
158+
assert_predicate replacement, :master?
159+
end
160+
117161
private
118162

119163
def exit_during_setup(worker_id:)

‎ruby/test/ci/queue/redis_test.rb‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,7 @@ def test_suite_bin_packing_uses_moving_average_for_duration
491491
assert_equal 1, chunks.size
492492
chunk = chunks.first
493493
assert chunk.chunk?, 'Expected a chunk'
494-
assert_equal 'TestSuite:chunk_0', chunk.id
494+
assert_match /\ATestSuite:chunk_0:[0-9a-f]{16}\z/, chunk.id
495495
assert_equal 8000.0, chunk.estimated_duration
496496
end
497497

@@ -635,11 +635,11 @@ def test_moving_average_ordering_by_duration
635635

636636
# Should be ordered by duration descending: SlowTest, MediumTest, FastTest
637637
assert_equal 3, chunks.size
638-
assert_equal 'SlowTest:chunk_0', chunks[0].id
638+
assert_match /\ASlowTest:chunk_0:[0-9a-f]{16}\z/, chunks[0].id
639639
assert_equal 10_000.0, chunks[0].estimated_duration
640-
assert_equal 'MediumTest:chunk_0', chunks[1].id
640+
assert_match /\AMediumTest:chunk_0:[0-9a-f]{16}\z/, chunks[1].id
641641
assert_equal 5000.0, chunks[1].estimated_duration
642-
assert_equal 'FastTest:chunk_0', chunks[2].id
642+
assert_match /\AFastTest:chunk_0:[0-9a-f]{16}\z/, chunks[2].id
643643
assert_equal 1000.0, chunks[2].estimated_duration
644644
end
645645

0 commit comments

Comments
 (0)