perf(rpc): avoid historical state queries for block base fee and validators #1118
Codecov Report
:x: Patch coverage is
92.72727% with 4 lines in your changes missing coverage. Please review.:white_check_mark: Project coverage is 47.21%. Comparing base (
eb8f544) to head (76d9e3b).| Files with missing lines | Patch % | Lines |
|---|---|---|
| rpc/backend/backend.go | 50.00% | 1 Missing and 1 partial :warning: |
| rpc/backend/utils.go | 95.45% | 1 Missing and 1 partial :warning: |
<details><summary>Additional details and impacted files</summary>

@@ Coverage Diff @@
## develop #1118 +/- ##
===========================================
+ Coverage 47.18% 47.21% +0.03%
===========================================
Files 200 200
Lines 17633 17633
===========================================
+ Hits 8320 8326 +6
+ Misses 8449 8446 -3
+ Partials 864 861 -3
| Files with missing lines | Coverage Δ | |
|---|---|---|
| rpc/backend/blocks.go | 78.14% <100.00%> (+0.10%) | :arrow_up: |
| rpc/backend/chain\_info.go | 73.20% <100.00%> (+0.39%) | :arrow_up: |
| rpc/backend/backend.go | 61.53% <50.00%> (-2.10%) | :arrow_down: |
| rpc/backend/utils.go | 61.13% <95.45%> (+4.52%) | :arrow_up: |
</details>
<details><summary> :rocket: New features to boost your workflow: </summary>
</details>
CodeQL / Calling the system time
Calling the system time may be a possible source of non-determinism
CodeQL / Calling the system time
Calling the system time may be a possible source of non-determinism
Removed the wall-clock dependency: cache entries now expire by block height (reused only within 10k blocks of the block they were resolved for), so time.Now() is gone (c9661fe1).
Same fix as the other thread: the entry now stores the block height it was resolved for instead of a time.Now() expiry (c9661fe1).
@claude review
Claude finished @JayT106's task in 2m 18s —— View job
---
Code Review
---
Summary
This PR is a well-targeted optimization: it avoids costly historical state queries for base fee and miner in the most-called block/receipt RPCs. The approach is sound, the tests are thorough, and the tradeoffs are clearly documented. No consensus-breaking or state-breaking changes detected.
---
Findings
1. Misleading fallback comment in BaseFee() — rpc/backend/chain_info.go:90
if baseFee := rpctypes.BaseFeeFromEvents(blockRes.FinalizeBlockEvents); baseFee != nil {
return baseFee, nil
}
// no event: fee market inactive at this height
res, err := b.queryClient.BaseFee(...)
BaseFeeFromEvents returns nil in three distinct situations:
base_fee attribute absentbase_fee attribute present but value is malformed (tested by "pass - malformed feemarket event falls back to state query")The last two cases are not "fee market inactive" — the comment overstates when the state fallback fires. Minor, but worth fixing for future readers.
---
2. nextBaseFeeParent in processBlock still issues a historical state query — rpc/backend/utils.go:212
ctx := types.ContextWithHeight(blockHeight)
params, err := b.queryClient.FeeMarket.Params(ctx, &feemarkettypes.QueryParamsRequest{})
if err != nil {
return err
}
header.BaseFee = nextBaseFeeParent(params.Params, blockHeight, header.BaseFee)
processBlock is called for every block in eth_feeHistory. It queries FeeMarket.Params at blockHeight (historical state), then passes the result to nextBaseFeeParent. While the PR description explicitly scopes this optimization to eth_getBlockBy, receipts, and headers — and correctly notes eth_feeHistory still needs versiondb — the nextBaseFeeParent logic here is purely about accuracy (governance override reflected), not about eliminating the state query. The query itself is still historical.
This is not a regression (the old code queried state too), but it is worth calling out so the scope of the optimization is clear: processBlock is not helped by this PR.
---
3. Cache entry records served block height, not fetch height — rpc/backend/utils.go:380
b.validatorAccounts.Add(key, validatorAccountEntry{acc: acc, height: header.Height})
The cached height is the block height being served, not the height at which the gRPC query actually ran (latest). This is the intended design — the window check answers "is this entry close enough to the block I'm serving now?" — but it has an edge case:
If we serve block 1000, cache with height=1000, and later serve block 11001 (beyond the 10k window), we refetch at latest. If the validator was at the same consensus address, we cache again with height=11001. Fine. But if we serve blocks out of order (e.g., a client calls eth_getBlockByNumber for block 1, then block 2, then block 3 …), every call within 10k blocks hits the cache regardless of which block they asked for. This is the correct behavior.
The subtle case: if we serve block 50000 (cache height=50000) and then serve block 1 (gap = 49999 > 10000), we refetch. The refetch queries b.ctx (latest height = ~50000+), which may no longer know about a validator that existed at block 1. The fallback to ContextWithHeight(1) then fires. This is exactly the intended fallback path. ✓
No bug, but worth confirming the logic is intentional (it is, per the PR description).
---
4. BaseFeeFromEvents nil-return on malformed value stops attribute scan — rpc/types/utils.go:327
for _, attr := range event.Attributes {
if attr.Key == feemarkettypes.AttributeKeyBaseFee {
result, success := new(big.Int).SetString(attr.Value, 10)
if success {
return result
}
return nil // ← stops scanning, signals "no parseable fee"
}
}
On a malformed base_fee attribute, the function returns nil (triggering the state fallback in the caller). This is safe, but means a chain event with base_fee="" causes an extra state query per block lookup. Low likelihood in practice, but the behavior is non-obvious — it would read more clearly if the early return had a brief comment, e.g.:
return nil // malformed value; caller falls back to state
---
What's good
Attributes[0] positional assumption and int64 truncation.nextBaseFeeParent: extracting the governance-override logic into a named function makes the intent clear and is shared correctly between NextBaseFee and processBlock.TestGetValidatorAccount table explicitly asserts that failed lookups are not* cached (line suite.Require().Zero(suite.backend.validatorAccounts.Len(), "failed lookups must not be cached")). Calling the result a second time from cache is also verified. Good coverage.---
Overall this is clean and well-reasoned. The findings above are minor (comment accuracy, scope clarity). The code is ready to merge after addressing or acknowledging these.
The comment is slightly misleading — BaseFeeFromEvents returns nil for three cases: no feemarket event, event with no base_fee attribute, and event with a malformed base_fee value. Only the first is "fee market inactive"; the other two fall back here too.
// no parseable base_fee event: fall back to state (inactive fee market, missing attribute, or malformed value)
Already fixed in f7a6f4c3: the comment now reads "no parseable event (fee market inactive, or malformed event): fall back to state", which covers a missing attribute and a bad value.
@claude review
Claude finished @JayT106's task in 3m 41s —— View job
---
Code Review
rpc/backend/utils.go — validator account cacherpc/backend/chain_info.go — BaseFee / NextBaseFeerpc/backend/backend.go — LRU cache setuprpc/backend/blocks.go — block formatting---
Summary
The approach is sound and well-executed. The core idea — read base fee from the BeginBlock event and resolve the miner at the latest height — eliminates the expensive historical state queries on memiavl nodes without versiondb. No consensus or state-machine changes; this is purely an RPC performance improvement with no breaking changes.
---
Findings
1. nextBaseFee still performs a historical params query for eth_feeHistory
In processBlock (called per block during eth_feeHistory), nextBaseFee calls:
b.queryClient.FeeMarket.Params(types.ContextWithHeight(height), ...)
This replaces the old params query at the same height, so there's no regression. The PR description explicitly acknowledges this. Worth a note in the CHANGELOG or PR body that
eth_feeHistory's per-block param query still requires versiondb.2. BaseFee behavior change for pruned nodes with no event
Old path: on state error → iterated events → returned nil (no error).
New path: on state error → returns nil, err.
All callers handle the error gracefully (log + treat as nil baseFee), so there's no functional regression. The new behavior is actually better — the caller now knows why the fee is missing. ✓
3. Cache window semantics (subtle, intentional)
validatorAccountEntry.height stores header.Height (the block being queried), not the latest height at resolution time. This means two calls for blocks > 10 000 apart will both be cache misses, even for the same validator. For a streaming workload (sequential blocks) this is fine. For random historical access it re-queries, which is the safe fallback anyway. The tradeoff is documented.
4. Minor: missing colon before %w in error message
rpc/backend/utils.go:363 — "failed to get validator account %w" should be "failed to get validator account: %w" per Go error wrapping convention (errors.Is/errors.As still work either way, but the message is easier to read with a colon).
5. Uncoverable panic path in backend.go
lru.New only fails when size ≤ 0, which can't happen with the constant 1024. The codecov 50% miss on backend.go is these two lines — structurally untestable. No action needed.
6. processBlock base fee source change
Old: extracted baseFeePerGas from the assembled eth block JSON map.
New: uses targetOneFeeHistory.BaseFee (set two lines earlier from blockBaseFee).
Both are equivalent, and the new path additionally applies the governance-stored params.BaseFee override when enabled — matching the chain's own CalculateBaseFee exactly. ✓
7. Thread safety
hashicorp/golang-lru/v2 uses a sync.Mutex internally; concurrent Get/Add calls are safe. Concurrent cache misses may trigger duplicate queries (last writer wins), which is harmless. ✓
8. No breaking changes
No consensus, no state-machine, no amino/protobuf changes. Pure RPC-layer optimization. Safe to merge to develop. ✓
---
Minor inline comments posted below.
Nit: missing colon before %w — Go convention is "failed to get validator account: %w".
return nil, fmt.Errorf("failed to get validator account: %w", err)
ContextWithHeight(height) here is still a historical state query (for feemarket params). For NextBaseFee this is fine since height is the latest block. For processBlock (called per-block in eth_feeHistory) this is an acknowledged limitation — worth a brief comment so future readers don't remove the ContextWithHeight thinking it can be b.ctx.
Added the colon: "failed to get validator account: %w" (0ffd4327).
Added a one-line comment: params come from the block's height because they decide the next block's base fee, so it's a historical query for eth_feeHistory (0ffd4327).
Consider using a range list
Consider caching the base fee if its simple (does not need to be in this PR)
Implemented in 23b77a6b: each validator's entry now keeps a sorted list of block ranges (the 10k-block window around every block it was resolved for, merged when they touch), capped at 64 ranges by dropping the one farthest from the new block.
Tracked in #1121.
Benchmark on Cronos mainnet data
Setup
cronosmainnet_25-1_rocksdb-memiavl-20261013 (RocksDB + memiavl, no versiondb), on an Apple M4 Max.snapshot-interval = 1000.Results
| Endpoint | Concurrency | v1.7.9 mean / p99 | This PR mean / p99 |
|---|---|---|---|
| eth_getBlockByNumber | 1 | 83 ms / 128 ms | 0.17 ms / 0.27 ms |
| eth_getBlockByNumber, replay 900–999 blocks | 1 | 123 ms / 133 ms | 0.19 ms / 0.66 ms |
| eth_getBlockByNumber | 8 | 277 ms / 375 ms | 0.43 ms / 1.1 ms |
| eth_getBlockReceipts | 1 | 4.2 ms / 65 ms | 0.21 ms / 1.4 ms |
| eth_getBlockReceipts | 8 | 12.6 ms / 157 ms | 0.58 ms / 2.7 ms |
| eth_getTransactionReceipt (EIP-1559) | 1 | 39 ms / 66 ms | 0.62 ms / 2.2 ms |
| eth_getTransactionReceipt (EIP-1559) | 8 | 127 ms / 184 ms | 1.25 ms / 2.1 ms |
miner, baseFeePerGas and effectiveGasPrice for 90 blocks and 86 tx receipts; no errors.@claude review
Claude finished @JayT106's task in 2m 17s —— View job
---
Code Review
rpc/backend/utils.go — validator cache (range-list logic)rpc/backend/backend.go — cache initializationrpc/backend/chain_info.go — base fee changesrpc/backend/blocks.go — block RPC changes---
Summary
This is a well-engineered performance optimization. The benchmark results (83 ms → 0.17 ms for eth_getBlockByNumber) speak for themselves. No state-breaking changes — the PR is purely in the RPC layer.
---
Breaking / Consensus Changes
None. All changes are in rpc/backend/; no state machine, codec, or migration code is touched.
---
Correctness
BaseFee — event-first path (chain_info.go:83)
The inversion (events first, state fallback) is correct and well-tested. One subtlety worth noting: BaseFeeFromEvents returns nil if the base_fee attribute is found but malformed, not just when it's absent. That means a malformed event causes a state fallback. The test suite now covers this explicitly ("malformed feemarket event falls back to state query" / "fail - malformed feemarket event, grpc BaseFee error"). ✅
Old code also had a subtle bug fixed here: it hardcoded Attributes[0] (would miss base_fee at any non-zero index) and used strconv.ParseInt (silently truncated values above MaxInt64). Both are gone. ✅
nextBaseFee — governance override (utils.go:133)
if stored := p.BaseFee.BigInt(); p.IsBaseFeeEnabled(height+1) && stored != nil && stored.Sign() > 0 {
parent.BaseFee = stored
}
p.BaseFee is the feemarket module's stored param, which the chain updates every block. Using it (rather than the event-derived blockBaseFee) means a governance param overwrite is reflected immediately in eth_feeHistory. In normal operation the two values are identical. The IsBaseFeeEnabled(height+1) guard correctly handles pre-London historical ranges. ✅
The stored != nil guard is technically redundant (sdkmath.Int.BigInt() on a valid Int always returns non-nil), but it's harmless defensive code.
getValidatorAccount — range-list cache (utils.go:349)
The core invariant — ranges are sorted, non-overlapping, and immutable once stored — is correctly maintained by withBlock. Verified the merge logic:
to >= r.from-1 (touching counts) → iranges[j].from > r.to+1r, insert back via slices.Concatheight when over the capThe drop condition:
if height-ranges[0].to > ranges[len(ranges)-1].from-height {
ranges = ranges[1:] // leftmost is farther
} else {
ranges = ranges[:len(ranges)-1] // rightmost is farther or equal
}
If
height falls inside the merged range (always true), one of these distances is negative and the other positive, so the comparisons are unambiguous. ✅Acknowledged concurrency tradeoff: two concurrent misses can each call withBlock independently; the second Add overwrites the first's ranges. The cost is one extra RPC call on the next miss — not a correctness issue. The comment on line 376 documents this. ✅
---
Minor Observations
1. covers binary search (utils.go:381): searches by ranges[i].to — valid because non-overlapping disjoint ranges sorted by .from are also sorted by .to. Correct.
2. withBlock on a fresh entry (!ok path, utils.go:374): entry starts as zero-value validatorAccountEntry{} (nil ranges). withBlock on an empty slice produces [{height-w, height+w}]. Correct.
3. BaseFee nil-base-fee path (chain_info.go:96): when no event and state returns res.BaseFee == nil (fee market disabled or pre-London), returns nil, nil. Previously this same condition fell back to events; now events are already exhausted. Behavior is equivalent. ✅
4. lru.New error (backend.go:237): lru.New only errors when size ≤ 0. The constant validatorAccountCacheSize = 1024 makes this unreachable; the panic is safe. ✅
---
Test Coverage
The new tests in utils_test.go are thorough:
TestGetValidatorAccount covers: latest-height hit, historical fallback, cache reuse, range extension, account re-registration, not-found, and malformed address.TestValidatorAccountEntryWithBlock covers: empty entry, non-touching, touching, spanning-merge, and all three cap-drop directions (left/middle/right of full list).The 4 uncovered lines (codecov) are in the lru.New panic path and the BaseFeeFromEvents fallback inside BaseFee — both are expected gaps that don't warrant concern.
---
Overall
This is a high-quality PR. The base-fee fix (from int64-capped + Attributes[0] hardcode to big.Int + key-search) is a correctness improvement on top of the performance win. The validator cache design (immutable-slice range list, accepted concurrent-write loss) is a reasonable tradeoff between simplicity and accuracy. No issues blocking merge.
JayT106
What
eth_getBlockBy,eth_getBlockReceipts,eth_getTransactionReceiptand the header RPCs no longer query state at the block's height for base fee or validator.Issue
On memiavl nodes without versiondb, every state query at a past height rebuilds that state (~650 ms on Cronos mainnet).
eth_getBlockByNumbermakes 2 such queries: ~1.3 s.miner) comes back as the zero address.Solution
BaseFeeFromEvents). State is queried only when there's no event. This also fixes the old fallback's int64 parse and itsAttributes[0]lookup.eth_baseFee,eth_feeHistory): derived from the storedbase_feeparam, as the chain does, so a governance overwrite is reflected. Skipped when the fee market is disabled.mineris informational.eth_callat past heights,eth_feeHistory's params query,debug_trace, …) still need versiondb.