Skip to content

fix(node): thread real shutdown tokens into the three orphaned watchers (#1230) - #1237

Merged
thiras merged 1 commit into
mainfrom
fix/1230-thread-real-shutdown-tokens
Jul 16, 2026
Merged

thiras merged 1 commit into
mainfrom
fix/1230-thread-real-shutdown-tokens

Conversation

@thiras

@thiras thiras commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Closes #1230.

Stacked on #1235 (refactor/1227-delete-confirmations). Both rewrite the same six WatcherConfig literals, so this is based on that branch rather than main — review #1235 first; the base flips to main once it merges.

Problem

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; the only teardown was AbortOnDrop.

Fix

The three 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.

Atomic across all three, per the issue: fixing one in isolation is worse than fixing none, because the value is removing the inconsistency.

payment_settlement is 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 — inside close_open_channels_on_shutdown, before the channel-close deadline, so a slow closeChannel can't starve the flush. The runtime cannot express that ordering from outside.

⚠️ Not the type-level fix the issue proposes

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.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: 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::Persisted 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 if it held a different token than cfg.shutdown, nothing would notice. Contrast #1235, which did move reorg_margin into 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, so AbortOnly has 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, beside gossip_shutdown and 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 Store admission 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_shutdown there's no checkpoint to flush and no deadline this must beat. The cancel buys a clean exit; AbortOnDrop remains the backstop.

Testing

run had no test at all. Every existing test drives run_tick, so CursorPolicy::flush and both of run'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_checkpoint defaults 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, following blacklist_watcher::run's existing precedent)
  • pre-commit run --all-files — all hooks pass

Notes for review

  • The shutdown-sequence placement is the thing to review. It's the only part not enforced by a type or a test, and the doc now says so explicitly.
  • No behaviour change for the three watchers in the common case — all are non-persisting, so flush is a no-op and AbortOnDrop already killed them at the next await. The win is that a future CursorPolicy::Persisted on 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

Copilot AI review requested due to automatic review settings July 16, 2026 19:25
@thiras thiras self-assigned this Jul 16, 2026
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 02ddfd18-58d9-4745-a27c-a4227bc5ea71

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Note

🎁 Summarized by CodeRabbit Free

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

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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR 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 their bootstrap signatures and config wiring.
  • Cancel those tokens in runtime/mod.rs during shutdown (after router.shutdown()), aligning behavior with existing graceful-shutdown patterns.
  • Add resumable_watcher tests to cover run’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.

Comment on lines +221 to +225
/// 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.

@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 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.

Comment on lines +796 to +803
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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

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
  1. Always cap max_backfill_span at a safe limit (e.g., 10,000 blocks) to prevent RPC range-limit errors.

@thiras
thiras force-pushed the refactor/1227-delete-confirmations branch from 3edb6db to 85a8393 Compare July 16, 2026 21:48
Base automatically changed from refactor/1227-delete-confirmations to main July 16, 2026 22:29
@thiras
thiras force-pushed the fix/1230-thread-real-shutdown-tokens branch from 394e9b3 to b404c8b Compare July 16, 2026 22:46
thiras added a commit that referenced this pull request Jul 16, 2026
`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]>
@thiras
thiras force-pushed the fix/1230-thread-real-shutdown-tokens branch from b404c8b to 84d29f0 Compare July 16, 2026 23:20
@thiras
thiras merged commit ac6ef63 into main Jul 16, 2026
22 checks passed
@thiras
thiras deleted the fix/1230-thread-real-shutdown-tokens branch July 16, 2026 23:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

node: three watchers construct an inert CancellationToken and throw it away — no graceful shutdown path

2 participants