Skip to content

refactor(node): shared ChainProjection<T> wrapper + WatcherHandle shutdown ownership (#1255) (#1236) - #1282

Merged
thiras merged 2 commits into
mainfrom
refactor/chain-projection-watcher-handle-1255
Jul 18, 2026
Merged

thiras merged 2 commits into
mainfrom
refactor/chain-projection-watcher-handle-1255

Conversation

@thiras

@thiras thiras commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two coupled node-crate refactors, landing together.

#1255 — shared ChainProjection<T> wrapper. The three chain-backed DHT
projections each hand-rolled the same scaffolding: poison-tolerant RwLock
accessors, a "bump the size gauge only on a real change" helper, and an owned
AbortOnDrop watcher handle. New dht/chain_projection.rs factors these into
with_read/with_write, mutate_gauged, and ChainProjection<T> (the
Arc<RwLock<T>> state + the owned Arc<WatcherHandle>). ChainStakerSet and
ChainNodeAddressDirectory become thin façades; ChainOriginDirectory holds
one too, its read_cache/write_cache now delegating to the shared helpers.
Five copies of the poison-recovery arm collapse to one — which also gained its
first test coverage.

#1236 — inverted watcher-shutdown ownership. resumable_watcher::spawn(...) -> WatcherHandle now mints the CancellationToken internally and WatcherConfig
loses its shutdown field, so no call site can conjure an inert token — the
mistake #1230 fixed by convention, made unrepresentable. All six LogSink
watchers moved onto spawn:

  • the five flush-only sinks ignore the token (move |_| sink);
  • blacklist uses the make_sink: FnOnce(&CancellationToken) -> S seam so
    its sink shares the loop's token (its re-scope short-circuits on shutdown);
  • settlement holds the handle and calls .shutdown() at its own point
    before the channel-close deadline.

The runtime drops five token mints and calls handle.shutdown() at the same
load-bearing ordered positions (capacity-bond/slash/reputation deliberately
after router.shutdown(), since the staker set gates DHT admission during drain).

Testing

  • cargo build && cargo clippy --all-targets — clean (-D warnings)
  • cargo fmt -- --check — clean
  • RUSTDOCFLAGS=-D warnings cargo doc — clean
  • cargo nextest run -p decdn-node — 850 passed, including a new
    accessors_recover_a_poisoned_lock (first poison-path coverage) and a new
    spawn_hands_the_sink_the_token_shutdown_cancels (pins that spawn wires the
    sink and handle to one token).
  • The graceful-shutdown path is exercised end-to-end by the existing
    sighup_signal / runtime::tests shutdown tests.

Review notes

A five-agent review found the design correct (no cycle, shutdown ordering
preserved, mutate_gauged/make_sink faithful, anti-panic clean). One
follow-up worth tracking, not addressed here: blacklist moved off the runtime
JoinSet onto a detached spawn, so a panic in its task (unlikely under the
anti-panic policy) is no longer surfaced at shutdown, and it has no health
metrics — worth a follow-up to add blacklist watcher on_backoff/on_established
hooks for parity with the other five.

Closes #1255
Closes #1236

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Reliability

    • Improved background monitoring for blacklist, settlement, slash, reputation, and directory data.
    • Watchers now shut down in a coordinated manner, reducing interruptions during service restarts.
  • Data Consistency

    • Improved checkpoint handling and state preservation during graceful shutdowns.
    • Enhanced recovery when cached data encounters temporary access issues.
  • Monitoring

    • Metrics remain accurate by updating only when tracked data actually changes.

…wnership (#1255) (#1236)

Extract the scaffolding the three chain-backed DHT projections hand-rolled
into a shared ChainProjection<T> (#1255), and invert watcher-shutdown token
ownership so no call site can mint an inert CancellationToken (#1236). The two
dovetail: ChainProjection's watcher field is the Arc<WatcherHandle> #1236 adds.

#1255 — ChainProjection<T>:
- New dht/chain_projection.rs: with_read/with_write (poison-tolerant RwLock
  accessors, one warn! site) + mutate_gauged (republish the size gauge only on
  a real change, sampled under the lock) + ChainProjection<T> (bundles the
  Arc<RwLock<T>> state and the owned Arc<WatcherHandle>).
- ChainStakerSet / ChainNodeAddressDirectory become thin facades over it;
  ChainOriginDirectory holds one too, its read_cache/write_cache now delegating
  to the shared helpers (keeping its recompute-based gauge).
- Collapses five copies of the poison-recovery idiom to one, which also gained
  its first test coverage.

#1236 — inverted watcher-shutdown ownership:
- resumable_watcher::spawn(provider, cfg, make_sink) -> WatcherHandle mints the
  shutdown token internally; WatcherConfig loses its shutdown field; run takes
  the token as an explicit param (so the flush test still drives it directly).
- All six LogSink watchers moved onto spawn: five ignore the token (|_| sink);
  blacklist uses the make_sink: FnOnce(&CancellationToken) -> S seam so its sink
  shares the loop's token; settlement holds the handle and cancels at its own
  ordering point before the channel-close deadline.
- runtime drops five token mints and calls handle.shutdown() at the same
  load-bearing ordered positions (blacklist/origin early, origin then flushes
  its Origin checkpoint; capacity-bond/slash/reputation after router.shutdown).

cargo clippy --all-targets, fmt, and rustdoc all clean; 850 node tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 18, 2026 15:12
@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 37 minutes

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

How can I continue?

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

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

How do review limits work?

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

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

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 6e55eb23-7e76-418d-aaa5-f410d7103002

📥 Commits

Reviewing files that changed from the base of the PR and between 781a742 and 250453f.

📒 Files selected for processing (2)
  • crates/node/src/dht/chain_origin_directory.rs
  • crates/node/src/runtime/mod.rs

Walkthrough

The change replaces externally managed watcher cancellation tokens and abort-on-drop tasks with WatcherHandle ownership and shutdown calls. It also adds shared ChainProjection infrastructure for DHT cache access, mutation metrics, watcher retention, and poison-tolerant lock recovery.

Changes

Watcher lifecycle and DHT projection

Layer / File(s) Summary
Explicit watcher cancellation contract
crates/node/src/chain_events/resumable_watcher.rs, crates/node/src/chain_events/shared_head.rs
WatcherConfig no longer stores shutdown state; watcher execution receives an explicit token, and tests use the updated API.
Shared DHT projection storage
crates/node/src/dht/chain_projection.rs, crates/node/src/dht/chain_staker_set.rs, crates/node/src/dht/node_address.rs, crates/node/src/dht/chain_origin_directory.rs, crates/node/src/dht/capacity_bond_registry.rs
DHT caches use ChainProjection, shared watcher handles, poison-tolerant access helpers, and gauge-aware mutations.
Service watcher handle migration
crates/node/src/blacklist_watcher.rs, crates/node/src/slash_watcher.rs, crates/node/src/payment_settlement.rs, crates/node/src/reputation_indexer.rs
Watcher construction uses resumable_watcher::spawn, and services retain WatcherHandle values for shutdown.
Ordered runtime shutdown
crates/node/src/runtime/mod.rs
Runtime startup stores watcher handles and invokes shutdown in ordered stages around router shutdown and checkpoint flushing.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Runtime
  participant WatcherHandle
  participant ResumableWatcher
  participant Sink
  Runtime->>ResumableWatcher: spawn(provider, config, sink factory)
  ResumableWatcher-->>Runtime: return WatcherHandle
  ResumableWatcher->>Sink: provide shared cancellation token
  Runtime->>WatcherHandle: shutdown()
  WatcherHandle->>ResumableWatcher: cancel token
  ResumableWatcher->>Sink: stop processing and flush checkpoint
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the background chain watchers to use a new WatcherHandle and spawn pattern, making inert shutdown tokens unrepresentable and consolidating shared scaffolding for DHT projections into a new chain_projection module. Since there are no review comments, I have no feedback to provide on the review itself.

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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Refactors the decdn-node chain watcher + DHT projection surfaces to (1) deduplicate the chain-backed projection scaffolding and (2) make graceful watcher shutdown ownership unrepresentable at call sites by moving token ownership into a returned WatcherHandle. This keeps shutdown ordering in runtime explicit while reducing repeated poison-recovery / gauge-update patterns across the DHT projections.

Changes:

  • Introduce dht::chain_projection with shared poison-tolerant accessors and “update gauge only on real mutation” helpers, and wrap the projections’ state + watcher ownership in ChainProjection<T>.
  • Invert watcher shutdown ownership: resumable_watcher::spawn mints the shutdown token internally and returns a WatcherHandle; the runtime/services now call handle.shutdown() instead of cancelling externally-owned tokens.
  • Update watcher call sites (capacity bond, slash, origin directory, reputation indexer, blacklist, settlement) and extend tests to cover poison recovery and spawn token wiring.

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/node/src/slash_watcher.rs Switches slash watcher to WatcherHandle ownership + explicit shutdown() method.
crates/node/src/runtime/mod.rs Reworks watcher construction/shutdown sequencing to use WatcherHandle instead of runtime-minted tokens; captures origin + blacklist handles for ordered shutdown.
crates/node/src/reputation_indexer.rs Migrates settlement indexer watcher to WatcherHandle and adds a shutdown() entrypoint for runtime sequencing.
crates/node/src/payment_settlement.rs Makes settlement watcher token owned by the service via WatcherHandle to preserve its deadline-sensitive shutdown ordering.
crates/node/src/dht/node_address.rs Refactors node-address bindings projection to use shared ChainProjection and shared mutate/gauge helper.
crates/node/src/dht/mod.rs Wires in new chain_projection module.
crates/node/src/dht/chain_staker_set.rs Refactors staker-set projection to use ChainProjection and shared mutate/gauge helper.
crates/node/src/dht/chain_projection.rs New shared projection scaffolding: poison recovery helpers, gauged mutation helper, and ChainProjection<T> wrapper + tests.
crates/node/src/dht/chain_origin_directory.rs Moves origin directory cache access to shared helpers; stores watcher handle via ChainProjection and exposes it for runtime ordering.
crates/node/src/dht/capacity_bond_registry.rs Updates shared capacity-bond watcher to WatcherHandle and returns it for runtime-ordered shutdown.
crates/node/src/chain_events/shared_head.rs Updates tests to pass shutdown token directly to resumable_watcher::run after config field removal.
crates/node/src/chain_events/resumable_watcher.rs Removes WatcherConfig.shutdown, makes run accept an explicit token, adds WatcherHandle + spawn factory, and updates tests.
crates/node/src/blacklist_watcher.rs Converts blacklist watcher from async fn run into spawn -> WatcherHandle using the make_sink(&token) seam.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/node/src/runtime/mod.rs Resolved
@github-actions

github-actions Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.67% (was 81.61%, ▲ +0.06%) — 48825/59782 lines

File Coverage Lines Δ
crates/node/src/blacklist_watcher.rs 24.90% 63/253 ▲ +0.29%
crates/node/src/chain_events/resumable_watcher.rs 87.67% 526/600 ▲ +1.69%
crates/node/src/chain_events/shared_head.rs 94.27% 181/192 ▲ +0.09%
crates/node/src/dht/capacity_bond_registry.rs 66.49% 246/370 ● 0.00%
crates/node/src/dht/chain_origin_directory.rs 72.74% 811/1115 ▲ +0.21%
crates/node/src/dht/chain_projection.rs 71.43% 50/70 new
crates/node/src/dht/chain_staker_set.rs 84.03% 100/119 ▲ +7.56%
crates/node/src/dht/node_address.rs 81.58% 93/114 ▲ +8.25%
crates/node/src/payment_settlement.rs 57.01% 943/1654 ▲ +0.21%
crates/node/src/reputation_indexer.rs 61.16% 307/502 ▲ +0.12%
crates/node/src/runtime/mod.rs 47.22% 967/2048 ▼ 0.07%
crates/node/src/slash_watcher.rs 58.49% 124/212 ▲ +0.55%
History
Commit Total Δ vs base
781a742 81.67% ▲ +0.06%
250453f (HEAD) 81.67% ▲ +0.06%

@thiras thiras changed the title refactor(node): ChainProjection<T> wrapper + WatcherHandle shutdown ownership (#1255) (#1236) refactor(node): shared ChainProjection<T> wrapper + WatcherHandle shutdown ownership (#1255) (#1236) Jul 18, 2026
…ndle inversion

Two comment blocks still described the removed `shutdown` token model
(Copilot review on #1282):
- runtime origin-watcher block called the cancel "unconditional / a no-op",
  but it is now an `Option<Arc<WatcherHandle>>` the runtime `shutdown()`s.
- `ChainOriginDirectory::bootstrap` doc still required callers to pass a
  `shutdown` token; the watcher now mints its own via `spawn`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras
thiras merged commit 66fde65 into main Jul 18, 2026
23 checks passed
@thiras
thiras deleted the refactor/chain-projection-watcher-handle-1255 branch July 18, 2026 19:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants