summaryrefslogtreecommitdiffhomepage
path: root/pkg/sync/atomicptrmap/atomicptrmap_test.go
blob: 75a9997efa40705fbb386ec1f9d0fe4d5f8bfec3 (plain)
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// Copyright 2020 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package atomicptrmap

import (
	"context"
	"fmt"
	"math/rand"
	"reflect"
	"runtime"
	"testing"
	"time"

	"gvisor.dev/gvisor/pkg/sync"
)

func TestConsistencyWithGoMap(t *testing.T) {
	const maxKey = 16
	var vals [4]*testValue
	for i := 1; /* leave vals[0] nil */ i < len(vals); i++ {
		vals[i] = new(testValue)
	}
	var (
		m   = make(map[int64]*testValue)
		apm testAtomicPtrMap
	)
	for i := 0; i < 100000; i++ {
		// Apply a random operation to both m and apm and expect them to have
		// the same result. Bias toward CompareAndSwap, which has the most
		// cases; bias away from Range and RangeRepeatable, which are
		// relatively expensive.
		switch rand.Intn(10) {
		case 0, 1: // Load
			key := rand.Int63n(maxKey)
			want := m[key]
			got := apm.Load(key)
			t.Logf("Load(%d) = %p", key, got)
			if got != want {
				t.Fatalf("got %p, wanted %p", got, want)
			}
		case 2, 3: // Swap
			key := rand.Int63n(maxKey)
			val := vals[rand.Intn(len(vals))]
			want := m[key]
			if val != nil {
				m[key] = val
			} else {
				delete(m, key)
			}
			got := apm.Swap(key, val)
			t.Logf("Swap(%d, %p) = %p", key, val, got)
			if got != want {
				t.Fatalf("got %p, wanted %p", got, want)
			}
		case 4, 5, 6, 7: // CompareAndSwap
			key := rand.Int63n(maxKey)
			oldVal := vals[rand.Intn(len(vals))]
			newVal := vals[rand.Intn(len(vals))]
			want := m[key]
			if want == oldVal {
				if newVal != nil {
					m[key] = newVal
				} else {
					delete(m, key)
				}
			}
			got := apm.CompareAndSwap(key, oldVal, newVal)
			t.Logf("CompareAndSwap(%d, %p, %p) = %p", key, oldVal, newVal, got)
			if got != want {
				t.Fatalf("got %p, wanted %p", got, want)
			}
		case 8: // Range
			got := make(map[int64]*testValue)
			var (
				haveDup = false
				dup     int64
			)
			apm.Range(func(key int64, val *testValue) bool {
				if _, ok := got[key]; ok && !haveDup {
					haveDup = true
					dup = key
				}
				got[key] = val
				return true
			})
			t.Logf("Range() = %v", got)
			if !reflect.DeepEqual(got, m) {
				t.Fatalf("got %v, wanted %v", got, m)
			}
			if haveDup {
				t.Fatalf("got duplicate key %d", dup)
			}
		case 9: // RangeRepeatable
			got := make(map[int64]*testValue)
			apm.RangeRepeatable(func(key int64, val *testValue) bool {
				got[key] = val
				return true
			})
			t.Logf("RangeRepeatable() = %v", got)
			if !reflect.DeepEqual(got, m) {
				t.Fatalf("got %v, wanted %v", got, m)
			}
		}
	}
}

func TestConcurrentHeterogeneous(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	var (
		apm testAtomicPtrMap
		wg  sync.WaitGroup
	)
	defer func() {
		cancel()
		wg.Wait()
	}()

	possibleKeyValuePairs := make(map[int64]map[*testValue]struct{})
	addKeyValuePair := func(key int64, val *testValue) {
		values := possibleKeyValuePairs[key]
		if values == nil {
			values = make(map[*testValue]struct{})
			possibleKeyValuePairs[key] = values
		}
		values[val] = struct{}{}
	}

	const numValuesPerKey = 4

	// These goroutines use keys not used by any other goroutine.
	const numPrivateKeys = 3
	for i := 0; i < numPrivateKeys; i++ {
		key := int64(i)
		var vals [numValuesPerKey]*testValue
		for i := 1; /* leave vals[0] nil */ i < len(vals); i++ {
			val := new(testValue)
			vals[i] = val
			addKeyValuePair(key, val)
		}
		wg.Add(1)
		go func() {
			defer wg.Done()
			r := rand.New(rand.NewSource(rand.Int63()))
			var stored *testValue
			for ctx.Err() == nil {
				switch r.Intn(4) {
				case 0:
					got := apm.Load(key)
					if got != stored {
						t.Errorf("Load(%d): got %p, wanted %p", key, got, stored)
						return
					}
				case 1:
					val := vals[r.Intn(len(vals))]
					want := stored
					stored = val
					got := apm.Swap(key, val)
					if got != want {
						t.Errorf("Swap(%d, %p): got %p, wanted %p", key, val, got, want)
						return
					}
				case 2, 3:
					oldVal := vals[r.Intn(len(vals))]
					newVal := vals[r.Intn(len(vals))]
					want := stored
					if stored == oldVal {
						stored = newVal
					}
					got := apm.CompareAndSwap(key, oldVal, newVal)
					if got != want {
						t.Errorf("CompareAndSwap(%d, %p, %p): got %p, wanted %p", key, oldVal, newVal, got, want)
						return
					}
				}
			}
		}()
	}

	// These goroutines share a small set of keys.
	const numSharedKeys = 2
	var (
		sharedKeys      [numSharedKeys]int64
		sharedValues    = make(map[int64][]*testValue)
		sharedValuesSet = make(map[int64]map[*testValue]struct{})
	)
	for i := range sharedKeys {
		key := int64(numPrivateKeys + i)
		sharedKeys[i] = key
		vals := make([]*testValue, numValuesPerKey)
		valsSet := make(map[*testValue]struct{})
		for j := range vals {
			val := new(testValue)
			vals[j] = val
			valsSet[val] = struct{}{}
			addKeyValuePair(key, val)
		}
		sharedValues[key] = vals
		sharedValuesSet[key] = valsSet
	}
	randSharedValue := func(r *rand.Rand, key int64) *testValue {
		vals := sharedValues[key]
		return vals[r.Intn(len(vals))]
	}
	for i := 0; i < 3; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			r := rand.New(rand.NewSource(rand.Int63()))
			for ctx.Err() == nil {
				keyIndex := r.Intn(len(sharedKeys))
				key := sharedKeys[keyIndex]
				var (
					op  string
					got *testValue
				)
				switch r.Intn(4) {
				case 0:
					op = "Load"
					got = apm.Load(key)
				case 1:
					op = "Swap"
					got = apm.Swap(key, randSharedValue(r, key))
				case 2, 3:
					op = "CompareAndSwap"
					got = apm.CompareAndSwap(key, randSharedValue(r, key), randSharedValue(r, key))
				}
				if got != nil {
					valsSet := sharedValuesSet[key]
					if _, ok := valsSet[got]; !ok {
						t.Errorf("%s: got key %d, value %p; expected value in %v", op, key, got, valsSet)
						return
					}
				}
			}
		}()
	}

	// This goroutine repeatedly searches for unused keys.
	wg.Add(1)
	go func() {
		defer wg.Done()
		r := rand.New(rand.NewSource(rand.Int63()))
		for ctx.Err() == nil {
			key := -1 - r.Int63()
			if got := apm.Load(key); got != nil {
				t.Errorf("Load(%d): got %p, wanted nil", key, got)
			}
		}
	}()

	// This goroutine repeatedly calls RangeRepeatable() and checks that each
	// key corresponds to an expected value.
	wg.Add(1)
	go func() {
		defer wg.Done()
		abort := false
		for !abort && ctx.Err() == nil {
			apm.RangeRepeatable(func(key int64, val *testValue) bool {
				values, ok := possibleKeyValuePairs[key]
				if !ok {
					t.Errorf("RangeRepeatable: got invalid key %d", key)
					abort = true
					return false
				}
				if _, ok := values[val]; !ok {
					t.Errorf("RangeRepeatable: got key %d, value %p; expected one of %v", key, val, values)
					abort = true
					return false
				}
				return true
			})
		}
	}()

	// Finally, the main goroutine spins for the length of the test calling
	// Range() and checking that each key that it observes is unique and
	// corresponds to an expected value.
	seenKeys := make(map[int64]struct{})
	const testDuration = 5 * time.Second
	end := time.Now().Add(testDuration)
	abort := false
	for time.Now().Before(end) {
		apm.Range(func(key int64, val *testValue) bool {
			values, ok := possibleKeyValuePairs[key]
			if !ok {
				t.Errorf("Range: got invalid key %d", key)
				abort = true
				return false
			}
			if _, ok := values[val]; !ok {
				t.Errorf("Range: got key %d, value %p; expected one of %v", key, val, values)
				abort = true
				return false
			}
			if _, ok := seenKeys[key]; ok {
				t.Errorf("Range: got duplicate key %d", key)
				abort = true
				return false
			}
			seenKeys[key] = struct{}{}
			return true
		})
		if abort {
			break
		}
		for k := range seenKeys {
			delete(seenKeys, k)
		}
	}
}

type benchmarkableMap interface {
	Load(key int64) *testValue
	Store(key int64, val *testValue)
	LoadOrStore(key int64, val *testValue) (*testValue, bool)
	Delete(key int64)
}

// rwMutexMap implements benchmarkableMap for a RWMutex-protected Go map.
type rwMutexMap struct {
	mu sync.RWMutex
	m  map[int64]*testValue
}

func (m *rwMutexMap) Load(key int64) *testValue {
	m.mu.RLock()
	defer m.mu.RUnlock()
	return m.m[key]
}

func (m *rwMutexMap) Store(key int64, val *testValue) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.m == nil {
		m.m = make(map[int64]*testValue)
	}
	m.m[key] = val
}

func (m *rwMutexMap) LoadOrStore(key int64, val *testValue) (*testValue, bool) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.m == nil {
		m.m = make(map[int64]*testValue)
	}
	if oldVal, ok := m.m[key]; ok {
		return oldVal, true
	}
	m.m[key] = val
	return val, false
}

func (m *rwMutexMap) Delete(key int64) {
	m.mu.Lock()
	defer m.mu.Unlock()
	delete(m.m, key)
}

// syncMap implements benchmarkableMap for a sync.Map.
type syncMap struct {
	m sync.Map
}

func (m *syncMap) Load(key int64) *testValue {
	val, ok := m.m.Load(key)
	if !ok {
		return nil
	}
	return val.(*testValue)
}

func (m *syncMap) Store(key int64, val *testValue) {
	m.m.Store(key, val)
}

func (m *syncMap) LoadOrStore(key int64, val *testValue) (*testValue, bool) {
	actual, loaded := m.m.LoadOrStore(key, val)
	return actual.(*testValue), loaded
}

func (m *syncMap) Delete(key int64) {
	m.m.Delete(key)
}

// benchmarkableAtomicPtrMap implements benchmarkableMap for testAtomicPtrMap.
type benchmarkableAtomicPtrMap struct {
	m testAtomicPtrMap
}

func (m *benchmarkableAtomicPtrMap) Load(key int64) *testValue {
	return m.m.Load(key)
}

func (m *benchmarkableAtomicPtrMap) Store(key int64, val *testValue) {
	m.m.Store(key, val)
}

func (m *benchmarkableAtomicPtrMap) LoadOrStore(key int64, val *testValue) (*testValue, bool) {
	if prev := m.m.CompareAndSwap(key, nil, val); prev != nil {
		return prev, true
	}
	return val, false
}

func (m *benchmarkableAtomicPtrMap) Delete(key int64) {
	m.m.Store(key, nil)
}

// benchmarkableAtomicPtrMapSharded implements benchmarkableMap for testAtomicPtrMapSharded.
type benchmarkableAtomicPtrMapSharded struct {
	m testAtomicPtrMapSharded
}

func (m *benchmarkableAtomicPtrMapSharded) Load(key int64) *testValue {
	return m.m.Load(key)
}

func (m *benchmarkableAtomicPtrMapSharded) Store(key int64, val *testValue) {
	m.m.Store(key, val)
}

func (m *benchmarkableAtomicPtrMapSharded) LoadOrStore(key int64, val *testValue) (*testValue, bool) {
	if prev := m.m.CompareAndSwap(key, nil, val); prev != nil {
		return prev, true
	}
	return val, false
}

func (m *benchmarkableAtomicPtrMapSharded) Delete(key int64) {
	m.m.Store(key, nil)
}

var mapImpls = [...]struct {
	name string
	ctor func() benchmarkableMap
}{
	{
		name: "RWMutexMap",
		ctor: func() benchmarkableMap {
			return new(rwMutexMap)
		},
	},
	{
		name: "SyncMap",
		ctor: func() benchmarkableMap {
			return new(syncMap)
		},
	},
	{
		name: "AtomicPtrMap",
		ctor: func() benchmarkableMap {
			return new(benchmarkableAtomicPtrMap)
		},
	},
	{
		name: "AtomicPtrMapSharded",
		ctor: func() benchmarkableMap {
			return new(benchmarkableAtomicPtrMapSharded)
		},
	},
}

func benchmarkStoreDelete(b *testing.B, mapCtor func() benchmarkableMap) {
	m := mapCtor()
	val := &testValue{}
	for i := 0; i < b.N; i++ {
		m.Store(int64(i), val)
	}
	for i := 0; i < b.N; i++ {
		m.Delete(int64(i))
	}
}

func BenchmarkStoreDelete(b *testing.B) {
	for _, mapImpl := range mapImpls {
		b.Run(mapImpl.name, func(b *testing.B) {
			benchmarkStoreDelete(b, mapImpl.ctor)
		})
	}
}

func benchmarkLoadOrStoreDelete(b *testing.B, mapCtor func() benchmarkableMap) {
	m := mapCtor()
	val := &testValue{}
	for i := 0; i < b.N; i++ {
		m.LoadOrStore(int64(i), val)
	}
	for i := 0; i < b.N; i++ {
		m.Delete(int64(i))
	}
}

func BenchmarkLoadOrStoreDelete(b *testing.B) {
	for _, mapImpl := range mapImpls {
		b.Run(mapImpl.name, func(b *testing.B) {
			benchmarkLoadOrStoreDelete(b, mapImpl.ctor)
		})
	}
}

func benchmarkLookupPositive(b *testing.B, mapCtor func() benchmarkableMap) {
	m := mapCtor()
	val := &testValue{}
	for i := 0; i < b.N; i++ {
		m.Store(int64(i), val)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		m.Load(int64(i))
	}
}

func BenchmarkLookupPositive(b *testing.B) {
	for _, mapImpl := range mapImpls {
		b.Run(mapImpl.name, func(b *testing.B) {
			benchmarkLookupPositive(b, mapImpl.ctor)
		})
	}
}

func benchmarkLookupNegative(b *testing.B, mapCtor func() benchmarkableMap) {
	m := mapCtor()
	val := &testValue{}
	for i := 0; i < b.N; i++ {
		m.Store(int64(i), val)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		m.Load(int64(-1 - i))
	}
}

func BenchmarkLookupNegative(b *testing.B) {
	for _, mapImpl := range mapImpls {
		b.Run(mapImpl.name, func(b *testing.B) {
			benchmarkLookupNegative(b, mapImpl.ctor)
		})
	}
}

type benchmarkConcurrentOptions struct {
	// loadsPerMutationPair is the number of map lookups between each
	// insertion/deletion pair.
	loadsPerMutationPair int

	// If changeKeys is true, the keys used by each goroutine change between
	// iterations of the test.
	changeKeys bool
}

func benchmarkConcurrent(b *testing.B, mapCtor func() benchmarkableMap, opts benchmarkConcurrentOptions) {
	var (
		started sync.WaitGroup
		workers sync.WaitGroup
	)
	started.Add(1)

	m := mapCtor()
	val := &testValue{}
	// Insert a large number of unused elements into the map so that used
	// elements are distributed throughout memory.
	for i := 0; i < 10000; i++ {
		m.Store(int64(-1-i), val)
	}
	// n := ceil(b.N / (opts.loadsPerMutationPair + 2))
	n := (b.N + opts.loadsPerMutationPair + 1) / (opts.loadsPerMutationPair + 2)
	for i, procs := 0, runtime.GOMAXPROCS(0); i < procs; i++ {
		workerID := i
		workers.Add(1)
		go func() {
			defer workers.Done()
			started.Wait()
			for i := 0; i < n; i++ {
				var key int64
				if opts.changeKeys {
					key = int64(workerID*n + i)
				} else {
					key = int64(workerID)
				}
				m.LoadOrStore(key, val)
				for j := 0; j < opts.loadsPerMutationPair; j++ {
					m.Load(key)
				}
				m.Delete(key)
			}
		}()
	}

	b.ResetTimer()
	started.Done()
	workers.Wait()
}

func BenchmarkConcurrent(b *testing.B) {
	changeKeysChoices := [...]struct {
		name string
		val  bool
	}{
		{"FixedKeys", false},
		{"ChangingKeys", true},
	}
	writePcts := [...]struct {
		name                 string
		loadsPerMutationPair int
	}{
		{"1PercentWrites", 198},
		{"10PercentWrites", 18},
		{"50PercentWrites", 2},
	}
	for _, changeKeys := range changeKeysChoices {
		for _, writePct := range writePcts {
			for _, mapImpl := range mapImpls {
				name := fmt.Sprintf("%s_%s_%s", changeKeys.name, writePct.name, mapImpl.name)
				b.Run(name, func(b *testing.B) {
					benchmarkConcurrent(b, mapImpl.ctor, benchmarkConcurrentOptions{
						loadsPerMutationPair: writePct.loadsPerMutationPair,
						changeKeys:           changeKeys.val,
					})
				})
			}
		}
	}
}