Skip to content

Commit e6d4a41

Browse files
committed
Implement loser-tree merging for populating in-memory soroban state
1 parent 8a71e20 commit e6d4a41

7 files changed

Lines changed: 319 additions & 63 deletions

File tree

‎src/bucket/BucketListSnapshot.cpp‎

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -708,6 +708,198 @@ SearchableLiveBucketListSnapshot::scanForEntriesOfType(
708708
loopAllBuckets(scanBucket);
709709
}
710710

711+
namespace
712+
{
713+
// Iterator for `BucketEntry`s of a given type in a bucket. Expects the stream
714+
// to be positioned at the start of the type range.
715+
class BucketEntryIterator
716+
{
717+
BucketEntry mEntry;
718+
LedgerKey mKey;
719+
XDRInputFileStream& mStream;
720+
LedgerEntryType const mType;
721+
722+
public:
723+
BucketEntryIterator(XDRInputFileStream& stream, LedgerEntryType type)
724+
: mStream(stream), mType(type)
725+
{
726+
}
727+
728+
BucketEntry const&
729+
getEntry() const
730+
{
731+
return mEntry;
732+
}
733+
LedgerKey const&
734+
getKey() const
735+
{
736+
return mKey;
737+
}
738+
bool advance();
739+
};
740+
741+
bool
742+
BucketEntryIterator::advance()
743+
{
744+
while (mStream.readOne(mEntry))
745+
{
746+
if (isBucketMetaEntry<LiveBucket>(mEntry))
747+
{
748+
continue;
749+
}
750+
mKey = getBucketLedgerKey(mEntry);
751+
if (mKey.type() > mType)
752+
{
753+
break;
754+
}
755+
756+
auto type = mEntry.type();
757+
releaseAssert(type == LIVEENTRY || type == INITENTRY ||
758+
type == DEADENTRY);
759+
return true;
760+
}
761+
return false;
762+
}
763+
} // namespace
764+
765+
void
766+
SearchableLiveBucketListSnapshot::scanForLiveEntriesOfType(
767+
LedgerEntryType type,
768+
std::function<void(LedgerEntry const&, LedgerKey const&)> callback) const
769+
{
770+
// We implement this as a k-way merge over all buckets. We use a loser tree
771+
// for this. The benefit over a heap is ~2x fewer comparisons. A loser tree
772+
// is like a single-elimination tournament. The leaves of the tree are the
773+
// iterators, and the internal nodes represent the loser of the comparison
774+
// between the two children. This implementation represents the binary tree
775+
// in an array, where the tournament tree is from indices [1, 2n) (leaves
776+
// are [n, 2n)). Index 0 is used for keeping track of the overall winner. To
777+
// update, we just need to advance the iterator for the winning node and
778+
// then do the log(k) comparisons upward along the path to the root to
779+
// update the losers. While loser trees often store the whole node value at
780+
// intermediate nodes, we just store an index, since copying the XDR types
781+
// is probably more expensive than the extra indirection.
782+
783+
std::vector<BucketEntryIterator> iterators;
784+
loopAllBuckets([&iterators, type,
785+
this](std::shared_ptr<LiveBucket const> const& bucket) {
786+
if (bucket->isEmpty())
787+
{
788+
return Loop::INCOMPLETE;
789+
}
790+
791+
auto range = bucket->getRangeForType(type);
792+
if (!range)
793+
{
794+
return Loop::INCOMPLETE;
795+
}
796+
797+
auto& stream = getStream(bucket);
798+
stream.seek(range->first);
799+
800+
iterators.emplace_back(stream, type);
801+
return Loop::INCOMPLETE;
802+
});
803+
804+
if (iterators.empty())
805+
{
806+
return;
807+
}
808+
809+
size_t const numIterators = iterators.size();
810+
811+
constexpr int exhausted = -1;
812+
std::vector<int> tree;
813+
tree.resize(numIterators * 2);
814+
for (size_t i = 0; i < numIterators; ++i)
815+
{
816+
if (iterators[i].advance())
817+
{
818+
tree[numIterators + i] = i;
819+
}
820+
else
821+
{
822+
tree[numIterators + i] = exhausted;
823+
}
824+
}
825+
826+
auto leftWins = [&iterators](int leftIndex, int rightIndex) -> bool {
827+
if (leftIndex == exhausted)
828+
{
829+
return false;
830+
}
831+
if (rightIndex == exhausted)
832+
{
833+
return true;
834+
}
835+
if (auto cmp = compareLedgerKeys(iterators[leftIndex].getKey(),
836+
iterators[rightIndex].getKey());
837+
cmp != std::partial_ordering::equivalent)
838+
{
839+
releaseAssert(cmp != std::partial_ordering::unordered);
840+
return cmp == std::partial_ordering::less;
841+
}
842+
return leftIndex < rightIndex;
843+
};
844+
845+
// Play the match at index i; store the loser, return the winner
846+
auto play = [&tree, &leftWins](auto& play, size_t index) -> int {
847+
if (2 * index >= tree.size())
848+
{
849+
return tree[index];
850+
}
851+
int left = play(play, 2 * index);
852+
int right = play(play, 2 * index + 1);
853+
if (leftWins(left, right))
854+
{
855+
tree[index] = right;
856+
return left;
857+
}
858+
else
859+
{
860+
tree[index] = left;
861+
return right;
862+
}
863+
};
864+
tree[0] = play(play, 1);
865+
866+
bool first = true;
867+
LedgerKey last;
868+
while (tree[0] != exhausted)
869+
{
870+
int index = tree[0];
871+
auto& iter = iterators[index];
872+
if (auto& key = iter.getKey(); first || key != last)
873+
{
874+
last = key;
875+
auto& entry = iter.getEntry();
876+
if (entry.type() == LIVEENTRY || entry.type() == INITENTRY)
877+
{
878+
callback(entry.liveEntry(), key);
879+
}
880+
}
881+
first = false;
882+
883+
if (!iter.advance())
884+
{
885+
tree[index + numIterators] = exhausted;
886+
}
887+
int winner = tree[index + numIterators];
888+
889+
int i = (index + numIterators) / 2;
890+
while (i > 0)
891+
{
892+
if (leftWins(tree[i], winner))
893+
{
894+
std::swap(tree[i], winner);
895+
}
896+
i /= 2;
897+
}
898+
899+
tree[0] = winner;
900+
}
901+
}
902+
711903
// Helper function to handle scan logic in a single bucket.
712904
Loop
713905
SearchableLiveBucketListSnapshot::scanForEvictionInBucket(

‎src/bucket/BucketListSnapshot.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,13 @@ class SearchableLiveBucketListSnapshot
234234
LedgerEntryType type,
235235
std::function<Loop(BucketEntry const&)> callback) const;
236236

237+
// Iterate over all live entries of a given type. Note that this handles
238+
// shadowing and only returns the latest live entry for each key.
239+
void scanForLiveEntriesOfType(
240+
LedgerEntryType type,
241+
std::function<void(LedgerEntry const&, LedgerKey const&)> callback)
242+
const;
243+
237244
friend class ImmutableLedgerData;
238245
friend class ImmutableLedgerView;
239246
};

‎src/bucket/LedgerCmp.cpp‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Copyright 2026 Stellar Development Foundation and contributors. Licensed
2+
// under the Apache License, Version 2.0. See the COPYING file at the root
3+
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
4+
5+
#include "bucket/LedgerCmp.h"
6+
7+
namespace
8+
{
9+
template <typename T>
10+
std::partial_ordering
11+
lexComparePartial(T&& lhs1, T&& rhs1)
12+
{
13+
return lhs1 <=> rhs1;
14+
}
15+
16+
template <typename T, typename... U>
17+
std::partial_ordering
18+
lexComparePartial(T&& lhs1, T&& rhs1, U&&... args)
19+
{
20+
if (auto cmp = lhs1 <=> rhs1; cmp != std::partial_ordering::equivalent)
21+
{
22+
return cmp;
23+
}
24+
return lexComparePartial(std::forward<U>(args)...);
25+
}
26+
} // namespace
27+
28+
namespace stellar
29+
{
30+
std::partial_ordering
31+
compareLedgerKeys(LedgerKey const& a, LedgerKey const& b)
32+
{
33+
LedgerEntryType aty = a.type();
34+
LedgerEntryType bty = b.type();
35+
36+
if (aty < bty)
37+
return std::partial_ordering::less;
38+
39+
if (aty > bty)
40+
return std::partial_ordering::greater;
41+
42+
switch (aty)
43+
{
44+
case ACCOUNT:
45+
return a.account().accountID <=> b.account().accountID;
46+
case TRUSTLINE:
47+
return lexComparePartial(a.trustLine().accountID,
48+
b.trustLine().accountID, a.trustLine().asset,
49+
b.trustLine().asset);
50+
case OFFER:
51+
return lexComparePartial(a.offer().sellerID, b.offer().sellerID,
52+
a.offer().offerID, b.offer().offerID);
53+
case DATA:
54+
return lexComparePartial(a.data().accountID, b.data().accountID,
55+
a.data().dataName, b.data().dataName);
56+
case CLAIMABLE_BALANCE:
57+
return a.claimableBalance().balanceID <=>
58+
b.claimableBalance().balanceID;
59+
case LIQUIDITY_POOL:
60+
return a.liquidityPool().liquidityPoolID <=>
61+
b.liquidityPool().liquidityPoolID;
62+
case CONTRACT_DATA:
63+
{
64+
return lexComparePartial(
65+
a.contractData().contract, b.contractData().contract,
66+
a.contractData().key, b.contractData().key,
67+
a.contractData().durability, b.contractData().durability);
68+
}
69+
case CONTRACT_CODE:
70+
return lexComparePartial(a.contractCode().hash, b.contractCode().hash);
71+
case CONFIG_SETTING:
72+
{
73+
return a.configSetting().configSettingID <=>
74+
b.configSetting().configSettingID;
75+
}
76+
case TTL:
77+
return lexComparePartial(a.ttl().keyHash, b.ttl().keyHash);
78+
}
79+
80+
return std::partial_ordering::unordered;
81+
}
82+
} // namespace stellar

‎src/bucket/LedgerCmp.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
#pragma once
66

7+
#include <compare>
78
#include <type_traits>
89

910
#include "bucket/BucketUtils.h"
@@ -123,6 +124,10 @@ struct LedgerEntryIdCmp
123124
}
124125
};
125126

127+
// Like LedgerEntryIdCmp, but only compares LedgerKeys, and does a 3-way
128+
// comparison instead of a less-than.
129+
std::partial_ordering compareLedgerKeys(LedgerKey const& a, LedgerKey const& b);
130+
126131
/**
127132
* Compare two BucketEntries for identity by comparing their respective
128133
* LedgerEntries (ignoring their hashes, as the LedgerEntryIdCmp ignores their

‎src/ledger/ImmutableLedgerView.cpp‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,14 @@ ImmutableLedgerView::scanLiveEntriesOfType(
462462
mLiveSnapshot.scanForEntriesOfType(type, std::move(callback));
463463
}
464464

465+
void
466+
ImmutableLedgerView::scanCurrentLiveEntriesOfType(
467+
LedgerEntryType type,
468+
std::function<void(LedgerEntry const&, LedgerKey const&)> callback) const
469+
{
470+
mLiveSnapshot.scanForLiveEntriesOfType(type, std::move(callback));
471+
}
472+
465473
// === Hot Archive BucketList wrapper methods ===
466474

467475
std::shared_ptr<HotArchiveBucketEntry const>

‎src/ledger/ImmutableLedgerView.h‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,10 +169,20 @@ class ImmutableLedgerView : public virtual AbstractLedgerView
169169
uint32_t ledgerSeq, EvictionMetrics& metrics, EvictionIterator iter,
170170
std::shared_ptr<EvictionStatistics> stats,
171171
StateArchivalSettings const& sas, uint32_t ledgerVers) const;
172+
173+
// Scan the live bucket list for entries of a given type. Note this iterates
174+
// over all BucketEntry, so some may be shadowed and outdated.
172175
void scanLiveEntriesOfType(
173176
LedgerEntryType type,
174177
std::function<Loop(BucketEntry const&)> callback) const;
175178

179+
// Scan the live bucket list for entries of a given type. Calls callback
180+
// with the latest live version for each entry.
181+
void scanCurrentLiveEntriesOfType(
182+
LedgerEntryType type,
183+
std::function<void(LedgerEntry const&, LedgerKey const&)> callback)
184+
const;
185+
176186
// === Hot Archive BucketList methods ===
177187
std::shared_ptr<HotArchiveBucketEntry const>
178188
loadArchiveEntry(LedgerKey const& k) const;
@@ -211,6 +221,7 @@ class ApplyLedgerView : private ImmutableLedgerView,
211221
using ImmutableLedgerView::loadLiveKeysFromLedger;
212222
using ImmutableLedgerView::loadPoolShareTrustLinesByAccountAndAsset;
213223
using ImmutableLedgerView::scanAllArchiveEntries;
224+
using ImmutableLedgerView::scanCurrentLiveEntriesOfType;
214225
using ImmutableLedgerView::scanForEviction;
215226
using ImmutableLedgerView::scanLiveEntriesOfType;
216227
};

0 commit comments

Comments
 (0)