Skip to content

feat(node): share one eth_blockNumber read across all chain watchers (#1110) - #1225

Merged
thiras merged 2 commits into
mainfrom
feat/1110-shared-head-read
Jul 16, 2026
Merged

thiras merged 2 commits into
mainfrom
feat/1110-shared-head-read

Conversation

@thiras

@thiras thiras commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Stacked on #1224 (docs). Base will retarget to main once that merges — both touch the same runtime/mod.rs region.

Why

Each of the seven chain watchers runs its own poll loop against its own provider, so every tick costs 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'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-flight HeadSource that every watcher reads head through. Head reads drop from 7/tick to ≤2 per interval.

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 ever widens an already-idempotent rescan or defers work by one tick — it cannot open a gap.

Settlement's NoneFallback::Head first 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

  • TTL = 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×.
  • Failures are cached for the same TTL. This is the subtle one: without it a wedged provider serializes timeouts, so the 7th watcher waits up to 70s before its tick even fails — delaying its *_backoff_started gauge 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 in run_tick (not the head source), 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'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 all get_block_number" refactor would have broken this.

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 (a cached head would desync the ordered Asserter queue and mis-serve a head as a get_logs response) and is commented as such.
  • 7 new unit tests covering TTL / single-flight / error-caching, using Asserter::read_q() as an RPC counter — an unconsumed response proves no second call was made.
  • head_read_failure_fails_the_tick pins the preserved context and backoff path.
  • A wiremock counting test proves the reduction end-to-end through the real run loop: 6 watchers × 6 ticks = 36 head() calls collapse to 6 RPCs.

fmt / clippy --all-targets (incl. anvil-e2e) / doc clean; 795 node tests pass.

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings July 16, 2026 15:38
@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

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

Next review available in: 26 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 9db4e1f9-9f8f-4a3c-8176-e3a4ac6180f6

📥 Commits

Reviewing files that changed from the base of the PR and between e904b3e and bdd0c83.

📒 Files selected for processing (12)
  • crates/node/src/blacklist_watcher.rs
  • crates/node/src/chain_events/mod.rs
  • crates/node/src/chain_events/resumable_watcher.rs
  • crates/node/src/chain_events/shared_head.rs
  • crates/node/src/dht/chain_origin_directory.rs
  • crates/node/src/dht/chain_staker_set.rs
  • crates/node/src/dht/node_address.rs
  • crates/node/src/payment_settlement.rs
  • crates/node/src/reputation_indexer.rs
  • crates/node/src/runtime/mod.rs
  • crates/node/src/slash_watcher.rs
  • crates/node/tests/anvil_settlement_e2e.rs

Note

🎁 Summarized by CodeRabbit Free

Your 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 @coderabbitai help to get the list of available commands.

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

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) for eth_blockNumber.
  • Updated resumable_watcher::WatcherConfig (and all watcher bootstraps) to accept an Arc<dyn HeadSource> and use it for head reads.
  • Wired a single shared SharedHead instance in runtime::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.

Comment on lines +326 to +329
let Ok(url) = server.uri().parse() else {
// Not an assertion about the code under test - bail rather than panic.
return;
};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@gemini-code-assist gemini-code-assist 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.

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.

@thiras
thiras force-pushed the feat/1110-shared-head-read branch from 268954f to 7eb3cd4 Compare July 16, 2026 16:26
Base automatically changed from docs/1110-getlogs-poll-interval-docs to main July 16, 2026 16:36
…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]>
@thiras
thiras force-pushed the feat/1110-shared-head-read branch from 7eb3cd4 to 3e51cc5 Compare July 16, 2026 16:41
@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 88.92% (2488/2798 lines)
▲ +0.00pp vs base (88.92% → 88.92%)
Run: 29517908035

@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.58% (was 80.51%, ▲ +0.07%) — 47884/59423 lines

File Coverage Lines Δ
crates/node/src/blacklist_watcher.rs 23.08% 63/273 ▼ 0.17%
crates/node/src/chain_events/mod.rs 91.67% 11/12 new
crates/node/src/chain_events/resumable_watcher.rs 93.03% 347/373 ▲ +9.83%
crates/node/src/chain_events/shared_head.rs 94.36% 184/195 new
crates/node/src/dht/chain_origin_directory.rs 63.83% 637/998 ▼ 0.13%
crates/node/src/dht/chain_staker_set.rs 34.81% 118/339 ▼ 0.21%
crates/node/src/dht/node_address.rs 40.57% 99/244 ▼ 0.34%
crates/node/src/payment_settlement.rs 54.55% 906/1661 ▼ 0.07%
crates/node/src/reputation_indexer.rs 54.71% 279/510 ▼ 0.22%
crates/node/src/runtime/mod.rs 49.36% 1083/2194 ▼ 0.25%
crates/node/src/slash_watcher.rs 43.06% 93/216 ▼ 0.40%
History
Commit Total Δ vs base
3e51cc5 80.58% ▲ +0.07%
bdd0c83 (HEAD) 80.58% ▲ +0.07%

…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]>
@thiras
thiras merged commit bdf1c4f into main Jul 16, 2026
23 checks passed
@thiras
thiras deleted the feat/1110-shared-head-read branch July 16, 2026 17:35
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