Skip to content

execution: FCU background-commit worker + generation-chain reader consistency - #21414

Open
mh0lt wants to merge 186 commits into
mainfrom
mh/perf-semaphore-pr-v2
Open

execution: FCU background-commit worker + generation-chain reader consistency#21414
mh0lt wants to merge 186 commits into
mainfrom
mh/perf-semaphore-pr-v2

Conversation

@mh0lt

@mh0lt mh0lt commented May 26, 2026

Copy link
Copy Markdown
Contributor

Important

Perf stack PR #4. Predecessors #21380 (State Cache Consolidation) and #21386 (branch/code cache rework) are merged; this PR is based on main.

Summary

Decouples the FCU semaphore from the post-FCU flush+commit+prune so async-commit (--fcu.background.commit=true) actually delivers the throughput it promises. Previously the semaphore was held for the whole commit window, so FCU(N+1) waited on FCU(N)'s MDBX commit — async commit was a regression. This PR moves the commit to a background worker, releases the semaphore the moment updateForkChoice returns, and chains FCU(N+1)'s in-memory state to FCU(N)'s in-flight commit generation so reads cascade through it instead of a stale DB.

Gated by the existing fcuBackgroundCommit flag. In this PR the default is temporarily true so CI exercises the background-commit path under full load; it will be reverted to false before this PR merges (see below). Both paths produce the same execution and the same durable state; the only thing background commit changes is timing — the flush+commit moves off the FCU critical path so the durable write lands slightly later. What is executed and what is committed are identical.

Default flip: temporary, reverted before merge

This PR currently sets fcuBackgroundCommit = true by default so CI exercises the background-commit path under full load. Before this PR merges, the default will be reverted to false. The permanent flip ships in a follow-up once the safety prerequisites land:

  • #22494 — bound per-generation retention (drainCommittedGens is a no-op today → OOM risk); make the background worker yield to foreground rather than hold the semaphore; coordinated in-flight-SD unwind for SetHead.
  • #21314 — deliver the published SharedDomains to production readers (eth_getProof, parity storage keys) instead of the test-only resolver.

Until then, background commit stays opt-in in production.

Mechanism

  1. Semaphore decouple. updateForkChoice releases e.semaphore before the bg commit goroutine spawns — not after runPostForkchoice. Next FCU is no longer blocked on the previous commit's MDBX fsync.
  2. Background bg-commit worker. New execution/execmodule/bg_commit.go: a single FIFO commit worker, plus fgTryAcquire/fgAcquire/fgRelease wrappers that every foreground op (FCU / ValidateChain / InsertBlocks / AssembleBlock / SetHead) registers through. The worker acquires the foreground semaphore before each commit, so the commit RwTx never overlaps a foreground roTx and never pins MDBX pages — no freelist/DB growth. An in-flight commit is never aborted: a foreground op that arrives mid-commit just makes the next commit wait. (Making the worker yield to foreground instead of holding the semaphore — true foreground priority — is the execution/execmodule, node/shards: remove the global Events.LatestSD published-SD pointer (decouple readers via a publication id) #22494 follow-up.)
  3. Commit-generation chain. Completed FCU generations form a chain; the next FCU's SharedDomains SetParent()s to the newest generation so it reads not-yet-committed domain state. drainCommittedGens, run under the semaphore at FCU entry, closes the chain as a unit once every generation has committed.
  4. Overlay continuity for block data. ValidateChain, InsertBlocks, and the FCU currentContext all init their block overlay from the latest in-flight generation's BlockOverlayTemporalTx, so headers/bodies/TDs/receipts written by InsertBlocks(N) are visible to ValidateChain(N+1) before the async commit lands. Closes the "txns not found in block" engineapi failure.
  5. commitWorker lifecycle. Bounded shutdown: the worker drains its queue on Close, the commit channel is closed under commitMu, and the WaitGroup is joined before ExecModule.Close returns. No more for range commitCh deadlock at DB-close.
  6. Latest-state RPC reads + published-leaf snapshots. rpc/jsonrpc/* and txpool read through the in-flight SD via a published-leaf provider when currentContext is nil (during a bg commit). The outer layer (RPC / txpool / builder) reads the most-recently-PUBLISHED SD leaf snapshot, never the executor's actively-mutated currentContext, so cross-RPC consistency (e.g. getTransactionCount vs txpool validateTx) is preserved across the async-commit window. Latest-block metadata reads (block number / current header) are routed through the published SD block overlay so they see in-flight blocks; latest-state readers still on the raw DB (eth_getProof, parity storage keys) are Build SD-aware temporal view to remove FcuBackgroundCommit RPC plain-tx reverts #21314.
  7. Read-ahead prefetch routed through the SD (post-audit anomaly removed). An audit of the reader-consistency invariants — the state cache is a SharedDomains implementation feature (only the SD writes it), and all reads go through the in-flight SD — found the warmBody block prefetcher was the one violator: it read the raw tx and wrote the process-global cache directly, and under background commit read state behind the tip. It now prefetches through the published SD (own coordinated tx, read via AsGetter), so reads see in-flight tip state and cache population happens in the SD's own read-fill. This removes the anomaly and collapses the two cache-fill sites into one. (Follow-up execution: SD-owned run-task worker abstraction + drop the parallel-exec scheduler queue #22520: an SD-owned run-task API and dropping the parallel-exec start queue.)

Files

Area Files
New bg-commit subsystem execution/execmodule/bg_commit.go
ExecModule integration execution/execmodule/{exec_module,forkchoice,inserters,set_head,scoped_read,block_building}.go
Domain SD chain db/state/execctx/domain_shared.go, db/state/temporal_mem_batch.go, db/kv/kv_interface.go
Block-overlay temporal-tx db/kv/membatchwithdb/memory_mutation.go
RPC + node wiring (published-leaf) rpc/jsonrpc/*.go, rpc/rpchelper/helper.go, node/eth/backend.go

Validation

  • Build + make lint clean.
  • TestEngineApiExecBlockBatch…ReorgDepth…Unwind (engineapi async-commit suite, see execution/engineapi/) — the repro for the original "txns not found in block" failure. Flips green with this PR; pre-fix it was 0/12.
  • Background and foreground commit produce the same execution and durable state — the only difference is when the commit lands. This is the core invariant the async-commit suite pins.
  • Full execution/execmodule package green under -race in both serial and parallel exec modes.

Out of scope (tracked follow-ups)

Related

Mark Holt and others added 30 commits May 21, 2026 21:35
Pure refactor — behavior preserved. Splits the encoded-branch→cells
decode logic out of HexPatriciaHashed.unfoldBranchNode into a free
function DecodeBranchInto so the same code is consumed by:

  - unfoldBranchNode (existing trie unfold path)
  - future cache populators (decoded-payload BranchCache)
  - future parallel pre-unfold orchestrator (Stage E)

Today these would each have to re-derive the encoded-branch parsing
logic. Centralising it ensures one decoder, one set of edge cases, one
place to fix any bug in the on-disk format handling.

DecodeBranchInto is intentionally PURE — it does not call
deriveHashedKeys. Trie callers (which need hashed keys for the fold
state machine) follow the decode with their own keccak loop.
Cache callers can skip the derive step entirely until the cell is
consumed by the trie.

Tests:
- TestDecodeBranchInto_RoundTrip: BranchEncoder.EncodeBranch produces
  bytes that DecodeBranchInto recovers cell-for-cell. Property test
  that keeps the canonical decoder consistent with the canonical
  encoder.
- TestDecodeBranchInto_DeletedFlag: touchMap/afterMap convention with
  the deleted parameter.
- TestDecodeBranchInto_TruncatedInput: clean errors on truncated input
  (no panic).

Plus the existing commitment test suite (incl. trie-mismatch tests in
TestBranchData_*) all pass without modification, confirming the
refactor preserves unfoldBranchNode's behavior.

This is the foundation for the next refactors in the
representation-reduction track (see
agentspecs/trie-data-pipeline-complexity-tax.md): subsequent PRs will
introduce a decoded-payload cache that reads through this same
decoder, and will lift unfoldKeyPath as a per-key traversal primitive
that the warmer + future Stage E both consume.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Introduces a new BranchCache type, distinct from WarmupCache and
designed for the longer-lived caching the cross-block persistence
work needs (step 7 of the representation-reduction sequence).

Distinguishing characteristics vs WarmupCache:

  - Bounded LRU tail with configurable capacity (vs WarmupCache's
    unbounded map). Suitable for caches that outlive a single Process
    without unbounded memory growth.
  - Single pinned slot for the root branch (compact prefix [0x00]).
    Root never evicts. Atomic-pointer load/store on the hot read
    path, no lock involved.
  - dirty-flag + PutIfClean invariants — same semantics as the
    invariants added to WarmupCache in the previous commit. Lets
    cross-block writers race safely with fold updates.
  - Lazy GetDecoded — same lazy-decode pattern as WarmupCache's
    GetBranchDecoded; cells populated on first decoded-read and
    cached for subsequent reads.

NOT yet wired into the trie's read or write paths. This commit just
adds the type, with tests. The trie integration (where this cache
plugs into branchFromCacheOrDB and the encoder's PutBranch) is the
discussion point at the step 6 boundary — see the conversation
captured at this point in the representation-reduction sequence.

Today the cache is intended to be ephemeral (per-Process,
constructed alongside the trie, dies with it). Step 7 lifts the
lifetime to the aggTx level for cross-block persistence; the cache
shape (bounded LRU + pinned root + dirty-flag) is in place ahead
of that.

Tests:
- TestBranchCache_RootPinning: root branch lands in pinned slot,
  deep branches land in LRU tail; per-tier hit counters update
  independently.
- TestBranchCache_RootSurvivesEvictionPressure: root persists when
  tail is overfilled past capacity.
- TestBranchCache_DirtyFlag: PutIfClean refuses dirty entry,
  unconditional Put replaces and clears dirty.
- TestBranchCache_GetDecoded: lazy-decode round-trip with
  BranchEncoder; cells pointer reused across reads.
- TestBranchCache_Invalidate: removes from both tiers.
- TestBranchCache_Clear: empties both tiers, resets stats.
- TestBranchCache_Stats: deterministic format with per-tier counts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Doc-only addition to BranchCache's package-level comment, capturing
the caller invariants the cache assumes and the conditions under
which the existing concurrent trie satisfies them.

Three caller invariants:
  1. Single writer per prefix at any moment.
  2. Mark-dirty-then-Put discipline for racing writers.
  3. Decoded cells from GetDecoded are read-only (alias entry storage).

The current ConcurrentPatriciaHashed satisfies all three by
construction:
  - Mounts partition by first nibble (disjoint prefix spaces, no
    cross-mount writes to the same key).
  - Root branch written by single sequential fold post-Wait.
  - Mount→root grid roll-up is rootMu-protected (in-memory grid
    only, separate from cache writes).

Doc explicitly flags that any future parallel fold redesign (Stage F
in agentspecs/stage-e-pre-unfold-design.md) MUST preserve these
invariants — particularly the single-writer-per-prefix one, which
breaks if parent branches are written incrementally as children
complete in parallel. The required coordination layer goes at the
orchestrator (per-parent atomic counter; only the last-decrementer
writes the parent), NOT inside the cache. The cache's existing
primitives (atomic dirty flag, thread-safe LRU, atomic root pointer)
are sufficient for that orchestrator to build on.

Motivation: Stage F is likely deferred because the bench data shows
fold isn't the bottleneck for the canonical SSTORE-bloat workload.
But adding the constraint to the cache later (after caching is in
production) is much harder than documenting it now — correctness
regressions from a missed coordination layer can hide for many
blocks. Documenting the contract on the cache itself ensures any
engineer touching parallel fold sees it.

No code change. Doc-only. All tests still pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Step 7a of the representation-reduction sequence: per-Process
integration of the BranchCache type added in the previous commit.

Plumbing:

  - Trie interface gains SetBranchCache(*BranchCache).
    HexPatriciaHashed implementation propagates to its branchEncoder.
    ConcurrentPatriciaHashed implementation propagates the SAME
    instance to root + all 16 mounts (sharing one cache is correct
    under the concurrency contract — mounts partition prefix space
    by first nibble, so cross-mount writes target distinct keys).

  - InitializeTrieAndUpdates constructs a new BranchCache(default)
    per trie instance and attaches it. Lifetime today = trie
    lifetime = per-Process. Future cross-block persistence work
    (step 7b) lifts this to aggTx scope by constructing the cache
    one layer up and passing it in.

Read path (HPH.branchFromCacheOrDB):
  L1 WarmupCache (existing) → L2 BranchCache (new) → L3 ctx.Branch.
  L3 hits with non-empty result populate L2 so subsequent reads hit
  L2 within the cache's lifetime. L1 stays first because warmup
  workers may have pre-fetched with prefix-walk-derived freshness.

Write path (BranchEncoder.CollectUpdate):
  - MarkDirty(prefix) BEFORE encode work — protects against
    concurrent warmup-style writers racing into PutIfClean during
    the encode (race documented in the cache's Concurrency Contract).
  - Put(prefixCopy, updateCopy) AFTER ctx.PutBranch succeeds —
    replaces the dirty entry with fresh canonical bytes. Single
    writer per prefix per fold step (current sequential fold +
    first-nibble mount partitioning) means no race on this Put.

Lifecycle:
  HPH.Reset clears the BranchCache when called from the root trie
  (gated by !hph.mounted). Mounted subtries share the root's cache,
  so a mount calling Clear would dump entries the root still wants.
  Carries the invariant from PR #19954 commit 1612d56.

Today's expected performance impact: minimal. Per-Process lifetime
means cache is empty at Process start, so first reads always miss.
The cache helps only branches that are read multiple times within
ONE Process — uncommon in current code paths. Step 7b is where
the real perf swing comes from (cross-block persistence so block
N reads hit branches written by block N-1).

This commit is the safe stepping stone: it validates the wire-up
end-to-end (read path + write path + concurrency contract +
lifecycle) without changing perf characteristics. Bench should
match Run I baseline (7.16 mgas/s on canonical SSTORE-bloat block).

All commitment tests pass, lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Previously the BranchCache was constructed inside InitializeTrieAndUpdates,
giving it per-SharedDomains lifetime. SharedDomains is reconstructed for
every batch / many tx boundaries — verified with logs in the prototype
(921 fresh BranchCache constructions per bench run) — so the cache started
cold every batch and never delivered the cross-block hits the design is
about. Per-Process scope kept cache-cleanup correctness simple but defeated
the whole point of caching.

Place the cache on the commitment Domain struct (one cache per aggregator,
matching the pattern on add_execution_context_with_caches where each
domain owns its valueCache). ConfigureDomains attaches the cache once
after domains are initialised — idempotent, lifetime = aggregator
lifetime. AggregatorRoTx exposes BranchCache() returning the commitment
domain's cache, so SharedDomains' construction path can fetch it without
forcing db/state/execctx to import db/state (db/state already imports
execctx via squeeze.go, so the reverse import would create a cycle).

The placeholder commitment.BranchCacheProvider interface lets the SD
construction path use a duck-typed type assertion on tx.AggTx() any.

Plumb the cache through NewSharedDomainsCommitmentContext into
InitializeTrieAndUpdates as an explicit parameter; nil falls back to a
fresh per-init cache so test helpers without an aggregator still get a
valid cache.

Reset behaviour: HexPatriciaHashed.Reset no longer calls Clear on the
cache. Aggregator-scope persistence requires the cache to survive Reset
between commitment calculations. Callers that genuinely need to
invalidate the cache (unwind, fork validation) now call ClearBranchCache
explicitly. The bench is forward-only so this is a safe change for
measurement; an explicit unwind clear path can land in a follow-up
commit when needed.
Adds two debug-gated diagnostics for cross-block-cache-lifetime
investigations. Both off by default — meant to be flipped on when a
correctness regression surfaces and you need to localise *where in the
fold path* the cache started lying, instead of waiting for a downstream
trie-root-mismatch many blocks later.

1. BRANCH_CACHE_VERIFY: branchFromCacheOrDB cross-checks every L2
   (BranchCache) hit against ctx.Branch and increments a divergence
   counter when bytes disagree. Logs the prefix and both byte forms so
   the first divergent read shows up directly in the erigon log.
   BranchCache.VerifyDivergences() exposes the count for assertion in
   tests.

2. BRANCH_CACHE_FINGERPRINT: SharedDomainsCommitmentContext.ComputeCommitment
   emits a "[cache-fp]" log at end of every compute with (block, root,
   cache fingerprint, divergence count). Two builds running the same
   workload can be diffed offline ("first block at which their fp's
   differ") to nail down the first block where lifecycle invariants
   diverged. Fingerprint is an order-independent FNV-1a fold over
   (key-hash, data-hash) pairs across both root and tail tiers.

Adds maphash.LRU.Range so the Fingerprint can iterate the LRU tail
without touching recency (Peek under the hood). The wrapper otherwise
discards original byte-keys on insert; mixing by hash instead of key is
correctness-equivalent up to hash collision, which is acceptable at the
working-set sizes here.

Motivation: today we just chased a wrong-root regression to commit
d673052 (aggregator-scope cache lifetime). Took two full bench cycles
(~12 min) to localise. With the divergence detector running, the first
divergent read would surface in the erigon log within seconds. With
fingerprint logging in two builds (one good, one regressed), the
diverging block boundary would be a single grep across two log files.
The deferred-encoding path (CollectDeferredUpdate + ApplyDeferredUpdates)
parallelises EncodeBranch + merge work at apply time. The cache
correctness consequence: between collect and apply, sd.mem holds the
old state while the cache is also unchanged. When apply finally fires
(end of Process or duplicate-prefix flush mid-Process), sd.mem
advances but the cache isn't touched — CollectDeferredUpdate doesn't
have a cache hook (and wiring one breaks
TestSharedDomain_RepeatedUnwindAcrossStepBoundary +
TestCustomTraceReceiptDomain because it violates an implicit
trie-during-Process cache stability invariant).

The result on the FV bench: cache stays at the very-first-Process's
read-side L3 fallback bytes for prefixes the trie writes, while
ctx.Branch advances to each block's actual state. Divergence on every
hot prefix (root, root-zone children) starting from block 2.

Use CollectUpdate (inline) instead. CollectUpdate writes
sd.mem + WarmupCache + BranchCache atomically at fold time via
PutBranch — cache mirrors sd.mem at every write, the trie sees its own
writes consistently, and the cross-Process cache state matches what
post-FCU MDBX commit produced. Loses the encoder's parallel-encoding
optimisation, but bench profile is I/O-bound, not encode-CPU-bound, so
the trade is favourable.

History (ETL) writes are still inline via DomainPut. Splitting that
("sd.mem inline, history queued for flush at FCU") is the proper
architectural answer to defer the slow disk work without touching the
sd.mem invariant — tracked as a follow-up.
Bisection helper: force branchFromCacheOrDB to skip the L2 BranchCache
read path entirely so every read goes via ctx.Branch (sd.mem → MDBX).
Cache writes still fire so verify-mode can keep comparing cache vs
canonical. Flipping the env at runtime distinguishes "cache holds bad
data" (bench passes further with cache reads off) from "deeper compute
bug" (same failure regardless).

Used in the 2026-05-06 investigation to confirm the cache was actively
corrupting block 13's compute on the canonical SSTORE-bloat bench: with
cache reads on, wrong-trie-root at block 13. With reads off, blocks
13-16 produce the correct roots and the bench advances to a separate
failure at block 17 (unrelated pre-existing bug).

Default off; gate via env DISABLE_BRANCH_CACHE_READS=true.
When verifyBranchCache=true and a cache hit disagrees with ctx.Branch,
sample sd.mem, sd.parent.mem, and tx-direct (MDBX) for the same prefix
and dump all layers in the divergence log line. Comparing those four
byte sequences against the cached and canonical bytes pinpoints which
state layer holds the bytes the cache disagrees with — the rewriter we
need to identify before fixing the canonical-store-divergence bugs the
cache currently exposes.

Decision matrix (read off the log line):

- cache != tx, sd.mem == cache → in-memory writer is fresh, MDBX is
  stale (commit-timing issue).
- cache != tx, tx == ctx.Branch, sd.mem != cache, parent.mem != cache
  → MDBX has been rewritten by something outside the CollectUpdate
  write path (collation, file build, squeeze).
- cache != ctx.Branch, parent.mem matches ctx.Branch but sd.mem doesn't
  → parent merge is the source.
- cache != ctx.Branch, all of sd.mem / parent.mem / tx == ctx.Branch
  → cache itself was populated incorrectly (write-side bug).

Three changes:

1. SharedDomains.ProbeReadLayers (db/state/execctx/domain_shared.go):
   public method that samples sd.mem, sd.parent.mem (private field
   accessed from the same package), and tx.GetLatest. Read-only; copies
   bytes so callers can hold them past tx lifetime.

2. TrieContext (execution/commitment/commitmentdb/commitment_context.go):
   add probeSd + probeTx fields populated at trieContext()
   construction; expose ProbeStateLayers method that delegates to
   sd.ProbeReadLayers. The local `sd` interface gets the
   ProbeReadLayers method too so the duck-typed reference can call it
   without an import cycle to execctx.

3. branchFromCacheOrDB log site (execution/commitment/hex_patricia_hashed.go):
   on divergence with verifyBranchCache, type-assert ctx for the probe
   interface and append sd_mem / parent_mem / mdbx fields to the log
   line. Existing field shape preserved for log parsers; new fields
   are additive.

Pre-existing test failures
(TestSharedDomain_RepeatedUnwindAcrossStepBoundary,
TestValidateChainAndUpdateForkChoiceWithSideForksThatGoBackAndForwardInHeight)
are unchanged — they were failing on the stack before this probe
landed and are part of what the divergence work is meant to localise.
Per-write provenance for divergence-detection diagnostics. When a
divergence fires (cache hit disagrees with ctx.Branch), we now log
which write site produced the cached bytes and when, so we can
correlate the bad write against the FCU / build / step timeline.

Tag fields added to branchCacheEntry:
- origin       short label of the write site (e.g. "CollectUpdate",
               "L3-fallback-read")
- writeSeq     monotonic counter per BranchCache instance
- writeTimeNanos unix nanos at write time

Put / PutIfClean signatures take an origin string. Two writers
updated:
- BranchEncoder.CollectUpdate → "CollectUpdate"
- branchFromCacheOrDB L3-fallback Put → "L3-fallback-read"

GetWithOrigin returns bytes plus the metadata; uses a non-counting
peek so it can be called alongside Get without double-counting hits.

The divergence-detection log site at branchFromCacheOrDB now appends
cache_origin / cache_seq / cache_t_ns fields. Combine with the
existing sd_mem / parent_mem / mdbx fields to localise both who wrote
the stale bytes and which layer the canonical value lives in.

Pre-existing test failures
(TestValidateChainAndUpdateForkChoiceWithSideForksThatGoBackAndForwardInHeight)
are unchanged from previous commits.
BranchCache previously sat in front of the sd.mem -> parent.mem -> MDBX
read chain (consulted in branchFromCacheOrDB before ctx.Branch). The
shared aggregator-scope cache was written from CollectUpdate by every
SD running commitment compute, including fork-validator SDs whose
writes never reach MDBX. Origin-tagged probe (run-step7b-probe-sdid)
showed five distinct SD pointers writing the same prefix to a single
cache entry, so any reader whose lineage didn't match the most-recent
writer saw bytes that disagreed with MDBX -> wrong trie root from
block 13 onward in the canonical SSTORE-bloat fork bench.

Layering after this change:

  Read:  sd.mem -> sd.parent.mem -> branchCache -> aggTx (MDBX)
  Write: sd.mem only (DomainPut path)
  Flush: sd.mem -> MDBX, then branchCache.Clear()

The cache now mirrors MDBX-flushed bytes only. Writers' in-flight bytes
live in sd.mem above; cache hits below sd.mem are always equivalent to
reading MDBX, so cross-SD pollution is impossible by construction.
Cache fills lazily on the MDBX-read path inside sd.GetLatest, and
clear-on-flush prevents pre-flush bytes from coexisting with new MDBX
state. Per-key invalidation is a follow-up (PR2).

BranchCache entries gain a step field so Get returns (data, step, ok)
matching the aggTx contract. Without this, sd.GetLatest's cache hit
returned step=0 and CheckDataAvailable rejected the boot SeekCommitment
with "commitment state out of date".

Removed:
  - cache.Put from CollectUpdate (commitment.go)
  - cache.Put + divergence detection from branchFromCacheOrDB
    (hex_patricia_hashed.go); now just calls ctx.Branch
  - L3-fallback Put (cache fills via sd.GetLatest now)

Validated on canonical cold bench (run-step8b): first FCU VALID, all
payloads through end VALID, 0 cache divergences, 0 wrong-root errors.
Prior probe bench had 23 divergences and INVALID payloads from the
fail block onward.

Probe scaffolding (SiteIdentity, ProbeStateLayers, divergence counters)
left in place for now; can be stripped in a cleanup follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…ache state

Update the BranchCache type comment to reflect the architectural
state after the WarmupCache consolidation (steps 2a-2c, 3, 4):

- BranchCache is the single branch cache (WarmupCache deleted)
- Aggregator-scope lifetime, plumbed via BranchCacheProvider
- Passive store: cache itself never reaches into underlying state
- Branch warmer is branch-scoped; no leaf-data prefetch
- Block-processing trie walker takes Updates from executor +
  memoization for siblings — no prefetch needed
- Witness / proof generation walker drives its own state reads;
  if that path turns out to be cold-bound it indicates a need for
  separate account/storage caches (treat as separate concern with
  different scope/lifetime/invalidation; do not regrow the branch
  warmer to cover it)
- disk_sto / disk_acc counters on cache-fp log surface any
  unexpected fall-through to ctx.Account / ctx.Storage as a signal
  of memoization gap or missing walker-side prefetch

Doc-only; no behaviour change.
Adds a third cache tier between the root-pin slot and the LRU tail:
a per-prefix pinned map fed by PinEntry. Pinned entries:

- Never evict (no LRU pressure on this tier).
- Are checked in lookup before the LRU tail, after the root slot.
- Survive Put/SD.Flush updates: a Put for a pinned prefix updates
  the pinned entry in place rather than displacing it. Cross-block
  correctness via the existing dirty-flag invalidation discipline
  is preserved — the new bytes land in the same pinned slot.
- Carry the same metadata as Put-tier entries (step, origin,
  writeSeq, writeTimeNanos) so divergence-detection and Stats
  treat them uniformly.

Sized by the preload policy. Intended consumer is the storage
trunk preload for big contracts (the 'storage root trunk cache for
big accounts' direction): per-contract trunk branches at depth
65-70 get pinned at SD/cache creation, persist for the cache's
lifetime.

PinEntry is the public API; pinnedHits/pinnedMisses atomic
counters are the new stats. PinnedCount() exposes current size for
observability.

Step 2 of the storage-trunk pin prototype.
Adds a function to pre-pin commitment branches for a given contract's
storage subtree. Walks the trie depth-by-depth from depth 64
(storage subtree root) down to maxDepth: reads each branch via the
supplied CommitmentReader, pins it via BranchCache.PinEntry, decodes
the child bitmap, and recurses only into children that actually
exist (no blind 16-way probing).

contractHash is keccak256(address); the trunk lives at the prefix
corresponding to the first 64 nibbles of the storage path.

For a dense storage subtree (the SSTORE-bloat workload's bloat
contract), expected pin count is ~16 + 256 + 4096 ≈ 4.4 K branches
at depth 65/66/67, plus the root at depth 64. Sparse subtrees
produce fewer.

Loading strategy: per-prefix lookups via the reader. Simplest
correct implementation. A bulk seg.Getter range-scan over sorted
.kv would amortize disk seeks (per the parity-cluster observation
in the consolidation memo) but requires building a prefix-range
API on top of recsplit; defer until per-prefix lookup is shown
to bottleneck.

Step 3 of the storage-trunk pin prototype.
Adds a SharedDomains constructor hook that, when PIN_CONTRACT_TRUNKS is
set, fires a one-shot background goroutine to preload the
storage-subtree-trunk of each listed contract into BranchCache's
pinned tier. Format: comma-separated list of 64-hex-char contract
hashes (each is keccak256(addr)).

Mechanism:
- BranchCache.TryClaimPreload (atomic CAS) ensures the goroutine fires
  exactly once per cache lifetime, even though many SDs may be
  constructed (per-tx instances etc.).
- Goroutine wraps sd.GetLatest as a CommitmentReader and calls
  commitment.PreloadContractTrunk for each contract hash, depth 64-70.
- Logs progress per contract on completion.

Closure-over-(sd, tx) is the prototype shape — works for the bench
(both live for the whole process). Production deployment needs to
revisit the lifetime — sd's tx may not outlive the goroutine.

Step 4 of the storage-trunk pin prototype. Bench measurement is
the next step (commit 5).
Previous async-goroutine shape (d204c1b) shared the SD's MDBX
tx with the calling thread. Concurrent cursor use under the same
tx tripped Go's cgo-pointer-pinning runtime check:

  panic: runtime error: cgo argument has Go pointer to unpinned
  Go pointer

surfacing in an unrelated PruneBlocks goroutine during boot.

Make the preload synchronous in the SD constructor for now: same
TryClaimPreload guard (fires once per cache lifetime), but no
goroutine. Boot pays the per-contract preload time as a one-off.

Background-with-own-tx is the proper shape and remains a
follow-up; owning the SD's tx exclusively for the preload
duration is the safe shape until that lands.
… cap

The previous bench (run-pin-trunk-instrumented-cold-cgroup-191347)
hung at SD construction with no [trunk-preload] log lines for 5+
minutes. Erigon never reached "engine RPC ready" so all blocks
came in as SYNCING.

Two changes to localise + bound:

1. **Localisation**: add INFO logs at triggerTrunkPreload entry,
   per-contract starting/done with took, and a 500-prefix
   progress log inside PreloadContractTrunk. Whatever it does
   (or hangs on) is now observable.

2. **Bound**: cap PreloadContractTrunk at 10000 branches
   (vs ~4.4K expected for a saturated 4-level subtree at
   maxDepth=67). Drops maxDepth from 70 → 67 in the trigger
   (depth 64-67 = 16+256+4096 max branches) so we don't
   recurse into the per-slot tail where pinning has no value.
   Preload fails-fast on pathological subtrees rather than
   blocking SD construction indefinitely.
The previous shape (d204c1b) ran triggerTrunkPreload BEFORE
sd.SeekCommitment in NewSharedDomains. Bench result: when the
preload fired (PIN_CONTRACT_TRUNKS set), every subsequent block
came back SYNCING — engine kept attempting backward-download which
fails on this peerless setup, no block ever validated, no cache-fp
ever fired. Without the preload firing, the same binary works
fine (verify-bench PASS at 3.26s).

Hypothesis (untested but matches the symptom): preload's
sd.GetLatest reads ran before SeekCommitment had resolved the SD's
view of the chain head. Pinned values were therefore inconsistent
with the committed state, and the trie compute on the first block
got wrong root → SYNCING → backward-download → no peers → death
spiral with no Flush ever updating the (stale) pinned entries.

Fix is mechanical: move the preload call to after SeekCommitment.
The TryClaimPreload guard still ensures fire-once-per-cache
lifetime.

If subsequent bench shows pin_count > 0 + pin_hit > 0 + blocks
validating normally, the hypothesis is confirmed; if SYNCING
repeats, the bug is something else and we need to revert and
debug differently.
…ParaTrieDB

Previous prototype iterations both broke block validation:
  1. Async sharing the SD's MDBX tx (d204c1b) → cgo
     "unpinned Go pointer" panic from concurrent cursor use.
  2. Synchronous from NewSharedDomains (5a81976 / 4c9ead456d) →
     blocked the engine HTTP handler for ~3-4s during the preload
     window, causing the bench's first NewPayload to be dropped.
     Confirmed: the bench's height=24358001 is ABSENT from the
     erigon log; the next received block (24358002) then fails
     backward-download (no peers) → SYNCING forever.

Restructure:
  - Move trigger from NewSharedDomains to EnableParaTrieDB. The
    latter is called from the staged-sync exec-stage init, NOT
    from request handlers, AND has access to a kv.TemporalRoDB.
  - triggerTrunkPreload now takes the DB (not a tx) and spawns
    a goroutine that opens its OWN tx via db.BeginTemporalRo.
    No shared cursors with the main pipeline; no blocking the
    engine.
  - Reader uses tx.GetLatest directly (not sd.GetLatest) — the SD
    layering would re-introduce shared-state risk and isn't needed
    (pinned bytes don't depend on sd.mem state).

Same TryClaimPreload guard ensures the preload fires once per
BranchCache lifetime regardless of how many SDs construct.

If this works the bench should:
  - Show [trunk-preload] log lines firing once
  - Pin ~4369 branches
  - TEST block cache-fp shows pin_hit > 0 and files_comm < 1K
  - All blocks validate normally (no SYNCING failure)
Make the trunk-pin maxDepth configurable via env (default 67) so we can
sweep depths to find the memory/perf sweet spot without rebuilding.
Bump the per-contract maxBranches cap from 10K to 200K so deeper
saturated subtrees don't get truncated mid-walk.
The previous code disabled the Warmuper for the parallel commitment path
out of concern that it would interact with the calculator's SetUpdates
call. In practice the Warmuper's reads are independent of the
calculator's update buffer — they pre-fetch branch data while EVM
execution runs, and the calculator's SetUpdates only affects
ComputeCommitment's input set, not the warmup paths.

Re-enabling produces a measured 8× throughput improvement on the
perf-devnet-3 SSTORE-bloated benchmark (block 24358306, the canonical
fixture for #20920), restoring the win first observed in Run H/I of the
trie-perf investigation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds atomic counters (branch hit/miss/evict + bytes-served, account
hit/miss, storage hit/miss) to WarmupCache, plus a Stats() string
formatter and ResetStats() for per-Process accumulation reset. Counters
are updated on every Get/Evict path (existing Put paths were already
counted via cache size).

Useful for:
- Confirming warmup effectiveness in production logs
- Per-block diagnostics when investigating commitment perf
- Future per-pool dashboards once a coordinator/observability layer
  lands (tracked separately)

No behavior change beyond the counter updates themselves. Stats() format
is one line, suitable for embedding in the existing
LogCommitments output. ResetStats() zeros counters without touching
cached data — useful for per-Process windowed measurement. Clear() also
resets counters along with the data, since data and counters were
accumulated together.

Test: TestWarmupCache_Stats covers hit/miss/evict accounting across
branch/account/storage paths and verifies Stats() format + ResetStats()
preserves data.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pure refactor — behavior preserved. Lifts the unfold-loop from
HexPatriciaHashed.followAndUpdate into its own method, parameterized
over (hashedKey, plainKey) and intended as the per-key traversal
primitive that future orchestrators consume.

Today only followAndUpdate calls it, replacing the inline loop with a
one-line call. The extracted method preserves the existing metric
attribution (StartUnfolding) and trace-print behavior verbatim.

Why now: this is the second step in the representation-reduction
sequence (see agentspecs/trie-data-pipeline-complexity-tax.md). Future
PRs will introduce orchestrators that drive unfold-only walks of
touched-key paths to fill cell state without going through the full
fold/update cycle:

  - Cache populator (decoded-payload BranchCache) needs to walk a
    touched-key path and capture the cells encountered, without
    triggering fold or modifying the trie's update buffer.
  - Stage E parallel pre-unfold orchestrator drives unfoldKeyPath
    across multiple HexPatriciaHashed instances concurrently to
    pre-warm trie state before commit.

Both consume the same primitive. Centralising it now means each future
orchestrator is a thin wrapper rather than a duplicate of the
unfold-loop logic.

Tests: full commitment test suite passes without modification (all 8+
test files in execution/commitment/), confirming the refactor preserves
followAndUpdate's behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds the carry-as-is correctness invariants from the PR #19954
investigation as scaffolding on the existing WarmupCache:

  - branchEntry.dirty atomic.Bool — signals "stale until cleared"
  - PutBranchIfClean(prefix, data) bool — skips write if entry dirty
  - MarkBranchDirty(prefix) — mark for later refusal of stale puts

These are scaffolding additions; no callsites use them yet. Existing
PutBranch unconditionally overwrites and clears any prior dirty flag
(creates a fresh entry), preserving today's semantic exactly for
existing callers.

Why now: the prototype investigation (see
agentspecs/commitment-cache-prototype-dev-context.md) found that
inline-invalidate-on-write is incompatible with deferred encoding —
update-in-place breaks correctness because there's a window between
fold (computes hash, holds new state) and encoder (writes encoded
bytes) where readers see stale cached bytes. The reth-research
(agentspecs/reth-1ggas-research.md §4) calls the dirty-flag pattern
out as the design that resolves this without forcing synchronous
encoding: the encoder marks the entry dirty BEFORE its own write
completes, so any racing read knows to bypass the cache for that key.

Today's WarmupCache lifecycle (per-Process, warmup completes before
fold begins) does NOT exhibit this race — these invariants are
infrastructure for the future cross-block persistence work where
warmup-style writers can outlive their parent Process.

Tests:
- TestWarmupCache_DirtyFlag: PutBranchIfClean refuses dirty entry,
  unconditional PutBranch clears dirty.
- TestWarmupCache_DirtyFlag_MarkAbsentKey: marking absent key is
  no-op (no panic, no entry created).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds an additive read method that returns cached branches in already-
decoded form, lazy-decoding on first decoded-read per entry and caching
the parsed cells for subsequent reads. No existing callsite changes;
existing GetBranch / GetAndEvictBranch / PutBranch callers continue to
work with encoded bytes unchanged.

Why now: this is step 5 of the representation-reduction sequence (see
agentspecs/trie-data-pipeline-complexity-tax.md). The trie's read path
currently does GetBranch (encoded) + DecodeBranchInto on every cache
hit — paying decode CPU on every read. Switching that callsite to
GetBranchDecoded (in a separate later commit) eliminates the redundant
decode.

The ENCODED form remains the source of truth — the encoder needs it
for the merge-with-prev step, and it's what gets written to disk via
PutBranch. The decoded form is derived lazily and cached alongside
the entry. When PutBranch overwrites an entry, the new entry starts
fresh and the next decoded read re-derives from the new bytes.

API design notes:
- Returns (bitmap, *[16]cell, ok). Caller derives touchMap/afterMap
  from bitmap based on its own deleted-vs-present-after context — the
  cache stores cells independent of that context so the same entry
  serves both readers.
- The returned *[16]cell aliases entry-owned storage. Read-only
  consumption is safe across concurrent calls (decode runs at most
  once per entry via sync.Once); MUST NOT be modified in place.
- Decode error → ok=false (don't count as hit OR miss; caller falls
  through to canonical re-read).

Tests:
- TestWarmupCache_GetBranchDecoded: round-trip equality with direct
  DecodeBranchInto, plus same-pointer reuse on repeat reads.
- TestWarmupCache_GetBranchDecoded_Miss: behaves like GetBranch on
  absent keys.
- TestWarmupCache_GetBranchDecoded_TruncatedData: graceful failure
  on corrupt entry (no panic).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…ng payloads

Closes a timing hole that surfaced once we wired the aggregator-scope
BranchCache: between an FCU completing and the next newPayload, MDBX
hasn't been committed yet (RunLoop's CommitCycle only fires under
memory pressure), but currentContext.mem holds the latest writes from
MergeExtendingFork. The fresh doms created in ValidateChain has no
parent and a fresh roTx, so its ctx.Branch reads stale-MDBX while the
aggregator-scope BranchCache (populated by the prior FV's
CollectUpdate writes) holds the fresh state. That's the cross-newPayload
divergence pattern observed in the bench (8-61 divergences and
wrong-trie-root errors at block 3-14 across runs).

Set doms.SetParent(currentContext) when the new payload extends the
current canonical head (header.ParentHash == ReadHeadBlockHash). For
fork payloads that don't extend head, leave parent unset:
unwindToCommonCanonical below reverts doms's view to the common
ancestor, and exposing currentContext.mem (post-divergence canonical
writes) via the parent chain would shadow the unwound base and break
fork validation. Verified by TestReorgsWithInsertChain — the
"head-only" predicate is what the current single-canonical-chain SD
topology supports.

A proper per-branch SD lineage (each fork's validation chains to the
last validated SD on its own branch, not always currentContext) is the
follow-up needed for concurrent multi-fork validation. The current
design supports a single canonical chain only; that's enough to close
the divergence we have today, with the lineage extension tracked
separately.
Foundation for the "Snapshot vs MDBX read-cost equivalence"
investigation (memory: snapshot-vs-mdbx-performance-equivalence.md).

This file produces the headline ratio that quantifies the gap the
investigation aims to close: warm-cache reads from snapshot .kv files
should cost the same as warm-cache reads from MDBX (same disk, same
page cache). H0 measures how far apart they are today.

Five sub-benches:
  - MDBX_path        full chain, key in MDBX
  - File_path        full chain, key in file
  - Forced_file_path file-only debug path, file-resident keys
  - Forced_db_path   DB-only debug path, MDBX-resident keys
  - Bloom_miss_path  file-only debug path, MDBX-resident keys
                     (file misses in xorfilter for every probe)

Two operating modes; only synthetic is wired in this commit:

  - Synthetic (testDbAndAggregatorBench fixture): writes 64 full
    16-tx steps, BuildFiles + repeated PruneSmallBatches drains all
    but the tip step into files. Phase 2 keys at txNums past the
    built-step boundary stay in MDBX. Partition by *actual* residency
    after setup so bench inputs match where keys really live.

  - Real-datadir (--snapdatadir flag): TODO. Opens an existing
    chaindata+snapshots datadir read-only and picks keys via cursor
    iteration / .kv decompressor walk. Required for production-
    relevant numbers since synthetic has tiny files and small values.

Initial synthetic results on AMD EPYC 4244P (Accounts domain):
  MDBX_path        173 ns/op
  File_path        226 ns/op   (1.31x MDBX)
  Forced_file_path  30 ns/op
  Forced_db_path   158 ns/op
  Bloom_miss_path   30 ns/op

Synthetic dataset is too small to surface the production gap that
pprof shows (xorfilter at 35% CPU on real bloat workload). H1-H4
benches and the real-datadir mode are the next steps.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds the --snapdatadir flag path to the H0 bench. Opens an existing
chaindata + snapshots datadir read-only via the same recipe as
cmd/integration (mdbx Accede + state.New + temporal.New) and picks
keys by cursor-walking the per-domain values table.

Pragmatic adjustments:

  - On heavily-pruned production datadirs (perf-devnet-3-run was
    100% pruned), every MDBX values-table row is step-shadowed by a
    file, so getLatestFromDb returns ok=false. The MDBX-side
    sub-benches skip in this case; File_path numbers stand on their
    own and the synthetic MDBX_path baseline serves as the cross-
    mode comparator.

  - skipIfEmpty short-circuits per sub-bench rather than failing the
    whole run, so we can still get the file-path numbers.

First production numbers (AMD EPYC 4244P, AccountsDomain, 2012
file-resident keys from perf-devnet-3-run, fully pruned):

  File_path        211 ns/op   (synthetic was 226; essentially same)
  Forced_file_path  30 ns/op   (synthetic was 30; identical)

Surprising finding: real .kv file reads cost the same as synthetic.
This means production bloat-workload bottleneck is NOT in
getLatestFromFiles — it must be in HistorySeek (.ef history files
walked by HistoryStateReader.GetAsOf). The GetAsOf shortcut work
flagged in getasof-regression-suspect.md is the right lead.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two related additions to the snapshot-vs-MDBX perf-equivalence
investigation (memory: snapshot-vs-mdbx-performance-equivalence.md):

1. H_GetAsOf bench (db/state/snapshot_vs_mdbx_bench_test.go).
   New runHGetAsOf with four sub-benches for HistorySeek-via-GetAsOf
   on file-resident keys: GetLatest_baseline, GetAsOf_recent (asOf
   near endTxNum), GetAsOf_mid (asOf at endTxNum/2), GetAsOf_floor
   (asOf=1). Tests the path the calculator's HistoryStateReader.Read
   uses, which is distinct from getLatestFromFiles measured in H0.

   Real-datadir results on perf-devnet-3 (AccountsDomain, endTxNum=2.9B):
     GetLatest_baseline 202 ns/op   0 allocs
     GetAsOf_recent     570 ns/op   0 allocs   <- 2.8x baseline, no result
     GetAsOf_mid        235 ns/op   5 allocs
     GetAsOf_floor      196 ns/op   4 allocs

   GetAsOf_recent (the calculator's pattern after PR #21010) scans
   the .ef looking for a record at-or-after endTxNum-1, finds none
   (most keys haven't changed in the last txNum), falls through to
   GetLatest. The 370ns/op overhead vs GetLatest is wasted scan.
   Confirms the GetAsOf shortcut described in
   getasof-regression-suspect.md as a real lever, though small in
   absolute terms (~2ms/block on the bloat workload).

2. Surface "took" + "keys" on the existing [commitment][cache-fp]
   Info log line (commitmentdb). Was already computed in the
   debug-level "[commitment] processed" log, but the bench runs with
   --log.dir.disable so debug logs aren't captured.

   This made it possible to attribute the 4.3s gap inside
   newPayload(TEST block) directly: the calculator's ComputeCommitment
   takes 4220ms for the 5910-key bloat block — 91% of the entire
   block wall time. Per-key cost is ~700us, consistent across blocks
   of all sizes. The actual perf lever for the bloat workload is
   making per-branch ComputeCommitment cheaper, not file/state reads.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds three groups of fields to the existing
[commitment][cache-fp] log line so the calculator's per-block
behaviour is observable at Info level (the bench runs with
--log.dir.disable, so debug logs aren't captured):

  - took, keys: ComputeCommitment wall + key-count for the block.
    Pre-existing internally, now surfaced.
  - load, skipped, reset: process-cumulative counts of
    computeCellHash decisions:
      * load    = had no memoized stateHash, fetched value from DB
      * skipped = had memoized stateHash, reused without fetch
      * reset   = had stateHash but had to invalidate it
    Surfaced via new commitment.SkipLoadResetCounters().
  - files_acc / files_sto / files_code / files_comm: per-domain
    file-read counts pulled from sd.Metrics().Domains[domain].
    Decomposes the aggregate `files=N` from the [domain reads]
    log line into its actual sources (e.g. on the SSTORE-bloated
    block the 32k file reads break down as 5.9k Storage value
    loads + 26.6k Commitment branch reads + a handful of others).

All counters are cumulative; per-block deltas are obtained by
subtracting consecutive cache-fp lines.

Pure observability — no behaviour change. Used as the measurement
framework for the snapshot-vs-MDBX perf-equivalence investigation
and the follow-on commits that target specific levers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
mh0lt added 2 commits July 28, 2026 18:32
…poralTx

The overlay is a general KV/temporal db, not block-specific, so drop the
misleading Block prefix (and ParentBlockOverlayTemporalTx -> ParentOverlayTemporalTx).
It was just OverlayTemporalTx on the parent, existing only to reach the
unexported parent field from another package. The sole caller runs before
InitBlockOverlay, so doms has no overlay of its own and OverlayTemporalTx
already yields exactly the parent chain.

Copilot AI 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.

Pull request overview

Copilot reviewed 96 out of 96 changed files in this pull request and generated 1 comment.

Comment thread execution/execmodule/getters.go Outdated
Comment on lines 80 to 82
view := sd.OverlayTemporalTx(roTx)
e.lock.RUnlock()
return view, func() { roTx.Rollback() }, nil

@yperbasis yperbasis left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Requesting changes on 868efdcf4e. All nine blockers from the last round are addressed, and the merge of main (1e9bae94fe) audited clean. The items below are new findings, mostly in the fixes themselves — consolidated from my pass, the open Copilot threads (each re-verified against this head), and a Codex pass.

P1

  1. Chain-aware HasPrefix can self-deadlock via recursive RLock. db/state/execctx/domain_shared.go:881: confirm runs inside p.mem.IteratePrefix, which holds latestStateLock.RLock across callbacks (db/state/temporal_mem_batch.go:710), and getLatestMetered re-RLocks the same mutex via sd.mem.GetLatest. Once a writer queues (putLatest — every DomainPut — takes the write lock), the inner RLock blocks behind it: under background commit + parallel exec, an exec worker's create-collision HasPrefix and the apply goroutine's DomainPut wedge each other mid-block. Same shape on parent mems vs closeAllGensClearRam. Restructure to the two-phase shape IteratePrefix already uses (collect candidates under the lock, resolve after it is released) — that also makes the returned "first live key" follow global key order, which is what the docstring claims; today it is per-generation scan order.

  2. A failed background commit still lets queued descendants commit over the hole. execution/execmodule/bg_commit.go:158: the failure branch triggers stopNode asynchronously and returns; genEpoch is unchanged, so the worker's next iteration commits an already-queued child generation before cancellation propagates. Each generation flushes only its own delta, so the DB advances past the failed parent with its state missing — durable, and it survives the restart the fatal path exists to enable. Poison synchronously before returning: bump genEpoch under fgMu (the supersede machinery already skips stale generations) or a terminal worker flag checked at runCommit entry.

P2

  1. WaitIdle tears down after its foreground barrier times out. execution/execmodule/exec_module.go:356 with the 5s production timeout (node/eth/backend.go:1594): on timeout it still runs stopCommitWorker + closeAllGens, so a slow FCU keeps reading through parent SDs while they are closed and wiped (misses degrade to stale committed reads until bacgroundCtx cancellation aborts the run), and its later enqueueCommit parks a generation with an open roTx in a channel nobody drains — the chainDB.Close hang WaitIdle exists to prevent. (Covers the open Copilot thread on exec_module.go:331.) On timeout, don't close generations: bump genEpoch, make enqueueCommit refuse stale/post-stop generations (roll the generation back instead of parking it), and log loudly — a visible bounded wait beats closing SDs under a live reader.

  2. The prune handoff dropped main's eager cleanup ordering. execution/execmodule/forkchoice.go:795 spawns the prune goroutine without calling cleanupBeforeSemaRelease() first (main's handOffSemaphore did). ResetPendingUpdates/ClearWithUnwind now always run concurrently with RunPrune, and a fast prune can fgRelease before the deferred cleanup runs, so the next acquirer observes unsettled state — the invariant documented at forkchoice.go:376. One line: run cleanupBeforeSemaRelease() before go; the "run this eagerly" comment is stale for both handoff paths.

  3. beginOverlayOrRo can return a nil view with a nil error (confirms today's Copilot thread). execution/execmodule/getters.go:80: flushBlockOverlayToDB (bulk >16-block InsertBlocks) calls sd.CloseBlockOverlay() (inserters.go:52) without e.lock, so the overlay can vanish between the getter's BlockOverlay() check and OverlayTemporalTx's re-load — GetPayloadBodies* then panics on the nil tx. A plain fallback to the already-open roTx is not enough: that snapshot predates the overlay flush and would miss the just-inserted blocks. Either take e.lock around the close, or on a nil view roll back and retry with a fresh roTx.

  4. The txpool cache swap is still ungated. node/eth/backend.go:735 hands the txpool the published-SD Cache even with FcuBackgroundCommit=false — a default-path behavior change this PR states it avoids. The read-after-close path degrades safely (mem reads are lock-serialized; misses fall through), but a view spanning FCU teardown falls back to a pre-commit coreTx → transient stale nonce/balance, and OnNewBlock is a no-op so nothing refreshes it. Gate the swap on the flag now; the leased/refcounted published SD is #22494.

P3

  1. db/kv/membatchwithdb/memory_mutation.go:962,995MemoryMutation.GetAsOf/HistorySeek still swallow DomainReader errors (err == nil && ok); mirror the read-view fix.
  2. Shutdown runs WaitForWarmup after WaitIdle/closeAllGens (node/eth/backend.go:1593-1605) while warmBody reads the published SD. Reordering alone is insufficient (newPayload can spawn new warmups); add a stop-gate on the read-aheader, then join.
  3. TestNotificationDispatchBackgroundCommit (execution/execmodule/exec_module_test.go:1831) is still skipped with a rationale the SetParent chain has since fixed, and no tracking issue. Un-skip (likely green), and add a failure-interleaving test pinning point 2 (a failed commit must not let a descendant commit).
  4. The chain path of IteratePrefix (db/state/execctx/domain_shared.go:913) materializes every candidate key before the first emit — early-exit callers lose streaming, and a catchup-window self-destruct of a large pre-Cancun contract under an in-flight generation spikes memory. Streaming merge, or at least a comment.
  5. Comments/docs: HasPrefix carries two stacked doc paragraphs (domain_shared.go:862-874) — keep one, stating the real ordering contract; enqueueCommit's "non-blocking by design" (bg_commit.go:97) holds only via the maxInFlightCommits bound (open Copilot thread); RawBlock.AsBlock (execution/types/block.go:811) should route through SetBlockAccessList for uniform no-aliasing (currently unreachable — zero non-test callers; open Copilot thread).
  6. Range/stream readers remain leaf-only (SharedDomains.RangeAsOf/HistoryRange/IndexRange) or committed-only (view RangeAsOf/IndexRange/HistoryRange); list them explicitly on the #22494/#21314 pre-default-flip checklist.
  7. Carried nits: the exec3_serial.go blockNum > 0 hunk still has no stated connection to this PR; GenerateChain still uses readSD[0] without asserting it matches parent.

Copilot thread housekeeping

Resolvable as fixed on this head: the config default, GetAsOf/HistorySeek parent walks, EachStorageSlot error propagation, the BAL copy (the clone lives in Block.SetBlockAccessList), and the forkchoice "worker republishes overlay" comment. Resolvable with tracking pointers: both drainCommittedGens threads (#22494) and the getProof thread (#21314). Folded into the items above: WaitIdle (point 3), the enqueueCommit comment and AsBlock (point 11), beginOverlayOrRo (point 5). Stale: the FlushKeepMem thread (that API left the PR).

Process

The only red check is infra (kurtosis: command not found on the runner) — re-run. The PR is conflicting with main; after the next merge please repeat the per-file clobber audit (git diff <merge>^1 <merge> -- <PR files>).

mh0lt added 2 commits July 29, 2026 13:35
- domain_shared: make HasPrefix/IteratePrefix two-phase (collect candidates
  under the mem read lock, resolve after releasing it) — the previous shape
  re-entered the same RWMutex via getLatest inside an IteratePrefix callback and
  could deadlock a queued DomainPut writer. HasPrefix now returns the first live
  key in global key order.
- bg_commit: poison the commit stream synchronously on a failed durable commit
  so no already-queued descendant generation commits its delta over the hole
  before shutdown propagates; enqueueCommit rolls a generation back instead of
  parking it once poisoned.
- exec_module: on WaitIdle timeout (foreground op still holding the semaphore)
  do not close the generation chain under the live reader — poison, stop the
  worker, and log; only close generations on a clean acquire.
- forkchoice: run cleanupBeforeSemaRelease() before handing the semaphore to the
  background prune goroutine so pending-update/unwind cleanup can't race prune.
- getters: guard beginOverlayOrRo against a nil view when the overlay is flushed
  concurrently — retry with a fresh roTx that sees the flushed blocks.
- memory_mutation: MemoryMutation.GetAsOf/HistorySeek stop swallowing the
  DomainReader error.
- un-skip TestNotificationDispatchBackgroundCommit (the SetParent chain fixed it).
# Conflicts:
#	execution/builder/block_builder.go
#	execution/execmodule/block_building.go
@mh0lt

mh0lt commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 928dbef + merge da3d119 (build + make lint clean, unit tests incl. -race green, merge audited). Thanks for the very thorough pass — most of these were defects in the previous round's fixes.

P1

  1. Recursive RLock in HasPrefix. Fixed — HasPrefix and IteratePrefix now share a collectPrefixCandidates helper that gathers keys under each mem's read lock and returns them sorted; value resolution (getLatest, which re-locks) happens only after the lock is released, so no read lock is ever held across a second acquisition. HasPrefix now returns the first live key in global key order, matching the docstring (collapsed to one).

  2. Failed commit lets a descendant commit over the hole. Fixed — on a failed durable commit the worker now poisonCommits() synchronously (under fgMu) before triggering stopNode; runCommit checks the poison at entry and enqueueCommit rolls a generation back instead of parking it, so no queued or future generation advances the DB past the hole.

P2

  1. WaitIdle teardown after a barrier timeout. Reworked — on a clean acquire it drains + closes generations as before; on timeout (a foreground op still holding the semaphore) it no longer closes the generation chain under the live reader — it poisons (so a late enqueueCommit rolls back rather than parks in the stopped worker), stops the worker, and logs loudly.

  2. Prune handoff dropped eager cleanup ordering. Fixed — cleanupBeforeSemaRelease() now runs before the prune goroutine spawns (it is a OnceFunc, so the outer defer is then a no-op).

  3. beginOverlayOrRo nil view. Fixed — on a nil view (overlay flushed concurrently) it rolls back the stale roTx and retries with a fresh one that sees the just-flushed blocks.

  4. Txpool cache swap ungated. Deferred with a note: pre-PR the txpool used kvcache.NewSimple(), which no longer exists, so the correct non-bg-commit cache isn't a clean restore and guessing risks the txpool read path. Since the flag defaults to false and the leased/refcounted published SD is execution/execmodule, node/shards: remove the global Events.LatestSD published-SD pointer (decouple readers via a publication id) #22494, I'd rather gate it in that follow-up than pick the wrong constructor here — let me know if you want a specific cache wired in now.

P3

    1. MemoryMutation.GetAsOf/HistorySeek — fixed; they no longer swallow the DomainReader error.
    1. TestNotificationDispatchBackgroundCommit — un-skipped (green on this head). The failure-interleaving test pinning point 2 I can add next.
    1. Collapsed the doubled HasPrefix docstring; noted the enqueueCommit bound.

Still open (tracked, not in this push): 8 (read-aheader stop-gate at shutdown), 10 (streaming IteratePrefix — commented for now), 12 (leaf-only range/stream readers → #22494/#21314 checklist), 13 (carried nits). I'll fold 8 and the point-2 test into the next commit unless you'd prefer them here.

The merge touched builder/execmodule block-building (main's #22835 Stop(ctx) deadlock fix) — reconciled to keep both main's ctx-aware Stop/done-channel and this PR's pinned ScopedReadView release + fgTryAcquire.

@mh0lt
mh0lt requested a review from yperbasis July 29, 2026 13:48

@yperbasis yperbasis left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please split this PRs into several smaller ones – right now it's too big to review. Ideally they should be independent, but can be stacked if necessary. Correctness fixes should come first.

@mh0lt

mh0lt commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Proposed split

Per the request to break this up, here's the shape. The correctness fixes that don't depend on the background-commit machinery come out as three independent PRs, each based on main (mergeable in parallel). What remains here is the background-commit feature itself, rebased on top.

PR 1 — exec/RPC robustness (independent)

  • Guard a nil header in eth_getProof (no crash when the header is missing).
  • Don't persist a genesis changeset in serial execution.
  • Treat an empty apply-loop close as clean completion rather than "more work pending".

PR 2 — overlay / mem-batch read correctness (independent)

  • OverlayTemporalReadView / MemoryMutation: surface a DomainReader error instead of swallowing it and falling through to the committed tx.
  • Keep standalone inverted-index writes in a per-batch local collection.

PR 3 — block access list as a first-class block object (independent)

  • Carry the EIP-7928 BAL on the block alongside header/body, and copy it on set so a transaction-owned slice can't alias the block's BAL.

This PR (#21414) — FCU background commit (rebased onto the above once they land)

  • Everything coupled to the generation chain / SharedDomains.SetParent: chain-aware HasPrefix/IteratePrefix/GetAsOf and published-SD reader routing, background commit + prune coordination, poison-on-failed-commit, WaitIdle teardown, and the changeset-reconstruction + fold-ahead root fix.

Merge order (our discipline)

PR 1, PR 2, PR 3 are independent and can merge in any order. This PR is held until all three are in main, then rebased so its diff is only the background-commit change. Recording the order here so we don't lose it.

I'll open PRs 1–3 next.

@mh0lt

mh0lt commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Opened the three independent PRs (all based on main):

Merge order/discipline: #22892, #22893, #22894 are independent and can merge in any order; this PR is held until all three land, then rebased so its diff is only the background-commit change.

(One adjustment from the proposed shape: the "standalone inverted-index writes in a local collection" change turned out to depend on the in-mem-history-reads infrastructure this PR builds — on main HistorySeek just delegates to GetAsOf and there's no RangeAsOf/iiMem — so it stays here rather than in #22893.)

pull Bot pushed a commit to Dustin4444/erigon that referenced this pull request Jul 31, 2026
…llowing them (erigontech#22893)

Independent correctness fix split out of erigontech#21414 (per the request to
break it up). Stands alone on `main`.

`MemoryMutation` and `OverlayTemporalReadView` `GetAsOf`/`HistorySeek`
gated the `DomainReader` result with `err == nil && ok`, so a reader
error fell through to the committed tx and was silently hidden. This
propagates the error and keeps the `ok`-based committed fallback (a
tombstone is `ok=true`, so it is not resurrected).

No dependency on the background-commit work; part of the split recorded
on erigontech#21414.
pull Bot pushed a commit to Dustin4444/erigon that referenced this pull request Jul 31, 2026
Independent correctness fixes split out of erigontech#21414 (per the request to
break it up). Each stands alone on `main`.

- **eth_getProof**: guard a nil header (no crash when the header is
missing).
- **serial exec**: don't persist a genesis changeset.
- **parallel exec**: treat an empty apply-loop close as clean completion
rather than "more work pending" (with a regression test).

No dependency on the background-commit work; part of the split recorded
on erigontech#21414.
pull Bot pushed a commit to Dustin4444/erigon that referenced this pull request Jul 31, 2026
…rigontech#22894)

Independent refactor split out of erigontech#21414 (per the request to break it
up). Stands alone on `main`.

EIP-7928 Block Access Lists are part of the payload and should be
consumed by execution from the block it is handed — the same model as
headers and bodies. Previously the BAL only existed transiently on
`RawBlock` during InsertBlocks and `RawBlock.AsBlock` dropped it, so the
block object never carried its own BAL and exec re-read it from the DB.

- `types.Block` gains an unexported `blockAccessList` sidecar
(`BlockAccessList`/`SetBlockAccessList`), carried out-of-band and never
in the block RLP/hash; `SetBlockAccessList` copies the input so a
tx-owned slice can't alias it. Regression test pins it out of RLP/hash.
- newPayload attaches the payload's BAL to the block; exec consumes it
from the block, falling back to the DB sidecar for snapshot/forward-sync
blocks.

Behaviour-preserving: the `!dbg.IgnoreBAL` gate and BAL validation are
unchanged — this only changes where exec sources the BAL (block vs
redundant DB re-read). It's the plumbing that lets the
parallel/fold-ahead commitment (in erigontech#21414) consume the BAL; nothing
computes commitment in parallel from it by itself. Part of the split
recorded on erigontech#21414.

---------

Co-authored-by: Alexey Sharov <askalexsharov@gmail.com>

@yperbasis yperbasis left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The 3 spin-off PRs have been merged into main. Plz merge latest main into this PR.

@yperbasis

Copy link
Copy Markdown
Member

@mh0lt Is the title still accurate and comprehensive?

# Conflicts:
#	db/rawdb/accessors_chain.go
#	db/state/execctx/domain_shared.go
#	execution/exec/blocks_read_ahead.go
#	execution/exec/blocks_read_ahead_test.go
#	execution/execmodule/execmoduletester/exec_module_tester.go
#	execution/stagedsync/exec3.go
#	execution/stagedsync/exec3_parallel.go
@mh0lt

mh0lt commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged current main (607ca289f0) — mergeable, build + make lint clean, and the commitment/bg-commit/wrong-root test suite green (incl. TestRecreateAndRewind, TestReorgOverSelfDestruct, TestReorgOverStateChange, execution/commitment, enginex, -race on execmodule).

This was not a mechanical merge — since this PR branched, main absorbed the commitment calculator and the glamsterdam runtime-gas EIPs (2780/8037/8038), and kept its exec-loop changeset save; this branch had diverged. Reconciliation:

  • exec3_parallel.go — took main's version (gets the gas-EIP APIs: FinalizedWrites(rules), ConsumeExecution/ConsumeState, split BlockRegularGasUsed, and completeBlock), then stripped main's exec-loop changeset accumulator so exec no longer touches changesets. The commitment calculator owns changeset reconstruction (changeset_reconstruct.go → state diffs 0-2, ComputeCommitment → commitment diffs 3), which is this PR's intended direction and avoids the double-save. changesetWindowStart stays (it feeds the calculator).
  • BAL — took main's refactors (header.HasBAL(), blockAccessListBytes()).
  • domain_shared.go — unioned this PR's readCoordinator with main's cacheApplier/visibleEnds; adopted main's new getLatestMetered(..., cacheReader()) signature at the chain-aware HasPrefix/IteratePrefix sites.
  • read-ahead — kept this PR's published-SD warmView (the merged wiring uses SetPublishedSD; the SD read-fill warms the same cache main's cache-populating getter targeted).
  • tester/builder — the merged NewExecModule combined main's stateCacheBudget with this PR's bg-commit params; fixed the tester call accordingly.

The standalone content of the three spin-off PRs (#22892/#22893/#22894) is now common with main, so the diff dropped to the background-commit change (chain-aware reader consistency, generation chain, calculator-owns-changeset, bg-commit worker).

@mh0lt mh0lt changed the title FCU semaphore decouple + foreground-priority bg-commit worker (PR #4 of the perf stack) execution: FCU background-commit worker + generation-chain reader consistency Aug 5, 2026
@mh0lt

mh0lt commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Re the title — you're right it was stale. Updated to "execution: FCU background-commit worker + generation-chain reader consistency" — the two halves the PR now is after the spin-offs landed. Dropped the "PR #4 of the perf stack" framing since the predecessors are merged.

// starts no background-commit worker — tests set DB state themselves and read
// it back deterministically. Exported from a _test.go file: usable by the
// execmodule_test binary, never compiled into a production build.
func NewGetterMockForTest(db kv.TemporalRwDB, blockReader dbservices.FullBlockReader, engine rules.Engine, config *chain.Config, logger log.Logger) *ExecModule {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

we should remove this and use ExecModuleTester instead

@taratorio taratorio left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this feature should be behind a feature flag and disabled by default because it doesn't solve any current high performance bottleneck. our efforts should be centred around new payload, not background flushing at this point in time

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants