File: map_loops_spec.rb

package info (click to toggle)
ruby-concurrent 1.1.6%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 30,284 kB
  • sloc: ruby: 30,875; java: 6,117; ansic: 288; makefile: 9; sh: 6
file content (508 lines) | stat: -rw-r--r-- 15,439 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
Thread.abort_on_exception = true

module Concurrent

  RSpec.describe 'MapTorture', stress: true, notravis: true do
    THREAD_COUNT  = 40
    KEY_COUNT     = (((2**13) - 2) * 0.75).to_i # get close to the doubling cliff
    LOW_KEY_COUNT = (((2**8 ) - 2) * 0.75).to_i # get close to the doubling cliff

    INITIAL_VALUE_CACHE_SETUP = lambda do |options, keys|
      cache         = Concurrent::Map.new
      initial_value = options[:initial_value] || 0
      keys.each { |key| cache[key] = initial_value }
      cache
    end
    ZERO_VALUE_CACHE_SETUP = lambda do |options, keys|
      INITIAL_VALUE_CACHE_SETUP.call(options.merge(:initial_value => 0), keys)
    end

    DEFAULTS = {
      key_count:    KEY_COUNT,
      thread_count: THREAD_COUNT,
      loop_count:   1,
      prelude:      '',
      cache_setup:  lambda { |options, keys| Concurrent::Map.new }
    }

    LOW_KEY_COUNT_OPTIONS    = {loop_count: 150,     key_count: LOW_KEY_COUNT}
    SINGLE_KEY_COUNT_OPTIONS = {loop_count: 100_000, key_count: 1}

    it 'concurrency' do
      code = <<-RUBY_EVAL
        cache[key]
        cache[key] = key
        cache[key]
        cache.delete(key)
      RUBY_EVAL
      do_thread_loop(:concurrency, code)
    end

    it '#put_if_absent' do
      do_thread_loop(
        :put_if_absent,
        'acc += 1 unless cache.put_if_absent(key, key)',
        key_count: 100_000
      ) do |result, cache, options, keys|
        expect_standard_accumulator_test_result(result, cache, options, keys)
      end
    end

    it '#compute_put_if_absent' do
      code = <<-RUBY_EVAL
        if key.even?
          cache.compute_if_absent(key) { acc += 1; key }
        else
          acc += 1 unless cache.put_if_absent(key, key)
        end
      RUBY_EVAL
      do_thread_loop(:compute_if_absent, code) do |result, cache, options, keys|
        expect_standard_accumulator_test_result(result, cache, options, keys)
      end
    end

    it '#compute_if_absent_and_present' do
      compute_if_absent_and_present
      compute_if_absent_and_present(LOW_KEY_COUNT_OPTIONS)
      compute_if_absent_and_present(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'add_remove_to_zero' do
      add_remove_to_zero
      add_remove_to_zero(LOW_KEY_COUNT_OPTIONS)
      add_remove_to_zero(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'add_remove_to_zero_via_merge_pair' do
      add_remove_to_zero_via_merge_pair
      add_remove_to_zero_via_merge_pair(LOW_KEY_COUNT_OPTIONS)
      add_remove_to_zero_via_merge_pair(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'add_remove' do
      add_remove
      add_remove(LOW_KEY_COUNT_OPTIONS)
      add_remove(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'add_remove_via_compute' do
      add_remove_via_compute
      add_remove_via_compute(LOW_KEY_COUNT_OPTIONS)
      add_remove_via_compute(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'add_remove_via_compute_if_absent_present' do
      add_remove_via_compute_if_absent_present
      add_remove_via_compute_if_absent_present(LOW_KEY_COUNT_OPTIONS)
      add_remove_via_compute_if_absent_present(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'add_remove_indiscriminate' do
      add_remove_indiscriminate
      add_remove_indiscriminate(LOW_KEY_COUNT_OPTIONS)
      add_remove_indiscriminate(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'count_up' do
      count_up
      count_up(LOW_KEY_COUNT_OPTIONS)
      count_up(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'count_up_via_compute' do
      count_up_via_compute
      count_up_via_compute(LOW_KEY_COUNT_OPTIONS)
      count_up_via_compute(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'count_up_via_merge_pair' do
      count_up_via_merge_pair
      count_up_via_merge_pair(LOW_KEY_COUNT_OPTIONS)
      count_up_via_merge_pair(SINGLE_KEY_COUNT_OPTIONS)
    end

    it 'count_race' do
      prelude = 'change = (rand(2) == 1) ? 1 : -1'
      code = <<-RUBY_EVAL
        v = cache[key]
        acc += change if cache.replace_pair(key, v, v + change)
      RUBY_EVAL
      do_thread_loop(
        :count_race,
        code,
        loop_count: 5,
        prelude: prelude,
        cache_setup: ZERO_VALUE_CACHE_SETUP
      ) do |result, cache, options, keys|
        result_sum = sum(result)
        expect(sum(keys.map { |key| cache[key] })).to eq result_sum
        expect(sum(cache.values)).to eq result_sum
        expect(options[:key_count]).to eq cache.size
      end
    end

    it 'get_and_set_new' do
      code = 'acc += 1 unless cache.get_and_set(key, key)'
      do_thread_loop(:get_and_set_new, code) do |result, cache, options, keys|
        expect_standard_accumulator_test_result(result, cache, options, keys)
      end
    end

    it 'get_and_set_existing' do
      code = 'acc += 1 if cache.get_and_set(key, key) == -1'
      do_thread_loop(
        :get_and_set_existing,
        code,
        cache_setup: INITIAL_VALUE_CACHE_SETUP,
        initial_value: -1
      ) do |result, cache, options, keys|
        expect_standard_accumulator_test_result(result, cache, options, keys)
      end
    end

    private

    def compute_if_absent_and_present(opts = {})
      prelude = 'on_present = rand(2) == 1'
      code = <<-RUBY_EVAL
        if on_present
          cache.compute_if_present(key) { |old_value| acc += 1; old_value + 1 }
        else
          cache.compute_if_absent(key)  { acc += 1; 1 }
        end
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code,
        {loop_count: 5, prelude: prelude}.merge(opts)
      ) do |result, cache, options, keys|
        stored_sum       = 0
        stored_key_count = 0
        keys.each do |k|
          if value = cache[k]
            stored_sum += value
            stored_key_count += 1
          end
        end
        expect(stored_sum).to eq sum(result)
        expect(stored_key_count).to eq cache.size
      end
    end

    def add_remove(opts = {})
      prelude = 'do_add = rand(2) == 1'
      code = <<-RUBY_EVAL
        if do_add
          acc += 1 unless cache.put_if_absent(key, key)
        else
          acc -= 1 if cache.delete_pair(key, key)
        end
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code,
        {loop_count: 5, prelude: prelude}.merge(opts)
      ) do |result, cache, options, keys|
        expect_all_key_mappings_exist(cache, keys, false)
        expect(cache.size).to eq sum(result)
      end
    end

    def add_remove_via_compute(opts = {})
      prelude = 'do_add = rand(2) == 1'
      code = <<-RUBY_EVAL
        cache.compute(key) do |old_value|
          if do_add
            acc += 1 unless old_value
            key
          else
            acc -= 1 if old_value
            nil
          end
        end
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code,
        {loop_count: 5, prelude: prelude}.merge(opts)
      ) do |result, cache, options, keys|
        expect_all_key_mappings_exist(cache, keys, false)
        expect(cache.size).to eq sum(result)
      end
    end

    def add_remove_via_compute_if_absent_present(opts = {})
      prelude = 'do_add = rand(2) == 1'
      code = <<-RUBY_EVAL
        if do_add
          cache.compute_if_absent(key)  { acc += 1; key }
        else
          cache.compute_if_present(key) { acc -= 1; nil }
        end
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code,
        {loop_count: 5, prelude: prelude}.merge(opts)
      ) do |result, cache, options, keys|
        expect_all_key_mappings_exist(cache, keys, false)
        expect(cache.size).to eq sum(result)
      end
    end

    def add_remove_indiscriminate(opts = {})
      prelude = 'do_add = rand(2) == 1'
      code = <<-RUBY_EVAL
        if do_add
          acc += 1 unless cache.put_if_absent(key, key)
        else
          acc -= 1 if cache.delete(key)
        end
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code,
        {loop_count: 5, prelude: prelude}.merge(opts)
      ) do |result, cache, options, keys|
        expect_all_key_mappings_exist(cache, keys, false)
        expect(cache.size).to eq sum(result)
      end
    end

    def count_up(opts = {})
      code = <<-RUBY_EVAL
        v = cache[key]
        acc += 1 if cache.replace_pair(key, v, v + 1)
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code,
        {loop_count: 5, cache_setup: ZERO_VALUE_CACHE_SETUP}.merge(opts)
      ) do |result, cache, options, keys|
        expect_count_up(result, cache, options, keys)
      end
    end

    def count_up_via_compute(opts = {})
      code = <<-RUBY_EVAL
        cache.compute(key) do |old_value|
          acc += 1
          old_value ? old_value + 1 : 1
        end
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code, {loop_count: 5}.merge(opts)
      ) do |result, cache, options, keys|
        expect_count_up(result, cache, options, keys)
        result.inject(nil) do |previous_value, next_value| # since compute guarantees atomicity all count ups should be equal
          expect(previous_value).to eq next_value if previous_value
          next_value
        end
      end
    end

    def count_up_via_merge_pair(opts = {})
      code = <<-RUBY_EVAL
        cache.merge_pair(key, 1) { |old_value| old_value + 1 }
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code,
        {loop_count: 5}.merge(opts)
      ) do |result, cache, options, keys|
        all_match      = true
        expected_value = options[:loop_count] * options[:thread_count]
        keys.each do |key|
          value = cache[key]
          if expected_value != value
            all_match = false
            break
          end
        end
        expect(all_match).to be_truthy
      end
    end

    def add_remove_to_zero(opts = {})
      code = <<-RUBY_EVAL
        acc += 1 unless cache.put_if_absent(key, key)
        acc -= 1 if cache.delete_pair(key, key)
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code,
        {loop_count: 5}.merge(opts)
      ) do |result, cache, options, keys|
        expect_all_key_mappings_exist(cache, keys, false)
        expect(cache.size).to eq sum(result)
      end
    end

    def add_remove_to_zero_via_merge_pair(opts = {})
      code = <<-RUBY_EVAL
        acc += (cache.merge_pair(key, key) {}) ? 1 : -1
      RUBY_EVAL
      do_thread_loop(
        __method__,
        code,
        {loop_count: 5}.merge(opts)
      ) do |result, cache, options, keys|
        expect_all_key_mappings_exist(cache, keys, false)
        expect(cache.size).to eq sum(result)
      end
    end

    def do_thread_loop(name, code, options = {}, &block)
      options = DEFAULTS.merge(options)
      meth    = define_loop(name, code, options[:prelude])
      keys    = to_keys_array(options[:key_count])
      run_thread_loop(meth, keys, options, &block)

      if options[:key_count] > 1
        options[:key_count] = (options[:key_count] / 40).to_i
        keys = to_hash_collision_keys_array(options[:key_count])
        run_thread_loop(
          meth,
          keys,
          options.merge(loop_count: options[:loop_count] * 5),
          &block
        )
      end
    end

    def run_thread_loop(meth, keys, options, &block)
      cache   = options[:cache_setup].call(options, keys)
      barrier = Concurrent::ThreadSafe::Test::Barrier.new(options[:thread_count])
      result = (1..options[:thread_count]).map do
        in_thread do
          setup_sync_and_start_loop(
            meth,
            cache,
            keys,
            barrier,
            options[:loop_count]
          )
        end
      end.map(&:value)
      block.call(result, cache, options, keys) if block_given?
    end

    def setup_sync_and_start_loop(meth, cache, keys, barrier, loop_count)
      my_keys = keys.shuffle
      barrier.await
      if my_keys.size == 1
        key = my_keys.first
        send("#{meth}_single_key", cache, key, loop_count)
      else
        send("#{meth}_multiple_keys", cache, my_keys, loop_count)
      end
    end

    def define_loop(name, body, prelude)
      inner_meth_name = :"_#{name}_loop_inner"
      outer_meth_name = :"_#{name}_loop_outer"
      # looping is splitted into the "loop methods" to trigger the JIT
      self.class.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
        def #{inner_meth_name}_multiple_keys(cache, keys, i, length, acc)
      #{prelude}
          target = i + length
          while i < target
            key = keys[i]
      #{body}
            i += 1
          end
          acc
        end unless method_defined?(:#{inner_meth_name}_multiple_keys)
      RUBY_EVAL

      self.class.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
        def #{inner_meth_name}_single_key(cache, key, i, length, acc)
      #{prelude}
          target = i + length
          while i < target
      #{body}
            i += 1
          end
          acc
        end unless method_defined?(:#{inner_meth_name}_single_key)
      RUBY_EVAL

      self.class.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
        def #{outer_meth_name}_multiple_keys(cache, keys, loop_count)
          total_length = keys.size
          acc = 0
          inc = 100
          loop_count.times do
            i = 0
            pre_loop_inc = total_length % inc
            acc = #{inner_meth_name}_multiple_keys(cache, keys, i, pre_loop_inc, acc)
            i += pre_loop_inc
            while i < total_length
              acc = #{inner_meth_name}_multiple_keys(cache, keys, i, inc, acc)
              i += inc
            end
          end
          acc
        end unless method_defined?(:#{outer_meth_name}_multiple_keys)
      RUBY_EVAL

      self.class.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
        def #{outer_meth_name}_single_key(cache, key, loop_count)
          acc = 0
          i   = 0
          inc = 100

          pre_loop_inc = loop_count % inc
          acc          = #{inner_meth_name}_single_key(cache, key, i, pre_loop_inc, acc)
          i += pre_loop_inc

          while i < loop_count
            acc = #{inner_meth_name}_single_key(cache, key, i, inc, acc)
            i += inc
          end
          acc
        end unless method_defined?(:#{outer_meth_name}_single_key)
      RUBY_EVAL
      outer_meth_name
    end

    def to_keys_array(key_count)
      arr = []
      key_count.times {|i| arr << i}
      arr
    end

    def to_hash_collision_keys_array(key_count)
      to_keys_array(key_count).map { |key| Concurrent::ThreadSafe::Test::HashCollisionKey(key) }
    end

    def sum(result)
      result.inject(0) { |acc, i| acc + i }
    end

    def expect_standard_accumulator_test_result(result, cache, options, keys)
      expect_all_key_mappings_exist(cache, keys)
      expect(options[:key_count]).to eq sum(result)
      expect(options[:key_count]).to eq cache.size
    end

    def expect_all_key_mappings_exist(cache, keys, all_must_exist = true)
      keys.each do |key|
        value = cache[key]
        if value || all_must_exist
          expect(key).to eq value unless key == value # don't do a bazzilion assertions unless necessary
        end
      end
    end

    def expect_count_up(result, cache, options, keys)
      keys.each do |key|
        value = cache[key]
        expect(value).to be_truthy unless value
      end
      expect(sum(cache.values)).to   eq sum(result)
      expect(options[:key_count]).to eq cache.size
    end
  end unless RUBY_ENGINE == 'rbx' || ENV['TRAVIS']
end