Skip to content

coins: tighten cache entry state invariants - #34864

Open
l0rinc wants to merge 8 commits into
bitcoin:masterfrom
l0rinc:l0rinc/coins-cache-invariants
Open

l0rinc wants to merge 8 commits into
bitcoin:masterfrom
l0rinc:l0rinc/coins-cache-invariants

Conversation

@l0rinc

@l0rinc l0rinc commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem: The coins cache still exposed and tested states that production code should not create: standalone FRESH entries, non-dirty BatchWrite() cursor entries, and spent FRESH entries.
That makes the representation harder to reason about, because CCoinsCacheEntry stores a separate DIRTY bit even though dirty entries are already tracked in the linked list.

Fix: This revives and splits the relevant parts of #30673 and #33018.
The series passes freshness through SetDirty(), removes fresh-only test states, treats BatchWrite() cursor entries as dirty by construction, rejects spent FRESH entries, removes the bare SetFresh() helper, and derives dirtiness from linked-list membership.
The final commits also tighten SpendCoin() around the same cache-state contract: repeated spends of an entry already cached as spent now return false without overwriting caller-owned output, while preserving the already-unchanged cache accounting. Callers must either check the result or explicitly discard it.
coinscache_sim now checks the real SpendCoin() result against its simulation model, and the no-op repeated-spend path no longer emits the utxocache:spent tracepoint because no spend occurs.
Production callers retain their behavior: checked inputs remain spendable, disconnects report unclean state, and replay ignores repeated deletes.

@DrahtBot

DrahtBot commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/34864.

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK andrewtoth
Stale ACK optout21

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #37038 (coins: store spent dbcache entries compactly by LarryRuane)
  • #36603 (Improve loadtxoutset performance by ajtowns)
  • #35793 (Implement BIP 54 (Consensus Cleanup) without mainnet activation by darosior)

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.

@andrewtoth andrewtoth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK

Thanks for picking this up.

Comment thread src/coins.cpp
cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
// We can mark it FRESH in the parent if it was FRESH in the child
// Otherwise it might have just been flushed from the parent's cache
// and already exist in the grandparent

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why remove this comment? It's still relevant and provides valuable context.

@l0rinc l0rinc Apr 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restored above the new SetDirty call

Comment thread src/txdb.cpp Outdated
LogDebug(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.ApproximateSize() * (1.0 / 1048576.0));
m_db->WriteBatch(batch);
LogDebug(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...", (unsigned int)dirty_count, (unsigned int)count);
LogDebug(BCLog::COINDB, "Committed %u transaction outputs to coin database...", dirty_count);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changed adjective could be left here. Existing transaction outputs that are deleted are changed. The log now can be conflated with committing only new transactions outputs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added changed back

Comment thread src/coins.h

void SetClean() noexcept
{
if (!m_flags) return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this touched here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just for symmetry with SetDirty

Comment thread src/coins.h
Assume(pair.second.m_prev && pair.second.m_next);
pair.second.m_flags |= DIRTY | (fresh ? FRESH : 0);
Assume(pair.second.IsDirty());
pair.second.m_fresh = fresh;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a behavior change, and the commit message says:

Make `SetDirty()` take the resulting freshness explicitly so callers cannot accidentally preserve an old fresh state by passing `false`.

Why do we want to set a fresh entry to not-fresh? If an entry is fresh, it should stay fresh until cleaned or erased as before.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a behavior change

Why do we want to set a fresh entry to not-fresh?

Added Assume(!pair.second.m_fresh || fresh) so the API can't silently clear FRESH, thanks

@l0rinc
l0rinc force-pushed the l0rinc/coins-cache-invariants branch from 5c30d62 to fa9683a Compare April 19, 2026 20:09

@l0rinc l0rinc left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adjusted the code and commit messages, thanks.

git range-diff 745d97496188d50ad3e1a7173bb30d363e97b9c8..5c30d62df48656399e48fdda52d4c6cbd4471789 000efb0bdf928195ddc168be80741c55708b047a..fa9683af5f74d81c4907ad81d888a94ef2e880be

Comment thread src/coins.h
Assume(pair.second.m_prev && pair.second.m_next);
pair.second.m_flags |= DIRTY | (fresh ? FRESH : 0);
Assume(pair.second.IsDirty());
pair.second.m_fresh = fresh;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a behavior change

Why do we want to set a fresh entry to not-fresh?

Added Assume(!pair.second.m_fresh || fresh) so the API can't silently clear FRESH, thanks

Comment thread src/coins.h

void SetClean() noexcept
{
if (!m_flags) return;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just for symmetry with SetDirty

Comment thread src/txdb.cpp Outdated
LogDebug(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.ApproximateSize() * (1.0 / 1048576.0));
m_db->WriteBatch(batch);
LogDebug(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...", (unsigned int)dirty_count, (unsigned int)count);
LogDebug(BCLog::COINDB, "Committed %u transaction outputs to coin database...", dirty_count);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added changed back

Comment thread src/coins.cpp
cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
// We can mark it FRESH in the parent if it was FRESH in the child
// Otherwise it might have just been flushed from the parent's cache
// and already exist in the grandparent

@l0rinc l0rinc Apr 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restored above the new SetDirty call

@optout21 optout21 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK fa9683af5f74d81c4907ad81d888a94ef2e880be

My perspective on the benefit of this change is as follows: The CCoinsCacheEntry class is capable of expressing several combinations of properties, some of which are invalid and never used. They are invalid logically, and enforced by convention only. Post-change the invalid states cannot be represented. This change is a code maintainability benefit, because any code change could potentially break the conventions. It also results in slightly simpler code.

The relevant state space dimensions are:

  • The "dirty" and "fresh" properties were represented as independent bools (stored in a bitfield), however, of the 2x2 combinations the fresh-but-not-dirty is invalid (because new entries in the cache that are not present in an underlying level must always be saved). This combination is not used.
  • A dirty (or fresh) entry must be placed in the linked list of dirty elements. The dirty flag and the existence of the linked list pointers may contradict.

Post change:

  • Dirtyness is implicitly represented by being included in the linked list, not by an explicit flag.
  • Freshness is represented as a single bool flag, and the setter methods have been changed to prevent the invalid state. Asserts have been also added.

The essence of the change is concentrated to the CCoinsCacheEntry class, and is relatively simple. However, auxiliary changes are needed to ensure/assert the call sites and the tests. Moreover, the change is broken up into smaller consistent steps.

An overview of the commits (in chronological order):

  • SetFresh is being folded into SetDirty with a fresh flag. At the relevant call site the "freshness" information is already available.
  • Tests are adjusted to not use the invalid fresh-but-not-dirty state.
  • In BatchWrite drop the conditional for invalid non-dirty cases, replace them with assert.
  • Also in BatchWrite, for the invalid fresh-but-spent case instead of being ignored it is handled as an exception.
  • Drop SetFresh.
  • Small refactor to fold the now-single-use AddFlags into SetDirty
  • Perform the internal representation change (Dirtiness is derived from the linked list pointers, and freshness is stored as a bool. Extra asserts are added to checks for preconditions. Also, the default value for the fresh option on SetDirty is removed (so its usage is more explicit)).

I have reimplemented part of the changes independently. I've reviewed the code, and found no issues. (Note: as the PR had only light review so far, further changes are likely.)

@ptrinh

ptrinh commented Jun 24, 2026

Copy link
Copy Markdown

Tested the coins fuzz targets on this branch (commit fa9683af5f), since the PR turns the previously-handled FRESH+spent cases in BatchWrite() into hard asserts/throws and the safety of that rests on those states never occurring in practice.

Setup: arm64 macOS (Apple M-series), Homebrew clang 22, -DBUILD_FOR_FUZZING=ON -DSANITIZERS=fuzzer,address,undefined. Started from an empty corpus (no qa-assets seed), libFuzzer, 2h per target:

  • coins_view: 3,230,233 execs, peak cov 2961 edges / 14028 features
  • coinscache_sim: 1,443,489 execs, peak cov 1700 edges / 12217 features

No crashes, OOMs, sanitizer errors, or hits on the new BatchWrite() logic_error. The coins unit suites (coins_tests, coinscachepair_tests, coinsviewoverlay_tests, coinstatsindex_tests) also pass on this branch.

Caveat: this was an unseeded 2h run, so it's shallower than a seeded run against the qa-assets corpus would be; happy to do a longer seeded run if useful. I also read through the BatchWrite/SetDirty/IsDirty changes and the fresh-implies-dirty invariant looks internally consistent.

@l0rinc
l0rinc force-pushed the l0rinc/coins-cache-invariants branch from fa9683a to 4812de5 Compare July 5, 2026 05:49
@l0rinc l0rinc changed the title coins: make cache freshness imply dirtiness and remove invalid test states coins: tighten cache entry state invariants Jul 5, 2026
@l0rinc

l0rinc commented Jul 5, 2026

Copy link
Copy Markdown
Contributor Author

Rebased and added two commits tightening SpendCoin() return-value handling

@optout21

optout21 commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

reACK f27eba8

No issues. A net reduction in complexity around coins view flags (my previous reivew had more details).

andrewtoth and others added 8 commits September 30, 2026 15:30
Limit fixtures to entries that are dirty whenever they are fresh, and prepare the fuzz harness to avoid spent fresh entries and duplicate insertion accounting.
Record that repeated spends report success and overwrite caller-owned output, while retaining the existing state and accounting checks.

Co-authored-by: Lőrinc <[email protected]>
Fresh entries must also be dirty.
Require the resulting freshness at every `SetDirty()` call and remove the bare `SetFresh()` helper, so callers cannot create a fresh entry without linking it into the dirty list.

Co-authored-by: Andrew Toth <[email protected]>
`CoinsViewCacheCursor` iterates the dirty-entry list.
Treat cursor entries as dirty instead of checking them again, while retaining assertions of the cursor contract.

Co-authored-by: Andrew Toth <[email protected]>
Spending a fresh entry erases it locally because the parent never knew it existed.
Reject a spent fresh entry before merging it into the parent cache instead of treating it as a valid state.
`SetDirty()` is the only remaining caller of `AddFlags()`.
Inline the helper so the representation change is confined to the entry's state management.
List membership already identifies dirty entries, so the separate `DIRTY` bit duplicates state.
Store only freshness and require it to be preserved while an entry remains dirty.

Co-authored-by: Andrew Toth <[email protected]>
Return false without overwriting caller-owned output when an entry is already cached as spent.
Cache accounting was already unchanged for reachable spent entries.
Production callers retain their behavior: checked inputs remain spendable, disconnects report unclean state, and replay ignores repeated deletes.
The rejected spend no longer emits the `utxocache:spent` tracepoint.
Mark `SpendCoin()` as `[[nodiscard]]` so accidental ignored results are rejected.
The mempool consistency check requires successful spends, while replay explicitly ignores repeated deletes after an interrupted coins DB flush.
@l0rinc
l0rinc force-pushed the l0rinc/coins-cache-invariants branch from f27eba8 to 6fd59bf Compare September 30, 2026 22:30
@l0rinc

l0rinc commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

Rebased to make sure related changes are included and applied some AI review cleanup suggestions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants