Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. Code Coverage & BenchmarksFor details see: https://corecheck.dev/bitcoin/bitcoin/pulls/34320. ReviewsSee the guideline for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
Are there any flamegraphs or benchmarks, to see how this affects performance? |
I'm not sure what to measure exactly because the current code was already delegating to |
Added assumeutxo load, reindex-chainstate and pruned IBD measurements to the PR description |
I'm not sure about this. bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
return (it != cacheCoins.end() && !it->second.coin.IsSpent());
}vs std::optional<Coin> CCoinsViewCache::GetCoin(const COutPoint& outpoint) const
{
if (auto it{FetchCoin(outpoint)}; it != cacheCoins.end() && !it->second.coin.IsSpent()) return it->second.coin;
return std::nullopt;
} |
I see 4 uses of
For 1 and 2, we are checking for the non-existence of the coin so we won't need the full value. In this case not caching the value makes sense. I think 1 and 2 would benefit from |
Disassembly with separate translation units indicates
But there's nothing to cache since these will return an empty optional. For BIP30 and
This is a good point, the disassembly indicates there's no devirtualization and no inlining in if (AccessCoin(tx.vin[i].prevout).IsSpent()) {and if (m_view.AccessCoin(txin.prevout).IsSpent()) {I have added a new benchmark as a first commit to check the performance of on-disk Benchmark baseline:
Benchmark with
Replace remaining
(ran it 5 times for each commit and copied the fastest (with smallest noise). The small difference is reproducible, but not very important as long as it's not measurably slower) Benchmarking script and results on Linuxfor commit in 3544b98927050956f68cb183bf2686f5c65e5ebb 8c568500442144fbcd457eccda5a1956aa98ca81; do \
git fetch origin $commit >/dev/null 2>&1 && git checkout $commit >/dev/null 2>&1 && echo "" && git log -1 --pretty='%h %s' && \
rm -rf build >/dev/null 2>&1 && cmake -B build -DBUILD_BENCH=ON -DCMAKE_BUILD_TYPE=Release >/dev/null 2>&1 && \
cmake --build build -j$(nproc) >/dev/null 2>&1 && \
for _ in $(seq 5); do \
sleep 5; \
./build/bin/bench_bitcoin -filter='HaveInputsOnDisk' -min-time=1000; \
done; \
doneresulting in
|
9b4e044 to
8c56850
Compare
This tells us that
Same as above.
I think everywhere we use AccessCoin we assert the unspentness. This would now break that pattern and use AccessCoin to check existence via spentness. I think HaveCoin conveys intent better here. Can we instead just remove HaveCoin on the db then, and the default implementation would just forward to |
HaveCoin calls with GetCoinCCoinsViewDB::HaveCoin
|
Thanks @andrewtoth, I didn't like the suggestion at first since we keep polluting the interface, but after applying your suggestion I'm fine with the results, it's simpler and better separated from the other similar PRs. |
67068ee to
3d25cbf
Compare
3d25cbf to
4166ee8
Compare
23dd085 to
69fa15a
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
c68262b to
c01f70e
Compare
|
Rebased, removed the contentious #35078 squash - ready for review again. |
c01f70e to
46a8e39
Compare
CCoinsViewDB::HaveCoinCCoinsViewDB::HaveCoin to GetCoin
There was a problem hiding this comment.
As I see, what this PR solves is the code duplication across ReadImpl and ExistsImpl. And it does it by touching Exists, Read, and HaveCoin. For the HaveCoin path the value is passed upwards unnecessarily, which is a minor regression.
I think a simpler solution is to get rid of ExistsImpl, and replace it with !!ReadImpl. Unless I miss something, this achieves the same.
In a diagram:
Original:
HaveCoin ──> Exists ──> ExistsImpl
GetCoin ───> Read ────> ReadImpl
PR34320:
HaveCoin ─┐ Exists ─┐
┌─────────────┘ │
└─> GetCoin ───> Read ──┴─> ReadRaw ──> ReadImpl
Alternative:
HaveCoin ──> Exists ─┐
│
GetCoin ───> Read ───┴──> ReadImpl
See concretely here:
https://github.com/optout21/bitcoin/commits/pr34320_alt/
It would mean the following diff instead of the 3 code-commits:
git diff 053194a8042ce29a6a840e0efd47d85b4fcef32e..d35223c8ffbd87f4895f938e0d5e833de65d85c3
diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp
index 3743d43482..f19e23308e 100644
--- a/src/dbwrapper.cpp
+++ b/src/dbwrapper.cpp
@@ -321,21 +321,6 @@ std::optional<std::string> CDBWrapper::ReadImpl(std::span<const std::byte> key)
return strValue;
}
-bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
-{
- leveldb::Slice slKey(CharCast(key.data()), key.size());
-
- std::string strValue;
- leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
- if (!status.ok()) {
- if (status.IsNotFound())
- return false;
- LogError("LevelDB read failure: %s", status.ToString());
- HandleError(status);
- }
- return true;
-}
-
size_t CDBWrapper::EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const
{
leveldb::Slice slKey1(CharCast(key1.data()), key1.size());
diff --git a/src/dbwrapper.h b/src/dbwrapper.h
index 51775ee636..2c786b7b54 100644
--- a/src/dbwrapper.h
+++ b/src/dbwrapper.h
@@ -190,7 +190,6 @@ private:
inline static const std::string OBFUSCATION_KEY{"\000obfuscate_key", 14}; // explicit size to avoid truncation at leading \0
std::optional<std::string> ReadImpl(std::span<const std::byte> key) const;
- bool ExistsImpl(std::span<const std::byte> key) const;
size_t EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const;
auto& DBContext() const LIFETIMEBOUND { return *Assert(m_db_context); }
@@ -235,7 +234,7 @@ public:
DataStream ssKey{};
ssKey.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
ssKey << key;
- return ExistsImpl(ssKey);
+ return !!ReadImpl(ssKey);
}| @@ -80,7 +80,7 @@ std::optional<Coin> CCoinsViewDB::GetCoin(const COutPoint& outpoint, bool) const | |||
|
|
|||
| bool CCoinsViewDB::HaveCoin(const COutPoint& outpoint) const | |||
| { | |||
| return m_db->Exists(CoinEntry(&outpoint)); | |||
| return !!GetCoin(outpoint, /*peek_only=*/false); | |||
There was a problem hiding this comment.
I expand on this in a top-level comment.
What I meant is that I don't see the benefit of this change ('Exists' is still there), but I see a small regression: that the value is returned unnecessarily to one higher level, and the exists-only intent is lost.
46a8e39 to
ccc0656
Compare
That's part of the reason. The other reason here is that
That wouldn't attempt deserialization and wouldn't cache the results. I have rebased and dropped the benchmark for simplicity. |
| @@ -86,7 +86,7 @@ std::optional<Coin> CCoinsViewDB::PeekCoin(const COutPoint& outpoint) const | |||
|
|
|||
| bool CCoinsViewDB::HaveCoin(const COutPoint& outpoint) const | |||
| { | |||
| return m_db->Exists(CoinEntry(&outpoint)); | |||
| return !!GetCoin(outpoint); | |||
There was a problem hiding this comment.
I think I would still prefer if the HaveCoin member function and virtual member function would be removed, and test code just call GetCoin(...) directly.
There was a problem hiding this comment.
Andrew specifically mentioned he considers it the right level of abstraction, see: #34320 (comment)
@andrewtoth is that still your preference here?
There was a problem hiding this comment.
It is fine to keep it as a member for the coins view cache imo, but I don't think we should carry around dead virtual functions in the rest of them.
That depends how the contract is understood/defined.
Can you elaborate more on caching? I can't see additional caching introduced with this change:
This last point also means that for all usage through Details
|
| Aspect | Original | Current |
|---|---|---|
| Private impl method | ExistsImpl (dedicated) |
ReadImpl (shared with Read) |
| LevelDB call | pdb->Get() |
pdb->Get() (same) |
Value after LevelDB Get |
strValue is local, destroyed immediately |
strValue returned as optional<string>, propagated up two levels, then discarded by !! |
| String lifetime | Never leaves ExistsImpl |
Escapes ReadImpl, escapes ReadRaw, discarded in Exists |
| Code reuse | Exists and Read had separate impl paths |
Exists reuses ReadRaw → ReadImpl |
| Stack overhead | Lower — no string move up stack | Extra std::string move through two return values |
Notes
- Both versions call
leveldb::DB::Get(), which always fetches the full value. LevelDB has no cheaper "key probe" API, so there is no I/O difference. - The only runtime cost difference is the
std::stringmove through two return levels in the current version, which the compiler may optimize away. - The trade-off is fewer lines of code (reuse of
ReadRaw) in exchange for that minor overhead.
CCoinsViewDB::HaveCoin() — Call Chain Comparison
Current Version (with local changes)
CCoinsViewDB::HaveCoin(outpoint) [txdb.cpp:87-90]
return !!GetCoin(outpoint)
│
└─► CCoinsViewDB::GetCoin(outpoint) [txdb.cpp:73-80]
m_db->Read(CoinEntry(&outpoint), coin)
│
└─► CDBWrapper::Read(key, value) [dbwrapper.h:222-235]
ReadRaw(key)
│
└─► CDBWrapper::ReadRaw(key) [dbwrapper.h:213-219]
ssKey << key // serialize CoinEntry
return ReadImpl(ssKey)
│
└─► CDBWrapper::ReadImpl(span<byte>) [dbwrapper.cpp:315-327]
leveldb::DB::Get(readoptions, slKey, &strValue)
if IsNotFound → return nullopt
if other error → LogError + HandleError (throws)
return strValue // optional<string>
if (!strValue) return false
m_obfuscation(ssValue) // XOR deobfuscation
SpanReader{ssValue} >> coin // deserialize into Coin object
return true
if Read returned false → return nullopt
Assert(!coin.IsSpent()) // sanity check
return coin // optional<Coin> with value
│
// optional<Coin> propagates back to HaveCoin
// !! discards the fully-deserialized Coin, returns just bool
Original Version (without local changes)
CCoinsViewDB::HaveCoin(outpoint) [old txdb.cpp]
return m_db->Exists(CoinEntry(&outpoint))
│
└─► CDBWrapper::Exists(key) [old dbwrapper.h]
ssKey << key // serialize CoinEntry
return ExistsImpl(ssKey)
│
└─► CDBWrapper::ExistsImpl(span<byte>) [old dbwrapper.cpp, now deleted]
leveldb::DB::Get(readoptions, slKey, &strValue)
if IsNotFound → return false
if other error → LogError + HandleError (throws)
return true // bool only; strValue discarded
Key Differences
| Aspect | Original | Current |
|---|---|---|
| Call depth | 3 levels (HaveCoin → Exists → ExistsImpl) |
6 levels (HaveCoin → GetCoin → Read → ReadRaw → ReadImpl → LevelDB) |
| LevelDB call | pdb->Get() |
pdb->Get() (same) |
| Deobfuscation | None — raw bytes discarded | Yes — XOR applied to the value bytes |
| Deserialization | None — raw bytes discarded | Yes — full Coin object constructed |
| Sanity check | None | Assert(!coin.IsSpent()) |
| Work discarded | Raw strValue string (cheap) |
Fully constructed Coin object (expensive) |
| Return path | bool returned directly from ExistsImpl |
optional<Coin> bubbles up, collapsed to bool by !! |
Notes
- Both versions issue one
leveldb::DB::Get()call — there is no I/O difference. - The current version does substantially more CPU work for the same boolean result: it deobfuscates the raw bytes and deserializes them into a full
Coinobject (including readingCTxOut, amount, script, block height, coinbase flag), then immediately throws it all away via!!. - The original
ExistsImpldiscardedstrValuebefore it ever left the function, never touching the value bytes beyond the LevelDB read. - The regression is a direct consequence of removing the dedicated
ExistsImplpath and reroutingHaveCointhroughGetCoinfor code-reuse reasons.
|
I find that it's relatively painless to remove If the real goal here is slimming the interface, I suggest to do that and state that (but the current form of this PR I still find incoherent). For minimal changes to remove |
|
Continuing, I think the real design question raised here is: Is A. For all coin stores, including A. does not fully hold currently, as there are several methods of |
Add unit tests covering `CCoinsViewCache::HaveInputs()`. The tests document that `HaveInputs()` consults the cache first and that a cache miss pulls from the backing view via `GetCoin()`. The spy view inherits from `CoinsViewEmpty` so only the `GetCoin()`/`HaveCoin()` interaction under test is customized. Co-authored-by: Novo <[email protected]>
Split the raw LevelDB lookup into `CDBWrapper::ReadRaw()` so later commits can change typed `Read()` deserialization behavior without duplicating key serialization. Move `Write()` below the read and existence helpers, and return from successful iterator decode paths inside the `try` blocks so this commit stays behavior-neutral.
`ExistsImpl` duplicates `CDBWrapper::ReadImpl()`: both issue a LevelDB `Get`, but only `ReadImpl()` keeps the returned bytes. Introduce a small helper returning the raw value bytes as `std::string`, make `Read()` deserialize from it, and make `Exists()` just check whether the raw read succeeded. After this series, `CCoinsViewDB::HaveCoin()` also goes through `GetCoin()` / `Read()`, while the remaining `CDBWrapper::Exists()` callers are infrequent metadata checks, so reusing `ReadRaw()` does not affect a performance-sensitive path.
`m_db->Exists(CoinEntry(&outpoint))` only checks whether some value is stored for the coin key, while `CCoinsViewDB::HaveCoin()` should match `GetCoin()` and report whether the outpoint can be read as an unspent `Coin`. `CCoinsViewCache::HaveCoin()` already goes through `FetchCoin()` and `GetCoin()` on cache misses, so keep the required override but make it a thin adapter to `GetCoin()` instead of giving `CCoinsViewDB::HaveCoin()` its own `Exists()`-based semantics.
ccc0656 to
dc4300b
Compare
…ially copyable types 3e8e21b txgraph: avoid moving primitive members (Lőrinc) d9f94aa rpc: avoid moving RPC enum types (Lőrinc) b67baed coins: avoid moving `COutPoint` values (Lőrinc) Pull request description: Inspired by #34320 (comment). **Problem:** A few code paths use rvalue references or `std::move()` for types where moving provides no benefit. `EmplaceCoinInternalDANGER` took `COutPoint&&`, forcing callers to pass trivially copyable outpoints as rvalues even though the cache stores its own key. Some call sites also use `std::move()` on enum and primitive values, where it only adds noise. > [!NOTE] > `CheckTriviallyCopyableMove` remains `false` since `std::move()` on trivially copyable types can still be useful as intent documentation, for example to signal that a value should not be reused after a call. **Fix:** Take trivially copyable arguments by const reference where the callee only needs to store its own copy, and pass existing values directly at the call sites. Also remove `std::move()` from enum and primitive assignments where it has no semantic effect. ACKs for top commit: maflcko: review ACK 3e8e21b 🖇 hodlinator: re-ACK 3e8e21b andrewtoth: ACK 3e8e21b hebasto: ACK 3e8e21b, I have reviewed the code and it looks OK. Tree-SHA512: cbe55b13290ae261bba359dc6e5a3bbdfb7ae9d31bdf8e0da2eef65a0df776e4081ceeac3c82731a631bda656a86b3789651fa1f4d87875cee1dc96351bdfd7c
… for a few trivially copyable types b871374 txgraph: avoid moving primitive members (Lőrinc) 1c048e9 rpc: avoid moving RPC enum types (Lőrinc) 74c1dc6 coins: avoid moving `COutPoint` values (Lőrinc) Pull request description: Inspired by bitcoin/bitcoin#34320 (comment). **Problem:** A few code paths use rvalue references or `std::move()` for types where moving provides no benefit. `EmplaceCoinInternalDANGER` took `COutPoint&&`, forcing callers to pass trivially copyable outpoints as rvalues even though the cache stores its own key. Some call sites also use `std::move()` on enum and primitive values, where it only adds noise. > [!NOTE] > `CheckTriviallyCopyableMove` remains `false` since `std::move()` on trivially copyable types can still be useful as intent documentation, for example to signal that a value should not be reused after a call. **Fix:** Take trivially copyable arguments by const reference where the callee only needs to store its own copy, and pass existing values directly at the call sites. Also remove `std::move()` from enum and primitive assignments where it has no semantic effect. ACKs for top commit: maflcko: review ACK b871374 🖇 hodlinator: re-ACK b871374 andrewtoth: ACK b871374 hebasto: ACK b871374, I have reviewed the code and it looks OK. Tree-SHA512: cbe55b13290ae261bba359dc6e5a3bbdfb7ae9d31bdf8e0da2eef65a0df776e4081ceeac3c82731a631bda656a86b3789651fa1f4d87875cee1dc96351bdfd7c
|
Thanks @optout21 for the thoughtful comments and for putting together the patch. |
… for a few trivially copyable types 3e8e21b2efcee4299f50030c37176ace29b315ec txgraph: avoid moving primitive members (Lőrinc) d9f94aa882ae7ac5697d30c4478d9a1d633c3728 rpc: avoid moving RPC enum types (Lőrinc) b67baed4e7e4c553426f1192a97725bc53b9df70 coins: avoid moving `COutPoint` values (Lőrinc) Pull request description: Inspired by bitcoin/bitcoin#34320 (comment). **Problem:** A few code paths use rvalue references or `std::move()` for types where moving provides no benefit. `EmplaceCoinInternalDANGER` took `COutPoint&&`, forcing callers to pass trivially copyable outpoints as rvalues even though the cache stores its own key. Some call sites also use `std::move()` on enum and primitive values, where it only adds noise. > [!NOTE] > `CheckTriviallyCopyableMove` remains `false` since `std::move()` on trivially copyable types can still be useful as intent documentation, for example to signal that a value should not be reused after a call. **Fix:** Take trivially copyable arguments by const reference where the callee only needs to store its own copy, and pass existing values directly at the call sites. Also remove `std::move()` from enum and primitive assignments where it has no semantic effect. ACKs for top commit: maflcko: review ACK 3e8e21b2efcee4299f50030c37176ace29b315ec 🖇 hodlinator: re-ACK 3e8e21b2efcee4299f50030c37176ace29b315ec andrewtoth: ACK 3e8e21b2efcee4299f50030c37176ace29b315ec hebasto: ACK 3e8e21b2efcee4299f50030c37176ace29b315ec, I have reviewed the code and it looks OK. Tree-SHA512: cbe55b13290ae261bba359dc6e5a3bbdfb7ae9d31bdf8e0da2eef65a0df776e4081ceeac3c82731a631bda656a86b3789651fa1f4d87875cee1dc96351bdfd7c
Split out of #34132 (comment).
Problem:
CCoinsViewDB::HaveCoin()currently answers a different question from the cache-backed coins view path.It calls
CDBWrapper::Exists(), which only checks whether LevelDB has a value for the coin key, whileGetCoin()tries to read the value as an unspentCoin.This makes the direct DB view's
HaveCoin()semantics diverge fromCCoinsViewCache::HaveCoin(), which fetches throughGetCoin()on cache misses.The separate
CDBWrapper::ExistsImpl()read path also duplicatesReadImpl()even though the remainingCDBWrapper::Exists()callers are infrequent metadata checks.Fix: Make
CCoinsViewDB::HaveCoin()delegate toGetCoin(), so it reports whether the outpoint can be read as an unspentCoin(not just whether the database contains any value).Also have
CDBWrapper::Read()andExists()share aReadRaw()helper instead of keeping separate LevelDB read implementations.Testing: Add a unit test documenting that
CCoinsViewCache::HaveInputs()checks the cache first and calls the backing view'sGetCoin(), notHaveCoin(), on cache miss.