Repository navigation
feat(node): eth_getLogs resumable watcher, off eth_newFilter (#1106, #1108, #1092) - #1110
Conversation
…1108, #1092) Every on-chain watcher's live path went through alloy `watch_logs` (`eth_newFilter` + `eth_getFilterChanges`), which the default public Arbitrum Sepolia RPC and most keyless endpoints reject with `-32601` — so a correctly bonded, registered node silently spun in a retry loop while logging "runtime ready" (#1106). The `from_block`-seeded watchers also re-scanned `[from_block, head]` (~275M blocks) every boot, tripping rate limits into a crash-loop (#1108). Generalize `chain_events` into one `resumable_watcher::run` getLogs polling loop (#1092): each tick reads head, scans `[cursor, head-confirmations]` in windows, feeds a `LogSink`, and advances/persists the cursor per window — the first tick IS the backfill, later ticks the live tail. Migrate all seven watchers onto it (settlement, slash, blacklist, origin, reputation-indexer, staker-set, node-address); `watch_logs` is now grep-clean. - Keyed `KeyedCheckpointStore` (redb) + debounced decorator; settlement and origin persist their scan cursor (`CheckpointKey::{ChannelOpened,Origin}`), so restarts resume instead of re-scanning from genesis (#1108). - Slash: bounded appeal-window lookback each boot (no resume cursor — the in-memory store must rebuild, but only the still-appealable tail matters). - Blacklist: full replay each boot (no persisted cursor) — its in-memory deny-set has no enumeration source, so a resume would drop still-out-of-scope entries, a slashable compliance gap; the crash-loop is instead fixed below. Durable deny-set resume is a tracked follow-up. - Startup RPC preflight tolerates a transient 429/5xx with bounded backoff instead of exiting the process (the #1108 crash-loop root cause). cargo build/clippy/fmt/doc clean; 912 node+incentive unit tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Warning Review limit reached
Next review available in: 27 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 (1)
WalkthroughThe change adds keyed checkpoint persistence and a shared resumable ChangesWatcher migration
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant Runtime
participant ResumableWatcher
participant Provider
participant LogSink
participant CheckpointStore
Runtime->>ResumableWatcher: start configured watcher
ResumableWatcher->>Provider: poll confirmed logs
Provider-->>ResumableWatcher: return log windows
ResumableWatcher->>LogSink: apply decoded logs
ResumableWatcher->>CheckpointStore: persist keyed cursor
Runtime->>ResumableWatcher: cancel during shutdown
ResumableWatcher->>CheckpointStore: flush cursor
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 |
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 88.71% (2452/2764 lines) |
There was a problem hiding this comment.
Code Review
This pull request refactors the on-chain event watchers to use a unified, resumable eth_getLogs polling loop (resumable_watcher), replacing the previous server-side filters to improve compatibility with public RPC endpoints. It also introduces KeyedCheckpointStore to persist scan cursors independently for different watchers. The review feedback highlights critical improvements: capping max_backfill_span at 10_000 (instead of u64::MAX) in chain_staker_set.rs and node_address.rs to prevent RPC range limit errors during lag, and enforcing a default timeout in the timed helper in resumable_watcher.rs to avoid getting permanently wedged by stalling RPC providers.
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.
There was a problem hiding this comment.
Pull request overview
This PR migrates the node’s on-chain event watchers away from alloy’s filter-based watch_logs (which depends on eth_newFilter) to a single shared, resumable eth_getLogs polling watcher, addressing RPC compatibility and restart/backfill crash-loop issues.
Changes:
- Introduces
chain_events::resumable_watcher, a unifiedeth_getLogspolling loop with cursor/backoff policies and optional per-window checkpoint persistence. - Migrates settlement, origin directory, slash, reputation indexer, staker-set, node-address, and blacklist watchers to the new poller; adds keyed watcher checkpoints (
CheckpointKey+KeyedCheckpointStore). - Makes the startup RPC preflight tolerant of transient failures (429/5xx/timeouts) with bounded retry/backoff to avoid systemd crash-loops during cold-start backfills.
Reviewed changes
Copilot reviewed 15 out of 15 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/chain_events/resumable_watcher.rs | New shared resumable eth_getLogs polling watcher with cursor policies, per-window persistence, and backoff. |
| crates/node/src/chain_events/mod.rs | Adds module wrapper and documents the new watcher approach. |
| crates/node/src/chain_events.rs | Removes legacy filter-based watch_logs helper utilities. |
| crates/incentive/src/store.rs | Replaces single-cursor watcher checkpoint trait with keyed checkpoint API (CheckpointKey, KeyedCheckpointStore). |
| crates/incentive/src/lib.rs | Re-exports new checkpoint types/traits. |
| crates/node/src/channel_store.rs | Implements keyed checkpoint persistence in redb (watcher_checkpoint_v1 multi-key table). |
| crates/node/src/payment_settlement.rs | Migrates settlement watcher to resumable poller and updates debounced checkpointing to keyed API. |
| crates/node/src/dht/chain_origin_directory.rs | Migrates origin directory watcher to resumable poller with persisted cursor (CheckpointKey::Origin). |
| crates/node/src/slash_watcher.rs | Migrates slash watcher to resumable poller with bounded boot lookback (appeal window). |
| crates/node/src/reputation_indexer.rs | Migrates settlement/reputation indexer to resumable poller with bounded head-window cursor policy. |
| crates/node/src/dht/chain_staker_set.rs | Migrates staker set watcher to resumable poller (live-from-head, enumeration bootstrapped). |
| crates/node/src/dht/node_address.rs | Migrates node-address watcher to resumable poller (live-from-head, enumeration bootstrapped). |
| crates/node/src/blacklist_watcher.rs | Migrates blacklist watcher to resumable poller; keeps full replay each boot (no persisted cursor) plus periodic re-scope. |
| crates/node/src/runtime/mod.rs | Wires new watcher parameters (poll interval, keyed checkpoint store) and adds transient-tolerant RPC preflight. |
| crates/node/tests/anvil_settlement_e2e.rs | Updates E2E test wiring for the keyed checkpoint store and new poll interval parameters. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 80.43% (was 80.07%, ▲ +0.35%) — 44762/55654 lines
History
|
…out, idle reconcile, mid-tick shutdown Four fixes from PR #1110 review: - Cap `max_backfill_span` at `MAX_BACKFILL_BLOCK_SPAN` (was `u64::MAX`) for the live-from-head staker-set and node-address watchers: on a lag (RPC outage / rate-limit) their recovery tick scans `[cursor, head]`, which unchunked would trip a provider range limit and wedge in a failure loop. - `timed` now applies a `DEFAULT_RPC_CALL_TIMEOUT` (10s) when a watcher passes `None`, so a provider that stalls the connection can't wedge the tick and block shutdown (the alloy HTTP provider has no request timeout of its own). - Run `on_tick_complete` on idle ticks too: the blacklist re-scope (which catches no-event scope transitions) is a time-gated pass in `on_tick_complete`, so on a quiet chain — every tick `from > to` — it would otherwise never run. - Check `shutdown` between backfill windows so a large first-boot backfill (blacklist full replay, slash appeal-window span) yields promptly to graceful shutdown instead of blocking until the whole tick completes. cargo build/clippy/fmt clean; 912 node+incentive tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…s, FullReplay variant, cursor/preflight tests Follow-up to the PR #1110 comprehensive review (no correctness bugs found; the core invariants were traced and verified). Addresses the accuracy and test-coverage findings: - Rewrote the stale module headers/doc comments that still narrated the deleted `.watch()` / `eth_newFilter` / resync / resubscribe architecture (settlement, slash, staker-set, node-address, reputation, origin) so they describe the getLogs poller's actual control flow — including the settlement failure/recovery path and the origin "healing is now event-driven, not periodic" note. Fixed dangling references to deleted symbols (`backfill_closing_channels`, `resolve_backfill_start`, `watcher_loop`, `run_watcher_once`). - Scoped the `timed` doc: it bounds only the loop's `get_block_number`/`get_logs`; a sink-internal `.call()` (getOrigins, nodeIdOf, …) is still unbounded (bounding those is a tracked follow-up). - Replaced the `HeadMinusWindow{u64::MAX}` sentinel with a named `CursorPolicy::FullReplay { floor }`; relabelled the reserved, not-persisted `CheckpointKey::Blacklist`. - Tests: preflight classifier + retry/recover/exhaust/fatal (wiremock; extracted `preflight_retry` for an injectable backoff); per-key `DebouncedCheckpointStore` isolation (key-aware mock); froze all three `CheckpointKey` on-disk literals. cargo build/clippy/fmt/doc clean; 917 node+incentive tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Multi-agent review disposition (commits 320a244, 0d6fbb7)Ran a comprehensive review (code / silent-failure / type-design / comment-accuracy / test-coverage). No correctness or fund-stranding bug was found — the code-reviewer and silent-failure-hunter independently traced and verified the core invariants (#751 anti-strand, #1108 per-window resume, cursor math, redb backward-compat, blacklist deny-set completeness, origin no-missed-revoke, preflight retry). Findings were accuracy / robustness / test-coverage. Addressed
Deferred (verified-correct today; tracked follow-ups)
|
…view Review findings on the #1106/#1108 getLogs migration, most-severe first: - Checkpoint load error no longer falls back to head for NoneFallback::Head (settlement): the first persisted window would durably overwrite the stored floor, permanently discarding the #751/#762 downtime gap. The tick now fails into backoff and re-resolves; the FromBlock fallback (origin) keeps degrading to a wider idempotent rescan. - Origin watcher gets a real graceful shutdown: runtime threads a cancelled token into ChainOriginDirectory::bootstrap and deterministically flushes CheckpointKey::Origin at shutdown (was a throwaway token + abort-only teardown, silently dropping up to a debounce window of cursor progress on every clean stop, violating the KeyedCheckpointStore flush contract). - OriginSink heals deferred getOrigins re-reads: a failed authoritative re-read is queued and retried in on_tick_complete every tick (tick fails -> backoff while any remain). Previously one 429 after e.g. AssignmentActivated left the namespace fail-closed for the process lifetime with the persisted cursor already past the event. - ChannelToppedUp durable-write failure now fails the tick (was log-and-skip, permanently capping a paying client's channel at its stale deposit ceiling); same policy as ChannelOpened. - DebouncedCheckpointStore seeds only after the inner load succeeds: flipping seeded before the fallible load left last_persisted=None on error, defeating the monotonic-floor guard the seed exists to provide. - Blacklist enforcement failure (scope-check/evict) pulls the batched re-scope forward to the poll cadence until clean (was: wait out the full content_blacklist_poll_interval_sec, default 10 min, while serving the blob is slashable). - Slash: re-sighting a deduped slashId backfills a missed appeal_window_close hint; undecodable-log warn now carries block/tx. Tests: mock-transport run_tick coverage pinning the anti-strand invariant (sink Err mid-window leaves cursor AND durable checkpoint at the last completed window; retry re-delivers) plus idle-tick semantics; cursor-policy pins for blacklist (FullReplay - compliance), settlement (Persisted/Head) and origin (Persisted/FromBlock); debounce seed-failure regression test; checkpoint load-error policy tests; appeal-window test pinned to the concrete block count instead of restating the formula. Docs: rpc_call_timeout None actually means the 10s default; removed the dangling backfill_closing_channels recovery claim (recovery is cursor-bound, per the reconcile_closing_channel residual note); swept subscription-era vocabulary (resubscribe/event-stream) and the stale per-open checkpoint narrative from the rewritten watchers; reputation indexer now imports the shared MAX_BACKFILL_BLOCK_SPAN instead of mirroring it. Co-Authored-By: Claude Fable 5 <[email protected]>
…ation The anvil settlement e2e failed on every commit of this PR at 'watcher did not observe ChannelSettled / forget channel 2': this PR made close_open_channels_on_shutdown cancel the settlement watcher (correct for a real shutdown), but the test called it to close channel 2 and then expected the now-dead watcher to observe a later ChannelSettled. Fix the test to match the new shutdown semantics without weakening coverage: - Close channel 2 directly on-chain (provider party, zero-voucher — its claimedNonce is 0 since it stayed below the redeem threshold) so the watcher stays alive to observe the settle. Channel 1's on-chain withdraw already proves a persisted voucher is accepted on-chain, so the dropped shutdown-close-of-channel-2 assertion loses no unique coverage. - Move the service's own close_open_channels_on_shutdown to after the buyer path (the buyer channel is below the redeem threshold, so the still-alive redeemer never touches it, and its full-deposit reclaim still holds) and before channel 3 — which is served by its own dedicated service, so the original watcher is no longer needed there. This is also where the original redeemer must be quiesced so it can't race the auto-settle service. Verified locally against anvil+forge: the full e2e passes. Co-Authored-By: Claude Fable 5 <[email protected]>
…sage (#1110) Review catch on #1224: the min-interval error message named only `eth_getLogs`, which is the exact failure mode this PR exists to fix — the knob drives two consumers, and the message named one of them. It also claimed a sub-minimum interval polls "faster than any provider tolerates". That contradicts the `MIN_EVENT_POLL_INTERVAL_MS` rationale 120 lines above it, which keeps the floor at 250ms precisely BECAUSE a dev anvil tolerates alloy's localhost cadence (and `crates/e2e` drives one at 500ms). Drop the universal claim for "too frequently", matching the sibling rpc_watchdog_interval_sec message. Same overclaim removed from the test comment. The message keeps `event_poll_interval_ms` and `minimum 250ms`, so `resolve_blockchain_rejects_event_poll_interval_below_minimum` still passes. fmt/clippy clean; 703 common+cli tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…sage (#1110) Review catch on #1224: the min-interval error message named only `eth_getLogs`, which is the exact failure mode this PR exists to fix — the knob drives two consumers, and the message named one of them. It also claimed a sub-minimum interval polls "faster than any provider tolerates". That contradicts the `MIN_EVENT_POLL_INTERVAL_MS` rationale 120 lines above it, which keeps the floor at 250ms precisely BECAUSE a dev anvil tolerates alloy's localhost cadence (and `crates/e2e` drives one at 500ms). Drop the universal claim for "too frequently", matching the sibling rpc_watchdog_interval_sec message. Same overclaim removed from the test comment. The message keeps `event_poll_interval_ms` and `minimum 250ms`, so `resolve_blockchain_rejects_event_poll_interval_below_minimum` still passes. fmt/clippy clean; 703 common+cli tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…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]>
`struct AbortOnDrop(JoinHandle<()>)` plus its `Drop` impl was copy-pasted SEVEN times — slash, reputation-indexer, node-address, settlement, origin-directory, buyer-channel, and staker-set — all byte-identical. That made it read as though each watcher had its own teardown policy when they never differed. Pure move: one definition in `chain_events`, seven local copies deleted. No behavior change. Prepares the CapacityBond watcher merge, where two of those copies have to unify anyway. clippy/fmt clean; 795 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tions (#1110) `ChainStakerSet` (membership) and `ChainNodeAddressDirectory` (node→address bindings) are both derived from the same CapacityBond contract, but each ran its own bootstrap and its own `eth_getLogs` loop against the same address — with node-address's two topics a strict SUBSET of staker-set's five. Two paginated `getActiveNodes` reads at boot, two poll loops forever after. Add `dht::capacity_bond_registry`: one enumeration, one loop, demuxing to both projections. Watchers drop 7 → 6 (6 → 6 in the default config, where pull-through is off — see below). `chain_staker_set` and `node_address` keep their facades, trait impls, projection helpers and all their existing tests; each loses its bootstrap/sink/hooks/pagination and gains `from_parts`. The correctness point that shapes the sink: only the ENUMERATION differs between the two views. The live arms are a clean union — `NodeRegistered` inserts into both unfiltered, because staker-set's live arm applies no `isActive` check either (its filter is bootstrap-only). Reading "staker-set is the filtered view" as a live-path difference and encoding it in the sink would drop registrations from the active set. - One sink with match arms, not a `Tee<A,B>`: `NodeRegistered` is the only shared topic and is the whole point — one `decode_log_data` feeds both. A tee decodes twice and needs `log.clone()` (`apply` takes `Log` by value). Follows the `ChainOriginDirectory` precedent (2 addresses x 7 topics, one sink). - `NodeAutoEjected` deactivates WITHOUT clearing the binding: ejection flips `isActive` only, and the operator may still be owed payment on an open channel. This is the most plausible silent bug in the merge and has a dedicated test. - Bindings are `Option`-gated on `node_to_node_pull_through_enabled`. The reason is metric semantics, not cost: building it unconditionally would publish `node_address_directory_size` on every default node, meaning "registered nodes" rather than "resolvable payout targets". - Both gauge families are kept, node-address's gated on the projection existing. They now describe one shared loop, so they are perfectly correlated — but freezing `node_address_watcher_down_seconds` at 0 forever would be an alert that can never fire, which is worse than deleting it. Retiring one is a follow-up. - `seed_cursor: Some(snapshot_block)` closes a latent gap both watchers had: events landing between the enumeration and the first tick's head read were missed. Head is read BEFORE the enumeration (the `ChainOriginDirectory` ordering) — the reverse would lose exactly the events being recovered. This matters more since #1221 made gossip announce ACCEPTANCE depend on live registry freshness. - `RegistryChainReads` makes the event handlers unit-testable without a provider: these two modules had ZERO tests before, and now have 11. Removing a non-fatal error path (deliberate, and unreachable): node-address bootstrap failure used to log-and-disable pull-through. `getActiveNodes` failure was ALREADY fatal — the unconditional staker-set bootstrap ran first and propagated it, so node-address's arm was never reached on that path. With the read shared, the bindings projection has no RPC of its own; it derives from page data already in hand and cannot fail independently. No node that boots today loses pull-through; none that boots today starts failing. fmt/clippy(--all-targets, incl. anvil-e2e)/doc clean; 806 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…etLogs (#1110) (#1224) * docs(node,common,cli): re-anchor event_poll_interval_ms docs to eth_getLogs (#1110) #1106 moved every watcher off alloy `watch_logs` (`eth_newFilter` + `eth_getFilterChanges`) onto one `eth_getLogs` polling loop, but nine doc sites still describe the deleted API. They all paraphrase one root rationale (`MIN_EVENT_POLL_INTERVAL_MS`), whose two stated justifications are both dead: there are no long-lived watcher filters, and alloy's localhost floor no longer governs log polling. The wording hid a real change: `event_poll_interval_ms` now has TWO unrelated consumers, and the docs described only the wrong one. - `resumable_watcher`'s `WatcherConfig::poll_interval` — the `eth_getLogs` tick cadence of every chain watcher. - alloy's pending-transaction receipt heartbeat, via `with_poll_interval` (`client().set_poll_interval`), consumed by `PendingTransactionBuilder::get_receipt` when the node awaits a mined settlement / channel tx. `with_poll_interval` is therefore NOT dead code, and `resolved.rs` was doubly wrong — it claimed the knob drives watcher filter polling via `with_poll_interval` when that path only reaches the receipt heartbeat. Both consumers are now named at every site, and `with_poll_interval`'s own doc is re-anchored to the heartbeat. The 250ms floor is unchanged; its rationale is rewritten: ~6 watcher loops each scanning `[cursor, head]` 4x/second trips provider rate limits just as the original flood did. Historical references explaining WHY the old API was abandoned (`resumable_watcher.rs`, `chain_events/mod.rs`, `slash_watcher.rs`, `blacklist_watcher.rs`, `chain_origin_directory.rs`) are left intact. ADRs are untouched: they are spec-level intent and do not mandate a transport. Docs only — no behavior change. fmt/clippy/doc clean; 703 common+cli and 786 node tests pass, including `resolve_blockchain_rejects_event_poll_interval_below_minimum`, which asserts the reworded message text. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(common): name both poll-interval consumers in the validation message (#1110) Review catch on #1224: the min-interval error message named only `eth_getLogs`, which is the exact failure mode this PR exists to fix — the knob drives two consumers, and the message named one of them. It also claimed a sub-minimum interval polls "faster than any provider tolerates". That contradicts the `MIN_EVENT_POLL_INTERVAL_MS` rationale 120 lines above it, which keeps the floor at 250ms precisely BECAUSE a dev anvil tolerates alloy's localhost cadence (and `crates/e2e` drives one at 500ms). Drop the universal claim for "too frequently", matching the sibling rpc_watchdog_interval_sec message. Same overclaim removed from the test comment. The message keeps `event_poll_interval_ms` and `minimum 250ms`, so `resolve_blockchain_rejects_event_poll_interval_below_minimum` still passes. fmt/clippy clean; 703 common+cli tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…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]>
`struct AbortOnDrop(JoinHandle<()>)` plus its `Drop` impl was copy-pasted SEVEN times — slash, reputation-indexer, node-address, settlement, origin-directory, buyer-channel, and staker-set — all byte-identical. That made it read as though each watcher had its own teardown policy when they never differed. Pure move: one definition in `chain_events`, seven local copies deleted. No behavior change. Prepares the CapacityBond watcher merge, where two of those copies have to unify anyway. clippy/fmt clean; 795 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tions (#1110) `ChainStakerSet` (membership) and `ChainNodeAddressDirectory` (node→address bindings) are both derived from the same CapacityBond contract, but each ran its own bootstrap and its own `eth_getLogs` loop against the same address — with node-address's two topics a strict SUBSET of staker-set's five. Two paginated `getActiveNodes` reads at boot, two poll loops forever after. Add `dht::capacity_bond_registry`: one enumeration, one loop, demuxing to both projections. Watchers drop 7 → 6 (6 → 6 in the default config, where pull-through is off — see below). `chain_staker_set` and `node_address` keep their facades, trait impls, projection helpers and all their existing tests; each loses its bootstrap/sink/hooks/pagination and gains `from_parts`. The correctness point that shapes the sink: only the ENUMERATION differs between the two views. The live arms are a clean union — `NodeRegistered` inserts into both unfiltered, because staker-set's live arm applies no `isActive` check either (its filter is bootstrap-only). Reading "staker-set is the filtered view" as a live-path difference and encoding it in the sink would drop registrations from the active set. - One sink with match arms, not a `Tee<A,B>`: `NodeRegistered` is the only shared topic and is the whole point — one `decode_log_data` feeds both. A tee decodes twice and needs `log.clone()` (`apply` takes `Log` by value). Follows the `ChainOriginDirectory` precedent (2 addresses x 7 topics, one sink). - `NodeAutoEjected` deactivates WITHOUT clearing the binding: ejection flips `isActive` only, and the operator may still be owed payment on an open channel. This is the most plausible silent bug in the merge and has a dedicated test. - Bindings are `Option`-gated on `node_to_node_pull_through_enabled`. The reason is metric semantics, not cost: building it unconditionally would publish `node_address_directory_size` on every default node, meaning "registered nodes" rather than "resolvable payout targets". - Both gauge families are kept, node-address's gated on the projection existing. They now describe one shared loop, so they are perfectly correlated — but freezing `node_address_watcher_down_seconds` at 0 forever would be an alert that can never fire, which is worse than deleting it. Retiring one is a follow-up. - `seed_cursor: Some(snapshot_block)` closes a latent gap both watchers had: events landing between the enumeration and the first tick's head read were missed. Head is read BEFORE the enumeration (the `ChainOriginDirectory` ordering) — the reverse would lose exactly the events being recovered. This matters more since #1221 made gossip announce ACCEPTANCE depend on live registry freshness. - `RegistryChainReads` makes the event handlers unit-testable without a provider: these two modules had ZERO tests before, and now have 11. Removing a non-fatal error path (deliberate, and unreachable): node-address bootstrap failure used to log-and-disable pull-through. `getActiveNodes` failure was ALREADY fatal — the unconditional staker-set bootstrap ran first and propagated it, so node-address's arm was never reached on that path. With the read shared, the bindings projection has no RPC of its own; it derives from page data already in hand and cannot fail independently. No node that boots today loses pull-through; none that boots today starts failing. fmt/clippy(--all-targets, incl. anvil-e2e)/doc clean; 806 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…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]>
…rm (#1110) Review on #1226 flagged `rpc_call_timeout: None` as an unbounded RPC and asked for `Some(Duration::from_secs(10))`. That premise is wrong: `timed` does `unwrap_or(DEFAULT_RPC_CALL_TIMEOUT)`, so `None` already IS 10s. The suggestion is a behavioural no-op that would hardcode the constant at the call site and diverge from `DEFAULT_RPC_CALL_TIMEOUT`, and 5 of 6 watchers pass `None` as the convention. But the rule behind it is right, and points at a real unbounded call the review missed 300 lines up: `ContractReads::node_id_of` did a bare `.nodeIdOf(op).call().await`. `WatcherConfig::rpc_call_timeout` covers only the loop's own `get_logs` — `timed`'s own doc says sink follow-ups stay unbounded unless the sink wraps itself. This matters more BECAUSE of the merge, and the regression is this PR's own: a stalled `nodeIdOf` used to wedge only the staker-set loop, since node-address ran its own; now one loop feeds both projections, so it wedges bindings too. Bound it here rather than defer, following the `blacklist_watcher::scope_check` precedent. A timeout surfaces as `Err`, which `on_operator_change` already counts via `staker_set_watcher_resolve_failure` and skips without tripping the stream backoff — the path `node_id_of_failure_bumps_resolve_failure_and_returns_ok` already covers. `timed` now takes `IntoFuture` rather than `Future`, so an alloy `.call()` (an `EthCall`, not a future) wraps directly instead of every caller spelling `.into_future()`. Every `Future` is an `IntoFuture`, so this is a strict widening and existing callers are untouched. `tokio::time::timeout` already accepted `IntoFuture` — the wrapper was what narrowed it. `timed`'s timeout arm had NO test, so the bound rested on untested code. Added three (paused clock, no wall-clock cost): a hanging call times out at the default and names itself, an explicit timeout wins over the default, and a prompt success passes through. fmt/clippy/doc clean; 809 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…1110) (#1225) * feat(node): share one eth_blockNumber read across all chain watchers (#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]> * test(node): make the shared-head counting test fail loudly and stop timing-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]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
`struct AbortOnDrop(JoinHandle<()>)` plus its `Drop` impl was copy-pasted SEVEN times — slash, reputation-indexer, node-address, settlement, origin-directory, buyer-channel, and staker-set — all byte-identical. That made it read as though each watcher had its own teardown policy when they never differed. Pure move: one definition in `chain_events`, seven local copies deleted. No behavior change. Prepares the CapacityBond watcher merge, where two of those copies have to unify anyway. clippy/fmt clean; 795 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tions (#1110) `ChainStakerSet` (membership) and `ChainNodeAddressDirectory` (node→address bindings) are both derived from the same CapacityBond contract, but each ran its own bootstrap and its own `eth_getLogs` loop against the same address — with node-address's two topics a strict SUBSET of staker-set's five. Two paginated `getActiveNodes` reads at boot, two poll loops forever after. Add `dht::capacity_bond_registry`: one enumeration, one loop, demuxing to both projections. Watchers drop 7 → 6 (6 → 6 in the default config, where pull-through is off — see below). `chain_staker_set` and `node_address` keep their facades, trait impls, projection helpers and all their existing tests; each loses its bootstrap/sink/hooks/pagination and gains `from_parts`. The correctness point that shapes the sink: only the ENUMERATION differs between the two views. The live arms are a clean union — `NodeRegistered` inserts into both unfiltered, because staker-set's live arm applies no `isActive` check either (its filter is bootstrap-only). Reading "staker-set is the filtered view" as a live-path difference and encoding it in the sink would drop registrations from the active set. - One sink with match arms, not a `Tee<A,B>`: `NodeRegistered` is the only shared topic and is the whole point — one `decode_log_data` feeds both. A tee decodes twice and needs `log.clone()` (`apply` takes `Log` by value). Follows the `ChainOriginDirectory` precedent (2 addresses x 7 topics, one sink). - `NodeAutoEjected` deactivates WITHOUT clearing the binding: ejection flips `isActive` only, and the operator may still be owed payment on an open channel. This is the most plausible silent bug in the merge and has a dedicated test. - Bindings are `Option`-gated on `node_to_node_pull_through_enabled`. The reason is metric semantics, not cost: building it unconditionally would publish `node_address_directory_size` on every default node, meaning "registered nodes" rather than "resolvable payout targets". - Both gauge families are kept, node-address's gated on the projection existing. They now describe one shared loop, so they are perfectly correlated — but freezing `node_address_watcher_down_seconds` at 0 forever would be an alert that can never fire, which is worse than deleting it. Retiring one is a follow-up. - `seed_cursor: Some(snapshot_block)` closes a latent gap both watchers had: events landing between the enumeration and the first tick's head read were missed. Head is read BEFORE the enumeration (the `ChainOriginDirectory` ordering) — the reverse would lose exactly the events being recovered. This matters more since #1221 made gossip announce ACCEPTANCE depend on live registry freshness. - `RegistryChainReads` makes the event handlers unit-testable without a provider: these two modules had ZERO tests before, and now have 11. Removing a non-fatal error path (deliberate, and unreachable): node-address bootstrap failure used to log-and-disable pull-through. `getActiveNodes` failure was ALREADY fatal — the unconditional staker-set bootstrap ran first and propagated it, so node-address's arm was never reached on that path. With the read shared, the bindings projection has no RPC of its own; it derives from page data already in hand and cannot fail independently. No node that boots today loses pull-through; none that boots today starts failing. fmt/clippy(--all-targets, incl. anvil-e2e)/doc clean; 806 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rm (#1110) Review on #1226 flagged `rpc_call_timeout: None` as an unbounded RPC and asked for `Some(Duration::from_secs(10))`. That premise is wrong: `timed` does `unwrap_or(DEFAULT_RPC_CALL_TIMEOUT)`, so `None` already IS 10s. The suggestion is a behavioural no-op that would hardcode the constant at the call site and diverge from `DEFAULT_RPC_CALL_TIMEOUT`, and 5 of 6 watchers pass `None` as the convention. But the rule behind it is right, and points at a real unbounded call the review missed 300 lines up: `ContractReads::node_id_of` did a bare `.nodeIdOf(op).call().await`. `WatcherConfig::rpc_call_timeout` covers only the loop's own `get_logs` — `timed`'s own doc says sink follow-ups stay unbounded unless the sink wraps itself. This matters more BECAUSE of the merge, and the regression is this PR's own: a stalled `nodeIdOf` used to wedge only the staker-set loop, since node-address ran its own; now one loop feeds both projections, so it wedges bindings too. Bound it here rather than defer, following the `blacklist_watcher::scope_check` precedent. A timeout surfaces as `Err`, which `on_operator_change` already counts via `staker_set_watcher_resolve_failure` and skips without tripping the stream backoff — the path `node_id_of_failure_bumps_resolve_failure_and_returns_ok` already covers. `timed` now takes `IntoFuture` rather than `Future`, so an alloy `.call()` (an `EthCall`, not a future) wraps directly instead of every caller spelling `.into_future()`. Every `Future` is an `IntoFuture`, so this is a strict widening and existing callers are untouched. `tokio::time::timeout` already accepted `IntoFuture` — the wrapper was what narrowed it. `timed`'s timeout arm had NO test, so the bound rested on untested code. Added three (paused clock, no wall-clock cost): a hanging call times out at the default and names itself, an explicit timeout wins over the default, and a prompt success passes through. fmt/clippy/doc clean; 809 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tions (#1110) (#1226) * refactor(node): hoist AbortOnDrop into chain_events (#1110) `struct AbortOnDrop(JoinHandle<()>)` plus its `Drop` impl was copy-pasted SEVEN times — slash, reputation-indexer, node-address, settlement, origin-directory, buyer-channel, and staker-set — all byte-identical. That made it read as though each watcher had its own teardown policy when they never differed. Pure move: one definition in `chain_events`, seven local copies deleted. No behavior change. Prepares the CapacityBond watcher merge, where two of those copies have to unify anyway. clippy/fmt clean; 795 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * refactor(node): one CapacityBond watcher feeding both registry projections (#1110) `ChainStakerSet` (membership) and `ChainNodeAddressDirectory` (node→address bindings) are both derived from the same CapacityBond contract, but each ran its own bootstrap and its own `eth_getLogs` loop against the same address — with node-address's two topics a strict SUBSET of staker-set's five. Two paginated `getActiveNodes` reads at boot, two poll loops forever after. Add `dht::capacity_bond_registry`: one enumeration, one loop, demuxing to both projections. Watchers drop 7 → 6 (6 → 6 in the default config, where pull-through is off — see below). `chain_staker_set` and `node_address` keep their facades, trait impls, projection helpers and all their existing tests; each loses its bootstrap/sink/hooks/pagination and gains `from_parts`. The correctness point that shapes the sink: only the ENUMERATION differs between the two views. The live arms are a clean union — `NodeRegistered` inserts into both unfiltered, because staker-set's live arm applies no `isActive` check either (its filter is bootstrap-only). Reading "staker-set is the filtered view" as a live-path difference and encoding it in the sink would drop registrations from the active set. - One sink with match arms, not a `Tee<A,B>`: `NodeRegistered` is the only shared topic and is the whole point — one `decode_log_data` feeds both. A tee decodes twice and needs `log.clone()` (`apply` takes `Log` by value). Follows the `ChainOriginDirectory` precedent (2 addresses x 7 topics, one sink). - `NodeAutoEjected` deactivates WITHOUT clearing the binding: ejection flips `isActive` only, and the operator may still be owed payment on an open channel. This is the most plausible silent bug in the merge and has a dedicated test. - Bindings are `Option`-gated on `node_to_node_pull_through_enabled`. The reason is metric semantics, not cost: building it unconditionally would publish `node_address_directory_size` on every default node, meaning "registered nodes" rather than "resolvable payout targets". - Both gauge families are kept, node-address's gated on the projection existing. They now describe one shared loop, so they are perfectly correlated — but freezing `node_address_watcher_down_seconds` at 0 forever would be an alert that can never fire, which is worse than deleting it. Retiring one is a follow-up. - `seed_cursor: Some(snapshot_block)` closes a latent gap both watchers had: events landing between the enumeration and the first tick's head read were missed. Head is read BEFORE the enumeration (the `ChainOriginDirectory` ordering) — the reverse would lose exactly the events being recovered. This matters more since #1221 made gossip announce ACCEPTANCE depend on live registry freshness. - `RegistryChainReads` makes the event handlers unit-testable without a provider: these two modules had ZERO tests before, and now have 11. Removing a non-fatal error path (deliberate, and unreachable): node-address bootstrap failure used to log-and-disable pull-through. `getActiveNodes` failure was ALREADY fatal — the unconditional staker-set bootstrap ran first and propagated it, so node-address's arm was never reached on that path. With the read shared, the bindings projection has no RPC of its own; it derives from page data already in hand and cannot fail independently. No node that boots today loses pull-through; none that boots today starts failing. fmt/clippy(--all-targets, incl. anvil-e2e)/doc clean; 806 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(node): bound the sink's nodeIdOf read, and test timed's timeout arm (#1110) Review on #1226 flagged `rpc_call_timeout: None` as an unbounded RPC and asked for `Some(Duration::from_secs(10))`. That premise is wrong: `timed` does `unwrap_or(DEFAULT_RPC_CALL_TIMEOUT)`, so `None` already IS 10s. The suggestion is a behavioural no-op that would hardcode the constant at the call site and diverge from `DEFAULT_RPC_CALL_TIMEOUT`, and 5 of 6 watchers pass `None` as the convention. But the rule behind it is right, and points at a real unbounded call the review missed 300 lines up: `ContractReads::node_id_of` did a bare `.nodeIdOf(op).call().await`. `WatcherConfig::rpc_call_timeout` covers only the loop's own `get_logs` — `timed`'s own doc says sink follow-ups stay unbounded unless the sink wraps itself. This matters more BECAUSE of the merge, and the regression is this PR's own: a stalled `nodeIdOf` used to wedge only the staker-set loop, since node-address ran its own; now one loop feeds both projections, so it wedges bindings too. Bound it here rather than defer, following the `blacklist_watcher::scope_check` precedent. A timeout surfaces as `Err`, which `on_operator_change` already counts via `staker_set_watcher_resolve_failure` and skips without tripping the stream backoff — the path `node_id_of_failure_bumps_resolve_failure_and_returns_ok` already covers. `timed` now takes `IntoFuture` rather than `Future`, so an alloy `.call()` (an `EthCall`, not a future) wraps directly instead of every caller spelling `.into_future()`. Every `Future` is an `IntoFuture`, so this is a strict widening and existing callers are untouched. `tokio::time::timeout` already accepted `IntoFuture` — the wrapper was what narrowed it. `timed`'s timeout arm had NO test, so the bound rested on untested code. Added three (paused clock, no wall-clock cost): a hanging call times out at the default and names itself, an explicit timeout wins over the default, and a prompt success passes through. fmt/clippy/doc clean; 809 node tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
) Same standard this PR applied to the observability appendix, turned on its own prose. Each is verified against code, not restated from intent. - `RegistryHandles` claimed `node_address_directory_size` "stays absent" with pull-through off. It does not: `DecdnMetrics` registers as one unconditional group, so the gauge exports a permanent `0` on every default node (pull-through is off by default) — indistinguishable from a pull-through-on node whose directory collapsed, which is the alert condition. This is the mirror of the frozen-at-0 argument used to retire `node_address_watcher_*`, so the doc now states the constraint instead of denying it. Making it genuinely absent needs a split group or labelled family; left as follow-up. - The CHANGELOG's "has independent producers" was false — every producer is the shared `capacity-bond` loop. The projection-vs-loop clause is the correct and sufficient rationale on its own. - `apply_change`'s bool was justified as "the only observable signal that a change was real". It is not: `staker_set_active_count` is republished only on mutation, and a test observes realness through exactly that gauge. Re-anchored to the `HashSet::insert`/`remove` contract it actually mirrors — a return value justifiable only by its tests should not exist. - `ConfigStakerSet` described itself as what the runtime wires "until" the chain set "is ready". It shipped in #1110 and is wired at runtime/mod.rs:744; every remaining `ConfigStakerSet` construction is under `#[cfg(test)]`. Also drops "subscribes to", which collides with the vocabulary this PR retired — it is an `eth_getLogs` poll. The runbook still scoped these metrics to the staker set "specific"ally, the framing f152fa3 re-anchored in the appendix. Post-#1226 one loop feeds both projections, and the operator impact of the bindings half — missed `NodeRegistered` bindings leave providers unpayable and silently skipped — was deleted along with the retired metric's doc and survived nowhere in the tree. Restored where an operator reads during an incident. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
* refactor(node): retire StakerSet::subscribe_changes (#1231) `ChainStakerSet` maintained a `broadcast::Sender<StakerChange>` and republished on every membership change. Nothing subscribed. The only call site of `subscribe_changes` in the repo was a unit test asserting the receiver never fires, so every `send` in `apply_change` was unconditionally a `SendError` — a fully-built producer pipeline with no consumer, plus a 128-slot channel whose capacity rationale described a slow subscriber that did not exist. Removed: the trait method and its four impls, both `changes_tx` fields, `CHANGES_CHANNEL_CAPACITY`, the `broadcast::channel` construction, the send, and the test. `apply_change` stays — it also republishes `staker_set_active_count` and mutates the set — but now returns whether membership actually moved. The two idempotence tests used `rx.try_recv()` as their *observation channel*, so deleting the sender would have deleted the assertion mechanism, not just a field. The bool is what `apply_change` already computed internally, and it tests the same property more directly than the channel did. `StakerChange` survives as the internal change-representation, but moves from `staker_set` to `chain_staker_set` as `pub(super)`: `ConfigStakerSet` no longer touches it, and its only producer (`capacity_bond_registry`) and only consumer (`apply_change`) are both on the chain-backed path. It also stops being public API — `dht::mod`'s `pub use` drops it. Its doc referenced `StakerSet::subscribe_changes`, which would have dangled. `ConfigStakerSet` and the `dht_loopback` `AllStaked` stub both lose the sender they held solely to satisfy the trait, and `AllStaked` collapses to a unit struct. The trait doc now records that the absence of a subscription seam is deliberate, so the next reader adds one alongside a consumer rather than ahead of one. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * refactor(node): retire the node_address_watcher_* metric family (#1231) Since #1226 collapsed the node-address and staker-set watchers into one `capacity-bond` loop, `decdn_node_address_watcher_{restarts_total, down_seconds}` moved in lockstep with their staker-set counterparts — one loop's health reported twice. #1226 kept both deliberately, on two grounds. Both fail: - "Retiring one would break existing dashboards and alerts." No dashboard, alert, ADR, or runbook in this repo has ever referenced the family: it appears in neither `monitoring/grafana-dashboard.json` nor `monitoring/prometheus-alerts.yml`, and `grep -rn node_address adr/ docs/ monitoring/` is empty. - "Freezing `node_address_watcher_down_seconds` at 0 forever would be an alert that can never fire, which is worse than deleting it." This was the stronger argument, and it cut the other way — the family was gated on the bindings projection existing, so a pull-through-off node reported exactly that frozen 0. `decdn_node_address_directory_size` is **kept**. It is not correlated with anything: it measures the projection rather than the loop, has its own producers in `set_binding` / `remove_binding` plus the bootstrap seed, moves only on `NodeRegistered`/`NodeDeregistered` while the active set moves on all five events, and has its own tests. With the trio gone, `hooks()` loses its `bindings_live` parameter — the gate existed only for the deleted metrics — and the two `composed_hooks_*` tests collapse into one. `node_address_directory_size` keeps its own independent `track_node_addresses` gate at the bootstrap site. The replacement statement lands where `hooks` is: the capacity-bond loop's health is `staker_set_watcher_*`, and it covers the bindings projection because one loop feeds both. Removing exported metrics is operator-visible even with no in-repo consumer, so this carries a CHANGELOG entry naming the migration. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(node): re-anchor the staker-set watcher metric docs post-#1226 (#1231) The observability docs for the staker-set watcher family still describe the pre-#1092/#1106/#1226 world. Two kinds of rot, both fixed here: **Dangling function references.** `adr/appendix-observability.md` and `metrics.rs` attribute the metrics' paired `warn!` sites to `watcher_loop` and `apply_operator_change`. Neither function exists anywhere in the tree. They are now `resumable_watcher::run` ("watcher RPC error; restarting after backoff") and `capacity_bond_registry`'s `RegistrySink::on_operator_change`. **`eth_newFilter`-era language.** The docs describe down-seconds in terms of "no established filters" and "a healthy filter stream persists indefinitely", and the restart counter in terms of "a clean stream end (filter expiry / provider rotation)". There are no filters — #1106 removed `eth_newFilter`/`eth_getFilterChanges` from the hot path (the default public Arbitrum Sepolia RPC rejects them with -32601), and the watchers have been `eth_getLogs` pollers since. Re-anchored to the poll tick, and the restart counter's filter-expiry carve-out is dropped: a poll loop has no stream to end cleanly. The ADR section intro also now attributes the metrics to the one shared `capacity-bond` loop, and records that they cover the bindings projection because the same loop feeds it — which is what makes them sufficient after #1231 retired the parallel node-address family. Also fixes the identical "no established filters" claim on `origin_directory_watcher_down_seconds` (#651). Not this issue's family, but the same stale claim a few lines away in the same file; leaving it behind in a doc block being cleaned for staleness is worse than the original. The `##### Active-Staker Set Watcher Metrics` heading is unchanged, so `docs/runbook.md`'s anchor into it still resolves. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * refactor(node): split hooks() and close the established-leg test gap (#1231) Finishes the `bindings_live` removal. `hooks()` returned a positional `(WatcherHook, WatcherHook)` of two structurally identical boxed closures — `let (on_established, on_backoff) = hooks(&metrics)` type-checks identically when reversed, and the consequence is a silent metrics inversion: failures would close the drift window instead of opening it. The `bindings_live` gate was the only reason for a combined function returning a pair. With it gone, this matches the convention every other watcher already uses (`slash_watcher`, `chain_origin_directory`): two named functions, inlined at the `WatcherConfig` literal, so there is nothing to transpose. The guard test could not see either failure. Its `down_seconds 0` assertion holds whether or not `established()` is ever called — `down_since.elapsed()` floors to 0 for the first full second — and the surviving `restarts_total 1` assertion is driven solely by `backoff()`. Verified: the test stayed green both with the tuple reversed and with the `established` hook body replaced by a no-op, leaving that leg with zero coverage. Asserting on a third call fixes it. `backoff_started` is edge-triggered on `down_since` being unset, so the re-arm to 2 only counts if `established` actually closed the window. Verified this fails on the neutered hook and on the reversed tuple, and passes on correct code. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(node): correct four claims the #1231 cleanup left inaccurate (#1231) Same standard this PR applied to the observability appendix, turned on its own prose. Each is verified against code, not restated from intent. - `RegistryHandles` claimed `node_address_directory_size` "stays absent" with pull-through off. It does not: `DecdnMetrics` registers as one unconditional group, so the gauge exports a permanent `0` on every default node (pull-through is off by default) — indistinguishable from a pull-through-on node whose directory collapsed, which is the alert condition. This is the mirror of the frozen-at-0 argument used to retire `node_address_watcher_*`, so the doc now states the constraint instead of denying it. Making it genuinely absent needs a split group or labelled family; left as follow-up. - The CHANGELOG's "has independent producers" was false — every producer is the shared `capacity-bond` loop. The projection-vs-loop clause is the correct and sufficient rationale on its own. - `apply_change`'s bool was justified as "the only observable signal that a change was real". It is not: `staker_set_active_count` is republished only on mutation, and a test observes realness through exactly that gauge. Re-anchored to the `HashSet::insert`/`remove` contract it actually mirrors — a return value justifiable only by its tests should not exist. - `ConfigStakerSet` described itself as what the runtime wires "until" the chain set "is ready". It shipped in #1110 and is wired at runtime/mod.rs:744; every remaining `ConfigStakerSet` construction is under `#[cfg(test)]`. Also drops "subscribes to", which collides with the vocabulary this PR retired — it is an `eth_getLogs` poll. The runbook still scoped these metrics to the staker set "specific"ally, the framing f152fa3 re-anchored in the appendix. Post-#1226 one loop feeds both projections, and the operator impact of the bindings half — missed `NodeRegistered` bindings leave providers unpayable and silently skipped — was deleted along with the retired metric's doc and survived nowhere in the tree. Restored where an operator reads during an incident. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Summary
Fixes #1106 (watchers hard-depend on
eth_newFilter) and #1108 (full-history re-scan crash-loop) by generalizingchain_eventsinto a single sharedeth_getLogspolling watcher (the #1092 refactor) and migrating all seven on-chain watchers onto it.Every watcher's live path went through alloy
watch_logs(eth_newFilter+eth_getFilterChanges), which the default public Arbitrum Sepolia RPC and most keyless endpoints reject with-32601— so a correctly-bonded, registered node silently spun in a retry loop while still loggingnode runtime ready. Thefrom_block-seeded watchers also re-scanned[from_block, head](~275M blocks) on every boot, tripping rate limits into a systemd crash-loop.Approach
resumable_watcher::runis one cursor loop: each poll tick reads head, scans[cursor, head − confirmations]inMAX_BACKFILL_BLOCK_SPANwindows viaeth_getLogs, feeds aLogSink, then advances — and, for a persisted watcher, durably records — the cursor per window. The first tick's big range is the historical backfill; later ticks are the live tail. This unifies the three previously hand-rolled backfill+resubscribe loops.All seven watchers migrated (settlement, slash, blacklist, origin, reputation-indexer, staker-set, node-address).
rg 'watch_logs|watch_contract_events|watch_filter' crates/is call-clean.Per-watcher #1108 strategy
ChannelOpened, none→head)Origin, none→from_block)getOriginskeeps membership authoritative)head − appeal_windoweach boothead − MAX_BACKFILLeach bootgetActiveNodesenumerationSupporting changes
KeyedCheckpointStore(redbwatcher_checkpoint_v1, additive keys, backward-compatible with the pre-existingchannel_opened_last_block) + keyedDebouncedCheckpointStore.429/5xxwith bounded backoff instead of exiting — the actual Event watchers re-scan full history on every start; needs persisted cursor / bounded backfill #1108 crash-loop root cause. A fatal4xxor an exhausted retry budget still aborts bring-up.Deviations from the issue text (flagged for review)
node runtime readybanner; the getLogs switch removes the silent-failure root cause.Verification
cargo build && cargo clippy --all-targets && cargo fmt --check && cargo doc— clean.cargo nextest run -p decdn-node -p decdn-incentive— 912 pass; doctests pass.watch_logs/eth_newFiltercall on the hot path.resolve_persisted_startnone→head vs none→from_block, window clamps, confirmations lag) and the keyed multi-key store round-trip live inresumable_watcher/channel_store.https://sepolia-rollup.arbitrum.io/rpc) and confirm watchers establish streams with noeth_newFilter does not existloop, then restart and confirm settlement/origin resume from the persisted cursor.Closes #1106, closes #1108. Advances #1092.
🤖 Generated with Claude Code
Summary by CodeRabbit
eth_getLogsevent watcher with bounded backfill, reorg-safe recovery, and graceful shutdown.