-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathBucketListTests.cpp
More file actions
1875 lines (1687 loc) · 68.7 KB
/
BucketListTests.cpp
File metadata and controls
1875 lines (1687 loc) · 68.7 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
// Copyright 2019 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
// This file contains tests for the BucketList, and mid-level invariants
// concerning the sizes of levels in it, shadowing, the propagation and
// archival of entries as they move between levels, and so forth.
#include "bucket/BucketInputIterator.h"
#include "bucket/BucketManager.h"
#include "bucket/BucketOutputIterator.h"
#include "bucket/HotArchiveBucket.h"
#include "bucket/HotArchiveBucketList.h"
#include "bucket/LiveBucket.h"
#include "bucket/LiveBucketList.h"
#include "bucket/test/BucketTestUtils.h"
#include "crypto/Hex.h"
#include "ledger/LedgerStateSnapshot.h"
#include "ledger/LedgerTypeUtils.h"
#include "ledger/test/LedgerTestUtils.h"
#include "lib/util/stdrandom.h"
#include "main/Application.h"
#include "main/Config.h"
#include "test/TestUtils.h"
#include "test/test.h"
#include "util/Math.h"
#include "util/ProtocolVersion.h"
#include "util/Timer.h"
#include "util/UnorderedSet.h"
#include "xdr/Stellar-ledger.h"
#include <autocheck/generator.hpp>
#include <catch.hpp>
#include <deque>
#include <sstream>
using namespace stellar;
using namespace BucketTestUtils;
namespace BucketListTests
{
namespace
{
uint32_t
size(uint32_t level)
{
return 1 << (2 * (level + 1));
}
uint32_t
half(uint32_t level)
{
return size(level) >> 1;
}
uint32_t
prev(uint32_t level)
{
return size(level - 1);
}
uint32_t
lowBoundExclusive(uint32_t level, uint32_t ledger)
{
return roundDown(ledger, size(level));
}
uint32_t
highBoundInclusive(uint32_t level, uint32_t ledger)
{
return roundDown(ledger, prev(level));
}
void
checkBucketSizeAndBounds(LiveBucketList& bl, uint32_t ledgerSeq, uint32_t level,
bool isCurr)
{
std::shared_ptr<LiveBucket> bucket;
uint32_t sizeOfBucket = 0;
uint32_t oldestLedger = 0;
if (isCurr)
{
bucket = bl.getLevel(level).getCurr();
sizeOfBucket = LiveBucketList::sizeOfCurr(ledgerSeq, level);
oldestLedger = LiveBucketList::oldestLedgerInCurr(ledgerSeq, level);
}
else
{
bucket = bl.getLevel(level).getSnap();
sizeOfBucket = LiveBucketList::sizeOfSnap(ledgerSeq, level);
oldestLedger = LiveBucketList::oldestLedgerInSnap(ledgerSeq, level);
}
std::set<uint32_t> ledgers;
uint32_t lbound = std::numeric_limits<uint32_t>::max();
uint32_t ubound = 0;
for (LiveBucketInputIterator iter(bucket); iter; ++iter)
{
auto lastModified = (*iter).liveEntry().lastModifiedLedgerSeq;
ledgers.insert(lastModified);
lbound = std::min(lbound, lastModified);
ubound = std::max(ubound, lastModified);
}
REQUIRE(ledgers.size() == sizeOfBucket);
REQUIRE(lbound == oldestLedger);
if (ubound > 0)
{
REQUIRE(ubound == oldestLedger + sizeOfBucket - 1);
}
}
// If pred is false for ledger < L and true for ledger >= L then
// binarySearchForLedger will return L.
uint32_t
binarySearchForLedger(uint32_t lbound, uint32_t ubound,
std::function<uint32_t(uint32_t)> const& pred)
{
while (lbound + 1 != ubound)
{
uint32_t current = (lbound + ubound) / 2;
if (pred(current))
{
ubound = current;
}
else
{
lbound = current;
}
}
return ubound;
}
} // namespace
} // namespace BucketListTests
using namespace BucketListTests;
template <class BucketListT>
static void
basicBucketListTest()
{
VirtualClock clock;
Config const& cfg = getTestConfig();
auto test = [&](Config const& cfg) {
try
{
Application::pointer app = createTestApplication(clock, cfg);
BucketListT bl;
CLOG_DEBUG(Bucket, "Adding batches to bucket list");
UnorderedSet<LedgerKey> seenKeys;
for (uint32_t i = 1;
!app->getClock().getIOContext().stopped() && i < 130; ++i)
{
app->getClock().crank(false);
if constexpr (std::is_same_v<BucketListT, LiveBucketList>)
{
bl.addBatch(
*app, i, getAppLedgerVersion(app), {},
LedgerTestUtils::
generateValidUniqueLedgerEntriesWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE,
TTL},
8),
LedgerTestUtils::
generateValidLedgerEntryKeysWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE,
TTL},
5));
}
else
{
bl.addBatch(
*app, i, getAppLedgerVersion(app),
LedgerTestUtils::generateUniquePersistentLedgerEntries(
8, seenKeys),
LedgerTestUtils::generateUniquePersistentLedgerKeys(
5, seenKeys));
}
if (i % 10 == 0)
CLOG_DEBUG(Bucket, "Added batch {}, hash={}", i,
binToHex(bl.getHash()));
for (uint32_t j = 0; j < BucketListT::kNumLevels; ++j)
{
auto const& lev = bl.getLevel(j);
auto currSz = countEntries(lev.getCurr());
auto snapSz = countEntries(lev.getSnap());
CHECK(currSz <= BucketListT::levelHalf(j) * 100);
CHECK(snapSz <= BucketListT::levelHalf(j) * 100);
}
}
}
catch (std::future_error& e)
{
CLOG_DEBUG(Bucket, "Test caught std::future_error {}: {}",
e.code().value(), e.what());
REQUIRE(false);
}
};
if constexpr (std::is_same_v<BucketListT, LiveBucketList>)
{
for_versions_with_differing_bucket_logic(cfg, test);
}
else
{
for_versions_from(23, cfg, test);
}
}
TEST_CASE_VERSIONS("bucket list", "[bucket][bucketlist]")
{
SECTION("live bl")
{
basicBucketListTest<LiveBucketList>();
}
SECTION("hot archive bl")
{
basicBucketListTest<HotArchiveBucketList>();
}
}
template <class BucketListT>
static void
updatePeriodTest()
{
std::map<uint32_t, uint32_t> currCalculatedUpdatePeriods;
std::map<uint32_t, uint32_t> snapCalculatedUpdatePeriods;
for (uint32_t i = 0; i < BucketListT::kNumLevels; ++i)
{
currCalculatedUpdatePeriods.emplace(
i, BucketListT::bucketUpdatePeriod(i, /*isCurr=*/true));
// Last level has no snap
if (i != BucketListT::kNumLevels - 1)
{
snapCalculatedUpdatePeriods.emplace(
i, BucketListT::bucketUpdatePeriod(i, /*isSnap=*/false));
}
}
// Artificially "close" ledgers until we've checked all update periods
for (uint32_t ledgerSeq = 1; !currCalculatedUpdatePeriods.empty() ||
!snapCalculatedUpdatePeriods.empty();
++ledgerSeq)
{
for (uint32_t level = 0; level < BucketListT::kNumLevels; ++level)
{
// Check if curr bucket is updated
auto currIter = currCalculatedUpdatePeriods.find(level);
if (currIter != currCalculatedUpdatePeriods.end())
{
// Level 0 curr bucket is updated every ledger
if (level == 0)
{
REQUIRE(currIter->second == ledgerSeq);
currCalculatedUpdatePeriods.erase(currIter);
}
else
{
// For all other levels, an update occurs when the level
// above spills
if (BucketListT::levelShouldSpill(ledgerSeq, level - 1))
{
REQUIRE(currIter->second == ledgerSeq);
currCalculatedUpdatePeriods.erase(currIter);
}
}
}
// Check if snap is updated
auto snapIter = snapCalculatedUpdatePeriods.find(level);
if (snapIter != snapCalculatedUpdatePeriods.end())
{
if (BucketListT::levelShouldSpill(ledgerSeq, level))
{
// Check that snap bucket calculation is correct
REQUIRE(snapIter->second == ledgerSeq);
snapCalculatedUpdatePeriods.erase(snapIter);
}
}
}
}
}
TEST_CASE("bucketUpdatePeriod arithmetic", "[bucket][bucketlist]")
{
SECTION("live bl")
{
updatePeriodTest<LiveBucketList>();
}
SECTION("hot archive bl")
{
updatePeriodTest<HotArchiveBucketList>();
}
}
TEST_CASE_VERSIONS("bucket list shadowing pre/post proto 12",
"[bucket][bucketlist]")
{
VirtualClock clock;
Config const& cfg = getTestConfig();
for_versions_with_differing_bucket_logic(cfg, [&](Config const& cfg) {
Application::pointer app = createTestApplication(clock, cfg);
LiveBucketList bl;
// Alice and Bob change in every iteration.
auto alice = LedgerTestUtils::generateValidAccountEntry(5);
auto bob = LedgerTestUtils::generateValidAccountEntry(5);
CLOG_DEBUG(Bucket, "Adding batches to bucket list");
uint32_t const totalNumEntries = 1200;
for (uint32_t i = 1;
!app->getClock().getIOContext().stopped() && i <= totalNumEntries;
++i)
{
app->getClock().crank(false);
auto liveBatch =
LedgerTestUtils::generateValidUniqueLedgerEntriesWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL}, 5);
BucketEntry BucketEntryAlice, BucketEntryBob;
alice.balance++;
BucketEntryAlice.type(LIVEENTRY);
BucketEntryAlice.liveEntry().data.type(ACCOUNT);
BucketEntryAlice.liveEntry().data.account() = alice;
liveBatch.push_back(BucketEntryAlice.liveEntry());
bob.balance++;
BucketEntryBob.type(LIVEENTRY);
BucketEntryBob.liveEntry().data.type(ACCOUNT);
BucketEntryBob.liveEntry().data.account() = bob;
liveBatch.push_back(BucketEntryBob.liveEntry());
bl.addBatch(
*app, i, getAppLedgerVersion(app), {}, liveBatch,
LedgerTestUtils::
generateValidUniqueLedgerEntryKeysWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL},
5));
if (i % 100 == 0)
{
CLOG_DEBUG(Bucket, "Added batch {}, hash={}", i,
binToHex(bl.getHash()));
// Alice and bob should be in either curr or snap of level 0
// and 1
for (uint32_t j = 0; j < 2; ++j)
{
auto const& lev = bl.getLevel(j);
auto curr = lev.getCurr();
auto snap = lev.getSnap();
bool hasAlice =
(curr->containsBucketIdentity(BucketEntryAlice) ||
snap->containsBucketIdentity(BucketEntryAlice));
bool hasBob =
(curr->containsBucketIdentity(BucketEntryBob) ||
snap->containsBucketIdentity(BucketEntryBob));
CHECK(hasAlice);
CHECK(hasBob);
}
// Alice and Bob should never occur in level 2 .. N because they
// were shadowed in level 0 continuously.
for (uint32_t j = 2; j < LiveBucketList::kNumLevels; ++j)
{
auto const& lev = bl.getLevel(j);
auto curr = lev.getCurr();
auto snap = lev.getSnap();
bool hasAlice =
(curr->containsBucketIdentity(BucketEntryAlice) ||
snap->containsBucketIdentity(BucketEntryAlice));
bool hasBob =
(curr->containsBucketIdentity(BucketEntryBob) ||
snap->containsBucketIdentity(BucketEntryBob));
if (protocolVersionIsBefore(
app->getConfig().LEDGER_PROTOCOL_VERSION,
LiveBucket::FIRST_PROTOCOL_SHADOWS_REMOVED) ||
j > 5)
{
CHECK(!hasAlice);
CHECK(!hasBob);
}
// On the last iteration, when bucket list population is
// complete, ensure that post-FIRST_PROTOCOL_SHADOWS_REMOVED
// Alice and Bob appear on lower levels unshadowed.
else if (i == totalNumEntries)
{
CHECK(hasAlice);
CHECK(hasBob);
}
}
}
}
});
}
TEST_CASE_VERSIONS("hot archive bucket tombstones expire at bottom level",
"[bucket][bucketlist][tombstones]")
{
VirtualClock clock;
Config const& cfg = getTestConfig();
testutil::BucketListDepthModifier<HotArchiveBucket> bldm(5);
auto app = createTestApplication(clock, cfg);
for_versions_from(23, *app, [&] {
HotArchiveBucketList bl;
auto lastSnapSize = [&] {
auto& level = bl.getLevel(HotArchiveBucketList::kNumLevels - 2);
return countEntries(level.getSnap());
};
auto countNonBottomLevelEntries = [&] {
auto size = 0;
for (uint32_t i = 0; i < HotArchiveBucketList::kNumLevels - 1; ++i)
{
auto& level = bl.getLevel(i);
size += countEntries(level.getCurr());
size += countEntries(level.getSnap());
}
return size;
};
// Populate a BucketList so everything but the bottom level is full.
UnorderedSet<LedgerKey> keys;
auto numExpectedEntries = 0;
auto ledger = 1;
while (lastSnapSize() == 0)
{
bl.addBatch(
*app, ledger, getAppLedgerVersion(app),
LedgerTestUtils::generateUniquePersistentLedgerEntries(5, keys),
LedgerTestUtils::generateUniquePersistentLedgerKeys(5, keys));
// Once all entries merge to the bottom level, only deleted entries
// should remain
numExpectedEntries += 5;
++ledger;
}
// Close ledgers until all entries have merged into the bottom level
// bucket
while (countNonBottomLevelEntries() != 0)
{
bl.addBatch(*app, ledger, getAppLedgerVersion(app), {}, {});
++ledger;
}
auto bottomCurr =
bl.getLevel(HotArchiveBucketList::kNumLevels - 1).getCurr();
REQUIRE(countEntries(bottomCurr) == numExpectedEntries);
for (HotArchiveBucketInputIterator iter(bottomCurr); iter; ++iter)
{
auto be = *iter;
REQUIRE(be.type() == HOT_ARCHIVE_ARCHIVED);
REQUIRE(keys.find(LedgerEntryKey(be.archivedEntry())) !=
keys.end());
}
});
}
TEST_CASE("hot archive accepts multiple archives and restores for same key",
"[bucket][bucketlist][tombstones]")
{
testutil::BucketListDepthModifier<HotArchiveBucket> bldm(3);
VirtualClock clock;
Config const& cfg = getTestConfig();
Application::pointer app = createTestApplication(clock, cfg);
HotArchiveBucketList bl;
BucketManager& bm = app->getBucketManager();
// This tests simulates an entry that is archived, restored, then becomes
// archived again for Hot Archive Merges. We'll populate the BucketList
// such that a LedgerKey was originally archived with value archivedEntryV0,
// was restored, and then was archived again with value archivedEntryV1.
LedgerEntry archivedEntryV0 =
LedgerTestUtils::generateValidLedgerEntryOfType(CONTRACT_CODE);
LedgerEntry archivedEntryV1 = archivedEntryV0;
archivedEntryV1.lastModifiedLedgerSeq += 10;
auto& firstLevel = bl.getLevel(0);
firstLevel.setCurr(HotArchiveBucket::fresh(
bm, getAppLedgerVersion(app), {archivedEntryV1}, {},
/*countMergeEvents=*/true, clock.getIOContext(),
/*doFsync=*/true));
firstLevel.setSnap(HotArchiveBucket::fresh(
bm, getAppLedgerVersion(app), {}, {LedgerEntryKey(archivedEntryV0)},
/*countMergeEvents=*/true, clock.getIOContext(),
/*doFsync=*/true));
auto& lastLevel = bl.getLevel(HotArchiveBucketList::kNumLevels - 1);
lastLevel.setCurr(HotArchiveBucket::fresh(
bm, getAppLedgerVersion(app), {archivedEntryV0}, {},
/*countMergeEvents=*/true, clock.getIOContext(),
/*doFsync=*/true));
auto lastBucketHasNewVersion = [&]() {
auto b = bl.getLevel(HotArchiveBucketList::kNumLevels - 1).getCurr();
for (HotArchiveBucketInputIterator iter(b); iter; ++iter)
{
auto be = *iter;
if (be.type() == HOT_ARCHIVE_ARCHIVED)
{
auto archivedEntry = be.archivedEntry();
if (archivedEntry == archivedEntryV1)
{
return true;
}
}
}
return false;
};
// Close ledgers until the newest version of the entry merges and overrides
// the older archived version and the restore.
bool newestValueMerged = false;
for (uint32_t ledgerSeq = 1; ledgerSeq < 1000; ++ledgerSeq)
{
bl.addBatch(*app, ledgerSeq, getAppLedgerVersion(app), {}, {});
if (lastBucketHasNewVersion())
{
newestValueMerged = true;
break;
}
}
REQUIRE(newestValueMerged);
}
TEST_CASE_VERSIONS("live bucket tombstones expire at bottom level",
"[bucket][bucketlist][tombstones]")
{
VirtualClock clock;
Config const& cfg = getTestConfig();
for_versions_with_differing_bucket_logic(cfg, [&](Config const& cfg) {
Application::pointer app = createTestApplication(clock, cfg);
LiveBucketList bl;
BucketManager& bm = app->getBucketManager();
auto& mergeTimer = bm.getMergeTimer();
CLOG_INFO(Bucket, "Establishing random bucketlist");
for (uint32_t i = 0; i < LiveBucketList::kNumLevels; ++i)
{
auto& level = bl.getLevel(i);
level.setCurr(LiveBucket::fresh(
bm, getAppLedgerVersion(app), {},
LedgerTestUtils::generateValidUniqueLedgerEntriesWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL}, 8),
LedgerTestUtils::
generateValidUniqueLedgerEntryKeysWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL}, 5),
/*countMergeEvents=*/true, clock.getIOContext(),
/*doFsync=*/true));
level.setSnap(LiveBucket::fresh(
bm, getAppLedgerVersion(app), {},
LedgerTestUtils::generateValidUniqueLedgerEntriesWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL}, 8),
LedgerTestUtils::
generateValidUniqueLedgerEntryKeysWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL}, 5),
/*countMergeEvents=*/true, clock.getIOContext(),
/*doFsync=*/true));
}
for (uint32_t i = 0; i < LiveBucketList::kNumLevels; ++i)
{
std::vector<uint32_t> ledgers = {LiveBucketList::levelHalf(i),
LiveBucketList::levelSize(i)};
for (auto j : ledgers)
{
auto n = mergeTimer.count();
bl.addBatch(
*app, j, getAppLedgerVersion(app), {},
LedgerTestUtils::
generateValidUniqueLedgerEntriesWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL},
8),
LedgerTestUtils::
generateValidUniqueLedgerEntryKeysWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL},
5));
app->getClock().crank(false);
for (uint32_t k = 0u; k < LiveBucketList::kNumLevels; ++k)
{
auto& next = bl.getLevel(k).getNext();
if (next.isLive())
{
next.resolve();
}
}
n = mergeTimer.count() - n;
CLOG_INFO(Bucket,
"Added batch at ledger {}, merges provoked: {}", j,
n);
REQUIRE(n > 0);
REQUIRE(n < 2 * LiveBucketList::kNumLevels);
}
}
EntryCounts e0(bl.getLevel(LiveBucketList::kNumLevels - 3).getCurr());
EntryCounts e1(bl.getLevel(LiveBucketList::kNumLevels - 2).getCurr());
EntryCounts e2(bl.getLevel(LiveBucketList::kNumLevels - 1).getCurr());
REQUIRE(e0.nDead != 0);
REQUIRE(e1.nDead != 0);
REQUIRE(e2.nDead == 0);
});
}
TEST_CASE_VERSIONS("bucket tombstones mutually-annihilate init entries",
"[bucket][bucketlist][bl-initentry]")
{
VirtualClock clock;
Config const& cfg = getTestConfig();
for_versions_with_differing_bucket_logic(cfg, [&](Config const& cfg) {
Application::pointer app = createTestApplication(clock, cfg);
LiveBucketList bl;
auto vers = getAppLedgerVersion(app);
autocheck::generator<bool> flip;
std::deque<LedgerEntry> entriesToModify;
for (uint32_t i = 1; i < 512; ++i)
{
std::vector<LedgerEntry> initEntries =
LedgerTestUtils::generateValidLedgerEntriesWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL}, 8);
std::vector<LedgerEntry> liveEntries;
std::vector<LedgerKey> deadEntries;
for (auto const& e : initEntries)
{
entriesToModify.push_back(e);
}
while (entriesToModify.size() > 100)
{
LedgerEntry e = entriesToModify.front();
entriesToModify.pop_front();
if (flip())
{
// Entry will survive another round of the
// queue.
if (flip())
{
// Entry will be changed before re-enqueueing.
LedgerTestUtils::randomlyModifyEntry(e);
liveEntries.push_back(e);
}
entriesToModify.push_back(e);
}
else
{
// Entry will die.
deadEntries.push_back(LedgerEntryKey(e));
}
}
bl.addBatch(*app, i, vers, initEntries, liveEntries, deadEntries);
app->getClock().crank(false);
for (uint32_t k = 0u; k < LiveBucketList::kNumLevels; ++k)
{
auto& next = bl.getLevel(k).getNext();
if (next.isLive())
{
next.resolve();
}
}
}
for (uint32_t k = 0u; k < LiveBucketList::kNumLevels; ++k)
{
auto const& lev = bl.getLevel(k);
auto currSz = countEntries(lev.getCurr());
auto snapSz = countEntries(lev.getSnap());
if (protocolVersionStartsFrom(
cfg.LEDGER_PROTOCOL_VERSION,
LiveBucket::
FIRST_PROTOCOL_SUPPORTING_INITENTRY_AND_METAENTRY))
{
// init/dead pairs should mutually-annihilate pretty readily as
// they go, empirically this test peaks at buckets around 600
// entries.
REQUIRE((currSz + snapSz) < 700);
}
CLOG_INFO(Bucket, "Level {} size: {}", k, (currSz + snapSz));
}
});
}
TEST_CASE_VERSIONS("single entry bubbling up",
"[bucket][bucketlist][bucketbubble]")
{
VirtualClock clock;
Config const& cfg = getTestConfig();
try
{
for_versions_with_differing_bucket_logic(cfg, [&](Config const& cfg) {
Application::pointer app = createTestApplication(clock, cfg);
LiveBucketList bl;
std::vector<stellar::LedgerKey> emptySet;
std::vector<stellar::LedgerEntry> emptySetEntry;
CLOG_DEBUG(Bucket, "Adding single entry in lowest level");
bl.addBatch(
*app, 1, getAppLedgerVersion(app), {},
LedgerTestUtils::generateValidLedgerEntriesWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL}, 1),
emptySet);
CLOG_DEBUG(Bucket, "Adding empty batches to bucket list");
for (uint32_t i = 2;
!app->getClock().getIOContext().stopped() && i < 300; ++i)
{
app->getClock().crank(false);
bl.addBatch(*app, i, getAppLedgerVersion(app), {},
emptySetEntry, emptySet);
if (i % 10 == 0)
CLOG_DEBUG(Bucket, "Added batch {}, hash={}", i,
binToHex(bl.getHash()));
CLOG_DEBUG(Bucket, "------- ledger {}", i);
for (uint32_t j = 0; j <= LiveBucketList::kNumLevels - 1; ++j)
{
uint32_t lb = lowBoundExclusive(j, i);
uint32_t hb = highBoundInclusive(j, i);
auto const& lev = bl.getLevel(j);
auto currSz = countEntries(lev.getCurr());
auto snapSz = countEntries(lev.getSnap());
CLOG_DEBUG(Bucket, "ledger {}, level {} curr={} snap={}", i,
j, currSz, snapSz);
if (1 > lb && 1 <= hb)
{
REQUIRE((currSz + snapSz) == 1);
}
else
{
REQUIRE(currSz == 0);
REQUIRE(snapSz == 0);
}
}
}
});
}
catch (std::future_error& e)
{
CLOG_DEBUG(Bucket, "Test caught std::future_error {}: {}",
e.code().value(), e.what());
REQUIRE(false);
}
}
template <class BucketListT>
static void
sizeOfTests()
{
stellar::uniform_int_distribution<uint32_t> dist;
for (uint32_t i = 0; i < 1000; ++i)
{
for (uint32_t level = 0; level < BucketListT::kNumLevels; ++level)
{
uint32_t ledger = dist(getGlobalRandomEngine());
if (BucketListT::sizeOfSnap(ledger, level) > 0)
{
uint32_t oldestInCurr =
BucketListT::oldestLedgerInSnap(ledger, level) +
BucketListT::sizeOfSnap(ledger, level);
REQUIRE(oldestInCurr ==
BucketListT::oldestLedgerInCurr(ledger, level));
}
if (BucketListT::sizeOfCurr(ledger, level) > 0)
{
uint32_t newestInCurr =
BucketListT::oldestLedgerInCurr(ledger, level) +
BucketListT::sizeOfCurr(ledger, level) - 1;
REQUIRE(newestInCurr == (level == 0
? ledger
: BucketListT::oldestLedgerInSnap(
ledger, level - 1) -
1));
}
}
}
}
TEST_CASE("BucketList sizeOf and oldestLedgerIn relations",
"[bucket][bucketlist][count]")
{
SECTION("live bl")
{
sizeOfTests<LiveBucketList>();
}
SECTION("hot archive bl")
{
sizeOfTests<HotArchiveBucketList>();
}
}
template <class BucketListT>
static void
snapSteadyStateTest()
{
// Deliberately exclude deepest level since snap on the deepest level
// is always empty.
for (uint32_t level = 0; level < BucketListT::kNumLevels - 1; ++level)
{
uint32_t const half = BucketListT::levelHalf(level);
// Use binary search (assuming that it does reach steady state)
// to find the ledger where the snap at this level first reaches
// max size.
uint32_t boundary = binarySearchForLedger(
1, std::numeric_limits<uint32_t>::max() / 2,
[level, half](uint32_t ledger) {
return (BucketListT::sizeOfSnap(ledger, level) == half);
});
// Generate random ledgers above and below the split to test that
// it was actually at steady state.
stellar::uniform_int_distribution<uint32_t> distLow(1, boundary - 1);
stellar::uniform_int_distribution<uint32_t> distHigh(boundary);
for (uint32_t i = 0; i < 1000; ++i)
{
uint32_t low = distLow(getGlobalRandomEngine());
uint32_t high = distHigh(getGlobalRandomEngine());
REQUIRE(BucketListT::sizeOfSnap(low, level) < half);
REQUIRE(BucketListT::sizeOfSnap(high, level) == half);
}
}
}
TEST_CASE("BucketList snap reaches steady state", "[bucket][bucketlist][count]")
{
SECTION("live bl")
{
snapSteadyStateTest<LiveBucketList>();
}
SECTION("hot archive bl")
{
snapSteadyStateTest<HotArchiveBucketList>();
}
}
template <class BucketListT>
static void
deepestCurrTest()
{
uint32_t const deepest = BucketListT::kNumLevels - 1;
// Use binary search to find the first ledger where the deepest curr
// first is non-empty.
uint32_t boundary = binarySearchForLedger(
1, std::numeric_limits<uint32_t>::max() / 2,
[deepest](uint32_t ledger) {
return (BucketListT::sizeOfCurr(ledger, deepest) > 0);
});
stellar::uniform_int_distribution<uint32_t> distLow(1, boundary - 1);
stellar::uniform_int_distribution<uint32_t> distHigh(boundary);
for (uint32_t i = 0; i < 1000; ++i)
{
uint32_t low = distLow(getGlobalRandomEngine());
uint32_t high = distHigh(getGlobalRandomEngine());
REQUIRE(BucketListT::sizeOfCurr(low, deepest) == 0);
REQUIRE(BucketListT::oldestLedgerInCurr(low, deepest) ==
std::numeric_limits<uint32_t>::max());
REQUIRE(BucketListT::sizeOfCurr(high, deepest) > 0);
REQUIRE(BucketListT::oldestLedgerInCurr(high, deepest) == 1);
REQUIRE(BucketListT::sizeOfSnap(low, deepest) == 0);
REQUIRE(BucketListT::oldestLedgerInSnap(low, deepest) ==
std::numeric_limits<uint32_t>::max());
REQUIRE(BucketListT::sizeOfSnap(high, deepest) == 0);
REQUIRE(BucketListT::oldestLedgerInSnap(high, deepest) ==
std::numeric_limits<uint32_t>::max());
}
}
TEST_CASE("BucketList deepest curr accumulates", "[bucket][bucketlist][count]")
{
SECTION("live bl")
{
deepestCurrTest<LiveBucketList>();
}
SECTION("hot archive bl")
{
deepestCurrTest<HotArchiveBucketList>();
}
}
template <class BucketListT>
static void
blSizesAtLedger1Test()
{
REQUIRE(BucketListT::sizeOfCurr(1, 0) == 1);
REQUIRE(BucketListT::sizeOfSnap(1, 0) == 0);
for (uint32_t level = 1; level < BucketListT::kNumLevels; ++level)
{
REQUIRE(BucketListT::sizeOfCurr(1, level) == 0);
REQUIRE(BucketListT::sizeOfSnap(1, level) == 0);
}
}
TEST_CASE("BucketList sizes at ledger 1", "[bucket][bucketlist][count]")
{
SECTION("live bl")
{
blSizesAtLedger1Test<LiveBucketList>();
}
SECTION("hot archive bl")
{
blSizesAtLedger1Test<HotArchiveBucketList>();
}
}
TEST_CASE("BucketList check bucket sizes", "[bucket][bucketlist][count]")
{
VirtualClock clock;
Config cfg(getTestConfig());
Application::pointer app = createTestApplication(clock, cfg);
LiveBucketList& bl = app->getBucketManager().getLiveBucketList();
std::vector<LedgerKey> emptySet;
auto ledgers =
LedgerTestUtils::generateValidUniqueLedgerEntriesWithExclusions(
{CONFIG_SETTING, CONTRACT_DATA, CONTRACT_CODE, TTL}, 256);
for (uint32_t ledgerSeq = 1; ledgerSeq <= 256; ++ledgerSeq)
{
if (ledgerSeq >= 2)
{
app->getClock().crank(false);
ledgers[ledgerSeq - 1].lastModifiedLedgerSeq = ledgerSeq;
auto lh =
app->getLedgerManager().getLastClosedLedgerHeader().header;
lh.ledgerSeq = ledgerSeq;
addLiveBatchAndUpdateSnapshot(*app, lh, {},
{ledgers[ledgerSeq - 1]}, emptySet);
}
for (uint32_t level = 0; level < LiveBucketList::kNumLevels; ++level)
{
checkBucketSizeAndBounds(bl, ledgerSeq, level, true);
checkBucketSizeAndBounds(bl, ledgerSeq, level, false);
}
}
}
TEST_CASE_VERSIONS("network config snapshots Soroban state size", "[soroban]")
{
VirtualClock clock;
// TODO(https://github.com/stellar/stellar-core/issues/4816): We should
// be using the default DB mode here, and also update the window size to
// make sure the upgrades work correctly.
Config cfg(getTestConfig(0, Config::TestDbMode::TESTDB_IN_MEMORY));
cfg.USE_CONFIG_FOR_GENESIS = true;
auto app = createTestApplication<BucketTestApplication>(clock, cfg);
for_versions_from(20, *app, [&] {
LedgerManagerForBucketTests& lm = app->getLedgerManager();
auto networkConfig = [&]() {
return app->getLedgerManager().getLastClosedSorobanNetworkConfig();
};
// Take snapshots more frequently for faster testing.
modifySorobanNetworkConfig(*app, [](SorobanNetworkConfig& cfg) {
cfg.mStateArchivalSettings.liveSorobanStateSizeWindowSamplePeriod =
7;
});
uint32_t windowSize = networkConfig()
.stateArchivalSettings()
.liveSorobanStateSizeWindowSampleSize;
std::deque<uint64_t> correctWindow;
for (auto i = 0u; i < windowSize; ++i)
{
correctWindow.push_back(0);
}
auto check = [&](bool init = false) {
// Check in-memory average from BucketManager
uint64_t sum = 0;
for (int i = 0; i < correctWindow.size(); ++i)
{
// Ensure that we're actually increasing the state size.
if (i < correctWindow.size() - 1 && correctWindow[i] != 0)
{
REQUIRE(correctWindow[i] < correctWindow[i + 1]);
}
sum += correctWindow[i];
}
uint64_t correctAverage = sum / correctWindow.size();
if (!init)
{
REQUIRE(correctAverage > 0);
}