-
Notifications
You must be signed in to change notification settings - Fork 264
/
mutable_tree_test.go
1496 lines (1216 loc) · 45.3 KB
/
mutable_tree_test.go
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 iavl
import (
"bytes"
"errors"
"fmt"
"runtime"
"sort"
"strconv"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
gomock "go.uber.org/mock/gomock"
dbm "github.com/cosmos/iavl/db"
"github.com/cosmos/iavl/fastnode"
"github.com/cosmos/iavl/internal/encoding"
iavlrand "github.com/cosmos/iavl/internal/rand"
"github.com/cosmos/iavl/mock"
)
var (
tKey1 = []byte("k1")
tVal1 = []byte("v1")
tKey2 = []byte("k2")
tVal2 = []byte("v2")
// FIXME: enlarge maxIterator to 100000
maxIterator = 100
)
func setupMutableTree(skipFastStorageUpgrade bool) *MutableTree {
memDB := dbm.NewMemDB()
tree := NewMutableTree(memDB, 0, skipFastStorageUpgrade, NewNopLogger())
return tree
}
// TestIterateConcurrency throws "fatal error: concurrent map writes" when fast node is enabled
func TestIterateConcurrency(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
tree := setupMutableTree(true)
wg := new(sync.WaitGroup)
for i := 0; i < 100; i++ {
for j := 0; j < maxIterator; j++ {
wg.Add(1)
go func(i, j int) {
defer wg.Done()
_, err := tree.Set([]byte(fmt.Sprintf("%d%d", i, j)), iavlrand.RandBytes(1))
require.NoError(t, err)
}(i, j)
}
tree.Iterate(func(_, _ []byte) bool { //nolint:errcheck
return false
})
}
wg.Wait()
}
// TestConcurrency throws "fatal error: concurrent map iteration and map write" and
// also sometimes "fatal error: concurrent map writes" when fast node is enabled
func TestIteratorConcurrency(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
tree := setupMutableTree(true)
_, err := tree.LoadVersion(0)
require.NoError(t, err)
// So much slower
wg := new(sync.WaitGroup)
for i := 0; i < 100; i++ {
for j := 0; j < maxIterator; j++ {
wg.Add(1)
go func(i, j int) {
defer wg.Done()
_, err := tree.Set([]byte(fmt.Sprintf("%d%d", i, j)), iavlrand.RandBytes(1))
require.NoError(t, err)
}(i, j)
}
itr, _ := tree.Iterator(nil, nil, true)
for ; itr.Valid(); itr.Next() { //nolint:revive
} // do nothing
}
wg.Wait()
}
// TestNewIteratorConcurrency throws "fatal error: concurrent map writes" when fast node is enabled
func TestNewIteratorConcurrency(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
tree := setupMutableTree(true)
for i := 0; i < 100; i++ {
wg := new(sync.WaitGroup)
it := NewIterator(nil, nil, true, tree.ImmutableTree)
for j := 0; j < maxIterator; j++ {
wg.Add(1)
go func(i, j int) {
defer wg.Done()
_, err := tree.Set([]byte(fmt.Sprintf("%d%d", i, j)), iavlrand.RandBytes(1))
require.NoError(t, err)
}(i, j)
}
for ; it.Valid(); it.Next() { //nolint:revive
} // do nothing
wg.Wait()
}
}
func TestDeleteVersionsTo(t *testing.T) {
tree := setupMutableTree(false)
_, err := tree.set([]byte("k1"), []byte("Fred"))
require.NoError(t, err)
_, version, err := tree.SaveVersion()
require.NoError(t, err)
_, _, err = tree.SaveVersion()
require.NoError(t, err)
require.NoError(t, tree.DeleteVersionsTo(version))
proof, err := tree.GetVersionedProof([]byte("k1"), version)
require.EqualError(t, err, ErrVersionDoesNotExist.Error())
require.Nil(t, proof)
proof, err = tree.GetVersionedProof([]byte("k1"), version+1)
require.Nil(t, err)
require.Equal(t, 0, bytes.Compare([]byte("Fred"), proof.GetExist().Value))
}
func TestDeleteVersionsFrom(t *testing.T) {
tree := setupMutableTree(false)
_, err := tree.set([]byte("k1"), []byte("Wilma"))
require.NoError(t, err)
_, version, err := tree.SaveVersion()
require.NoError(t, err)
_, _, err = tree.SaveVersion()
require.NoError(t, err)
_, _, err = tree.SaveVersion()
require.NoError(t, err)
require.NoError(t, tree.DeleteVersionsFrom(version+1))
proof, err := tree.GetVersionedProof([]byte("k1"), version)
require.Nil(t, err)
require.Equal(t, 0, bytes.Compare([]byte("Wilma"), proof.GetExist().Value))
proof, err = tree.GetVersionedProof([]byte("k1"), version+1)
require.EqualError(t, err, ErrVersionDoesNotExist.Error())
require.Nil(t, proof)
proof, err = tree.GetVersionedProof([]byte("k1"), version+2)
require.EqualError(t, err, ErrVersionDoesNotExist.Error())
require.Nil(t, proof)
}
func TestGetRemove(t *testing.T) {
require := require.New(t)
tree := setupMutableTree(false)
testGet := func(exists bool) {
v, err := tree.Get(tKey1)
require.NoError(err)
if exists {
require.Equal(tVal1, v, "key should exist")
} else {
require.Nil(v, "key should not exist")
}
}
testGet(false)
ok, err := tree.Set(tKey1, tVal1)
require.NoError(err)
require.False(ok, "new key set: nothing to update")
// add second key to avoid tree.root removal
ok, err = tree.Set(tKey2, tVal2)
require.NoError(err)
require.False(ok, "new key set: nothing to update")
testGet(true)
// Save to tree.ImmutableTree
_, version, err := tree.SaveVersion()
require.NoError(err)
require.Equal(int64(1), version)
testGet(true)
v, ok, err := tree.Remove(tKey1)
require.NoError(err)
require.True(ok, "key should be removed")
require.Equal(tVal1, v, "key should exist")
testGet(false)
}
func TestTraverse(t *testing.T) {
tree := setupMutableTree(false)
for i := 0; i < 6; i++ {
_, err := tree.set([]byte(fmt.Sprintf("k%d", i)), []byte(fmt.Sprintf("v%d", i)))
require.NoError(t, err)
}
require.Equal(t, 11, tree.nodeSize(), "Size of tree unexpected")
}
func TestMutableTree_DeleteVersionsTo(t *testing.T) {
tree := setupMutableTree(false)
type entry struct {
key []byte
value []byte
}
versionEntries := make(map[int64][]entry)
// create 10 tree versions, each with 1000 random key/value entries
for i := 0; i < 10; i++ {
entries := make([]entry, 1000)
for j := 0; j < 1000; j++ {
k := iavlrand.RandBytes(10)
v := iavlrand.RandBytes(10)
entries[j] = entry{k, v}
_, err := tree.Set(k, v)
require.NoError(t, err)
}
_, v, err := tree.SaveVersion()
require.NoError(t, err)
versionEntries[v] = entries
}
// delete even versions
versionToDelete := int64(8)
require.NoError(t, tree.DeleteVersionsTo(versionToDelete))
// ensure even versions have been deleted
for v := int64(1); v <= versionToDelete; v++ {
_, err := tree.LoadVersion(v)
require.Error(t, err)
}
// ensure odd number versions exist and we can query for all set entries
for _, v := range []int64{9, 10} {
_, err := tree.LoadVersion(v)
require.NoError(t, err)
for _, e := range versionEntries[v] {
val, err := tree.Get(e.key)
require.NoError(t, err)
if !bytes.Equal(e.value, val) {
t.Log(val)
}
// require.Equal(t, e.value, val)
}
}
}
func TestMutableTree_LoadVersion_Empty(t *testing.T) {
tree := setupMutableTree(false)
version, err := tree.LoadVersion(0)
require.NoError(t, err)
assert.EqualValues(t, 0, version)
version, err = tree.LoadVersion(-1)
require.NoError(t, err)
assert.EqualValues(t, 0, version)
_, err = tree.LoadVersion(3)
require.Error(t, err)
}
func TestMutableTree_InitialVersion(t *testing.T) {
memDB := dbm.NewMemDB()
tree := NewMutableTree(memDB, 0, false, NewNopLogger(), InitialVersionOption(9))
_, err := tree.Set([]byte("a"), []byte{0x01})
require.NoError(t, err)
_, version, err := tree.SaveVersion()
require.NoError(t, err)
assert.EqualValues(t, 9, version)
_, err = tree.Set([]byte("b"), []byte{0x02})
require.NoError(t, err)
_, version, err = tree.SaveVersion()
require.NoError(t, err)
assert.EqualValues(t, 10, version)
// Reloading the tree with the same initial version is fine
tree = NewMutableTree(memDB, 0, false, NewNopLogger(), InitialVersionOption(9))
version, err = tree.Load()
require.NoError(t, err)
assert.EqualValues(t, 10, version)
// Reloading the tree with an initial version beyond the lowest should error
tree = NewMutableTree(memDB, 0, false, NewNopLogger(), InitialVersionOption(10))
_, err = tree.Load()
require.Error(t, err)
// Reloading the tree with a lower initial version is fine, and new versions can be produced
tree = NewMutableTree(memDB, 0, false, NewNopLogger(), InitialVersionOption(3))
version, err = tree.Load()
require.NoError(t, err)
assert.EqualValues(t, 10, version)
_, err = tree.Set([]byte("c"), []byte{0x03})
require.NoError(t, err)
_, version, err = tree.SaveVersion()
require.NoError(t, err)
assert.EqualValues(t, 11, version)
}
func TestMutableTree_SetInitialVersion(t *testing.T) {
tree := setupMutableTree(false)
tree.SetInitialVersion(9)
_, err := tree.Set([]byte("a"), []byte{0x01})
require.NoError(t, err)
_, version, err := tree.SaveVersion()
require.NoError(t, err)
assert.EqualValues(t, 9, version)
}
func BenchmarkMutableTree_Set(b *testing.B) {
db := dbm.NewMemDB()
t := NewMutableTree(db, 100000, false, NewNopLogger())
for i := 0; i < 1000000; i++ {
_, err := t.Set(iavlrand.RandBytes(10), []byte{})
require.NoError(b, err)
}
b.ReportAllocs()
runtime.GC()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := t.Set(iavlrand.RandBytes(10), []byte{})
require.NoError(b, err)
}
}
func prepareTree(t *testing.T) *MutableTree {
mdb := dbm.NewMemDB()
tree := NewMutableTree(mdb, 1000, false, NewNopLogger())
for i := 0; i < 100; i++ {
_, err := tree.Set([]byte{byte(i)}, []byte("a"))
require.NoError(t, err)
}
_, ver, err := tree.SaveVersion()
require.True(t, ver == 1)
require.NoError(t, err)
for i := 0; i < 100; i++ {
_, err = tree.Set([]byte{byte(i)}, []byte("b"))
require.NoError(t, err)
}
_, ver, err = tree.SaveVersion()
require.True(t, ver == 2)
require.NoError(t, err)
newTree := NewMutableTree(mdb, 1000, false, NewNopLogger())
return newTree
}
func TestMutableTree_Version(t *testing.T) {
tree := prepareTree(t)
require.True(t, tree.VersionExists(1))
require.True(t, tree.VersionExists(2))
require.False(t, tree.VersionExists(3))
v, err := tree.GetLatestVersion()
require.NoError(t, err)
require.Equal(t, int64(2), v)
}
func checkGetVersioned(t *testing.T, tree *MutableTree, version int64, key, value []byte) {
val, err := tree.GetVersioned(key, version)
require.NoError(t, err)
require.True(t, bytes.Equal(val, value))
}
func TestMutableTree_GetVersioned(t *testing.T) {
tree := prepareTree(t)
ver, err := tree.LoadVersion(1)
require.True(t, ver == 2)
require.NoError(t, err)
// check key of unloaded version
checkGetVersioned(t, tree, 1, []byte{1}, []byte("a"))
checkGetVersioned(t, tree, 2, []byte{1}, []byte("b"))
checkGetVersioned(t, tree, 3, []byte{1}, nil)
tree = prepareTree(t)
ver, err = tree.LoadVersion(2)
require.True(t, ver == 2)
require.NoError(t, err)
checkGetVersioned(t, tree, 1, []byte{1}, []byte("a"))
checkGetVersioned(t, tree, 2, []byte{1}, []byte("b"))
checkGetVersioned(t, tree, 3, []byte{1}, nil)
}
func TestMutableTree_DeleteVersion(t *testing.T) {
tree := prepareTree(t)
ver, err := tree.LoadVersion(2)
require.True(t, ver == 2)
require.NoError(t, err)
require.NoError(t, tree.DeleteVersionsTo(1))
require.False(t, tree.VersionExists(1))
require.True(t, tree.VersionExists(2))
require.False(t, tree.VersionExists(3))
// cannot delete latest version
require.Error(t, tree.DeleteVersionsTo(2))
}
func TestMutableTree_LazyLoadVersionWithEmptyTree(t *testing.T) {
mdb := dbm.NewMemDB()
tree := NewMutableTree(mdb, 1000, false, NewNopLogger())
_, v1, err := tree.SaveVersion()
require.NoError(t, err)
newTree1 := NewMutableTree(mdb, 1000, false, NewNopLogger())
v2, err := newTree1.LoadVersion(1)
require.NoError(t, err)
require.True(t, v1 == v2)
newTree2 := NewMutableTree(mdb, 1000, false, NewNopLogger())
v2, err = newTree1.LoadVersion(1)
require.NoError(t, err)
require.True(t, v1 == v2)
require.True(t, newTree1.root == newTree2.root)
}
func TestMutableTree_SetSimple(t *testing.T) {
mdb := dbm.NewMemDB()
tree := NewMutableTree(mdb, 0, false, NewNopLogger())
const testKey1 = "a"
const testVal1 = "test"
isUpdated, err := tree.Set([]byte(testKey1), []byte(testVal1))
require.NoError(t, err)
require.False(t, isUpdated)
fastValue, err := tree.Get([]byte(testKey1))
require.NoError(t, err)
_, regularValue, err := tree.GetWithIndex([]byte(testKey1))
require.NoError(t, err)
require.Equal(t, []byte(testVal1), fastValue)
require.Equal(t, []byte(testVal1), regularValue)
fastNodeAdditions := tree.getUnsavedFastNodeAdditions()
require.Equal(t, 1, len(fastNodeAdditions))
fastNodeAddition := fastNodeAdditions[testKey1]
require.Equal(t, []byte(testKey1), fastNodeAddition.GetKey())
require.Equal(t, []byte(testVal1), fastNodeAddition.GetValue())
require.Equal(t, int64(1), fastNodeAddition.GetVersionLastUpdatedAt())
}
func TestMutableTree_SetTwoKeys(t *testing.T) {
tree := setupMutableTree(false)
const testKey1 = "a"
const testVal1 = "test"
const testKey2 = "b"
const testVal2 = "test2"
isUpdated, err := tree.Set([]byte(testKey1), []byte(testVal1))
require.NoError(t, err)
require.False(t, isUpdated)
isUpdated, err = tree.Set([]byte(testKey2), []byte(testVal2))
require.NoError(t, err)
require.False(t, isUpdated)
fastValue, err := tree.Get([]byte(testKey1))
require.NoError(t, err)
_, regularValue, err := tree.GetWithIndex([]byte(testKey1))
require.NoError(t, err)
require.Equal(t, []byte(testVal1), fastValue)
require.Equal(t, []byte(testVal1), regularValue)
fastValue2, err := tree.Get([]byte(testKey2))
require.NoError(t, err)
_, regularValue2, err := tree.GetWithIndex([]byte(testKey2))
require.NoError(t, err)
require.Equal(t, []byte(testVal2), fastValue2)
require.Equal(t, []byte(testVal2), regularValue2)
fastNodeAdditions := tree.getUnsavedFastNodeAdditions()
require.Equal(t, 2, len(fastNodeAdditions))
fastNodeAddition := fastNodeAdditions[testKey1]
require.Equal(t, []byte(testKey1), fastNodeAddition.GetKey())
require.Equal(t, []byte(testVal1), fastNodeAddition.GetValue())
require.Equal(t, int64(1), fastNodeAddition.GetVersionLastUpdatedAt())
fastNodeAddition = fastNodeAdditions[testKey2]
require.Equal(t, []byte(testKey2), fastNodeAddition.GetKey())
require.Equal(t, []byte(testVal2), fastNodeAddition.GetValue())
require.Equal(t, int64(1), fastNodeAddition.GetVersionLastUpdatedAt())
}
func TestMutableTree_SetOverwrite(t *testing.T) {
tree := setupMutableTree(false)
const testKey1 = "a"
const testVal1 = "test"
const testVal2 = "test2"
isUpdated, err := tree.Set([]byte(testKey1), []byte(testVal1))
require.NoError(t, err)
require.False(t, isUpdated)
isUpdated, err = tree.Set([]byte(testKey1), []byte(testVal2))
require.NoError(t, err)
require.True(t, isUpdated)
fastValue, err := tree.Get([]byte(testKey1))
require.NoError(t, err)
_, regularValue, err := tree.GetWithIndex([]byte(testKey1))
require.NoError(t, err)
require.Equal(t, []byte(testVal2), fastValue)
require.Equal(t, []byte(testVal2), regularValue)
fastNodeAdditions := tree.getUnsavedFastNodeAdditions()
require.Equal(t, 1, len(fastNodeAdditions))
fastNodeAddition := fastNodeAdditions[testKey1]
require.Equal(t, []byte(testKey1), fastNodeAddition.GetKey())
require.Equal(t, []byte(testVal2), fastNodeAddition.GetValue())
require.Equal(t, int64(1), fastNodeAddition.GetVersionLastUpdatedAt())
}
func TestMutableTree_SetRemoveSet(t *testing.T) {
tree := setupMutableTree(false)
const testKey1 = "a"
const testVal1 = "test"
// Set 1
isUpdated, err := tree.Set([]byte(testKey1), []byte(testVal1))
require.NoError(t, err)
require.False(t, isUpdated)
fastValue, err := tree.Get([]byte(testKey1))
require.NoError(t, err)
_, regularValue, err := tree.GetWithIndex([]byte(testKey1))
require.NoError(t, err)
require.Equal(t, []byte(testVal1), fastValue)
require.Equal(t, []byte(testVal1), regularValue)
fastNodeAdditions := tree.getUnsavedFastNodeAdditions()
require.Equal(t, 1, len(fastNodeAdditions))
fastNodeAddition := fastNodeAdditions[testKey1]
require.Equal(t, []byte(testKey1), fastNodeAddition.GetKey())
require.Equal(t, []byte(testVal1), fastNodeAddition.GetValue())
require.Equal(t, int64(1), fastNodeAddition.GetVersionLastUpdatedAt())
// Remove
removedVal, isRemoved, err := tree.Remove([]byte(testKey1))
require.NoError(t, err)
require.NotNil(t, removedVal)
require.True(t, isRemoved)
fastNodeAdditions = tree.getUnsavedFastNodeAdditions()
require.Equal(t, 0, len(fastNodeAdditions))
fastNodeRemovals := tree.getUnsavedFastNodeRemovals()
require.Equal(t, 1, len(fastNodeRemovals))
fastValue, err = tree.Get([]byte(testKey1))
require.NoError(t, err)
_, regularValue, err = tree.GetWithIndex([]byte(testKey1))
require.NoError(t, err)
require.Nil(t, fastValue)
require.Nil(t, regularValue)
// Set 2
isUpdated, err = tree.Set([]byte(testKey1), []byte(testVal1))
require.NoError(t, err)
require.False(t, isUpdated)
fastValue, err = tree.Get([]byte(testKey1))
require.NoError(t, err)
_, regularValue, err = tree.GetWithIndex([]byte(testKey1))
require.NoError(t, err)
require.Equal(t, []byte(testVal1), fastValue)
require.Equal(t, []byte(testVal1), regularValue)
fastNodeAdditions = tree.getUnsavedFastNodeAdditions()
require.Equal(t, 1, len(fastNodeAdditions))
fastNodeAddition = fastNodeAdditions[testKey1]
require.Equal(t, []byte(testKey1), fastNodeAddition.GetKey())
require.Equal(t, []byte(testVal1), fastNodeAddition.GetValue())
require.Equal(t, int64(1), fastNodeAddition.GetVersionLastUpdatedAt())
fastNodeRemovals = tree.getUnsavedFastNodeRemovals()
require.Equal(t, 0, len(fastNodeRemovals))
}
func TestMutableTree_FastNodeIntegration(t *testing.T) {
mdb := dbm.NewMemDB()
tree := NewMutableTree(mdb, 1000, false, NewNopLogger())
const key1 = "a"
const key2 = "b"
const key3 = "c"
const testVal1 = "test"
const testVal2 = "test2"
// Set key1
res, err := tree.Set([]byte(key1), []byte(testVal1))
require.NoError(t, err)
require.False(t, res)
unsavedNodeAdditions := tree.getUnsavedFastNodeAdditions()
require.Equal(t, len(unsavedNodeAdditions), 1)
// Set key2
res, err = tree.Set([]byte(key2), []byte(testVal1))
require.NoError(t, err)
require.False(t, res)
unsavedNodeAdditions = tree.getUnsavedFastNodeAdditions()
require.Equal(t, len(unsavedNodeAdditions), 2)
// Set key3
res, err = tree.Set([]byte(key3), []byte(testVal1))
require.NoError(t, err)
require.False(t, res)
unsavedNodeAdditions = tree.getUnsavedFastNodeAdditions()
require.Equal(t, len(unsavedNodeAdditions), 3)
// Set key3 with new value
res, err = tree.Set([]byte(key3), []byte(testVal2))
require.NoError(t, err)
require.True(t, res)
unsavedNodeAdditions = tree.getUnsavedFastNodeAdditions()
require.Equal(t, len(unsavedNodeAdditions), 3)
// Remove key2
removedVal, isRemoved, err := tree.Remove([]byte(key2))
require.NoError(t, err)
require.True(t, isRemoved)
require.Equal(t, []byte(testVal1), removedVal)
unsavedNodeAdditions = tree.getUnsavedFastNodeAdditions()
require.Equal(t, len(unsavedNodeAdditions), 2)
unsavedNodeRemovals := tree.getUnsavedFastNodeRemovals()
require.Equal(t, len(unsavedNodeRemovals), 1)
// Save
_, _, err = tree.SaveVersion()
require.NoError(t, err)
unsavedNodeAdditions = tree.getUnsavedFastNodeAdditions()
require.Equal(t, len(unsavedNodeAdditions), 0)
unsavedNodeRemovals = tree.getUnsavedFastNodeRemovals()
require.Equal(t, len(unsavedNodeRemovals), 0)
// Load
t2 := NewMutableTree(mdb, 0, false, NewNopLogger())
_, err = t2.Load()
require.NoError(t, err)
// Get and GetFast
fastValue, err := t2.Get([]byte(key1))
require.NoError(t, err)
_, regularValue, err := tree.GetWithIndex([]byte(key1))
require.NoError(t, err)
require.Equal(t, []byte(testVal1), fastValue)
require.Equal(t, []byte(testVal1), regularValue)
fastValue, err = t2.Get([]byte(key2))
require.NoError(t, err)
_, regularValue, err = t2.GetWithIndex([]byte(key2))
require.NoError(t, err)
require.Nil(t, fastValue)
require.Nil(t, regularValue)
fastValue, err = t2.Get([]byte(key3))
require.NoError(t, err)
_, regularValue, err = tree.GetWithIndex([]byte(key3))
require.NoError(t, err)
require.Equal(t, []byte(testVal2), fastValue)
require.Equal(t, []byte(testVal2), regularValue)
}
func TestIterate_MutableTree_Unsaved(t *testing.T) {
tree, mirror := getRandomizedTreeAndMirror(t)
assertMutableMirrorIterate(t, tree, mirror)
}
func TestIterate_MutableTree_Saved(t *testing.T) {
tree, mirror := getRandomizedTreeAndMirror(t)
_, _, err := tree.SaveVersion()
require.NoError(t, err)
assertMutableMirrorIterate(t, tree, mirror)
}
func TestIterate_MutableTree_Unsaved_NextVersion(t *testing.T) {
tree, mirror := getRandomizedTreeAndMirror(t)
_, _, err := tree.SaveVersion()
require.NoError(t, err)
assertMutableMirrorIterate(t, tree, mirror)
randomizeTreeAndMirror(t, tree, mirror)
assertMutableMirrorIterate(t, tree, mirror)
}
func TestIterator_MutableTree_Invalid(t *testing.T) {
tree := getTestTree(0)
itr, err := tree.Iterator([]byte("a"), []byte("b"), true)
require.NoError(t, err)
require.NotNil(t, itr)
require.False(t, itr.Valid())
}
func TestUpgradeStorageToFast_LatestVersion_Success(t *testing.T) {
// Setup
db := dbm.NewMemDB()
tree := NewMutableTree(db, 1000, false, NewNopLogger())
// Default version when storage key does not exist in the db
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
require.NoError(t, err)
require.False(t, isFastCacheEnabled)
mirror := make(map[string]string)
// Fill with some data
randomizeTreeAndMirror(t, tree, mirror)
// Enable fast storage
isUpgradeable, err := tree.IsUpgradeable()
require.True(t, isUpgradeable)
require.NoError(t, err)
enabled, err := tree.enableFastStorageAndCommitIfNotEnabled()
require.NoError(t, err)
require.True(t, enabled)
isUpgradeable, err = tree.IsUpgradeable()
require.False(t, isUpgradeable)
require.NoError(t, err)
_, _, err = tree.SaveVersion()
require.NoError(t, err)
isFastCacheEnabled, err = tree.IsFastCacheEnabled()
require.NoError(t, err)
require.True(t, isFastCacheEnabled)
}
func TestUpgradeStorageToFast_AlreadyUpgraded_Success(t *testing.T) {
// Setup
db := dbm.NewMemDB()
tree := NewMutableTree(db, 1000, false, NewNopLogger())
// Default version when storage key does not exist in the db
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
require.NoError(t, err)
require.False(t, isFastCacheEnabled)
mirror := make(map[string]string)
// Fill with some data
randomizeTreeAndMirror(t, tree, mirror)
// Enable fast storage
isUpgradeable, err := tree.IsUpgradeable()
require.True(t, isUpgradeable)
require.NoError(t, err)
enabled, err := tree.enableFastStorageAndCommitIfNotEnabled()
require.NoError(t, err)
require.True(t, enabled)
isFastCacheEnabled, err = tree.IsFastCacheEnabled()
require.NoError(t, err)
require.True(t, isFastCacheEnabled)
isUpgradeable, err = tree.IsUpgradeable()
require.False(t, isUpgradeable)
require.NoError(t, err)
// Test enabling fast storage when already enabled
enabled, err = tree.enableFastStorageAndCommitIfNotEnabled()
require.NoError(t, err)
require.False(t, enabled)
isFastCacheEnabled, err = tree.IsFastCacheEnabled()
require.NoError(t, err)
require.True(t, isFastCacheEnabled)
}
func TestUpgradeStorageToFast_DbErrorConstructor_Failure(t *testing.T) {
ctrl := gomock.NewController(t)
dbMock := mock.NewMockDB(ctrl)
rIterMock := mock.NewMockIterator(ctrl)
// rIterMock is used to get the latest version from disk. We are mocking that rIterMock returns latestTreeVersion from disk
rIterMock.EXPECT().Valid().Return(true).Times(1)
rIterMock.EXPECT().Key().Return(nodeKeyFormat.Key(GetRootKey(1)))
rIterMock.EXPECT().Close().Return(nil).Times(1)
expectedError := errors.New("some db error")
dbMock.EXPECT().Get(gomock.Any()).Return(nil, expectedError).Times(1)
dbMock.EXPECT().NewBatchWithSize(gomock.Any()).Return(nil).Times(1)
dbMock.EXPECT().ReverseIterator(gomock.Any(), gomock.Any()).Return(rIterMock, nil).Times(1)
tree := NewMutableTree(dbMock, 0, false, NewNopLogger())
require.NotNil(t, tree)
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
require.NoError(t, err)
require.False(t, isFastCacheEnabled)
}
func TestUpgradeStorageToFast_DbErrorEnableFastStorage_Failure(t *testing.T) {
ctrl := gomock.NewController(t)
dbMock := mock.NewMockDB(ctrl)
rIterMock := mock.NewMockIterator(ctrl)
// rIterMock is used to get the latest version from disk. We are mocking that rIterMock returns latestTreeVersion from disk
rIterMock.EXPECT().Valid().Return(true).Times(1)
rIterMock.EXPECT().Key().Return(nodeKeyFormat.Key(GetRootKey(1)))
rIterMock.EXPECT().Close().Return(nil).Times(1)
expectedError := errors.New("some db error")
batchMock := mock.NewMockBatch(ctrl)
dbMock.EXPECT().Get(gomock.Any()).Return(nil, nil).Times(1)
dbMock.EXPECT().NewBatchWithSize(gomock.Any()).Return(batchMock).Times(1)
dbMock.EXPECT().ReverseIterator(gomock.Any(), gomock.Any()).Return(rIterMock, nil).Times(1)
iterMock := mock.NewMockIterator(ctrl)
dbMock.EXPECT().Iterator(gomock.Any(), gomock.Any()).Return(iterMock, nil)
iterMock.EXPECT().Error()
iterMock.EXPECT().Valid().Times(2)
iterMock.EXPECT().Close()
batchMock.EXPECT().Set(gomock.Any(), gomock.Any()).Return(expectedError).Times(1)
batchMock.EXPECT().GetByteSize().Return(100, nil).Times(1)
tree := NewMutableTree(dbMock, 0, false, NewNopLogger())
require.NotNil(t, tree)
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
require.NoError(t, err)
require.False(t, isFastCacheEnabled)
enabled, err := tree.enableFastStorageAndCommitIfNotEnabled()
require.ErrorIs(t, err, expectedError)
require.False(t, enabled)
isFastCacheEnabled, err = tree.IsFastCacheEnabled()
require.NoError(t, err)
require.False(t, isFastCacheEnabled)
}
func TestFastStorageReUpgradeProtection_NoForceUpgrade_Success(t *testing.T) {
ctrl := gomock.NewController(t)
dbMock := mock.NewMockDB(ctrl)
rIterMock := mock.NewMockIterator(ctrl)
// We are trying to test downgrade and re-upgrade protection
// We need to set up a state where latest fast storage version is equal to latest tree version
const latestFastStorageVersionOnDisk = 1
const latestTreeVersion = latestFastStorageVersionOnDisk
// Setup fake reverse iterator db to traverse root versions, called by ndb's getLatestVersion
expectedStorageVersion := []byte(fastStorageVersionValue + fastStorageVersionDelimiter + strconv.Itoa(latestFastStorageVersionOnDisk))
// rIterMock is used to get the latest version from disk. We are mocking that rIterMock returns latestTreeVersion from disk
rIterMock.EXPECT().Valid().Return(true).Times(1)
rIterMock.EXPECT().Key().Return(nodeKeyFormat.Key(GetRootKey(1)))
rIterMock.EXPECT().Close().Return(nil).Times(1)
batchMock := mock.NewMockBatch(ctrl)
dbMock.EXPECT().Get(gomock.Any()).Return(expectedStorageVersion, nil).Times(1)
dbMock.EXPECT().NewBatchWithSize(gomock.Any()).Return(batchMock).Times(1)
dbMock.EXPECT().ReverseIterator(gomock.Any(), gomock.Any()).Return(rIterMock, nil).Times(1) // called to get latest version
tree := NewMutableTree(dbMock, 0, false, NewNopLogger())
require.NotNil(t, tree)
// Pretend that we called Load and have the latest state in the tree
tree.version = latestTreeVersion
_, latestVersion, err := tree.ndb.getLatestVersion()
require.NoError(t, err)
require.Equal(t, latestVersion, int64(latestTreeVersion))
// Ensure that the right branch of enableFastStorageAndCommitIfNotEnabled will be triggered
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
require.NoError(t, err)
require.True(t, isFastCacheEnabled)
shouldForce, err := tree.ndb.shouldForceFastStorageUpgrade()
require.False(t, shouldForce)
require.NoError(t, err)
enabled, err := tree.enableFastStorageAndCommitIfNotEnabled()
require.NoError(t, err)
require.False(t, enabled)
}
func TestFastStorageReUpgradeProtection_ForceUpgradeFirstTime_NoForceSecondTime_Success(t *testing.T) {
ctrl := gomock.NewController(t)
dbMock := mock.NewMockDB(ctrl)
batchMock := mock.NewMockBatch(ctrl)
iterMock := mock.NewMockIterator(ctrl)
rIterMock := mock.NewMockIterator(ctrl)
// We are trying to test downgrade and re-upgrade protection
// We need to set up a state where latest fast storage version is of a lower version
// than tree version
const latestFastStorageVersionOnDisk = 1
const latestTreeVersion = latestFastStorageVersionOnDisk + 1
// Setup db for iterator and reverse iterator mocks
expectedStorageVersion := []byte(fastStorageVersionValue + fastStorageVersionDelimiter + strconv.Itoa(latestFastStorageVersionOnDisk))
// Setup fake reverse iterator db to traverse root versions, called by ndb's getLatestVersion
// rItr, err := db.ReverseIterator(rootKeyFormat.Key(1), rootKeyFormat.Key(latestTreeVersion + 1))
// require.NoError(t, err)
// dbMock represents the underlying database under the hood of nodeDB
dbMock.EXPECT().Get(gomock.Any()).Return(expectedStorageVersion, nil).Times(1)
dbMock.EXPECT().NewBatchWithSize(gomock.Any()).Return(batchMock).Times(2)
dbMock.EXPECT().ReverseIterator(gomock.Any(), gomock.Any()).Return(rIterMock, nil).Times(1) // called to get latest version
startFormat := fastKeyFormat.Key()
endFormat := fastKeyFormat.Key()
endFormat[0]++
dbMock.EXPECT().Iterator(startFormat, endFormat).Return(iterMock, nil).Times(1)
// rIterMock is used to get the latest version from disk. We are mocking that rIterMock returns latestTreeVersion from disk
rIterMock.EXPECT().Valid().Return(true).Times(1)
rIterMock.EXPECT().Key().Return(nodeKeyFormat.Key(GetRootKey(latestTreeVersion)))
rIterMock.EXPECT().Close().Return(nil).Times(1)
fastNodeKeyToDelete := []byte("some_key")
// batchMock represents a structure that receives all the updates related to
// upgrade and then commits them all in the end.
updatedExpectedStorageVersion := make([]byte, len(expectedStorageVersion))
copy(updatedExpectedStorageVersion, expectedStorageVersion)
updatedExpectedStorageVersion[len(updatedExpectedStorageVersion)-1]++
batchMock.EXPECT().GetByteSize().Return(100, nil).Times(2)
batchMock.EXPECT().Delete(fastKeyFormat.Key(fastNodeKeyToDelete)).Return(nil).Times(1)
batchMock.EXPECT().Set(metadataKeyFormat.Key([]byte(storageVersionKey)), updatedExpectedStorageVersion).Return(nil).Times(1)
batchMock.EXPECT().Write().Return(nil).Times(1)
batchMock.EXPECT().Close().Return(nil).Times(1)
// iterMock is used to mock the underlying db iterator behing fast iterator
// Here, we want to mock the behavior of deleting fast nodes from disk when
// force upgrade is detected.
iterMock.EXPECT().Valid().Return(true).Times(1)
iterMock.EXPECT().Error().Return(nil).Times(1)
iterMock.EXPECT().Key().Return(fastKeyFormat.Key(fastNodeKeyToDelete)).Times(1)
// encode value
var buf bytes.Buffer
testValue := "test_value"
buf.Grow(encoding.EncodeVarintSize(int64(latestFastStorageVersionOnDisk)) + encoding.EncodeBytesSize([]byte(testValue)))
err := encoding.EncodeVarint(&buf, int64(latestFastStorageVersionOnDisk))
require.NoError(t, err)
err = encoding.EncodeBytes(&buf, []byte(testValue))
require.NoError(t, err)
iterMock.EXPECT().Value().Return(buf.Bytes()).Times(1) // this is encoded as version 1 with value "2"
iterMock.EXPECT().Valid().Return(true).Times(1)
// Call Next at the end of loop iteration
iterMock.EXPECT().Next().Return().Times(1)
iterMock.EXPECT().Error().Return(nil).Times(1)
iterMock.EXPECT().Valid().Return(false).Times(1)
// Call Valid after first iteraton
iterMock.EXPECT().Valid().Return(false).Times(1)
iterMock.EXPECT().Close().Return(nil).Times(1)