Repository navigation
feat(node): share one eth_blockNumber read across all chain watchers (#1110) - #1225
Conversation
|
Warning Review limit reached
Next review available in: 26 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (12)
Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
There was a problem hiding this comment.
Pull request overview
This PR reduces redundant eth_blockNumber RPC calls by introducing a shared, TTL-cached, single-flight head reader (chain_events::shared_head) and routing all chain watchers’ “read head block” operations through it. This targets rate-limit pressure on RPC endpoints caused by each watcher polling head independently.
Changes:
- Added
chain_events::shared_head::{HeadSource, SharedHead}implementing TTL caching + single-flight (including cached failures) foreth_blockNumber. - Updated
resumable_watcher::WatcherConfig(and all watcher bootstraps) to accept anArc<dyn HeadSource>and use it for head reads. - Wired a single shared
SharedHeadinstance inruntime::run()and updated the anvil settlement E2E test to provide an appropriate head source per service instance.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/chain_events/shared_head.rs | New shared head source with TTL caching, single-flight, and unit/integration-style tests. |
| crates/node/src/chain_events/resumable_watcher.rs | WatcherConfig now depends on HeadSource; tick reads head via the shared source. |
| crates/node/src/chain_events/mod.rs | Exposes shared_head publicly and centralizes DEFAULT_RPC_CALL_TIMEOUT + timed(). |
| crates/node/src/runtime/mod.rs | Constructs one shared SharedHead and passes it to all chain watchers. |
| crates/node/src/slash_watcher.rs | Accepts and forwards a shared HeadSource into watcher config. |
| crates/node/src/payment_settlement.rs | Accepts and forwards a shared HeadSource into watcher config. |
| crates/node/src/reputation_indexer.rs | Accepts shared HeadSource for the watcher while keeping the direct “reachability” head read. |
| crates/node/src/dht/chain_staker_set.rs | Accepts and forwards a shared HeadSource into watcher config. |
| crates/node/src/dht/node_address.rs | Accepts and forwards a shared HeadSource into watcher config. |
| crates/node/src/dht/chain_origin_directory.rs | Accepts and forwards a shared HeadSource into watcher config. |
| crates/node/src/blacklist_watcher.rs | Accepts and forwards a shared HeadSource into watcher config. |
| crates/node/tests/anvil_settlement_e2e.rs | Adds helper to build per-service SharedHead instances and passes them into bootstraps. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let Ok(url) = server.uri().parse() else { | ||
| // Not an assertion about the code under test - bail rather than panic. | ||
| return; | ||
| }; |
There was a problem hiding this comment.
Correct, and self-inflicted. The else { return; } was a workaround for clippy's panic denial — which traded a loud failure for a green test with zero assertions run, the worse outcome.
Fixed in bdd0c83 by adopting the repo's existing test-module idiom instead of working around the lint:
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
mod tests {(the same attribute used across dht/*.rs), then .expect("mock server uri parses").
|
|
||
| // The TTL bound: at most one head read per TTL window, +1 for a partial | ||
| // window at each end. | ||
| let ttl_bound = (per_ms(RUN_FOR) / per_ms(INTERVAL / 2)) as usize + 2; |
There was a problem hiding this comment.
Correct on the mechanism. Fixed in bdd0c83 — though by removing the assumption rather than padding it.
ttl_bound is now derived from measured elapsed instead of the intended RUN_FOR. Adding a fixed extra interval would still be a guess about how much jitter to tolerate; measuring makes the bound exact by construction, and the assertion message now reports the elapsed it used.
Your reasoning checks out against the code — run_tick reads head before any shutdown check, and run only tests the token in its select! before the tick, so an in-flight tick genuinely can land one more read after cancel().
It's also not theoretical: an idle local run measures 551.6ms against a 550ms RUN_FOR. That overshoot alone is under one TTL window, but CI jitter is a different matter.
One deliberate asymmetry: unshared still derives from RUN_FOR. An overshooting run means more real ticks, so under-counting there can only make that assertion stricter — never falsely green. Commented as such.
Also verified the test still has teeth, by mutation — giving each watcher its own SharedHead:
head reads (36) must respect the ttl bound (13) over 551.59883ms
36 = exactly WATCHERS * ticks (6 × 6), versus 6 shared. So the bound catches the regression it exists for, and independently confirms the 6× this PR claims.
There was a problem hiding this comment.
Code Review
This pull request introduces a shared, TTL-cached chain head block number reader (SharedHead implementing HeadSource) to collapse multiple concurrent eth_blockNumber RPC requests from different watchers into a single cached read per TTL window. Various watchers and services, including the blacklist watcher, staker set, origin directory, node address directory, payment settlement, reputation indexer, and slash watcher, have been refactored to accept and share this unified head source. Comprehensive unit and integration tests have been added to verify the caching, single-flight behavior, and error propagation of the new shared head source. There are no review comments, so I have no feedback to provide.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
268954f to
7eb3cd4
Compare
…1110) Each of the seven chain watchers ran its own poll loop against its own provider, so every tick cost one `eth_blockNumber` PER watcher — ~7 head reads per `event_poll_interval` against a single endpoint, on top of each watcher's own `eth_getLogs`. At the default 7s interval that is ~2 req/s (~173k/day) against an endpoint the node is already known to trip rate limits on (#1108). Add `chain_events::shared_head`: a TTL-cached, single-flight `HeadSource` that every watcher reads head through. `WatcherConfig` gains `head: Arc<dyn HeadSource>` and `run_tick` calls it instead of `provider.get_block_number()`. Why a stale head is safe — monotonicity. `SharedHead` only ever returns a head at-or-before the true head; it can never run ahead. `confirmations` is 0 at all seven sites and every consumer clamps AGAINST head (`resolve_persisted_start`, `resolve_head_window_start`, the `from > to` idle branch), so a lagging head only widens an already-idempotent rescan or defers work one tick — it cannot open a gap. Settlement's `NoneFallback::Head` first boot looks like the exception and is not: the #751/#762 hazard is anchoring the durable floor too HIGH, and a cache can only anchor it lower. Design notes: - TTL is `poll_interval / 2`. The watchers are not phase-aligned, so the TTL — not the single-flight — is what collapses the reads. A full-interval TTL would let a watcher act on a head an entire tick old, stretching the effective cadence of a documented knob toward 2x. - Failures are cached for the same TTL. Without that, a wedged provider serializes timeouts and the Nth watcher's tick — and its `*_backoff_started` gauge — is delayed by N x 10s. With it, one caller pays the timeout and the rest fail instantly, so every watcher backs off together exactly as before. - `.context("read head block")` stays in `run_tick`, so a failed head read renders identically to before and a test fake matches production. - The head source owns a plain read-only provider (no wallet/fillers) and deliberately skips `with_poll_interval`, which only sets the receipt heartbeat. - `reputation_indexer`'s bring-up `get_block_number` is deliberately NOT migrated: it is a fail-fast reachability smoke check, and a cached hit would satisfy it without touching the RPC, defeating its only purpose. `timed` + `DEFAULT_RPC_CALL_TIMEOUT` move up to `chain_events` (shared by the loop and the head source). Verification: both pre-existing mocked `run_tick` tests pass with UNCHANGED bodies (the compatibility canary) — `tick_cfg` uses a `Duration::ZERO` TTL, which is load-bearing and commented. New: 7 unit tests covering TTL/single-flight/error caching via `Asserter::read_q()`, `head_read_failure_fails_the_tick`, and a wiremock counting test that proves the reduction end-to-end through the real `run` loop (6 watchers x 6 ticks = 36 head() calls collapse to 6 RPCs). fmt/clippy(--all-targets, incl. anvil-e2e)/doc clean; 795 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
7eb3cd4 to
3e51cc5
Compare
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 88.92% (2488/2798 lines) |
Coverage reportTotal: 80.58% (was 80.51%, ▲ +0.07%) — 47884/59423 lines
History
|
…iming-flaking (#1110) Two review catches on #1225, both on the wiremock counting test. Setup failure passed silently. The `let Ok(url) = ... else { return; }` was a workaround for clippy's `panic` denial, and it turned an unparseable mock URI into a GREEN test with zero assertions run. Adopt the repo's test-module lint idiom (`#[allow(clippy::unwrap_used, expect_used, panic, indexing_slicing)]`, as used across `dht/*.rs`) and `.expect()` instead, so setup failure fails loudly. The TTL bound was derived from the INTENDED `RUN_FOR`, not measured wall time. The sleep can overshoot and, after `cancel()`, each watcher may still finish an in-flight tick (`run_tick` reads head before it checks shutdown) — every extra TTL window legitimately permits one more head read, so the bound could fail while the cache behaved perfectly. Now derived from measured `elapsed`. This is not theoretical: a local idle run measures 551.6ms against a 550ms `RUN_FOR`, and CI jitter is far worse. `unshared` stays derived from `RUN_FOR` deliberately — an overshooting run means MORE real ticks, so under-counting can only make that assertion stricter, never falsely green. Mock setup extracted to `counting_server()` (the added comments pushed the test past clippy's 100-line limit; a helper beats an `#[allow]`). Verified the test has teeth by mutation: giving each watcher its own `SharedHead` makes it report 36 head reads (exactly 6 watchers x 6 ticks) and fail the bound; shared, it reports 6. That is the same 6x this PR claims. fmt/clippy/doc clean; 795 node tests pass; counting test run 3x, no flake. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Why
Each of the seven chain watchers runs its own poll loop against its own provider, so every tick costs one
eth_blockNumberper watcher — ~7 head reads perevent_poll_intervalagainst a single endpoint, on top of each watcher's owneth_getLogs. At the default 7s interval that's ~2 req/s (~173k/day) against an endpoint the node is already known to trip rate limits on (#1108).This adds
chain_events::shared_head: a TTL-cached, single-flightHeadSourcethat every watcher reads head through. Head reads drop from 7/tick to ≤2 per interval.Why a stale head is safe — monotonicity
SharedHeadonly ever returns a head at-or-before the true head; it can never run ahead.confirmationsis 0 at all seven sites, and every consumer clamps against head (resolve_persisted_start,resolve_head_window_start, thefrom > toidle branch), so a lagging head only ever widens an already-idempotent rescan or defers work by one tick — it cannot open a gap.Settlement's
NoneFallback::Headfirst boot looks like the exception and isn't: the #751/#762 hazard is anchoring the durable floor too high, and a cache can only ever anchor it lower.The real cost is ≤ TTL of added observation latency, which is sub-tick by construction.
Design notes
poll_interval / 2. The watchers aren't phase-aligned (they bootstrap sequentially and drift), so the TTL — not the single-flight — is what collapses the reads. A full-interval TTL would let a watcher act on a head an entire tick old, silently stretching the effective cadence of a documented knob toward 2×.*_backoff_startedgauge by a minute. With it, one caller pays the timeout and the rest fail instantly, so every watcher backs off together exactly as it does today..context("read head block")stays inrun_tick(not the head source), so a failed head read renders identically to before and a test fake matches production.with_poll_interval, which only sets the receipt heartbeat.reputation_indexer's bring-upget_block_numberis deliberately NOT migrated — it's a fail-fast reachability smoke check, and a cached hit would satisfy it without touching the RPC, defeating its only purpose. A mechanical "replace allget_block_number" refactor would have broken this.Verification
run_ticktests pass with unchanged bodies — the compatibility canary.tick_cfguses aDuration::ZEROTTL, which is load-bearing (a cached head would desync the orderedAsserterqueue and mis-serve a head as aget_logsresponse) and is commented as such.Asserter::read_q()as an RPC counter — an unconsumed response proves no second call was made.head_read_failure_fails_the_tickpins the preserved context and backoff path.runloop: 6 watchers × 6 ticks = 36head()calls collapse to 6 RPCs.fmt/clippy --all-targets(incl.anvil-e2e) /docclean; 795 node tests pass.🤖 Generated with Claude Code