Skip to content

refactor(reference-index): replace ExEx with canonical cursor runtime#141

Merged
panos-xyz merged 12 commits into
mainfrom
codex/reth-main-reference-index
Jul 22, 2026
Merged

refactor(reference-index): replace ExEx with canonical cursor runtime#141
panos-xyz merged 12 commits into
mainfrom
codex/reth-main-reference-index

Conversation

@panos-xyz

@panos-xyz panos-xyz commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Important

This is a stacked PR on top of #140. PR #140 owns the Reth main upgrade and
engine-tree-ext removal; this PR should be reviewed only for the
reference-index changes. After #140 merges, this PR can be retargeted to
main.

Summary

  • replace the reference-index ExEx with a non-critical canonical-cursor runtime backed by its own MDBX database
  • remove the temporary reference-index disable flag and ExEx WAL dependency

Reference-index behavior

  • canonical provider data and the durable (block number, block hash) cursor are the source of truth; notifications are wake-up/rate signals only
  • rapid historical sync defers index I/O after more than 64 changed blocks in a rolling 2-second window, then resumes after 5 seconds without canonical activity
  • catch-up uses atomic batches of at most 512 blocks and drains notifications between batches
  • pre-Jade queries return the complete empty result without per-block index writes
  • post-Jade RPC results are served only when the durable cursor exactly matches the canonical head number and hash
  • normal suffix reorgs roll back and replay automatically; a reorg with no post-Jade common ancestor leaves the index unavailable for manual rebuild
  • reference-index failures do not terminate block execution; bodies-history pruning is rejected at startup because historical canonical bodies are required
  • the derived DB remains under <datadir>/morph/reference_index; there is no automatic migration or deletion of the unreleased ExEx schema

Validation

  • cargo fmt --all -- --check
  • cargo check --workspace --all-features
  • cargo clippy --workspace --all-targets --all-features -- -D warnings
  • cargo test --workspace --all-features --no-fail-fast
  • clean-branch targeted tests: reference index 36/36, node 32/32, RPC 83/83
  • clean-branch node/RPC reference-index E2E: 4/4
  • before the final scheduler-only review fixes, the morph Hive compatibility suite passed 103/103 RPC fixtures and 6/6 Morph Engine methods, with 0 unexpected or missing known divergences
  • the same validation pass completed 116 Emerald/Jade statetest rounds with 0 mismatch
  • the pre-review local post-Jade benchmark completed 45/45 blocks with 0 errors; throughput was effectively flat versus ExEx (+0.16% realized), while the ExEx baseline created about 60 MiB of WAL and the new runtime created none

Scope

This PR intentionally excludes the local benchmark harness, contracts, benchmark report, and snapshot scripts that are being developed separately.

Summary by CodeRabbit

  • New Features

    • The transaction reference index now runs automatically in the background.
    • Reference queries use the exact canonical chain tip for more consistent results.
    • Added clearer index lifecycle handling, including initializing, deferred, repairing, and unavailable states.
    • Added progress and health metrics for reference-index synchronization.
  • Bug Fixes

    • Improved handling of chain reorganizations, rapid synchronization, pruning, and temporary indexing delays.
    • RPC responses now provide clearer errors when the index is unavailable or behind.

panos-xyz and others added 3 commits July 13, 2026 21:48
validate_payload already registered an expectation in convert_payload_to_block;
clearing it on the early L1-index reject path matches the inner-failure cleanup
and avoids a stale cache entry until LRU eviction.
Format the L1-index cleanup path, upgrade crossbeam-epoch to 0.9.20, and
drop advisory ignores that no longer match after the reth main bump.
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@panos-xyz, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 9 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 64f00e58-d09a-41f4-a335-55bfdc2f82a1

📥 Commits

Reviewing files that changed from the base of the PR and between af29aad and 3a26df2.

📒 Files selected for processing (4)
  • crates/reference-index/src/metrics.rs
  • crates/reference-index/src/reader.rs
  • crates/reference-index/src/runtime.rs
  • crates/rpc/src/morph/handler.rs
📝 Walkthrough

Walkthrough

The reference index is migrated from ExEx startup integration to a background runtime with canonical-chain synchronization, phase-aware querying, bounded RPC catch-up, stricter metadata validation, and end-to-end RPC tests.

Changes

Reference index runtime migration

Layer / File(s) Summary
Index contracts and storage
Cargo.toml, crates/reference-index/Cargo.toml, crates/reference-index/src/{lib,types,source,db,writer,metrics,tables}.rs
Canonical-chain types, schema version 2 metadata, internal database helpers, metrics, and narrowed public exports are introduced.
Runtime synchronization and reconciliation
crates/reference-index/src/{backfill,reconcile,runtime}.rs
Bounded canonical backfill, suffix rollback, rapid-sync deferral, retries, pruning, and background notification processing are implemented.
Phase-aware RPC querying
crates/reference-index/src/reader.rs, crates/rpc/src/morph/{handler,rpc}.rs
ReferenceIndexHandle phases, exact canonical-tip validation, bounded waiting, pagination, and unavailable-state mapping replace the former reader flow.
Node wiring and end-to-end validation
bin/morph-reth/*, crates/node/*, crates/node/tests/it/reference_index.rs, crates/rpc/Cargo.toml
ExEx startup wiring is removed, add-ons launch the runtime unconditionally, incompatible pruning is rejected, and integration tests query the public RPC.
Estimated code review effort: 5 (Critical) ~120 minutes

Possibly related issues

  • Issue 144 — Adds the bounded server-side wait behavior and associated runtime wait metrics.
  • Issue 143 — Covers canonical-chain reorganization handling and finalized-block pruning.
  • Issue 145 — Covers phase-aware reader gating and pre-Jade RPC behavior.

Possibly related PRs

Suggested labels: enhancement

Suggested reviewers: chengwenxi

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: replacing the reference-index ExEx with a canonical cursor runtime.
Docstring Coverage ✅ Passed Docstring coverage is 95.44% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/reth-main-reference-index

Warning

Billing warning: we have not been able to collect payment for this subscription for more than 72 hours. Please update the payment method or pay any pending invoices in Billing to avoid service interruption.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@panos-xyz
panos-xyz force-pushed the codex/reth-main-reference-index branch from fc7af55 to c38f45f Compare July 14, 2026 10:19
@panos-xyz panos-xyz changed the title refactor(node): migrate to Reth main and replace reference-index ExEx refactor(reference-index): replace ExEx with canonical cursor runtime Jul 14, 2026
@panos-xyz
panos-xyz changed the base branch from main to codex/reth-main-upgrade July 14, 2026 10:19

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/node/src/validator.rs`:
- Around line 313-320: Ensure the validation flow consumes the withdraw-root
expectation for every failure path, including errors from
validate_next_l1_msg_index_for_block and inner validate_payload. Use block_hash
with post_execution_validator.take_withdraw_trie_root_expectation, preserving
successful validation and avoiding duplicate cleanup on any single path.

In `@crates/reference-index/src/runtime.rs`:
- Around line 263-304: Validate the jade_first_block boundary from both the
stored and resolve_jade_first_block paths before using it: block n must have
timestamp >= jade_timestamp and block n - 1 must have timestamp <
jade_timestamp. Revalidate the same boundary immediately before
commit_canonical_batch, and reject or retry when either condition fails so an
inconsistent concurrent-reorg boundary is never persisted.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8758adb6-0f39-4f44-894e-cf4db309beca

📥 Commits

Reviewing files that changed from the base of the PR and between 43c3e59 and fc7af55.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (51)
  • Cargo.toml
  • bin/morph-reth/Cargo.toml
  • bin/morph-reth/src/main.rs
  • crates/chainspec/src/hardfork.rs
  • crates/consensus/src/validation.rs
  • crates/engine-api/src/builder.rs
  • crates/engine-tree-ext/Cargo.toml
  • crates/engine-tree-ext/src/gate.rs
  • crates/engine-tree-ext/src/lib.rs
  • crates/engine-tree-ext/src/payload_validator.rs
  • crates/engine-tree-ext/src/trie_updates.rs
  • crates/engine-tree-ext/tests/jade_boundary.rs
  • crates/evm/Cargo.toml
  • crates/evm/src/block/mod.rs
  • crates/evm/src/context.rs
  • crates/evm/src/evm.rs
  • crates/node/Cargo.toml
  • crates/node/build.rs
  • crates/node/src/add_ons.rs
  • crates/node/src/args.rs
  • crates/node/src/exex/mod.rs
  • crates/node/src/exex/reference_index.rs
  • crates/node/src/lib.rs
  • crates/node/src/node.rs
  • crates/node/src/test_utils.rs
  • crates/node/src/validator.rs
  • crates/node/tests/it/engine.rs
  • crates/node/tests/it/helpers.rs
  • crates/node/tests/it/reference_index.rs
  • crates/payload/builder/src/builder.rs
  • crates/payload/types/src/attributes.rs
  • crates/payload/types/src/lib.rs
  • crates/reference-index/Cargo.toml
  • crates/reference-index/src/backfill.rs
  • crates/reference-index/src/db.rs
  • crates/reference-index/src/lib.rs
  • crates/reference-index/src/metrics.rs
  • crates/reference-index/src/reader.rs
  • crates/reference-index/src/reconcile.rs
  • crates/reference-index/src/runtime.rs
  • crates/reference-index/src/source.rs
  • crates/reference-index/src/tables.rs
  • crates/reference-index/src/types.rs
  • crates/reference-index/src/writer.rs
  • crates/revm/src/evm.rs
  • crates/revm/src/precompiles.rs
  • crates/rpc/Cargo.toml
  • crates/rpc/src/eth/call.rs
  • crates/rpc/src/eth/mod.rs
  • crates/rpc/src/morph/handler.rs
  • crates/rpc/src/morph/rpc.rs
💤 Files with no reviewable changes (10)
  • crates/engine-tree-ext/src/lib.rs
  • crates/engine-tree-ext/src/gate.rs
  • crates/node/src/lib.rs
  • crates/engine-tree-ext/Cargo.toml
  • crates/engine-tree-ext/src/trie_updates.rs
  • crates/engine-tree-ext/src/payload_validator.rs
  • crates/node/src/exex/reference_index.rs
  • crates/node/src/exex/mod.rs
  • bin/morph-reth/Cargo.toml
  • crates/engine-tree-ext/tests/jade_boundary.rs

@coderabbitai coderabbitai 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.

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/node/src/validator.rs`:
- Around line 313-320: Ensure the validation flow consumes the withdraw-root
expectation for every failure path, including errors from
validate_next_l1_msg_index_for_block and inner validate_payload. Use block_hash
with post_execution_validator.take_withdraw_trie_root_expectation, preserving
successful validation and avoiding duplicate cleanup on any single path.

In `@crates/reference-index/src/runtime.rs`:
- Around line 263-304: Validate the jade_first_block boundary from both the
stored and resolve_jade_first_block paths before using it: block n must have
timestamp >= jade_timestamp and block n - 1 must have timestamp <
jade_timestamp. Revalidate the same boundary immediately before
commit_canonical_batch, and reject or retry when either condition fails so an
inconsistent concurrent-reorg boundary is never persisted.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8758adb6-0f39-4f44-894e-cf4db309beca

📥 Commits

Reviewing files that changed from the base of the PR and between 43c3e59 and fc7af55.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (51)
  • Cargo.toml
  • bin/morph-reth/Cargo.toml
  • bin/morph-reth/src/main.rs
  • crates/chainspec/src/hardfork.rs
  • crates/consensus/src/validation.rs
  • crates/engine-api/src/builder.rs
  • crates/engine-tree-ext/Cargo.toml
  • crates/engine-tree-ext/src/gate.rs
  • crates/engine-tree-ext/src/lib.rs
  • crates/engine-tree-ext/src/payload_validator.rs
  • crates/engine-tree-ext/src/trie_updates.rs
  • crates/engine-tree-ext/tests/jade_boundary.rs
  • crates/evm/Cargo.toml
  • crates/evm/src/block/mod.rs
  • crates/evm/src/context.rs
  • crates/evm/src/evm.rs
  • crates/node/Cargo.toml
  • crates/node/build.rs
  • crates/node/src/add_ons.rs
  • crates/node/src/args.rs
  • crates/node/src/exex/mod.rs
  • crates/node/src/exex/reference_index.rs
  • crates/node/src/lib.rs
  • crates/node/src/node.rs
  • crates/node/src/test_utils.rs
  • crates/node/src/validator.rs
  • crates/node/tests/it/engine.rs
  • crates/node/tests/it/helpers.rs
  • crates/node/tests/it/reference_index.rs
  • crates/payload/builder/src/builder.rs
  • crates/payload/types/src/attributes.rs
  • crates/payload/types/src/lib.rs
  • crates/reference-index/Cargo.toml
  • crates/reference-index/src/backfill.rs
  • crates/reference-index/src/db.rs
  • crates/reference-index/src/lib.rs
  • crates/reference-index/src/metrics.rs
  • crates/reference-index/src/reader.rs
  • crates/reference-index/src/reconcile.rs
  • crates/reference-index/src/runtime.rs
  • crates/reference-index/src/source.rs
  • crates/reference-index/src/tables.rs
  • crates/reference-index/src/types.rs
  • crates/reference-index/src/writer.rs
  • crates/revm/src/evm.rs
  • crates/revm/src/precompiles.rs
  • crates/rpc/Cargo.toml
  • crates/rpc/src/eth/call.rs
  • crates/rpc/src/eth/mod.rs
  • crates/rpc/src/morph/handler.rs
  • crates/rpc/src/morph/rpc.rs
💤 Files with no reviewable changes (10)
  • crates/engine-tree-ext/src/lib.rs
  • crates/engine-tree-ext/src/gate.rs
  • crates/node/src/lib.rs
  • crates/engine-tree-ext/Cargo.toml
  • crates/engine-tree-ext/src/trie_updates.rs
  • crates/engine-tree-ext/src/payload_validator.rs
  • crates/node/src/exex/reference_index.rs
  • crates/node/src/exex/mod.rs
  • bin/morph-reth/Cargo.toml
  • crates/engine-tree-ext/tests/jade_boundary.rs
🛑 Comments failed to post (2)
crates/node/src/validator.rs (1)

313-320: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Consume withdraw-root expectations on every validation failure.

The precheck at Line 314 and validate_block’s inner error path return without removing the shared expectation. A stale entry can later be applied to the same block hash and falsely reject a retry or block-input validation.

Proposed cleanup
         let block_hash = payload.block.hash();
-        self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx)?;
+        if let Err(err) =
+            self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx)
+        {
+            self.post_execution_validator
+                .take_withdraw_trie_root_expectation(block_hash);
+            return Err(err);
+        }

     fn validate_block(
         &mut self,
         block: SealedBlock<morph_primitives::Block>,
         ctx: TreeCtx<'_, MorphPrimitives>,
     ) -> reth_engine_tree::tree::ValidationOutcome<MorphPrimitives> {
+        let block_hash = block.hash();
         self.validate_next_l1_msg_index_for_block(&block, &ctx)?;
-        let output = self.inner.validate_block(block, ctx)?;
-        self.validate_withdraw_trie_root(output)
+        match self.inner.validate_block(block, ctx) {
+            Ok(output) => self.validate_withdraw_trie_root(output),
+            Err(err) => {
+                self.post_execution_validator
+                    .take_withdraw_trie_root_expectation(block_hash);
+                Err(err)
+            }
+        }
     }

Also applies to: 325-332

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/node/src/validator.rs` around lines 313 - 320, Ensure the validation
flow consumes the withdraw-root expectation for every failure path, including
errors from validate_next_l1_msg_index_for_block and inner validate_payload. Use
block_hash with post_execution_validator.take_withdraw_trie_root_expectation,
preserving successful validation and avoiding duplicate cleanup on any single
path.
crates/reference-index/src/runtime.rs (1)

263-304: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate the Jade boundary before trusting or persisting it.

resolve_jade_first_block uses separate provider reads, so a concurrent reorg can produce a canonical but incorrect boundary. Once persisted, later turns skip resolution and can permanently omit Jade blocks or index pre-Jade blocks.

Before using either the stored or resolved value, verify that block n has timestamp >= jade_timestamp and block n - 1 has timestamp < jade_timestamp; revalidate immediately before committing the first batch.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/reference-index/src/runtime.rs` around lines 263 - 304, Validate the
jade_first_block boundary from both the stored and resolve_jade_first_block
paths before using it: block n must have timestamp >= jade_timestamp and block n
- 1 must have timestamp < jade_timestamp. Revalidate the same boundary
immediately before commit_canonical_batch, and reject or retry when either
condition fails so an inconsistent concurrent-reorg boundary is never persisted.

@claude claude 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.

Claude Code Review

Claude Code Review is paused for this repository. To reconnect it, an admin of this repository's GitHub organization (or the account owner, for personal repositories) who can also manage your Claude organization's Code Review settings needs to re-link GitHub in Code Review settings. This is a one-time step.

Tip: disable this comment in your organization's Code Review settings.

@panos-xyz
panos-xyz force-pushed the codex/reth-main-reference-index branch from e7f897c to 4a0d756 Compare July 16, 2026 03:27
Base automatically changed from codex/reth-main-upgrade to main July 16, 2026 08:47

@claude claude 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.

Claude Code Review

Claude Code Review is paused for this repository. To reconnect it, an admin of this repository's GitHub organization (or the account owner, for personal repositories) who can also manage your Claude organization's Code Review settings needs to re-link GitHub in Code Review settings. This is a one-time step.

Tip: disable this comment in your organization's Code Review settings.

panos-xyz and others added 3 commits July 21, 2026 00:45
…bounded RPC wait (#143 #144 #145) (#146)

* refactor(reference-index): simplify reader read gate (#145)

The reference-index read path gated every query through a 7-variant
ReferenceIndexPhase state machine plus a `generation` seqlock. Most of
that machinery was not load-bearing: read correctness already comes from
(1) the MDBX MVCC read-transaction snapshot, (2) the
`(indexed_to, indexed_hash) == tip` comparison, and (3) the RPC-layer
before/after `chain_info()` bracketing.

- Delete the `generation` seqlock: the spin-for-even loop and the
  end-of-read re-check. The re-check was over-conservative — it discarded
  a fully-correct result (single snapshot, == tip) as `IndexUnavailable`
  merely because the runtime flipped `phase` mid-read.
- Take `phase` out of the read path. It stays a pure metrics/log field
  (the runtime still sets it and the gauge still exports it). The one
  read-gate bit that remains — "Unavailable → tell clients not to retry"
  — is now a single `unavailable: AtomicBool` instead of a 7-way match.
  Deferred/Backfill/Repairing now fall through to the tip comparison,
  which returns `IndexBehind` on its own (Repairing is transient, so
  `IndexBehind`/retry is more correct than the old `IndexUnavailable`).
- Move the pre-Jade check to the RPC layer via `is_pre_jade`: pre-Jade is
  a complete, terminal empty answer (`Ok([])`), not `IndexBehind`, so the
  query never enters the reader.

query_at is now: check unavailable → open tx → read indexed_to/hash →
compare == tip → iterate → return.

* feat(reference-index): bounded server-side wait on IndexBehind (#144)

The index runtime is asynchronous (PR #141 decoupled it from block
execution), so for a few milliseconds after a new block becomes the
canonical tip the durable cursor still lags it. The common "submit a
MorphTx, then immediately query its reference" pattern lands in that
window and gets `IndexBehind`, forcing clients into a retry loop — a
problem that gets worse as block time shrinks (#123).

Instead of returning `IndexBehind` immediately, the RPC handler now waits
a bounded amount (default 100 ms, polled every 5 ms) for the runtime to
catch up to the canonical tip, then serves real data. The handler is a
`blocking` RPC method, so the sleep only occupies a blocking-pool thread,
never the async reactor, and is strictly bounded by the timeout.

- Re-reads the canonical tip each poll so a tip that advances mid-wait is
  retried against the fresh head rather than spuriously failing.
- Fails fast (no wait) when the runtime is `Deferred` (rapid sync) or
  `PreJade` (one-time Jade-activation boundary): neither catches up on the
  few-ms timescale the wait targets.
- Adds metrics: rpc_waits_total, rpc_wait_timeouts_total, and
  rpc_wait_duration_seconds, recorded via ReferenceIndexHandle.

Response shape and wire semantics are unchanged; only the timing of the
`IndexBehind` decision moves.

* perf(reference-index): bound reorg rewind floor to the L1 finalized block (#143)

Precise incremental reorg rollback relies on the `IndexedBlocks`
breadcrumb table (`block_number -> block_hash`). To support a reorg that
could theoretically rewind to the Jade start, the reconcile path required
retaining every breadcrumb across `jade_first ..= indexed_to`, so the
table grew linearly and unbounded with the chain.

A fixed depth cap is the wrong fix: any block not yet finalized on L1 can
reorg, and reorg depth is a function of block-production speed and the L1
batch-submission interval, not a constant. The correct hard boundary is
the L1 finalized block, which by definition can never be reorged.

- `reconcile_cursor` now floors the rewind at `max(finalized, jade_first)`
  instead of `jade_first`; without finality yet it falls back to
  `jade_first` (unchanged behavior). A divergence that reaches below
  finalized is impossible on a healthy chain, so it surfaces as
  `ManualRebuildRequired` rather than scanning to Jade.
- `commit_canonical_batch` prunes `IndexedBlocks` breadcrumbs below
  finalized, but only once the cursor tip has reached the pruning floor,
  so a deep backfill still below finalized keeps its rows (and the tip's
  own row) intact. Only the reorg breadcrumbs are pruned; the
  ReferenceIndex / BlockReferenceIndex query data is never touched, so
  pruned history stays fully queryable.
- `CanonicalChain` gains `finalized_block_number`, forwarding to
  `BlockIdReader::finalized_block_number` (morph sets finalized via the
  engine API `newSafeL2Block`); the existing `BlockReaderIdExt` blanket
  bound already provides it.

Accepted trade-off: while L1 submission stalls the retained window grows
to `tip - finalized`, bounded by L1 liveness rather than an artificial
constant. In steady state finalized tracks close to the tip, so the table
stays small.

* fix(reference-index): harden optimized read path

Bound finalized breadcrumb pruning, preserve Jade snapshot bracketing, and make RPC catch-up waits deterministic and accurately observed.
…ring set

The subsystem exported 14 metrics, several redundant or derivable. Reduce
to the 5 an operator actually acts on, with no in-repo dashboard consumers
to break:

- phase                   readiness lives here (Live == serving)
- lag_blocks              how far the index trails the canonical head
- reorgs_total            canonical suffix repairs
- failures_total          failed reconciliation turns
- rpc_wait_timeouts_total bounded RPC waits that still returned IndexBehind

Dropped:
- rpc_ready               strictly derivable from phase == Live
- target_block            duplicates the node's canonical-head metric
                          (and == indexed_block + lag_blocks)
- indexed_block           absolute cursor; lag_blocks is the actionable delta
- indexed_blocks_total    throughput counter, low signal for this index
- committed_batches_total only meaningful ratio'd against indexed_blocks_total
- lagged_notifications_total  niche; correlates with lag_blocks
- batch_duration_seconds  histogram; perf detail, not an operating signal
- rpc_waits_total / rpc_wait_duration_seconds  the timeout counter is the
                          actionable RPC-wait signal on its own

observe_rpc_wait now takes only `timed_out` and counts just the timeout;
the RpcWaitGuard no longer tracks a start instant.
@panos-xyz
panos-xyz merged commit 50b361c into main Jul 22, 2026
13 checks passed
@panos-xyz
panos-xyz deleted the codex/reth-main-reference-index branch July 22, 2026 00:39
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.

2 participants