Skip to content

fix(evmrpc): fail fast on pruned heights for debug_trace* (PLT-975) - #3907

Open
amir-deris wants to merge 13 commits into
mainfrom
amir/plt-975-fix-debug-trace-issues
Open

fix(evmrpc): fail fast on pruned heights for debug_trace* (PLT-975)#3907
amir-deris wants to merge 13 commits into
mainfrom
amir/plt-975-fix-debug-trace-issues

Conversation

@amir-deris

@amir-deris amir-deris commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Describe your changes and provide context

debug_trace* endpoints could silently return empty results or panic when block, receipt, or state data had been pruned. Guards also ran after the trace semaphore was acquired, so pruned requests could block on concurrency limits instead of failing immediately.

This PR adds retention checks before trace work begins and returns explicit errors when data is unavailable:

  • EnsureTraceHeightAvailable — for replay endpoints (debug_traceTransaction, debug_traceBlockByNumber, etc.): verifies block, parent block (height−1 for validator/state replay), receipt, and state retention. Fetches watermarks once per guard (single Status snapshot).
  • EnsureTraceCallHeightAvailable — for debug_traceCall: verifies block and state only (no receipt check, since TraceCall never reads receipts). Same single-snapshot watermark fetch.
  • ErrReceiptPruned — new sentinel wrapping ErrNotFound so eth_getTransactionReceipt still returns null for pruned receipts while trace guards can distinguish pruned from missing.
  • latestTraceHeight — resolves latest/pending/safe/finalized tags via the watermark's safe latest instead of the raw app tip, avoiding intermittent errors when receipts/state lag the tip by a block.
  • Guard ordering — retention checks intentionally run before the trace semaphore so pruned requests fail fast without consuming a slot; hash-based endpoints may perform Tendermint block lookups outside the concurrency limiter as part of those guards (reverses the previous semaphore-first invariant).
  • Backend.BlockByNumber — uses shared getBlockNumber + watermark resolution instead of a separate ConvertBlockNumber path; pending now resolves like latest per EVM RPC spec instead of panicking.
  • Minor fixes — empty tx list no longer reports a block trace cache hit (avoids serving a stale empty result when tx enumeration failed); nil EVM tx in block filtering is skipped safely.

Known limitation: tx-by-hash trace guards need a resolvable receipt (or index); once a receipt is fully TTL-reclaimed, ErrNotFound is indistinguishable from an unknown hash and the request proceeds into the trace path before failing downstream.

Fixes PLT-975.

Testing performed to validate your change

  • Added unit tests for watermark trace guards (EnsureTraceHeightAvailable, EnsureTraceCallHeightAvailable, parent block floor, genesis initial height, SS-disabled edge cases)
  • Added integration-style tests for trace endpoints rejecting pruned heights before semaphore acquisition
  • Added tests for latest tag guard matching block resolution via safe latest watermark
  • Added tests for receipt lookup error propagation (ErrReceiptPruned, store errors, ErrNotFound fallthrough)
  • Updated receipt store tests to expect ErrReceiptPruned below retention floor
  • Updated trace semaphore ordering tests (TraceBlockByNumber, TraceBlockByHash, TraceCall)

amir-deris and others added 8 commits August 10, 2026 17:21
…ights (PLT-975)

Guard all trace endpoints against block, receipt, and state retention before
acquiring the trace semaphore so pruned heights fail fast with explicit
errors instead of silent empty results or internal panics.

Co-authored-by: Cursor <cursoragent@cursor.com>
- Resolve latest/pending/safe/finalized trace tags via the watermark's
  safe latest instead of the raw app tip, so debug_trace* no longer
  intermittently errors while receipts/state lag the tip.
- Check the parent height (height-1) against state retention, matching
  how initializeBlock actually replays a traced block.
- Wrap ErrReceiptPruned around ErrNotFound so eth_getTransactionReceipt
  and friends keep returning null for pruned receipts instead of an
  RPC error, while trace guards can still react to it specifically.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@amir-deris amir-deris self-assigned this Aug 12, 2026
@amir-deris amir-deris changed the title Amir/plt 975 fix debug trace issues fix(evmrpc): fail fast on pruned heights for debug_trace* (PLT-975) Aug 12, 2026
@github-actions

github-actions Bot commented Aug 12, 2026

Copy link
Copy Markdown

The latest Buf updates on your PR. Results from workflow Buf / buf (pull_request).

BuildFormatLintBreakingUpdated (UTC)
✅ passed✅ passed✅ passed✅ passedAug 13, 2026, 12:14 PM

@codecov

codecov Bot commented Aug 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 61.94690% with 43 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.38%. Comparing base (99c9c29) to head (8e4b72f).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
evmrpc/tracers.go 60.00% 16 Missing and 10 partials ⚠️
evmrpc/watermark_manager.go 69.69% 5 Missing and 5 partials ⚠️
evmrpc/simulate.go 50.00% 1 Missing and 1 partial ⚠️
evmrpc/utils.go 0.00% 1 Missing and 1 partial ⚠️
sei-db/ledger_db/receipt/litt_receipt_store.go 60.00% 1 Missing and 1 partial ⚠️
evmrpc/trace_profile.go 0.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #3907      +/-   ##
==========================================
- Coverage   59.47%   58.38%   -1.09%     
==========================================
  Files        2323     2226      -97     
  Lines      198389   186928   -11461     
==========================================
- Hits       117982   109129    -8853     
+ Misses      69198    67505    -1693     
+ Partials    11209    10294     -915     
Flag Coverage Δ
sei-chain-pr 70.37% <61.06%> (?)
sei-db 70.41% <ø> (-0.22%) ⬇️
sei-db-state-db ?

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
evmrpc/tx.go 87.20% <100.00%> (+4.53%) ⬆️
sei-db/ledger_db/receipt/receipt_store.go 67.00% <ø> (ø)
evmrpc/trace_profile.go 65.93% <0.00%> (ø)
evmrpc/simulate.go 76.34% <50.00%> (-0.12%) ⬇️
evmrpc/utils.go 73.97% <0.00%> (-0.69%) ⬇️
sei-db/ledger_db/receipt/litt_receipt_store.go 68.51% <60.00%> (-0.28%) ⬇️
evmrpc/watermark_manager.go 82.78% <69.69%> (-3.78%) ⬇️
evmrpc/tracers.go 71.26% <60.00%> (+1.56%) ⬆️

... and 172 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@amir-deris
amir-deris marked this pull request as ready for review August 12, 2026 13:02
@cursor

cursor Bot commented Aug 12, 2026

Copy link
Copy Markdown

PR Summary

Medium Risk
Changes behavior of widely used debug trace RPC paths and guard ordering; mistakes could block valid traces or allow bad requests, but scope is EVM RPC/debug with extensive new tests.

Overview
debug_trace* now validates block, receipt, and state retention before acquiring the trace semaphore, so pruned or unavailable heights return explicit errors instead of empty results, panics, or concurrency-limit waits.

Replay endpoints use EnsureTraceHeightAvailable (block, parent block for replay, receipts, and state at height−1). debug_traceCall uses EnsureTraceCallHeightAvailable, which skips receipt checks. latest/pending/safe/finalized resolve via the watermark safe latest (latestTraceHeight) so traces align with receipt/state lag behind the app tip. Tx-hash guards propagate ErrReceiptPruned and other receipt-store errors; pruned receipts below retention now surface that sentinel from the litt store.

Backend.BlockByNumber drops ConvertBlockNumber in favor of getBlockNumber plus watermark-aware fetch; pending follows latest instead of panicking. eth_getTransaction* receipt lookups use errors.Is(ErrNotFound) instead of string matching. Block trace cache no longer treats an empty tx list as a hit; nil EVM txs in block filtering are skipped safely.

Reviewed by Cursor Bugbot for commit 8e4b72f. Bugbot is set up for automated code reviews on this repo. Configure here.

@amir-deris
amir-deris requested a review from masih August 12, 2026 13:07

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit e7399d0. Configure here.

Comment thread evmrpc/watermark_manager.go Outdated
@amir-deris
amir-deris requested a review from bdchatham August 12, 2026 13:07

@seidroid seidroid Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Solid, well-tested hardening of the debug_trace* retention guards: the new EnsureTraceHeightAvailable/EnsureTraceCallHeightAvailable split matches what each path actually reads, and the strings.Contains("not found")errors.Is migration is a real improvement. No blocking correctness or security defects found, but there is a coverage gap in the by-tx-hash pruned path (Codex's finding), several efficiency/duplication issues in the new guard layer, and a deliberately reversed guard/semaphore ordering invariant worth confirming.

Findings: 0 blocking | 14 non-blocking | 8 posted inline

Blockers

  • None at the file/PR level.

Non-blocking

  • The Cursor second-opinion pass produced no output (cursor-review.md is empty), so this review reflects only the Codex pass plus my own analysis.
  • Guard/semaphore ordering is deliberately inverted: the deleted TestHashBasedTraceEndpointsAcquireSemaphoreBeforeHashLookup (and its panicHashLookupClient) encoded the invariant that no Tendermint hash lookup happens before the trace semaphore is acquired. Now every debug_traceBlockByHash/debug_traceCall performs a block-by-hash index lookup plus 3-4 Status calls outside the concurrency limiter. Failing fast is the right goal, but the limiter no longer bounds that work — please confirm this trade-off is intended, and consider noting it in the PR description since it reverses a previously test-enforced property.
  • Test coverage regression: with that test removed, debug_traceCall no longer has any test asserting it returns errTraceConcurrencyLimit when the semaphore is full (TestTraceBlockByNumberRejectsConcurrencyLimitAfterGuard only covers TraceBlockByNumber).
  • Guard duplication: guardTraceRequest{,ByNumber,ByHash,ByNumberOrHash} and guardTraceCallRequest{,ByNumber,ByHash,ByNumberOrHash} are eight methods that are byte-identical except for the terminal EnsureTrace…HeightAvailable call. Per AGENTS.md ("guard at the choke point, never at each caller"), consider one resolution helper (resolveTraceHeight(ctx, endpoint, blockNrOrHash) (int64, error)) plus a single guard parameterized by the ensure func(context.Context, int64) error — halves the surface and makes a future third guard variant a one-liner instead of four new copies.
  • Consistency: evmrpc/block.go:358 still uses strings.Contains(err.Error(), "not found") on a receipt lookup while this PR converted the three sibling call sites in tx.go to errors.Is(err, receiptpkg.ErrNotFound). Behavior is unchanged today (the new pruned message still contains "not found"), but leaving one string-matcher behind is exactly the fragility the rest of the PR removes.
  • Test hygiene: TestEnsureTraceCallHeightAvailableIgnoresReceipts and TestTraceReceiptFloorBoundary (both in historical_debug_trace_test.go) build the same fixture and largely assert the same thing; and in TestEnsureTraceCallHeightAvailable, rs.earliest = 150 is a no-op since the fake was constructed with earliest: 150.
  • 8 suggestion(s)/nit(s) flagged inline on specific lines.

Comment thread evmrpc/tracers.go
if api.keeper != nil {
rcpt, err := api.keeper.GetReceipt(api.ctxProvider(LatestCtxHeight), hash)
if err != nil {
if errors.Is(err, receipt.ErrReceiptPruned) || !errors.Is(err, receipt.ErrNotFound) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] Pruned receipts are still indistinguishable from unknown tx hashes on the main by-hash path (raised by the Codex pass as High; I agree it's real, though I'd scope it as a coverage gap rather than a regression).

ErrReceiptPruned is only produced when the record is physically still present but below the retention floor:

  • littReceiptStore.GetReceiptFromStore returns it only after a successful receipts.Get; once litt's TTL actually reclaims the value, !exists → plain ErrNotFound (litt_receipt_store.go:263).
  • The default receiptStore.GetReceipt has no retention-floor check at all and always returns plain ErrNotFound (receipt_store.go:220).

In both cases this falls through to guardHistoricalDebugTraceHeight(ctx, endpoint, api.latestTraceHeight(ctx)), which passes, so debug_traceTransaction / debug_traceStateAccess / debug_traceTransactionProfile on a pruned tx do not fail fast — the stated goal of the PR — and instead proceed into the trace path.

An unknown hash genuinely has no resolvable height, so you can't fully close this. But you could make the fall-through informative: when errors.Is(err, receipt.ErrNotFound) and api.backend.watermarks.receiptStore.EarliestVersion() > blockEarliest, return something like "receipt not found; receipts below height %d have been pruned" rather than silently continuing. At minimum, worth documenting the limitation here.

// for debug_trace* replay endpoints (transaction/block). Replay loads parent
// block validators and parent state (height-1) and reads receipts at the
// requested height.
func (m *WatermarkManager) EnsureTraceHeightAvailable(ctx context.Context, height int64) error {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] EnsureTraceHeightAvailable recomputes Watermarks() three times (via EnsureBlockHeightAvailable, ensureReplayParentBlockAvailableEnsureBlockHeightAvailable, and EnsureStateHeightAvailable), and each Watermarks() call does a tmClient.Status(), a ctxProvider(LatestCtxHeight), a receiptStore.LatestVersion(), and two stateStore version reads. For debug_traceBlockByHash it's four Status calls per request (the guard's blockByHashRespectingWatermarks adds one more) — all now before the trace semaphore.

Two consequences: unnecessary per-request cost on an unauthenticated endpoint, and the three snapshots can disagree if the tip advances mid-guard.

Suggest fetching once and validating against the snapshot:

blockEarliest, stateEarliest, latest, err := m.Watermarks(ctx)
if err != nil { return err }
if err := ensureWithinWatermarks(height, blockEarliest, latest); err != nil { return err }
// ... parent, receipt, state checks against the same triple

The same applies to EnsureTraceCallHeightAvailable (two calls).

Comment thread evmrpc/watermark_manager.go Outdated
// ensureReplayParentBlockAvailable verifies the parent block height replay
// tracing loads for validator set lookup in initializeBlock.
func (m *WatermarkManager) ensureReplayParentBlockAvailable(ctx context.Context, height int64) error {
parentBlockHeight := max(height-1, 0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] Two issues with the parent-block floor:

  1. The max(height-1, 0) clamp is ineffective. EnsureBlockHeightAvailable(0) always fails, since blockEarliest comes from Tendermint's EarliestBlockHeight and is >= 1. So on a chain started at initial height 1, debug_traceBlockByNumber(1) is always rejected. If the intent was to make the genesis block traceable, clamp to m.genesisInitialHeight() (as EnsureTraceHeightAvailable already does for stateHeight) or skip the parent check when height <= genesisInitialHeight.

  2. The error message names the wrong height. Tracing the earliest retained block surfaces "requested height 149 has been pruned; earliest available is 150" to a caller who asked for 150 — confusing, and TestEnsureTraceHeightAvailableParentBlockFloor locks that message in. Consider wrapping: fmt.Errorf("cannot trace height %d: parent block unavailable: %w", height, err).

Comment thread evmrpc/tracers.go
}
}
return api.guardHistoricalDebugTraceHeight(ctx, endpoint, int64(receipt.BlockNumber)) //nolint:gosec
return api.guardHistoricalDebugTraceHeight(ctx, endpoint, api.latestTraceHeight(ctx))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] Two notions of "latest" are now mixed: this passes api.latestTraceHeight(ctx) (the watermark safe latest) into guardHistoricalDebugTraceHeight, which internally compares against api.ctxProvider(LatestCtxHeight).BlockHeight() (the raw app tip). When the watermark lags the tip — which the latestTraceHeight doc comment says is the normal case — the lookback check sees blockHeight < latest, so with max_trace_lookback_blocks set to 0 or 1 a plain debug_traceBlockByNumber("latest") would be rejected with "block number 99 is beyond max lookback of 0".

Harmless at the default of 10000, but the fix is small: have guardHistoricalDebugTraceHeight use api.latestTraceHeight(ctx) as its reference too, so both sides agree on what "latest" means. Same applies at lines 146/170/217.

Comment thread evmrpc/tracers.go
// make EnsureTraceHeightAvailable reject the most common trace requests.
func (api *DebugAPI) latestTraceHeight(ctx context.Context) int64 {
if api.backend != nil && api.backend.watermarks != nil {
if latest, err := api.backend.watermarks.LatestHeight(ctx); err == nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] The watermark error is silently discarded and the raw app tip is returned instead. That tip is then handed to guardTraceRequest, whose EnsureTraceHeightAvailable calls Watermarks() again and fails with the same underlying error — so the fallback buys nothing and hides the cause. Either propagate the error (latestTraceHeight(ctx) (int64, error)) or add a comment explaining why the tip is a safe substitute here.

Comment thread evmrpc/tracers.go
// blockTraceCacheGet assembles a per-tx hit; returns (nil, false) if any miss.
func blockTraceCacheGet(cache *keeper.TraceDB, height int64, txHashes []common.Hash, config *tracers.TraceConfig) ([]*tracers.TxTraceResult, bool) {
if cache == nil {
if cache == nil || len(txHashes) == 0 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] This makes a genuinely empty block always miss the cache and fall through to the full trace path, where the correct answer is the empty slice this used to return cheaply. Neither the diff nor the PR description explains the motivation. If the concern is that an empty txHashes can also mean "we failed to load the tx list", that ambiguity is better resolved at the call site (txHashesOf(block.Transactions()) in tryBlockTraceCacheBy{Number,Hash}) than by making empty blocks permanently uncacheable — and the renamed test ("empty tx list is not a cache hit") then documents the intent rather than just the mechanism.

Comment thread evmrpc/utils.go
continue
}
ethtx, _ := m.AsTransaction()
if ethtx == nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] Good catch on the nil deref, but the check papers over a discarded error two lines up. m.AsTransaction() returns (nil, err) on a decode failure; testing the error directly says why the tx is skipped and won't silently break if AsTransaction ever returns a non-nil tx alongside an error:

ethtx, err := m.AsTransaction()
if err != nil || ethtx == nil {
    continue
}

Also: this path isn't covered by any test in the PR — a decode-failure case in filterTransactions would pin the fix.

Comment thread evmrpc/simulate.go
func (b Backend) BlockByNumber(ctx context.Context, bn rpc.BlockNumber) (*ethtypes.Block, []tracersutils.TraceBlockMetadata, error) {
blockNum := b.ConvertBlockNumber(bn)
tmBlock, err := blockByNumberRespectingWatermarks(ctx, b.tmClient, b.watermarks, &blockNum, 1)
blockNumberPtr, err := getBlockNumber(ctx, b.tmClient, bn)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] Undocumented behavior change worth a line in the PR description: the removed ConvertBlockNumber panicked with "tracing on pending block is not supported" for rpc.PendingBlockNumber, whereas getBlockNumber maps pending to nil → the watermark safe latest. Replacing a panic with a sensible resolution is an improvement, but debug_traceBlockByNumber("pending") now silently traces the latest block instead of erroring, and no test covers the pending tag on this path.

seidroid[bot]
seidroid Bot previously requested changes Aug 13, 2026

@seidroid seidroid Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Solid, well-tested hardening of the debug_trace* retention guards, but the replay parent-block check floors at 0 instead of the chain's initial height, which makes tracing the genesis block (and the earliest tag) fail on any node. Several non-blocking notes on guard cost, the reversed semaphore-ordering invariant, and the empty-block cache fast path.

Findings: 1 blocking | 9 non-blocking | 6 posted inline

Blockers

  • None at the file/PR level.
  • 1 blocking issue(s) flagged inline on specific lines.

Non-blocking

  • cursor-review.md is empty — the Cursor pass produced no output, so this review reflects only the Codex finding (confirmed, see the inline comment on watermark_manager.go:237) plus my own.
  • No test covers a trace at the chain's initial height or the earliest block tag. TestEnsureTraceHeightAvailableParentBlockFloor pins the pruned-floor case at height 150 but never the genesis case, which is exactly the gap that lets the max(height-1, 0) bug through. Worth adding: EarliestBlockHeight: 1, EnsureTraceHeightAvailable(ctx, 1) → expect no error.
  • TestHashBasedTraceEndpointsAcquireSemaphoreBeforeHashLookup covered both TraceBlockByHash and TraceCall; the three replacement tests cover TraceBlockByNumber and TraceBlockByHash only. debug_traceCall now has no test asserting its guard runs before the semaphore.
  • In guardTraceRequestByHash (tracers.go:157) and guardTraceCallRequestByHash (tracers.go:198), the block == nil || block.Block == nil branch is unreachable: blockByHashRespectingWatermarks already dereferences block.Block.Height before returning a nil error, so it would have panicked first. Either drop the check or move the nil handling into that helper.
  • 5 suggestion(s)/nit(s) flagged inline on specific lines.

Comment thread evmrpc/watermark_manager.go Outdated
// ensureReplayParentBlockAvailable verifies the parent block height replay
// tracing loads for validator set lookup in initializeBlock.
func (m *WatermarkManager) ensureReplayParentBlockAvailable(ctx context.Context, height int64) error {
parentBlockHeight := max(height-1, 0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[blocker] Off-by-one at the chain's initial height. For height == genesisInitialHeight (1 on most chains) this checks height 0, which is always below blockEarliest (status.SyncInfo.EarliestBlockHeight, ≥ 1), so ensureWithinWatermarks rejects it with the misleading message requested height 0 has been pruned; earliest available is 1.

Concretely, on an archive node with EarliestBlockHeight: 1, both debug_traceBlockByNumber("0x1") and debug_traceBlockByNumber("earliest") (which resolveDebugTraceBlockNumber maps to Genesis.InitialHeight) now fail, as does debug_traceTransaction for any tx in the genesis block. Same for chains started above height 1.

The state leg two lines up already gets this right — stateHeight := max(height-1, m.genesisInitialHeight()). Use the same floor here:

parentBlockHeight := max(height-1, m.genesisInitialHeight())

(Also flagged by Codex as P1.)

Comment thread evmrpc/tracers.go
if returnErr = api.validateTraceTracer(config); returnErr != nil {
return nil, returnErr
}
if returnErr = api.guardTraceRequestByHash(ctx, "debug_traceBlockByHash", hash); returnErr != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] Moving the guard ahead of prepareTraceContext deliberately reverses the invariant that the now-deleted TestHashBasedTraceEndpointsAcquireSemaphoreBeforeHashLookup (and its panicHashLookupClient) existed to enforce. Two consequences worth being explicit about in the PR description:

  1. The Tendermint block-by-hash lookup and the watermark reads now run with unbounded concurrencyMaxConcurrentTraceCalls no longer caps them. A flood of debug_traceBlockByHash with unknown hashes is no longer throttled.
  2. The guard runs on the caller's ctx, not the traceTimeout context created by prepareTraceContext, so this pre-work is no longer bounded by TraceTimeout.

The fail-fast goal is right; the trade-off just deserves a note, and ideally the guard should still run under the trace timeout (create the timeout context first, acquire the semaphore after).

// for debug_trace* replay endpoints (transaction/block). Replay loads parent
// block validators and parent state (height-1) and reads receipts at the
// requested height.
func (m *WatermarkManager) EnsureTraceHeightAvailable(ctx context.Context, height int64) error {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] EnsureTraceHeightAvailable calls Watermarks three times (via EnsureBlockHeightAvailable, ensureReplayParentBlockAvailable, and EnsureStateHeightAvailable), each of which issues a tmClient.Status plus receipt/state version reads. For a latest-tagged request latestTraceHeight adds a fourth. Since this now runs before the semaphore (unbounded concurrency), the amplification is on the un-throttled path.

Fetching once and validating all legs against that snapshot would be both cheaper and internally consistent — right now the three checks can observe different watermark snapshots mid-flight:

blockEarliest, stateEarliest, latest, err := m.Watermarks(ctx)
if err != nil { return err }
// validate height, parent, receipt floor, and stateHeight against this snapshot

Comment thread evmrpc/tracers.go
// blockTraceCacheGet assembles a per-tx hit; returns (nil, false) if any miss.
func blockTraceCacheGet(cache *keeper.TraceDB, height int64, txHashes []common.Hash, config *tracers.TraceConfig) ([]*tracers.TxTraceResult, bool) {
if cache == nil {
if cache == nil || len(txHashes) == 0 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] This turns an empty block from an instant ([], true) into a full cache miss, so debug_traceBlockBy{Number,Hash} on an empty block now falls through to the complete replay path (parent state load, block init) only to produce []. On a chain with sub-second blocks, empty blocks are common enough that this is a real cost.

The PR describes it as a fix, but [] is the correct trace result for a block with no transactions. If the concern is masking a case where block.Transactions() came back empty because decoding failed rather than because the block is genuinely empty, the guard should distinguish those two rather than dropping the fast path for both.

Comment thread evmrpc/tracers.go
if api.keeper != nil {
rcpt, err := api.keeper.GetReceipt(api.ctxProvider(LatestCtxHeight), hash)
if err != nil {
if errors.Is(err, receipt.ErrReceiptPruned) || !errors.Is(err, receipt.ErrNotFound) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] This also propagates receipt.ErrNotConfigured (asserted by the new ErrNotConfigured subtest), which changes behavior on any node whose keeper has no receipt store: debug_traceTransaction / debug_traceStateAccess / debug_traceTransactionProfile previously fell through to the lookback check and now hard-fail with receipt store not configured.

If a nil receipt store is a supported deployment (rather than test-only), ErrNotConfigured should fall through like ErrNotFound does. If it isn't reachable in production, a one-line comment saying so would make the intent clear — right now the test reads as if it's a supported configuration being deliberately broken.

Comment thread evmrpc/tracers.go
return api.guardTraceRequest(ctx, endpoint, api.latestTraceHeight(ctx))
}

func (api *DebugAPI) guardTraceCallRequest(ctx context.Context, endpoint string, height int64) error {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] guardTraceCallRequest{,ByNumber,ByHash,ByNumberOrHash} are line-for-line duplicates of the guardTraceRequest* family above, differing only in which Ensure* they call. Per AGENTS.md's "guard at the choke point" guidance, this is the shape that invites the two families to drift — a future guard added to one is easy to forget in the other.

One family parameterized by the availability check would collapse eight methods to four:

type heightAvailability func(context.Context, int64) error

func (api *DebugAPI) guardTraceRequestByHash(ctx context.Context, endpoint string, hash common.Hash, ensure heightAvailability) error

with TraceCall passing watermarks.EnsureTraceCallHeightAvailable and the replay endpoints passing EnsureTraceHeightAvailable.

@seidroid seidroid Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The retention guards are well-decomposed and the guard-before-semaphore reordering is the right fix for PLT-975; no correctness blockers found. Remaining notes are efficiency (3 redundant Watermarks()/Status calls per trace request, now unbounded pre-semaphore), duplication across six near-identical guard wrappers, one unreachable defensive check, and a new intermittent "not yet available" failure mode for concrete tip heights.

Findings: 0 blocking | 13 non-blocking | 6 posted inline

Blockers

  • None at the file/PR level.

Non-blocking

  • Cursor's second-opinion pass produced no output (cursor-review.md is empty), so this synthesis merges only Claude's and Codex's findings.
  • Guard-before-semaphore intentionally reverses a previously-asserted invariant: the deleted TestHashBasedTraceEndpointsAcquireSemaphoreBeforeHashLookup asserted "hash lookup should not happen before trace context setup." Now every debug_traceBlockByHash/debug_traceCall-by-hash request performs a Tendermint block-by-hash lookup plus 3-4 Status calls outside MaxConcurrentTraceCalls. Spamming random hashes therefore drives unbounded concurrent blockstore work that the semaphore used to cap. Worth confirming another rate limit fronts the debug namespace, and ideally worth a comment recording that the ordering trade-off is deliberate so it isn't "fixed" back later.
  • New intermittent failure mode for concrete tip heights. latestTraceHeight clamps latest/pending/safe/finalized to the safe watermark, but the by-tx-hash path feeds rcpt.BlockNumber straight into EnsureTraceHeightAvailable. Since latest mins in stateStore.GetLatestVersion() (async SS writes) while eth_getTransactionReceipt has no watermark check, the common flow — send tx, poll for receipt, then debug_traceTransaction — can return "requested height N is not yet available; safe latest is N-1" whenever SS lags a block. Erroring beats a silently-empty trace, but a bounded retry/short wait for heights within a block or two of the tip would keep that flow from flapping.
  • Partial migration off string matching: evmrpc/block.go:367 (eth_getBlockReceipts) still does strings.Contains(err.Error(), "not found") on a receipt lookup. It happens to keep working only because ErrReceiptPruned's message ends in "receipt not found"; converting it to errors.Is(err, receiptpkg.ErrNotFound) alongside the three tx.go sites would remove that accidental coupling.
  • Coverage gap in the reordering tests: the new tests assert pre-semaphore rejection for TraceBlockByNumber and TraceBlockByHash, but the deleted test also covered TraceCall by hash, and nothing replaces it. guardTraceCallRequestByNumberOrHash (the only caller of EnsureTraceCallHeightAvailable in the endpoint path) has no test asserting it runs before prepareTraceContext.
  • No test asserts the pruned-height error actually surfaces through the JSON-RPC handler — all new tests call the guards or DebugAPI methods directly. Given the point of the PR is the client-visible error, one handler-level case (pruned height in, explicit JSON-RPC error out) would pin the contract.
  • Coverage limit of the fix worth noting in the PR body: ErrReceiptPruned is only produced while litt still physically holds the value (lazy TTL). Once the value actually expires, GetReceipt returns ErrNotFound, the tx-hash guard has no height to check, and the user gets "transaction not found" rather than a retention error for a tx that did exist.
  • 6 suggestion(s)/nit(s) flagged inline on specific lines.

// for debug_trace* replay endpoints (transaction/block). Replay loads parent
// block validators and parent state (height-1) and reads receipts at the
// requested height.
func (m *WatermarkManager) EnsureTraceHeightAvailable(ctx context.Context, height int64) error {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] This resolves watermarks three separate times per call: EnsureBlockHeightAvailable, ensureReplayParentBlockAvailableEnsureBlockHeightAvailable, and EnsureStateHeightAvailable each invoke Watermarks(ctx), which is a Tendermint Status RPC plus ctxProvider + receipt-store + state-store reads — and genesisInitialHeight() is called twice on top. Because the guard now runs before the trace semaphore, that cost is paid on every trace request with no concurrency bound.

Taking one snapshot and validating all three legs against it would cut it to a single fetch and also remove the cross-call inconsistency (each Watermarks call can observe a different tip/earliest, so the parent-block leg can be evaluated against a snapshot the block leg never saw):

blockEarliest, stateEarliest, latest, err := m.Watermarks(ctx)
if err != nil {
    return err
}
if err := ensureWithinWatermarks(height, blockEarliest, latest); err != nil {
    return err
}
parent := max(height-1, m.genesisInitialHeight())
if err := ensureWithinWatermarks(parent, blockEarliest, latest); err != nil {
    return err
}
// ... receipt leg, then state leg against stateEarliest/latest

Same applies to EnsureTraceCallHeightAvailable, which resolves watermarks twice.

Comment thread evmrpc/tracers.go
return api.guardTraceRequest(ctx, endpoint, api.latestTraceHeight(ctx))
}

func (api *DebugAPI) guardTraceCallRequest(ctx context.Context, endpoint string, height int64) error {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] guardTraceCallRequest* and guardTraceRequest* are six functions whose bodies are identical apart from which Ensure* they call. AGENTS.md asks that a correction leave the code readable as a sequence of named steps rather than accumulating parallel copies; a single set parameterized by the availability check would halve this and make it impossible for a future endpoint to wire up the by-number variant of one family and the by-hash variant of the other:

type traceAvailability func(context.Context, int64) error

func (api *DebugAPI) traceReplayAvailability() traceAvailability { ... }
func (api *DebugAPI) traceCallAvailability() traceAvailability { ... }

func (api *DebugAPI) guardTraceHeight(ctx context.Context, endpoint string, height int64, ensure traceAvailability) error
func (api *DebugAPI) guardTraceByHash(ctx context.Context, endpoint string, hash common.Hash, ensure traceAvailability) error
func (api *DebugAPI) guardTraceByNumberOrHash(...) error

The two Ensure* methods stay as the meaningful distinction, which is where the replay-vs-call difference actually lives.

Comment thread evmrpc/tracers.go
return api.guardTraceRequest(ctx, endpoint, height)
}

func (api *DebugAPI) guardTraceRequestByHash(ctx context.Context, endpoint string, hash common.Hash) error {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] The nil check here is narrower than the one in guardTraceRequest just above: that one tolerates api.backend.watermarks == nil, but this path falls through to blockByHashRespectingWatermarks, which returns errNoHeightSource when wm == nil. So a DebugAPI with a backend but no watermark manager fails debug_traceBlockByHash outright with "unable to determine height information", where the old code swallowed that error and let the trace proceed. Production always wires watermarks (server.go:89/294), so this is latent rather than live, but the condition should match its sibling:

if api.backend == nil || api.backend.watermarks == nil || api.tmClient == nil {

Same in guardTraceCallRequestByHash.

Comment thread evmrpc/utils.go
continue
}
ethtx, _ := m.AsTransaction()
if ethtx == nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] This guard can't fire. AsTransaction returns nil only when UnpackTxData(msg.Data) fails — and m.IsAssociateTx() three lines up calls GetAssociateTx, which panic(err)s on exactly that failure. So an undecodable EVM message panics before reaching here, and the PR description's "nil EVM tx in block filtering is skipped safely" doesn't hold for the case it targets.

If the goal is to survive an undecodable MsgEVMTransaction, the fix belongs in GetAssociateTx/IsAssociateTx (x/evm/types/message_evm_transaction.go:85) — return the decode failure instead of panicking, and let both call sites skip. If the panic is genuinely unreachable and this is belt-and-braces, dropping it keeps the loop honest about what it defends against.

Comment thread evmrpc/tracers.go
}

func (api *DebugAPI) guardHistoricalDebugTraceByNumber(ctx context.Context, endpoint string, number rpc.BlockNumber) error {
// latestTraceHeight resolves the height debug_trace* should use for latest-ish

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] Per AGENTS.md, godoc says what a thing is, not why it came to be or how it works inside — "It prefers ... since the tip can outrun ... and would otherwise make EnsureTraceHeightAvailable reject" is rationale, which belongs in an inline comment at the line that needs it. (Same class of thing in EnsureTraceCallHeightAvailable's and EnsureTraceHeightAvailable's godocs in watermark_manager.go, which describe the replay mechanism and name StateAndHeaderByNumberOrHash.) Suggest rewriting as a contract:

// latestTraceHeight returns the height debug_trace* resolves latest, pending,
// safe, and finalized to: the watermark's safe latest, or the app tip when no
// watermark is available.

The "tip outruns the stores by a block" rationale is load-bearing, so keep it — as an inline comment on the LatestHeight call. (Finding also raised by Codex.)

Comment thread evmrpc/tracers.go
// blockTraceCacheGet assembles a per-tx hit; returns (nil, false) if any miss.
func blockTraceCacheGet(cache *keeper.TraceDB, height int64, txHashes []common.Hash, config *tracers.TraceConfig) ([]*tracers.TxTraceResult, bool) {
if cache == nil {
if cache == nil || len(txHashes) == 0 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] Worth confirming the intent: for an empty tx list the old code returned ([], true), which short-circuited to the same [] the tracer produces for a block with no EVM txs — so this changes no result, it only stops counting a trivially-satisfiable assembly as a cache hit. The cost is that debug_traceBlockBy* on every empty block now falls through to a full replay setup instead of returning immediately, which on a chain with many empty blocks is a real latency regression for a metrics-honesty gain. If the goal is accurate hit accounting, keeping the fast path and not recording it as a hit would get both.

@seidroid
seidroid Bot dismissed their stale review August 13, 2026 11:56

Superseded: latest AI review found no blocking issues.

…e test.

Fetch watermarks once per EnsureTrace* guard to avoid redundant Status calls, restore debug_traceCall semaphore coverage, and document the guard-before-semaphore ordering.

Co-authored-by: Cursor <cursoragent@cursor.com>

@seidroid seidroid Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Solid, well-tested change: retention guards now run before the trace semaphore, debug_trace* fails fast with explicit errors on pruned block/receipt/state data, and the brittle strings.Contains("not found") checks are replaced with sentinel-error matching. One real inconsistency remains — latest-ish tags resolve to the watermark's safe latest while the max-lookback guard still compares against the raw app tip — plus a few non-blocking notes about guard work now running outside the semaphore and trace timeout.

Findings: 0 blocking | 9 non-blocking | 4 posted inline

Blockers

  • None at the file/PR level.

Non-blocking

  • cursor-review.md is empty — the Cursor pass produced no output, so this review reflects only the Codex findings plus my own.
  • Hash-based endpoints now do the Tendermint block-by-hash lookup twice per request: once in guardTraceRequestByHash/guardTraceCallRequestByHash and again in tryBlockTraceCacheByHash / tracersAPI.TraceBlockByHash. Worth caching the resolved height on the request path if this shows up in latency.
  • Guard cost per by-hash request is two Status snapshots, not one as the description implies: blockByHashRespectingWatermarks calls EnsureBlockHeightAvailable (→ Watermarks) and then guardTraceRequest calls EnsureTraceHeightAvailable (→ Watermarks again).
  • The deleted TestHashBasedTraceEndpointsAcquireSemaphoreBeforeHashLookup encoded the opposite invariant. The new ordering is covered for TraceBlockByHash (TestTraceBlockByHashChecksAvailabilityBeforeSemaphore), but there is no equivalent guard-before-semaphore test for TraceCall with a block hash — only with a block number. Worth adding so the reversed invariant is pinned on both hash paths.
  • The known limitation in the description (fully TTL-reclaimed receipts are indistinguishable from an unknown tx hash, so debug_traceTransaction proceeds into the trace path) is accurately stated and not blocking, but consider a follow-up issue so it doesn't get lost — it's the one remaining path where a pruned request still consumes a semaphore slot.
  • 4 suggestion(s)/nit(s) flagged inline on specific lines.

Comment thread evmrpc/tracers.go
switch number {
case rpc.SafeBlockNumber, rpc.FinalizedBlockNumber, rpc.LatestBlockNumber, rpc.PendingBlockNumber:
return api.ctxProvider(LatestCtxHeight).BlockHeight(), nil
return api.latestTraceHeight(ctx), nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] Latest-ish tags now resolve to the watermark's safe latest, but guardHistoricalDebugTraceHeight (line 236) still measures the lookback window against the raw app tip (api.ctxProvider(LatestCtxHeight).BlockHeight()). Whenever the receipt/state stores lag the tip — the exact condition latestTraceHeight exists to paper over — the two disagree by the lag:

  • With max_trace_lookback_blocks = 0 ("tip only"), debug_trace*("latest") resolves to tip-1, and isHistoricalDebugTraceBlock(tip-1, tip, 0) is true → the request is rejected with block number N is beyond max lookback of 0. That is the intermittent failure this PR set out to remove.
  • With the default 10000, a client that computes eth_blockNumber - 10000 (and eth_blockNumber also returns the safe latest, see evmrpc/info.go:49) asks for safeLatest-10000, which is < tip-10000 → rejected at the documented boundary.

Suggest threading the already-resolved latest into the lookback guard (e.g. have guardHistoricalDebugTraceHeight take the latest it should compare against, defaulting to latestTraceHeight(ctx)) so both halves of the guard use one height. TestTraceLatestTagGuardMatchesBlockResolution would have caught this if it called guardTraceRequestByNumber instead of resolveDebugTraceBlockNumber directly — its DebugAPI already has maxBlockLookback at the zero value. (Also reported by Codex.)

Comment thread evmrpc/tracers.go
if returnErr = api.validateTraceTracer(config); returnErr != nil {
return nil, returnErr
}
if returnErr = api.guardTraceRequestByHash(ctx, "debug_traceBlockByHash", hash); returnErr != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] Moving the guard ahead of prepareTraceContext is the right call for fail-fast, but note the guard work is now bounded by neither the trace semaphore nor traceTimeout: it runs on the caller's raw ctx, and blockByHashRespectingWatermarks(..., maxRetries: 1) sleeps a full second before retrying when the Tendermint client returns an error (an unknown hash short-circuits to ErrBlockNotFoundByHash without sleeping, so only genuine client errors hit this). Consider either creating the timeout context before the guard and cancelling it separately from semaphore release, or passing maxRetries: 0 on the guard path — the retry exists for the receipt/block commit race, which doesn't apply to a pure availability check.


// EnsureStateHeightAvailable verifies that historical state for the given block
// height has not been pruned from the state store.
func (m *WatermarkManager) EnsureStateHeightAvailable(ctx context.Context, height int64) error {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] EnsureStateHeightAvailable has no production caller — it's exercised only by watermark_manager_test.go. Either wire it into EnsureTraceCallHeightAvailable/EnsureTraceHeightAvailable (both currently inline the same ensureWithinWatermarks(height, stateEarliest, latest) check) or drop it, so the exported surface stays load-bearing.

Comment thread evmrpc/tracers.go
// tags. It prefers the watermark's safe latest over the raw app tip, since the
// tip can outrun the receipt/state stores by a block or so and would otherwise
// make EnsureTraceHeightAvailable reject the most common trace requests.
func (api *DebugAPI) latestTraceHeight(ctx context.Context) int64 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] The watermark error is swallowed and silently replaced with the raw app tip. On the guardTraceRequestByNumber path that's harmless — EnsureTraceHeightAvailable re-fetches and surfaces the same error. But on the guardTraceRequestByTxHash fallback (line 128) there's no re-check, so a Status failure quietly degrades the lookback guard to the unvalidated tip. Returning (int64, error) and letting callers propagate would make that explicit.

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.

1 participant