Repository navigation
fix(node): thread real shutdown tokens into the three orphaned watchers (#1230) - #1237
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
There was a problem hiding this comment.
Pull request overview
This PR fixes three node watchers that previously created a CancellationToken inline and dropped it, leaving them with no reachable graceful-shutdown path. It threads real shutdown tokens from the runtime into slash_watcher, reputation_indexer, and capacity_bond_registry, cancels them in the runtime shutdown sequence, and adds tests that exercise resumable_watcher::run’s cancel/flush behavior.
Changes:
- Thread runtime-owned
CancellationTokens into the three previously-orphaned watchers by changing theirbootstrapsignatures and config wiring. - Cancel those tokens in
runtime/mod.rsduring shutdown (afterrouter.shutdown()), aligning behavior with existing graceful-shutdown patterns. - Add
resumable_watchertests to coverrun’s shutdown flush path and cancellation behavior between backfill windows; expand docs clarifying the liveness limitation.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/slash_watcher.rs | bootstrap now accepts a shutdown token instead of minting/dropping one. |
| crates/node/src/runtime/mod.rs | Mints and later cancels shutdown tokens for the three watchers; threads tokens into bootstraps. |
| crates/node/src/reputation_indexer.rs | bootstrap now accepts a shutdown token instead of minting/dropping one. |
| crates/node/src/dht/capacity_bond_registry.rs | bootstrap now accepts a shutdown token instead of minting/dropping one. |
| crates/node/src/chain_events/resumable_watcher.rs | Documents shutdown-token liveness constraints and adds tests covering run cancel/flush and between-window cancellation. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| /// Liveness is a property of the surrounding program and no type expresses | ||
| /// it, so the enforcement is the `bootstrap` signatures: each takes a token | ||
| /// rather than minting one, which makes `CancellationToken::new()` greppable | ||
| /// to the runtime and to `payment_settlement`'s deliberate self-mint. It is | ||
| /// not a proof — reviewing a change to the shutdown *sequence* is. |
There was a problem hiding this comment.
Code Review
This pull request addresses an issue where several watchers were unable to be gracefully shut down because they were minting their own CancellationToken internally. The changes involve threading CancellationToken instances into the bootstrap methods of the CapacityBondRegistry, SettlementIndexer, and SlashWatcher, and managing these tokens in the main run loop to ensure a coordinated shutdown. Additionally, new tests were added to verify that the shutdown mechanism correctly triggers checkpoint flushing and stops backfill processes at window boundaries.
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.
| let mut cfg = tick_cfg(provider.clone(), Arc::new(MemoryCheckpointStore::default())); | ||
| cfg.cursor = CursorPolicy::Persisted { | ||
| store: Arc::clone(&store) as Arc<dyn KeyedCheckpointStore>, | ||
| key: CheckpointKey::ChannelOpened, | ||
| none_fallback: NoneFallback::FromBlock, | ||
| reorg_margin: 0, | ||
| }; | ||
| cfg.shutdown = shutdown.clone(); |
There was a problem hiding this comment.
For clarity and to avoid creating an unused MemoryCheckpointStore, construct the WatcherConfig directly in this test. This makes the test's specific setup more self-contained. Ensure max_backfill_span is kept at a safe limit (e.g., 10,000) to avoid RPC range-limit errors during recovery.
let cfg = WatcherConfig {
head: Arc::new(SharedHead::with_ttl(provider.clone(), Duration::ZERO, None)),
filter: Filter::new(),
from_block: 0,
poll_interval: Duration::from_secs(1),
max_backfill_span: 10,
cursor: CursorPolicy::Persisted {
store: Arc::clone(&store) as Arc<dyn KeyedCheckpointStore>,
key: CheckpointKey::ChannelOpened,
none_fallback: NoneFallback::FromBlock,
reorg_margin: 0,
},
initial_backoff: Duration::from_millis(1),
max_backoff: Duration::from_millis(1),
rpc_call_timeout: None,
shutdown: shutdown.clone(),
seed_cursor: None,
label: "test",
on_established: None,
on_backoff: None,
};References
- Always cap max_backfill_span at a safe limit (e.g., 10,000 blocks) to prevent RPC range-limit errors.
3edb6db to
85a8393
Compare
394e9b3 to
b404c8b
Compare
`detect changes` called GitHub's pulls/{n}/files endpoint via
dorny/paths-filter to decide which jobs run. That endpoint is a single
point of failure for the whole pipeline: when it 503s this job dies in
8s, every downstream job reports `skipping`, and the `ci-success`
alls-green gate fails — a red PR in which nothing ever compiled.
Not hypothetical. It blocked #1237 today: GitHub served its "Unicorn!"
HTML error page for /pulls/{n}/files repo-wide, an already-merged PR
reproduced it identically (so it was not branch-specific), and the rate
limit was untouched at 4975/5000 (so it was not throttling). Re-running
the failed jobs reproduced it in 8s. No re-run could ever have cleared
it, because nothing was wrong with the code.
`token: ''` is the action's own documented switch for this — its warning
text reads "set token: '' to detect changes using git diff against
'base'". git kept working throughout the REST outage.
Semantics are unchanged, not merely close:
- `actions/checkout` leaves a PR on the merge commit, so paths-filter's
`git diff base..HEAD` is the PR's effective diff — exactly what
listFiles returned.
- Both sides decompose renames into add + delete: the API does it
explicitly to mimic rename detection being off, which the git path
passes literally as `--no-renames`.
- `ensureRefAvailable` self-fetches the base SHA (`fetch --depth=1
origin <sha>`), so the default shallow checkout still resolves it and
no fetch-depth bump is needed.
- The `push` path already used git; this makes both events agree rather
than diverge by trigger.
`pull-requests: read` existed solely for that API call, so it is dropped.
No CHANGELOG entry: CI-internal with no operator-facing surface, per
5cfbaea.
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…rs (#1230) `slash_watcher`, `reputation_indexer`, and `capacity_bond_registry` each constructed a `CancellationToken` inline and never retained it, so nothing could ever cancel them: `cfg.shutdown.cancelled()` in `run` and `is_cancelled()` in `run_tick` were unreachable, and the only teardown was `AbortOnDrop`. Their `bootstrap` signatures now take a token instead of minting one. The signature change *is* the enforcement — you cannot forget to supply one, and `CancellationToken::new()` becomes greppable to two legitimate homes: `runtime/mod.rs`, and `payment_settlement`'s deliberate self-mint. Fixed as one change across all three: per the issue, fixing one in isolation is worse than fixing none, because the value is in removing the inconsistency. `payment_settlement` is deliberately untouched. It mints its own token *and* cancels it — at a point only it knows: inside `close_open_channels_on_shutdown`, before the channel-close deadline, so a slow `closeChannel` cannot starve the flush. The runtime cannot express that ordering from outside. ## Not a type-level fix, and why The issue proposes making `CursorPolicy::Persisted` require a live token so the type system rejects the bad combination. It cannot. `WatcherConfig .shutdown` is already a `CancellationToken`, not an `Option` — *presence* was always enforced, and presence was never the bug. The bug is a token nobody cancels, which is a liveness property of the surrounding program; `Persisted { shutdown: CancellationToken::new() }` is exactly as spellable as what was there. Putting a token in that variant is worse than useless: `flush()` never consults one (`run` flushes on the `cfg.shutdown` arm), so it would be structurally demanded and never read, and a token differing from `cfg.shutdown` would go unnoticed. And once all three sites are fixed, a `Teardown::AbortOnly` variant would have zero constructors — dead code on arrival. The one design that would close the hole — inverting ownership so no call site touches a token — does not survive contact with `blacklist_watcher` (whose sink needs the token, and which isn't spawned at all). Filed as #1236 with the rejected alternatives recorded. `WatcherConfig::shutdown`'s doc now states this limit rather than implying a guarantee: the enforcement is the signature plus review of the shutdown *sequence*, not the type. ## Shutdown ordering The three cancels land *after* `router.shutdown`, beside `gossip_shutdown` and for the same reason: cooperative exit of an infinite loop once nothing depends on it. The capacity-bond one is why it must be there — its projection is the cached active-staker set, which gates DHT `Store` admission and stake-lane probe shedding, so cancelling before the drain would freeze it while the router still serves. None of the three persists a cursor, so unlike `origin_watcher_shutdown` there is no checkpoint to flush and no deadline to beat. ## Testing Two tests, because `run` had none — every existing test drives `run_tick`, so `CursorPolicy::flush` and both of `run`'s flush arms were entirely unexercised. That gap is what let an unreachable branch look identical to a reachable one. - `cancelling_shutdown_flushes_the_checkpoint_and_returns` pins the mechanism, via a store that counts flushes (the trait's default `flush_checkpoint` is a no-op, which is why nothing noticed). - `cancel_between_windows_stops_the_backfill_at_a_window_boundary` pins the behaviour slash lacked. `run_tick`'s cancel check names "slash's appeal-window span" as a case it exists for, but slash's token was inert, so it never fired for one of the two watchers it names — on the longest tick in the system (~1037 windows). The cancel fires from inside the sink so the *between*-windows property is what is tested; the un-queued second window makes the asserter error if the stop does not happen. Both verified by mutation: removing the flush drops the count to 0; removing the between-window check makes window 2 run into an empty asserter queue. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
b404c8b to
84d29f0
Compare
Closes #1230.
Problem
slash_watcher,reputation_indexer, andcapacity_bond_registryeach constructed aCancellationTokeninline and never retained it, so nothing could ever cancel them.cfg.shutdown.cancelled()inrunandis_cancelled()inrun_tickwere unreachable; the only teardown wasAbortOnDrop.Fix
The three
bootstrapsignatures now take a token instead of minting one. The signature change is the enforcement: you cannot forget to supply one, andCancellationToken::new()becomes greppable to two legitimate homes —runtime/mod.rsandpayment_settlement's deliberate self-mint.Atomic across all three, per the issue: fixing one in isolation is worse than fixing none, because the value is removing the inconsistency.
payment_settlementis deliberately untouched. It's a fourth pattern the issue doesn't list, and it's the correct one: it mints its own token and cancels it, at a point only it knows — insideclose_open_channels_on_shutdown, before the channel-close deadline, so a slowcloseChannelcan't starve the flush. The runtime cannot express that ordering from outside.The issue prefers option (2), type-enforcing the coupling, and calls it "more interesting". It doesn't hold, and I'd rather say so than ship it:
WatcherConfig.shutdownis already aCancellationToken, not anOption— presence was always enforced, and presence was never the bug. The bug is a token nobody cancels: a liveness property of the surrounding program that no type expresses.Persisted { shutdown: CancellationToken::new() }is exactly as spellable as what was there.Putting a token in
CursorPolicy::Persistedis worse than useless:flush()never consults one (runflushes on thecfg.shutdownarm), so it would be structurally demanded and never read — and if it held a different token thancfg.shutdown, nothing would notice. Contrast #1235, which did movereorg_margininto that variant, because it genuinely is read from inside the arm. The rule: put data in the variant that reads it.And a
Teardown::{AbortOnly, Graceful}enum: once all three sites are fixed, all six watchers are graceful, soAbortOnlyhas zero constructors — dead code on arrival. It only earns its keep if you intend to keep an inert site, which is the thing being removed.The one design that would close the hole — inverting ownership so no call site touches a token — doesn't survive contact with
blacklist_watcher(whose sink needs the token, and which isn't spawned at all). Filed as #1236 with the rejected alternatives recorded so they aren't re-proposed.WatcherConfig::shutdown's doc now states the limit rather than implying a guarantee: enforcement is the signature plus review of the shutdown sequence, not the type. That honesty is the lesson of #1227.Shutdown ordering — the risky part
The three cancels land after
router.shutdown, besidegossip_shutdownand for the same stated reason (cooperative exit of an infinite loop once nothing depends on it).The capacity-bond one is why it must be there: its projection is the cached active-staker set, which gates DHT
Storeadmission and decides which probes the stake-lane reservation sheds. Cancelling before the drain would freeze that set while the router is still serving, so a membership change landing mid-drain would be missed by exactly the requests still in flight.Slash and the reputation indexer aren't consulted by the serve path and could stop earlier, but they stop here too — one cancel site is easier to keep correct than three orderings each justified separately.
None of the three persists a cursor, so unlike
origin_watcher_shutdownthere's no checkpoint to flush and no deadline this must beat. The cancel buys a clean exit;AbortOnDropremains the backstop.Testing
runhad no test at all. Every existing test drivesrun_tick, soCursorPolicy::flushand both ofrun's flush arms were entirely unexercised — that gap is precisely what let an unreachable branch look identical to a reachable one.cancelling_shutdown_flushes_the_checkpoint_and_returns— pins the mechanism, via a store that counts flushes.KeyedCheckpointStore::flush_checkpointdefaults to a no-op, which is why nothing noticed.cancel_between_windows_stops_the_backfill_at_a_window_boundary— pins the behaviour slash lacked.run_tick's cancel check names "slash's appeal-window span" as a case it exists for, but slash's token was inert, so it never fired for one of the two watchers it names — on the longest tick in the system (~1037 windows). The cancel fires from inside the sink, so the between-windows property is what's tested; cancelling up front would only prove a tick cancelled early scans nothing.Both verified by mutation: removing the flush drops the count to 0; removing the between-window check makes window 2 run into an empty asserter queue (
get_logs [10, 19] for test: empty asserter response queue) — exactly the mechanism the test's comment claims.Verification
cargo nextest run -p decdn-node— 810/810 (808 base + 2 new)cargo clippy --workspace --all-targets— clean (needed#[allow(clippy::too_many_arguments)]on two bootstraps, followingblacklist_watcher::run's existing precedent)pre-commit run --all-files— all hooks passNotes for review
flushis a no-op andAbortOnDropalready killed them at the next await. The win is that a futureCursorPolicy::Persistedon any of them no longer silently orphans the flush, and slash's ~1037-window first tick now actually yields where its comment always claimed it did.Follow-up from #1110. Last of four in the watcher-hygiene batch (#1228 → #1231 → #1227 → #1230).
🤖 Generated with Claude Code