-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrent_test.go
More file actions
1954 lines (1687 loc) · 52.3 KB
/
Copy pathconcurrent_test.go
File metadata and controls
1954 lines (1687 loc) · 52.3 KB
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package immukv
import (
"bytes"
"encoding/binary"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestConcurrentAccess(t *testing.T) {
// Create a test database
dbPath := "test_concurrent.db"
// Clean up any existing test database
cleanupTestFiles(dbPath)
// Open a new database
db, err := Open(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer func() {
db.Close()
cleanupTestFiles(dbPath)
}()
// Insert some initial data
for i := 0; i < 10; i++ {
key := fmt.Sprintf("init-key-%d", i)
value := fmt.Sprintf("init-value-%d", i)
if err := db.Set([]byte(key), []byte(value)); err != nil {
t.Fatalf("Failed to set initial data: %v", err)
}
}
// Number of concurrent operations
numOps := 100
// Wait group to synchronize goroutines
var wg sync.WaitGroup
wg.Add(numOps * 3) // For readers, writers, and deleters
// Track errors
var errMutex sync.Mutex
var errors []string
// Concurrent readers
for i := 0; i < numOps; i++ {
go func(id int) {
defer wg.Done()
// Read some keys
for j := 0; j < 5; j++ {
key := fmt.Sprintf("init-key-%d", j)
value, err := db.Get([]byte(key))
if err != nil {
// "key not found" is acceptable due to concurrent deletion
if err.Error() != "key not found" {
errMutex.Lock()
errors = append(errors, fmt.Sprintf("Reader %d failed to get key %s: %v", id, key, err))
errMutex.Unlock()
}
} else if len(value) > 0 {
// An empty value means the key was deleted by a concurrent
// deleter: in this engine "delete" is Set(key, nil), which
// leaves the key present with an empty value rather than
// removing it. Any non-empty value must be the original.
expectedPrefix := "init-value-"
if !bytes.HasPrefix(value, []byte(expectedPrefix)) {
errMutex.Lock()
errors = append(errors, fmt.Sprintf("Reader %d got unexpected value for key %s: %s", id, key, string(value)))
errMutex.Unlock()
}
}
// Brief pause to allow interleaving with other operations
time.Sleep(time.Millisecond)
}
}(i)
}
// Concurrent writers
for i := 0; i < numOps; i++ {
go func(id int) {
defer wg.Done()
// Write some keys
for j := 0; j < 5; j++ {
key := fmt.Sprintf("writer-%d-key-%d", id, j)
value := fmt.Sprintf("writer-%d-value-%d", id, j)
if err := db.Set([]byte(key), []byte(value)); err != nil {
errMutex.Lock()
errors = append(errors, fmt.Sprintf("Writer %d failed to set key %s: %v", id, key, err))
errMutex.Unlock()
}
// Brief pause to allow interleaving with other operations
time.Sleep(time.Millisecond)
}
}(i)
}
// Concurrent deleters
for i := 0; i < numOps; i++ {
go func(id int) {
defer wg.Done()
// Delete some keys (both existing and non-existing)
for j := 0; j < 5; j++ {
var key string
if j%2 == 0 && id%5 == 0 {
// Occasionally try to delete an initial key
key = fmt.Sprintf("init-key-%d", (id+j)%10)
} else {
// Try to delete a key that might have been written by a writer
key = fmt.Sprintf("writer-%d-key-%d", (id+j)%numOps, j)
}
if err := db.Set([]byte(key), nil); err != nil {
errMutex.Lock()
errors = append(errors, fmt.Sprintf("Deleter %d failed to delete key %s: %v", id, key, err))
errMutex.Unlock()
}
// Brief pause to allow interleaving with other operations
time.Sleep(time.Millisecond)
}
}(i)
}
// Wait for all goroutines to finish
wg.Wait()
// Check if there were any errors
if len(errors) > 0 {
for _, err := range errors {
t.Errorf("%s", err)
}
t.Fatalf("Encountered %d errors during concurrent operations", len(errors))
}
// Verify the database is still functional
// Try to read initial keys - some might have been deleted by concurrent deleters
keysFound := 0
for i := 0; i < 10; i++ {
key := fmt.Sprintf("init-key-%d", i)
value, err := db.Get([]byte(key))
if err != nil {
t.Errorf("Unexpected error reading initial key %s after concurrent operations: %v", key, err)
continue
}
// Concurrent deleters may have written empty (deleted) records.
// In the immutable model that surfaces as a present key with an
// empty value rather than a not-found error.
if len(value) == 0 {
continue
}
keysFound++
expectedValue := fmt.Sprintf("init-value-%d", i)
if !bytes.Equal(value, []byte(expectedValue)) {
t.Errorf("Value mismatch for initial key %s: got %s, want %s", key, string(value), expectedValue)
}
}
// We should find at least some initial keys (not all should be deleted)
if keysFound == 0 {
t.Errorf("All initial keys were deleted - this is unexpected")
}
// Try to write and read a new key
testKey := "final-test-key"
testValue := "final-test-value"
if err := db.Set([]byte(testKey), []byte(testValue)); err != nil {
t.Fatalf("Failed to set test key after concurrent operations: %v", err)
}
value, err := db.Get([]byte(testKey))
if err != nil {
t.Fatalf("Failed to get test key after concurrent operations: %v", err)
}
if !bytes.Equal(value, []byte(testValue)) {
t.Fatalf("Value mismatch for test key after concurrent operations: got %s, want %s", string(value), testValue)
}
}
func TestExclusiveAccess(t *testing.T) {
// Create a test database
dbPath := "test_exclusive.db"
// Clean up any existing test database
cleanupTestFiles(dbPath)
// Open a new database connection
db1, err := Open(dbPath)
if err != nil {
t.Fatalf("Failed to open first database connection: %v", err)
}
defer func() {
db1.Close()
cleanupTestFiles(dbPath)
}()
// Insert some initial data
for i := 0; i < 5; i++ {
key := fmt.Sprintf("key-%d", i)
value := fmt.Sprintf("value-%d", i)
if err := db1.Set([]byte(key), []byte(value)); err != nil {
t.Fatalf("Failed to set initial data: %v", err)
}
}
// Try to open a second connection to the same database
// This should fail because the database only allows one connection at a time
db2, err := Open(dbPath)
// The second connection should fail
if err == nil {
db2.Close() // Make sure to close it if it somehow succeeded
t.Fatalf("Expected second database connection to fail, but it succeeded")
}
// Verify the first connection still works
value, err := db1.Get([]byte("key-0"))
if err != nil {
t.Fatalf("Failed to read from first connection after attempting second connection: %v", err)
}
if !bytes.Equal(value, []byte("value-0")) {
t.Fatalf("Value mismatch: got %s, want %s", string(value), "value-0")
}
}
func TestReadOnlyMode(t *testing.T) {
// Create a test database
dbPath := "test_readonly.db"
// Clean up any existing test database
cleanupTestFiles(dbPath)
// Create and populate the database
writeDB, err := Open(dbPath)
if err != nil {
t.Fatalf("Failed to open database for writing: %v", err)
}
// Insert some data
for i := 0; i < 10; i++ {
key := fmt.Sprintf("key-%d", i)
value := fmt.Sprintf("value-%d", i)
if err := writeDB.Set([]byte(key), []byte(value)); err != nil {
writeDB.Close()
t.Fatalf("Failed to set data: %v", err)
}
}
// Close the write database
if err := writeDB.Close(); err != nil {
t.Fatalf("Failed to close write database: %v", err)
}
// Open the database in read-only mode
readDB, err := Open(dbPath, Options{"ReadOnly": true})
if err != nil {
t.Fatalf("Failed to open database in read-only mode: %v", err)
}
defer func() {
readDB.Close()
cleanupTestFiles(dbPath)
}()
// Verify we can read data
for i := 0; i < 10; i++ {
key := fmt.Sprintf("key-%d", i)
value, err := readDB.Get([]byte(key))
if err != nil {
t.Fatalf("Failed to read key %s in read-only mode: %v", key, err)
}
expectedValue := fmt.Sprintf("value-%d", i)
if !bytes.Equal(value, []byte(expectedValue)) {
t.Fatalf("Value mismatch for key %s in read-only mode: got %s, want %s", key, string(value), expectedValue)
}
}
// Try to write data (should fail)
err = readDB.Set([]byte("new-key"), []byte("new-value"))
if err == nil {
t.Fatalf("Expected error when writing in read-only mode, but got nil")
}
// Try to delete data (should fail)
err = readDB.Set([]byte("key-0"), nil)
if err == nil {
t.Fatalf("Expected error when deleting in read-only mode, but got nil")
}
// Try to open a second read-only connection (should fail due to exclusive access)
readDB2, err := Open(dbPath, Options{"ReadOnly": true})
if err == nil {
readDB2.Close()
t.Fatalf("Expected second read-only connection to fail, but it succeeded")
}
}
func TestTransactionWaitsForPreviousToFinish(t *testing.T) {
dbPath := "test_txn_wait.db"
cleanupTestFiles(dbPath)
db, err := Open(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer func() {
db.Close()
cleanupTestFiles(dbPath)
}()
// Start first transaction
tx1, err := db.Begin()
if err != nil {
t.Fatalf("Failed to begin first transaction: %v", err)
}
// Channel to signal when second transaction starts
secondStarted := make(chan struct{})
secondAcquired := make(chan struct{})
secondDone := make(chan struct{})
// Start second transaction in another goroutine
go func() {
close(secondStarted)
tx2, err := db.Begin()
if err != nil {
t.Errorf("Second transaction failed to begin: %v", err)
return
}
close(secondAcquired)
// Do something in tx2
err = tx2.Set([]byte("key2"), []byte("val2"))
if err != nil {
t.Errorf("Second transaction failed to set: %v", err)
}
err = tx2.Commit()
if err != nil {
t.Errorf("Second transaction failed to commit: %v", err)
}
close(secondDone)
}()
// Wait for goroutine to start and attempt Begin
<-secondStarted
// Sleep briefly to ensure goroutine is blocked on Begin
time.Sleep(100 * time.Millisecond)
select {
case <-secondAcquired:
t.Fatalf("Second transaction acquired lock before first committed!")
default:
// Expected: second transaction is blocked
}
// Commit first transaction
err = tx1.Set([]byte("key1"), []byte("val1"))
if err != nil {
t.Fatalf("First transaction failed to set: %v", err)
}
err = tx1.Commit()
if err != nil {
t.Fatalf("First transaction failed to commit: %v", err)
}
// Now second transaction should proceed
select {
case <-secondAcquired:
// Good: second transaction acquired lock after first committed
case <-time.After(1 * time.Second):
t.Fatalf("Second transaction did not acquire lock after first committed")
}
<-secondDone
// Check both keys are present
val, err := db.Get([]byte("key1"))
if err != nil || string(val) != "val1" {
t.Fatalf("key1 not found or value mismatch: %v, %s", err, val)
}
val, err = db.Get([]byte("key2"))
if err != nil || string(val) != "val2" {
t.Fatalf("key2 not found or value mismatch: %v, %s", err, val)
}
}
// TestConcurrentReadersDuringWrite tests that multiple readers can proceed concurrently while a writer is active
func TestConcurrentReadersDuringWrite(t *testing.T) {
dbPath := "test_concurrent_readers_writers.db"
// Clean up any existing test database
cleanupTestFiles(dbPath)
// Open a new database
db, err := Open(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer func() {
db.Close()
cleanupTestFiles(dbPath)
}()
// Insert initial data
numInitialKeys := 1000
for i := 0; i < numInitialKeys; i++ {
key := fmt.Sprintf("key-%d", i)
value := fmt.Sprintf("value-%d", i)
if err := db.Set([]byte(key), []byte(value)); err != nil {
t.Fatalf("Failed to set initial data: %v", err)
}
}
// Channels for synchronization
writerStarted := make(chan struct{})
writerFinished := make(chan struct{})
readersStarted := make(chan struct{}, 10)
readersFinished := make(chan struct{}, 10)
// Track read operations that happened during write
var concurrentReads atomic.Int64
var totalReads atomic.Int64
var readErrors atomic.Int64
// Start a long-running writer that will block for a significant time
go func() {
defer close(writerFinished)
close(writerStarted)
// Perform multiple write operations to ensure readers have time to run concurrently
for i := 0; i < 100; i++ {
key := fmt.Sprintf("writer-key-%d", i)
value := fmt.Sprintf("writer-value-%d", i)
if err := db.Set([]byte(key), []byte(value)); err != nil {
t.Errorf("Writer failed to set key %s: %v", key, err)
return
}
// Small delay to allow readers to interleave
time.Sleep(time.Millisecond)
}
}()
// Wait for writer to start
<-writerStarted
// Start multiple concurrent readers
numReaders := 10
var wg sync.WaitGroup
wg.Add(numReaders)
for i := 0; i < numReaders; i++ {
go func(readerID int) {
defer wg.Done()
defer func() { readersFinished <- struct{}{} }()
readersStarted <- struct{}{}
// Each reader performs multiple read operations
for j := 0; j < 50; j++ {
// Read from initial data
keyIndex := (readerID*50 + j) % numInitialKeys
key := fmt.Sprintf("key-%d", keyIndex)
totalReads.Add(1)
value, err := db.Get([]byte(key))
if err != nil {
readErrors.Add(1)
t.Errorf("Reader %d failed to get key %s: %v", readerID, key, err)
continue
}
expectedValue := fmt.Sprintf("value-%d", keyIndex)
if !bytes.Equal(value, []byte(expectedValue)) {
t.Errorf("Reader %d got unexpected value for key %s: got %s, want %s",
readerID, key, string(value), expectedValue)
continue
}
// Check if writer is still running (concurrent read)
select {
case <-writerFinished:
// Writer finished, this is not a concurrent read
default:
// Writer is still running, this is a concurrent read
concurrentReads.Add(1)
}
// Small delay to allow interleaving
time.Sleep(500 * time.Microsecond)
}
}(i)
}
// Wait for all readers to start
for i := 0; i < numReaders; i++ {
<-readersStarted
}
// Wait for all readers to finish
wg.Wait()
// Wait for writer to finish
<-writerFinished
// Verify that we had concurrent reads
totalReadsCount := totalReads.Load()
concurrentReadsCount := concurrentReads.Load()
readErrorsCount := readErrors.Load()
t.Logf("Total reads: %d, Concurrent reads: %d, Read errors: %d",
totalReadsCount, concurrentReadsCount, readErrorsCount)
if concurrentReadsCount == 0 {
t.Errorf("No concurrent reads detected - readers may be blocked by writer")
}
if readErrorsCount > 0 {
t.Errorf("Read errors occurred during concurrent access: %d", readErrorsCount)
}
// Verify that concurrent reads represent a significant portion of total reads
if float64(concurrentReadsCount)/float64(totalReadsCount) < 0.3 {
t.Errorf("Too few concurrent reads (%d/%d = %.2f%%) - concurrency may not be working properly",
concurrentReadsCount, totalReadsCount, float64(concurrentReadsCount)/float64(totalReadsCount)*100)
}
}
// TestReaderWriterThroughput tests that concurrent readers don't significantly impact writer throughput
func TestReaderWriterThroughput(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "test_reader_writer_throughput.db")
// Helper function to clean up database files
cleanupDB := func() {
cleanupTestFiles(dbPath)
}
// Helper function to initialize database with reader data
initializeDB := func() (*DB, error) {
// Clean up any existing test database
cleanupDB()
// Open a new database
db, err := Open(dbPath)
if err != nil {
return nil, err
}
// Insert initial data for readers
for i := 0; i < 10000; i++ {
key := fmt.Sprintf("read-key-%d", i)
value := fmt.Sprintf("read-value-%d", i)
if err := db.Set([]byte(key), []byte(value)); err != nil {
db.Close()
return nil, err
}
}
return db, nil
}
// Initialize database once
db, err := initializeDB()
if err != nil {
t.Fatalf("Failed to initialize database: %v", err)
}
db.Close()
defer cleanupDB()
// Run multiple iterations interleaved to get stable averages
const numIterations = 5
soloTimes := make([]time.Duration, 0, numIterations)
concurrentTimes := make([]time.Duration, 0, numIterations)
for iteration := 0; iteration < numIterations; iteration++ {
// Reopen database for solo test
db, err := Open(dbPath)
if err != nil {
t.Fatalf("Failed to reopen database for solo test iteration %d: %v", iteration, err)
}
// Test writer performance without concurrent readers
start := time.Now()
for i := 0; i < 1000; i++ {
key := fmt.Sprintf("write-key-solo-%d-%d", iteration, i)
value := fmt.Sprintf("write-value-solo-%d-%d", iteration, i)
if err := db.Set([]byte(key), []byte(value)); err != nil {
t.Fatalf("Failed to write during solo test iteration %d: %v", iteration, err)
}
}
soloWriteTime := time.Since(start)
soloTimes = append(soloTimes, soloWriteTime)
db.Close()
// Reopen database for concurrent test
db, err = Open(dbPath)
if err != nil {
t.Fatalf("Failed to reopen database for concurrent test iteration %d: %v", iteration, err)
}
// Test writer performance with concurrent readers
var wg sync.WaitGroup
stopReaders := make(chan struct{})
startReading := make(chan struct{})
readersReady := make(chan struct{}, 5) // Buffered channel for reader readiness
// Start multiple concurrent readers
numReaders := 5
wg.Add(numReaders)
for i := 0; i < numReaders; i++ {
go func(readerID int) {
defer wg.Done()
readCount := 0
// Signal that this reader is ready
readersReady <- struct{}{}
// Wait for start signal
<-startReading
for {
select {
case <-stopReaders:
return
default:
// Read different keys in sequence to create varied load
keyIndex := (readerID*1000 + readCount) % 10000
key := fmt.Sprintf("read-key-%d", keyIndex)
_, err := db.Get([]byte(key))
if err != nil {
// Ignore "key not found" errors
if err.Error() != "key not found" {
t.Errorf("Reader %d failed to get key %s: %v", readerID, key, err)
}
}
readCount++
}
}
}(i)
}
// Wait for all readers to be ready
for i := 0; i < numReaders; i++ {
<-readersReady
}
// Signal all readers to start reading
close(startReading)
// Test writer performance with concurrent readers
start = time.Now()
for i := 0; i < 1000; i++ {
key := fmt.Sprintf("write-key-concurrent-%d-%d", iteration, i)
value := fmt.Sprintf("write-value-concurrent-%d-%d", iteration, i)
if err := db.Set([]byte(key), []byte(value)); err != nil {
t.Fatalf("Failed to write during concurrent test iteration %d: %v", iteration, err)
}
}
concurrentWriteTime := time.Since(start)
concurrentTimes = append(concurrentTimes, concurrentWriteTime)
// Stop readers
close(stopReaders)
wg.Wait()
db.Close()
}
// Calculate averages
var soloSum, concurrentSum time.Duration
for i := 0; i < numIterations; i++ {
soloSum += soloTimes[i]
concurrentSum += concurrentTimes[i]
}
avgSoloTime := soloSum / numIterations
avgConcurrentTime := concurrentSum / numIterations
t.Logf("Average solo write time: %v (individual: %v)", avgSoloTime, soloTimes)
t.Logf("Average concurrent write time: %v (individual: %v)", avgConcurrentTime, concurrentTimes)
// Writer performance shouldn't degrade significantly due to concurrent
// readers, but the ratio is a noisy, machine-load-sensitive measurement,
// so we only report it (and fail only on a pathological >10x slowdown).
slowdownRatio := float64(avgConcurrentTime.Nanoseconds()) / float64(avgSoloTime.Nanoseconds())
t.Logf("Writer slowdown with concurrent readers: %.1fx (%v vs %v)",
slowdownRatio, avgConcurrentTime, avgSoloTime)
if slowdownRatio > 10.0 {
t.Errorf("Writer performance degraded pathologically with concurrent readers: %v vs %v (%.1fx slower)",
avgConcurrentTime, avgSoloTime, slowdownRatio)
}
}
// TestMultipleReadersSingleWriter ensures multiple readers can run truly concurrently
func TestMultipleReadersSingleWriter(t *testing.T) {
dbPath := "test_multiple_readers.db"
// Clean up any existing test database
cleanupTestFiles(dbPath)
// Open a new database
db, err := Open(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer func() {
db.Close()
cleanupTestFiles(dbPath)
}()
// Insert initial data
for i := 0; i < 50; i++ {
key := fmt.Sprintf("key-%d", i)
value := fmt.Sprintf("value-%d", i)
if err := db.Set([]byte(key), []byte(value)); err != nil {
t.Fatalf("Failed to set initial data: %v", err)
}
}
// Track concurrent executions
var activeReaders atomic.Int32
var maxConcurrentReaders atomic.Int32
var readCompletions atomic.Int64
// Start multiple readers that will run concurrently
numReaders := 20
var wg sync.WaitGroup
wg.Add(numReaders)
startSignal := make(chan struct{})
for i := 0; i < numReaders; i++ {
go func(readerID int) {
defer wg.Done()
// Wait for start signal to ensure all readers start simultaneously
<-startSignal
// Track active readers
current := activeReaders.Add(1)
// Update max concurrent readers
for {
max := maxConcurrentReaders.Load()
if current <= max || maxConcurrentReaders.CompareAndSwap(max, current) {
break
}
}
// Simulate some work to ensure readers overlap
time.Sleep(10 * time.Millisecond)
// Perform multiple reads
for j := 0; j < 10; j++ {
keyIndex := (readerID + j) % 50
key := fmt.Sprintf("key-%d", keyIndex)
_, err := db.Get([]byte(key))
if err != nil {
t.Errorf("Reader %d failed to get key %s: %v", readerID, key, err)
}
// Brief pause between reads
time.Sleep(time.Millisecond)
}
activeReaders.Add(-1)
readCompletions.Add(1)
}(i)
}
// Start all readers simultaneously
close(startSignal)
// Wait for all readers to complete
wg.Wait()
maxConcurrent := maxConcurrentReaders.Load()
completions := readCompletions.Load()
t.Logf("Max concurrent readers: %d, Total completions: %d", maxConcurrent, completions)
// Verify that multiple readers ran concurrently
if maxConcurrent < int32(numReaders/2) {
t.Errorf("Expected at least %d concurrent readers, but max was %d", numReaders/2, maxConcurrent)
}
if completions != int64(numReaders) {
t.Errorf("Expected %d reader completions, got %d", numReaders, completions)
}
}
// TestWriterBlocksOtherWriters ensures writers are still serialized
func TestWriterBlocksOtherWriters(t *testing.T) {
dbPath := "test_writer_serialization.db"
// Clean up any existing test database
cleanupTestFiles(dbPath)
// Open a new database
db, err := Open(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer func() {
db.Close()
cleanupTestFiles(dbPath)
}()
var writerOrder []int
var orderMutex sync.Mutex
numWriters := 5
var wg sync.WaitGroup
wg.Add(numWriters)
startSignal := make(chan struct{})
for i := 0; i < numWriters; i++ {
go func(writerID int) {
defer wg.Done()
// Wait for start signal
<-startSignal
// Each writer performs a slow write operation
key := fmt.Sprintf("writer-%d-key", writerID)
value := fmt.Sprintf("writer-%d-value", writerID)
// Record when this writer starts its operation
orderMutex.Lock()
writerOrder = append(writerOrder, writerID)
orderMutex.Unlock()
if err := db.Set([]byte(key), []byte(value)); err != nil {
t.Errorf("Writer %d failed to set key: %v", writerID, err)
}
// Simulate some additional work
time.Sleep(5 * time.Millisecond)
}(i)
}
// Start all writers simultaneously
close(startSignal)
// Wait for all writers to complete
wg.Wait()
// Verify all writers completed
if len(writerOrder) != numWriters {
t.Errorf("Expected %d writers to execute, got %d", numWriters, len(writerOrder))
}
// Verify all keys were written correctly
for i := 0; i < numWriters; i++ {
key := fmt.Sprintf("writer-%d-key", i)
expectedValue := fmt.Sprintf("writer-%d-value", i)
value, err := db.Get([]byte(key))
if err != nil {
t.Errorf("Failed to read key written by writer %d: %v", i, err)
continue
}
if !bytes.Equal(value, []byte(expectedValue)) {
t.Errorf("Incorrect value for writer %d: got %s, want %s", i, string(value), expectedValue)
}
}
t.Logf("Writer execution order: %v", writerOrder)
}
// TestCloseWithBlockedTransactions tests that calling Close() while transactions
// are blocked waiting properly wakes them up and returns appropriate errors
func TestCloseWithBlockedTransactions(t *testing.T) {
dbPath := "test_close_blocked_txn.db"
cleanupTestFiles(dbPath)
var db *DB
var err error
defer func() {
if db != nil {
_ = db.Close()
}
cleanupTestFiles(dbPath)
}()
db, err = Open(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
// Start first transaction that we'll keep open
tx1, err := db.Begin()
if err != nil {
t.Fatalf("Failed to begin first transaction: %v", err)
}
// Channels to coordinate the test
numBlockedTxns := 3
txnStarted := make(chan int, numBlockedTxns)
txnResults := make(chan error, numBlockedTxns)
allTxnsStarted := make(chan struct{})
// Start multiple goroutines that will try to begin transactions
// These should all block waiting for tx1 to complete
for i := 0; i < numBlockedTxns; i++ {
go func(txnID int) {
txnStarted <- txnID
// This Begin() call should block until tx1 completes or DB is closed
tx, err := db.Begin()
if err != nil {
// Expected: database is closed error
txnResults <- err
return
}
// If we get here, the transaction should fail because DB is closed
defer func() {
if tx != nil {
tx.Rollback() // Clean up if needed
}
}()
// Try to do something with the transaction
err = tx.Set([]byte(fmt.Sprintf("key%d", txnID)), []byte(fmt.Sprintf("val%d", txnID)))
if err != nil {
txnResults <- err
return
}
err = tx.Commit()
txnResults <- err
}(i)
}
// Wait for all goroutines to start and attempt Begin()
for i := 0; i < numBlockedTxns; i++ {
txnID := <-txnStarted
t.Logf("Transaction %d started and should be blocking", txnID)
}
close(allTxnsStarted)
// Give goroutines time to actually block on the condition variable
time.Sleep(200 * time.Millisecond)
// Verify none of the blocked transactions have completed yet
select {
case result := <-txnResults:
t.Fatalf("A blocked transaction completed unexpectedly with result: %v", result)
default:
// Expected: all transactions are still blocked
t.Log("Confirmed: all transactions are properly blocked")
}
// Now close the database while transactions are blocked
t.Log("Closing database while transactions are blocked...")
closeErr := db.Close()
if closeErr != nil {
t.Errorf("Database close failed: %v", closeErr)
}
// Collect results from all blocked transactions
var results []error
for i := 0; i < numBlockedTxns; i++ {
select {
case result := <-txnResults:
results = append(results, result)
t.Logf("Transaction %d result: %v", i, result)
case <-time.After(2 * time.Second):
t.Fatalf("Transaction %d did not complete after database close", i)
}
}
// Verify all transactions received appropriate errors
for i, result := range results {
if result == nil {
t.Errorf("Transaction %d should have failed but succeeded", i)
} else if !strings.Contains(result.Error(), "closed") {
t.Errorf("Transaction %d got unexpected error (should mention 'closed'): %v", i, result)
}
}
// Clean up the first transaction (should be safe to rollback after close)
rollbackErr := tx1.Rollback()
if rollbackErr != nil {
t.Logf("Expected rollback error after close: %v", rollbackErr)