Repository navigation
refactor: eliminate on-chain event-log replay across every watcher - #1504
Conversation
The slash-detection watcher rebuilt its store on every boot by re-scanning ~10.4M blocks (~1,037 eth_getLogs windows) of the `SlashJudge.Slashed` tail from a block floor. It now enumerates this operator's still-appealable slashes directly from `CapacityBond.operatorSlash*` (ADR 019) — no historical scan on any boot — and follows `SlashRecorded` at head, seeded at the enumeration snapshot block. A 15-minute resync re-enumerates as the drift backstop (a missed tail event never self-heals otherwise) and prunes closed windows. Every field now comes off the authoritative record: `appealWindowClose` carries protocol-pause extensions the old block-timestamp derivation dropped, and the offense/evidence read from `getSlashRecord` rather than the event. Boot enumeration is fatal, matching the CapacityBond registry bootstrap on the same contract that already gates startup — so it adds no new failure mode. Drops the `slash_judge_from_block` runtime wiring (the field is removed with the other *_from_block knobs once every watcher has migrated). Part of the effort to eliminate on-chain event-log replay. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…lOpened The buyer-channel boot reconcile no longer replays the last 700k blocks of `ChannelOpened(client == self)` logs in 10k-block windows to find orphaned deposits. It now reads a pinned head, treats `clientChannelNonce(self)` as the channel count, and pages `clientChannels(self, offset, PAGE_SIZE)` (oldest-first, 100 per page) at that block to enumerate every channel this node ever opened. Each id then flows through the unchanged `reconcile_one_opened` / `getChannel` / `reconcile_decision` per-id path, with the same `getChannel().client == self` guard. The client channel set is append-only per nonce (ids are recomputed from the nonce, never removed), so the pinned-block read is only for snapshot consistency, not correctness — no abort-on-mismatch is needed and a short/empty page is a clean stop. This removes the block-lookback horizon entirely: an orphan can no longer age out of a scan window. `reconcile_decision` (the pure policy) is unchanged. `BUYER_RECONCILE_LOOKBACK_BLOCKS` and the now-unused `check_backfill_range` window helper (buyer-only) are deleted; `backfill_windows` / `MAX_BACKFILL_BLOCK_SPAN` stay for the seller watcher and origin directory. Enumeration paging is extracted behind a `ClientChannelReads` trait seam and unit-tested against a scripted stub. Part of the effort to eliminate on-chain event-log replay. Co-Authored-By: Claude Opus 4.8 <[email protected]>
(1) boot enumerates blacklistedAddresses (union) + per-region blacklistedHashes at a pinned block with count-recheck, liveness-filtered via isOriginBlacklisted||isOperatorBlacklisted and isHashBlacklistedForOperator; (2) live tail (both families→one deny-set) + periodic re-enumerating backstop; readiness gate unchanged; (3) durable projection retired — BlacklistEntryStore, CheckpointKey::Blacklist, three blacklist_*_v1 tables deleted; shared KeyedCheckpointStore/DebouncedCheckpointStore/watcher_checkpoint_v1 kept. Part of the effort to eliminate on-chain event-log replay. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…amework The three *_from_block knobs are gone (config-breaking — unknown keys now fail under deny_unknown_fields); the dead replay machinery is deleted now every watcher enumerates: CursorStart::FullReplay, the ColdStart::FromBlock variant, and the WatcherConfig::with_from_block builder. Kept: CursorStart::HeadMinusWindow (rate-bounds watcher), ColdStart::Head + the cold_start field (settlement), and the from_block floor field — all still have live users. Part of the effort to eliminate on-chain event-log replay. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The three watcher migrations replaced event-log replay with pinned-block enumeration; the ADRs still described the replay model. - ADR 011: rewrite the node-behaviour section around enumerating the deny-set (address union + in-scope hashes) at a pinned block, following the tail, and re-enumerating periodically as the backstop. The version counter is no longer a delta-fetch cursor — enumeration rebuilds the full set on every boot — only a liveness signal; the emergency-expiry note now hangs off the liveness views the node applies to its snapshot. Drops the version-sync-recovery ladder. - ADR 019 §3.2: the blacklist sync step enumerates instead of recording a version checkpoint; a node returning from downtime is immediately current. - ADR 003: note the node reconciles its channels via the per-role enumeration views (clientChannels / providerChannels), not a ChannelOpened log scan; the log path stays for external wallets and indexers. - ADR 016: blacklistedAddresses enumerates the origin+operator union, not origins alone. - appendix-observability: the staker-set drift paragraph now reflects the periodic getActiveNodes resync that bounds the drift window. Part of the effort to eliminate on-chain event-log replay. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Warning Review limit reached
Next review available in: 7 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 (2)
WalkthroughThe pull request removes blockchain log-replay start-block configuration and replaces blacklist, slash, and buyer-channel restart recovery with pinned on-chain enumeration, live event tails, and periodic resynchronization. Durable blacklist projections and checkpoints are removed, with runtime wiring, tests, ADRs, and configuration fixtures updated. ChangesWatcher and reconciliation redesign
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant NodeRuntime
participant BlacklistWatcher
participant SlashWatcher
participant BuyerReconciler
participant ChainContracts
NodeRuntime->>BlacklistWatcher: bootstrap pinned deny-set
BlacklistWatcher->>ChainContracts: enumerate addresses and hashes
ChainContracts-->>BlacklistWatcher: deny-set snapshot
NodeRuntime->>SlashWatcher: bootstrap CapacityBond records
SlashWatcher->>ChainContracts: read slash index and records
ChainContracts-->>SlashWatcher: appealable slash snapshot
NodeRuntime->>BuyerReconciler: reconcile client channels
BuyerReconciler->>ChainContracts: enumerate IDs and call getChannel
ChainContracts-->>BuyerReconciler: channel state
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 |
Coverage reportTotal: 80.23% (was 80.81%, ▼ 0.58%) — 53717/66954 lines
History
|
Extracted the periodic re-enumeration Ok-arm of `on_tick_complete` into a `WatcherState::fold_reenumeration` helper (no behavior change) and pinned the correctness-critical asymmetry with unit tests: `known` is unioned so an out-of-scope entry the tail retained for a future ripening transition survives an in-scope-only re-enumeration, while chain origins are replaced wholesale as the authoritative current set and every origin is seeded into the pending retry map. Co-Authored-By: Claude Opus 4.8 <[email protected]>
alpergundogdu
left a comment
There was a problem hiding this comment.
Review of the replay→enumerate migration. The #1499 union concern is handled correctly and well-tested (enumerate_address_union filters on is_origin_blacklisted || is_operator_blacklisted, and operator_only_entry_survives_the_enumeration_liveness_filter guards the regression) — no operator-only hole. Enumerate/tail boundary is gap-free, count-mismatch aborts are correct, config removal is clean. Inline comments below; one medium correctness issue worth blocking on.
Also (can't inline — file not in this diff):
- [Low]
crates/common/src/admin.rs:478-485— theappeal_window_closedoc still says it's theSlashedblock timestamp + 30 days and not read from the slash record. This PR now reads it fromgetSlashRecord, so the comment is stale and contradictsslash_watcher.rs. Reconcile it alongside the pause-extension fix.
`SlashRecord.appealWindowClose` is the base deadline (`slashedAt + 30d`), fixed at mint; the deadline the contract enforces is `appealWindowClose + pausedTotal` (`SlashEscrowLib` adds the global pause offset at finalize / appeal-open time). The slash enumeration compared the base close against now, so after a protocol pause a slash whose base window had closed but whose effective window was still open was treated as closed — and because the enumeration is a backward walk that stops at the first closed record, it also hid older still-appealable slashes. An operator could miss the appeal window. The enumeration and the live tail now read `CapacityBond.pausedTotal()` at the same snapshot and surface `appealWindowClose + pausedTotal` — the pause is a uniform, monotonically growing global offset, so base-close ordering equals effective-close ordering and the backward-walk early-stop stays valid. Adds the `pausedTotal()` binding (selector 0x941608ab) and corrects the `getSlashRecord` binding doc, which wrongly claimed the record already carried pause extensions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
main advanced with #1508 (origin-aware discovery), #1504 (event-log replay elimination), and #1509. One real conflict + one semantic reconciliation: - crates/node/src/slash_watcher.rs: #1504 replaced the SlashJudge.Slashed event with CapacityBond.SlashRecorded (no offenseType field), so the Phase A test fixture edit is obsolete — took main's structure. - crates/node/src/handlers/client/wire.rs: #1508 added a drop-instead-of-sign block for origin-held CacheMiss whose ENTIRE rationale was avoiding phantom-announcement evidence. With phantom retired and ok:false inert, that defense is unnecessary — removed it so origin-held CacheMiss signs like every other refusal. Blacklisted hashes still route to ChainHashDenied via the refuses() guard. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…t claims the last round got wrong Second review round on the fix commit. Two of its fixes were incomplete and two of its doc "corrections" were themselves wrong — verified each against source this time rather than against the previous commit message. Behavioural: - The reload single-flight dropped the losing reload outright, and its comment claimed the in-flight pass "re-reads the live pin set". It does not: both rescan_origins and prewarm_pinned snapshot the pinned set when they start, so a pin added afterwards is invisible. Worse, `warm` was computed per task, so a reload that only REMOVED a pin would hold the lock through its rescan while a concurrent reload that ADDED one was dropped entirely — deterministic, not a race, and never retried until restart. The skip also dropped the rescan half, silently breaking the documented "startup and reload still rescan" guarantee that `fs_rescan_interval_sec = 0` relies on. Replaced with dirty/wanted flags set before the lock attempt and consumed by the holder in a loop, so a losing reload's pin set is genuinely covered and the comment is now true. - The shutdown-cancellation fix was applied to the startup warm only; the reload warm still called the uncancellable entry point from a bare spawn, so it kept the exact bug the last commit claimed to fix. Both legs now share one token, owned by RuntimeReloadState. - PrewarmReport gains `cancelled`, recorded where the fact is known. The runtime was sampling `token.is_cancelled()` after awaiting, which reports a completed warm as truncated if the cancel lands in between. The partition identity is restated against a new `attempted()` accessor, since a cancelled run leaves unreached hashes in no bin — the type doc asserted it unconditionally while prewarm_cancellable's doc said the opposite, 860 lines apart in one file. - `local_only = true` had become a bare literal at the prewarm call site, duplicating the never-front-USDC-to-a-peer guarantee. `populate_local_reporting` is now its single owner. Wrong claims from the previous round: - The `prewarm_bytes` rationale was inverted. It said `pull_through_bytes` meters wire bytes and the two diverge under DecompressMode::Auto. HttpOrigin disables reqwest decompression and decodes itself, and the pull meter sits downstream of that decoder — both count content bytes, as engine.rs already documented. The real divergences are failed pulls, coalesced fills, and a failed size lookup. - CHANGELOG cited `decdn_streams_failed_total` as evidence for a claim about which metrics are labelled. That metric exists in no crate. Three ADR edits from the previous round never landed at all — the batch script aborted on a failed assertion before writing — so the appendix, which CLAUDE.md makes the source of truth, still carried the "shares one alert" rationale, the probe-only RejectLayer row, and both retracted prewarm claims. Applied independently this time. Also corrected: node_origin's comment contradicted the one it cross-referenced; the chain_origin_directory analogy cited a path that propagates as an example of one that degrades; channel_open_error kept a premise the same edit undercut; prewarm's doc named a function it no longer calls; `prewarm_failures` claimed three causes when there are more; and a superseded CHANGELOG entry described replay machinery #1504 deleted. Tests: cancellation had zero coverage — added pre-cancelled and mid-set cases, the latter driven by an origin that cancels from inside its own fetch so there is no timing. The peer spy now serves real bytes, so a regression fails the report rather than only the fetch counter. Added the refused-metric assertion, the mixed fs+remote chain every doc correction is about, and a single-flight test that holds the guard to prove a losing reload leaves its work flagged. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ons, clear watcher-refactor drift (#1510) Follow-through on #1504 (every watcher off eth_getLogs replay onto enumeration views) and #1508 (the discovery half of #1130), which changed the ground under several open issues. cache.prewarm (#1130, v0.1) — the http/s3 half of origin-aware serving. Pulls cache.pinned_hashes into the store at startup and on reload so the first request does not pay full pull-through latency. Opt-in and restart-required: it spends origin egress on bytes nobody has asked for. An fs-ONLY origin chain is skipped by design (that content is already local and is advertised through the origin-held index); a mixed chain warms, and pins the fs entry serves are imported as a second copy. Fills local-origin-only, so it never fronts USDC to a peer. A hash filled by a concurrent pass is not counted as a fetch, so overlapping warms do not double-count paid egress. Both the startup and reload legs are cancelled before cache.shutdown() closes the store, so a restart mid-warm cannot inflate prewarm_failures_total into the shape that metric documents as a broken pin set. Reload warms coalesce rather than drop: a reload that loses the single-flight race leaves its work flagged and the holder re-runs, because both rescan and warm snapshot the pinned set when they start. New decdn_cache_prewarm_{blobs,bytes,refused,failures}_total. decdn config validate reports a flag set against an fs-only or empty chain as "set but INERT". A pinned set larger than cache.cache_size_mb now warns at startup and on reload, independent of prewarm — pinned blobs are LRU-exempt however they arrived, so the eviction driver can otherwise never reach its high-water target. selection stake policy (#1470, v0.1) — Candidate.stake becomes u64. The Option conflated "not looked up" with "looked up, holds no bond", and the tie-break ranked unknown strictly below a known zero; once on-chain stake lookup is wired, one flaky RPC read would have silently sunk a well-staked peer below an unbonded one. The type has no encoding for a failed read, so the lookup layer must retry or drop the candidate. Behaviour is unchanged — nothing populates stake yet, and nothing enforces the boundary until the lookup lands. metrics reason splits (#1475) — sibling counters are the convention; probe_hold_unavailable{reason} is the documented exception, earned because its values share one aggregate and one budget axis (they do not share an alert — the alert filters to reason="exhausted"). No metric renamed. The observability appendix documented decdn_gossip_messages_rejected_total{reason=...}, a labelled name the node has never exported; corrected there and in ADR 019 and appendix-peer-table-eviction, and the sibling families are now in the registry where they previously appeared nowhere. #1493 needed no code: #1504 already shipped ContentBlacklist._regionHashes with blacklistedHashCount/blacklistedHashes, the watcher bootstraps from a pinned-block enumeration, and ColdStart::FromBlock is gone workspace-wide. Its "scope to cached content" alternative was deliberately not taken — dispatch needs a synchronous verdict for ADR 011 wire-indistinguishability. Also clears drift #1504/#1508 left behind: chain_origin_directory described a start-block replay with a persisted cursor, backfill.rs cited a replay_floor that no longer exists, content_deny said the watcher "replays", and fs_rescan_interval_sec reached neither DEFAULT_CONFIG nor the config validate summary. Follow-ups filed: #1511 (fs zero-copy pass-through), #1513 (more appendix metric names the exporter never emitted), #1514 (split prewarm_failures by cause), #1517 (inflight-coalescing mutex poisoning is silent and sticky). Closes #1130 Closes #1470 Closes #1475 Closes #1493
PR #1510 bundled five changes; this removes only the `cache.prewarm` feature (its item #1) and leaves the other four intact — the #1470 `Candidate.stake: u64` change, the #1475 metric sibling-counter convention docs, and the #1504/#1508 watcher-drift fixes. Removed: - `CacheEngine::prewarm` / `prewarm_cancellable` / `prewarm_pinned` and the `PrewarmReport` / `PrewarmOutcome` / `FillOwnership` types. `populate_inner` reverts to `CacheResult<()>` (the `FillOwnership` metering existed only to feed prewarm's coalesced-vs-fetched counts). - The four `decdn_cache_prewarm_*` counters. - `cache.prewarm` config field, `DEFAULT_PREWARM`, `prewarm_enabled_for`, and the `decdn config validate` / template reporting of the flag. - Startup prewarm spawn, shutdown cancellation, and the reload-time single-flight warm machinery (`warm_in_flight` / `warm_dirty` / `warm_wanted` / `prewarm_stop`). - The prewarm integration-test file and all prewarm unit tests, plus the observability-appendix rows and CHANGELOG entry. Kept (per request): the oversized-pin-set warning (`warn_if_pins_exceed_cache`), which is independent of prewarm — it runs unconditionally at startup and on reload. The reload path reverts to a plain detached `rescan_origins` + budget-warn spawn. The `fs_rescan_interval_sec` `config validate` reporting (a #1508 drift fix) is also kept. Verification: cargo build, clippy --all-targets, fmt --check clean; cache/common/cli 1096 tests and node 897 tests pass; anvil-e2e compile gate and RUSTDOCFLAGS=-D warnings doc clean. Co-authored-by: Claude Opus 4.8 <[email protected]>
Why
Every deCDN watcher that had an on-chain enumeration source booted with zero replay; every watcher that lacked one replayed log history — the slash watcher scanned ~10.4M blocks (~1,037
eth_getLogs) every boot, the buyer reconcile 700k blocks, the blacklist watcher the whole chain behind a durable projection whose only job was to make the deny-set readable. #1497 added the contract-side enumeration views. This is the consumer half: migrate every remaining watcher onto them, then delete the replay machinery they made dead.This is the consolidated follow-up work from #1497/#1498/#1500 — landed as one branch so nothing is deferred.
What
operatorSlash*and followsSlashRecordedat head, seeded at the enumeration snapshot; a 15-minute resync is the drift backstop. Appeal windows now come off the authoritativegetSlashRecord(carries pause extensions) instead of a block-timestamp derivation.clientChannelsat a pinned block instead of scanning 700k blocks ofChannelOpened.reconcile_decisionis untouched.blacklistedAddresses, kept to the live members ofisOriginBlacklisted || isOperatorBlacklisted— the contract's own_syncAddrdisjunction, so a voted-out operator whose entry never touched the origin mapping is still caught) and the in-scope hashes (getScopeRegions→blacklistedHashesper region, liveness-filtered byisHashBlacklistedForOperator) at one pinned block with aseen != countabort. The live tail (both address event families → one deny-set) and a periodic re-enumerating backstop are retained, as is the fail-closed readiness gate. The durable projection is gone:BlacklistEntryStore,CheckpointKey::Blacklist, and the threeblacklist_*_v1redb tables are deleted. SharedKeyedCheckpointStore/DebouncedCheckpointStore/watcher_checkpoint_v1are kept.origin_directory_from_block,slash_judge_from_block,content_blacklist_from_block) are removed; underdeny_unknown_fieldsa config still setting any of them now fails to load (CHANGELOG entry added). The now-orphaned replay framework (CursorStart::FullReplay,ColdStart::FromBlock,WatcherConfig::with_from_block) is deleted.Testing
Full workspace green:
cargo build --workspace,cargo clippy --workspace --all-targets -- -D warnings(exit 0),cargo fmt --all --check,cargo test --workspace(one flaky signal test,persistent_sighup_observes_both_signals, passes 3/3 in isolation — benign fixture-only edit).cargo test --no-run -p decdn-e2e --features anvil-e2ecompiles, so the blacklist compliance e2e (origin_blacklist_compliance,g_node_04_blacklist_compliance) and the slash-restart e2e still build against the new signatures.Load-bearing new guard:
operator_only_entry_survives_the_enumeration_liveness_filterasserts an operator-only entry (origin predicate false) survives the union filter — the #1499 regression, with teeth.🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmithwith what you need. Autofix is disabled.Summary by CodeRabbit
Breaking Changes
Improvements
Documentation