Skip to content

refactor(node): decompose the ~1,876-line run() bring-up into ordered phase functions (#1253) - #1312

Merged
thiras merged 8 commits into
mainfrom
refactor/1253-run-phase-decomposition
Jul 19, 2026
Merged

thiras merged 8 commits into
mainfrom
refactor/1253-run-phase-decomposition

Conversation

@thiras

@thiras thiras commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1253.

What

decdn_node::runtime::run was a single ~1,876-line straight-line async fn carrying a blanket #[allow(clippy::cognitive_complexity, clippy::too_many_lines)], with all bring-up + teardown state expressed as ~147 flat locals (9 oneshot stop senders, 4 CancellationTokens, ~6 WatcherHandles, a JoinSet, and ~14 _c/_for_buyer Arc clones threaded implicitly between sections).

This PR decomposes it into a 72-line orchestrator over five free phase functions, each with explicit named inputs/outputs:

let started_at = Instant::now();
let infra = build_infra(&cfg, &reload_state).await?;
let ch    = build_chain_and_handlers(&cfg, &reload_state, &infra).await?;
let bg    = spawn_background_tasks(&cfg, config_path, &reload_state, &infra, &ch, started_at).await?;
let (router, signal) = serve_until_shutdown(…, ServeInputs { … }).await?;
let handles = ShutdownHandles { … };
shutdown(handles, router, signal, &bg.drain_trigger, infra.cache).await

The implicit Arc-clone web is now named struct seams: Infra, ChainHandlers<P>, Background, ServeInputs, ShutdownHandles<P>. run()'s blanket #[allow] is gone; the suppression now lives only on the specific dense leaf phases that earn it, each individually reviewable.

This is a legibility refactor with no behavior change.

How it stays behavior-preserving

  • Split by contiguous source range, never by reordering — the strongest behavior-preservation guarantee. Each phase body is a verbatim move (validated per-phase with normalized token-stream diffs); no ? added or removed inside logic.
  • The load-bearing teardown order is untouched (metrics-stop first; origin-watcher shutdown before the origin checkpoint flush; capacity-bond-watcher cancel after router.shutdown()).
  • shutdown opens with an exhaustive ShutdownHandles destructure (no .. rest), so a dropped stop signal becomes a compile error under -D warnings.
  • The one deliberate reordering (called out in build_chain_and_handlers): the buyer-side provider/store construction is relocated to the top of the background region so its opaque provider type never crosses the chain→background seam, keeping ChainHandlers single-generic. It's pure synchronous construction (no await, no side effect), and rpc_url (its only by-value consumer) becomes a ChainHandlers field; nothing between the block's old and new position interacts with it. Concretely this flips the relative order of the buyer construction vs the blacklist-watcher spawn + DHT bootstrap (which stay in build_chain_and_handlers and now run first) — behavior-irrelevant, since neither reads any buyer value and the buyer handles are first consumed later in the background task spawn.

Two premises from the issue were corrected in flight: run() is a free fn (not Runtime::run), and the five phases aren't contiguous by concern (handlers are built early but the router spawns last, gated on the blacklist watcher's first sync) — so the split is source-order-faithful.

New test

Adds an anvil-e2e-gated bring-up/shutdown smoke test — the only in-crate test that drives runtime::run end-to-end. It boots the real runtime against a freshly-deployed protocol (anvil + the production DeployProtocol script), polls admin_v1_health to readiness, triggers admin_v1_drain, and asserts run() returns Ok(()) within the shutdown deadline. This is the net that catches a dropped stop sender or a teardown reorder that type-checking cannot. Gated off by default, so the normal test run stays fast.

Review guidance

Reviewable commit-by-commit (7 commits, each independently green): extract shutdown → build_infra → serve_until_shutdown → build_chain_and_handlers (+ buyer relocation) → spawn_background_tasks → drop run()'s #[allow] → smoke test.

Verification

  • cargo clippy -p decdn-node --all-targets -- -D warnings — clean
  • cargo nextest run -p decdn-node — 865 passed, 0 skipped
  • cargo fmt -- --check — clean
  • cargo nextest run -p decdn-node --features anvil-e2e anvil_bringup_shutdown — passes

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor

    • Improved node startup, background task coordination, routing, and shutdown handling for more reliable operation.
    • Ensured shared caches, metrics, credentials, and network state remain consistent across runtime services.
  • Tests

    • Added an end-to-end startup and shutdown test covering live chain integration, health readiness, graceful draining, and clean completion.

thiras and others added 7 commits July 19, 2026 04:27
…nHandles (#1253)

First phase of decomposing the ~1,876-line `run()` bring-up (#1253). The
contiguous teardown block at the end of `run()` becomes a free
`async fn shutdown(handles, router, signal, drain_trigger, cache)`; every
stop sender, cancellation token, watcher handle, and the JoinSet now travels
through a named `ShutdownHandles` struct instead of ad-hoc locals.

The move is verbatim — the load-bearing teardown order is unchanged
(metrics-stop first; origin-watcher shutdown before the origin checkpoint
flush; capacity-bond-watcher cancel after router.shutdown). The only edit is a
deref adjustment on the `admin_stop_order` call now that `drain_trigger` is a
reference param. `shutdown` opens with an exhaustive `ShutdownHandles`
destructure (no `..` rest), so a dropped stop signal becomes a compile error
under `-D warnings`.

No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Second phase of #1253. The front infra-construction block of `run()` (RPC
preflight through the endpoint/gossip/limiter build) moves into a free
`async fn build_infra(cfg, reload_state) -> anyhow::Result<Infra>`. `run()`
immediately destructures the returned `Infra` into the same-named locals, so
every downstream reference is unchanged.

`started_at` stays as `run()`'s first statement (its doc-comment requires it
precede the RPC preflight). The two `reload_state.attach_cache` /
`attach_limiter` side effects stay verbatim inside `build_infra`. Awaiting the
extracted phase is wrapped in `Box::pin` to keep `run()`'s future under the
`large_futures` threshold; the two `&cfg` call sites drop to `cfg` now that the
param is a borrow. No behavior change; 865 tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ntil_shutdown() (#1253)

Third phase of #1253. The blacklist-gated router spawn, signal-stream install,
and the shutdown-signal `select!` loop move into a free
`async fn serve_until_shutdown(reload_state, config_path, drain_trigger, ServeInputs)
-> anyhow::Result<(Router, ShutdownSignal)>`. The router-build consumers
(`ep`, the three handlers, `gossip`, `limiter`, `blacklist_ready_rx`) travel in
a named `ServeInputs`; `drain_trigger` is borrowed (run() still owns the Arc for
the later `shutdown` call).

Verbatim move — the fail-closed blacklist-gate `?` is preserved. The only
textual change is `config_path.as_deref()` -> `config_path`, a no-op forced by
the new `Option<&Path>` param type. No behavior change; 865 tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…andlers() (#1253)

Fourth phase of #1253. The chain-providers, watchers, and handler-construction
region of `run()` moves into a free
`async fn build_chain_and_handlers(cfg, reload_state, infra) ->
anyhow::Result<ChainHandlers<impl Provider + Clone>>`. `infra` is now a held
binding (`let infra = ...`), and downstream references are qualified to
`infra.<field>` / `ch.<field>`; the phase is generic over the single opaque
seller-wallet provider carried by `payment_service`.

The one deliberate reordering (authorized by the plan): the buyer-side
construction block (`buyer_wallet_provider` / `buyer_channel_store` /
`buyer_pending_settle_store`) is relocated to the top of the background region
so its opaque provider type never crosses the chain->background seam — keeping
`ChainHandlers` single-generic. This is behavior-preserving: the block is pure
synchronous construction (no await, no side effect), and `rpc_url` (its only
by-value consumer) is now a `ChainHandlers` field. Nothing between the block's
old and new position reads or mutates its values.

Verified verbatim by a normalized token-stream comparison of the moved region;
the buyer-task tracing field name `payment_channel_addr` is preserved. No
behavior change; 865 tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tasks() (#1253)

Fifth phase of #1253. The background-tasks region of `run()` (relocated buyer
bootstrap, metrics/GC/republish/bucket runners, rpc watchdog, gossip service,
settlement indexer, reputation sweep, admin server, startup banner) moves into a
free `async fn spawn_background_tasks(cfg, config_path, reload_state, infra, ch,
started_at) -> anyhow::Result<Background>`. `run()` is now a thin ~70-line
orchestrator: build_infra -> build_chain_and_handlers -> spawn_background_tasks
-> serve_until_shutdown -> shutdown, with the seams carried by the named phase
structs.

Because the phase takes `&Infra`/`&ChainHandlers` by reference, the five
non-Copy `ch` fields the region consumed by value (`rpc_url`, `voucher_domain`,
`slash_domain`, `bind_domain`, `reputation_rpc_url`) become `.clone()` —
behavior-identical, since each is consumed once and `ch` never reads them again.
The `Copy` `ch.payment_channel_addr` is pre-bound into a `_for_buyer` local so
the buyer task's `async move` disjoint-captures the address, not the borrowed
`ch`. `Background` is non-generic; `drain_trigger` is borrowed (not moved) at
both the serve and shutdown calls. No behavior change; 865 tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ines)] (#1253)

With the bring-up decomposed into build_infra / build_chain_and_handlers /
spawn_background_tasks / serve_until_shutdown / shutdown, `run()` is a thin
~70-line orchestrator that trips neither lint, so its blanket `#[allow]` is
removed — the acceptance criterion for #1253. The suppression now lives only on
the specific dense leaf phases that earn it (each individually reviewable);
`serve_until_shutdown` keeps just `cognitive_complexity` (38/25 from the
SIGHUP-reload select loop), not `too_many_lines`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…time::run (#1253)

Closes the coverage gap the decomposition exposed: no in-crate test drove
`runtime::run` end-to-end, so a dropped stop sender or a reordered teardown
would only surface at runtime. This `anvil-e2e`-gated test boots the real
runtime in-process against a freshly-deployed protocol (anvil + the production
DeployProtocol script), polls `admin_v1_health` to readiness, triggers
`admin_v1_drain`, and asserts `run()` returns `Ok(())` within the shutdown
deadline — the only test that exercises the assembled `ShutdownHandles` and the
load-bearing teardown order together.

Operator stake/registration is not needed for bring-up (the registry bootstrap
only reads the staker set; buyer bootstrap is non-fatal), so the test stays a
focused smoke test. No production source changed; no visibility widened.
Gated off by default, so the normal test run stays fast.

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

coderabbitai Bot commented Jul 19, 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: 48 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: 4e342e5f-1676-4f8e-9c4d-ec88e9305132

📥 Commits

Reviewing files that changed from the base of the PR and between aaf9f05 and 639378f.

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

Walkthrough

The node runtime is reorganized into explicit infrastructure, chain-handler, background-task, and serving phases. A gated Anvil end-to-end test now deploys contracts, starts the runtime, checks health, invokes admin drain, and verifies graceful shutdown.

Changes

Runtime lifecycle and shutdown

Layer / File(s) Summary
Runtime phase orchestration
crates/node/src/runtime/mod.rs
Introduces Infra, ServeInputs, phase functions, and updated shutdown sequencing for runtime startup and serving.
Chain handlers and shared service wiring
crates/node/src/runtime/mod.rs
Builds chain-derived handlers, watchers, rate limiters, origin and payment services, and shared leech-governor state from Infra.
Background tasks and admin wiring
crates/node/src/runtime/mod.rs
Rewires maintenance tasks, republishing, gossip, buyer provisioning, settlement indexing, metrics, and admin services to phase-owned handles.
Live bring-up and graceful drain validation
crates/node/tests/anvil_bringup_shutdown_e2e.rs
Adds a feature-gated Anvil test covering contract deployment, runtime readiness, admin drain, and clean task completion.

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

Sequence Diagram(s)

sequenceDiagram
  participant Runtime
  participant Infra
  participant ChainHandlers
  participant BackgroundTasks
  participant AdminAPI
  Runtime->>Infra: build shared runtime handles
  Runtime->>ChainHandlers: build chain services and handlers
  Runtime->>BackgroundTasks: spawn maintenance and provisioning tasks
  Runtime->>AdminAPI: serve health and drain endpoints
  AdminAPI-->>Runtime: report readiness and receive drain request
  Runtime-->>BackgroundTasks: initiate shutdown
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 node runtime by decomposing the monolithic run function into modular phase functions (build_infra, build_chain_and_handlers, spawn_background_tasks, serve_until_shutdown, and shutdown) and introducing helper structs to manage state. It also adds an Anvil-backed end-to-end integration test to verify the bring-up and graceful shutdown sequence. Feedback is provided regarding redundant Box::pin allocations on immediately-awaited futures in the refactored run function.

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 thread crates/node/src/runtime/mod.rs Resolved

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 daemon runtime bring-up by decomposing the previously monolithic runtime::run into ordered phase functions with explicit input/output structs, and adds an anvil-backed end-to-end smoke test to exercise full bring-up + graceful drain shutdown.

Changes:

  • Split crates/node/src/runtime/mod.rs::run into phase functions (build_infra, build_chain_and_handlers, spawn_background_tasks, serve_until_shutdown, shutdown) with structured seams (Infra, ChainHandlers, Background, ServeInputs, ShutdownHandles).
  • Introduce an anvil-e2e-gated test that boots the real runtime against an anvil-deployed protocol, waits for admin health readiness, triggers admin_v1_drain, and asserts run() returns Ok(()).

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
crates/node/src/runtime/mod.rs Decomposes runtime bring-up/serve/shutdown into explicit phases and handle bundles while preserving the existing teardown sequence.
crates/node/tests/anvil_bringup_shutdown_e2e.rs Adds an anvil-backed bring-up/shutdown smoke test covering the assembled runtime end-to-end under the anvil-e2e feature.

💡 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 19, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.49% (was 81.77%, ▼ 0.28%) — 49713/61008 lines

File Coverage Lines Δ
crates/node/src/runtime/mod.rs 45.92% 1081/2354 ▼ 4.64%
History
Commit Total Δ vs base
aaf9f05 81.49% ▼ 0.28%
639378f (HEAD) 81.49% ▼ 0.28%

…ox::pin (#1253)

The `Box::pin` wrappers on `build_infra` / `build_chain_and_handlers` /
`spawn_background_tasks` were added mid-refactor, when the rest of `run()` was
still inline and the awaited phase futures were large enough to trip
`clippy::large_futures`. Now that every phase is extracted, `run()`'s frame is
small and the phase futures await cleanly on the stack — clippy `-D warnings`
passes without the boxes, so they are redundant heap allocations at bring-up.
Removed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras
thiras merged commit db018d4 into main Jul 19, 2026
23 checks passed
@thiras
thiras deleted the refactor/1253-run-phase-decomposition branch July 19, 2026 13:46
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.

refactor(node): decompose the 1,857-line run() bring-up into ordered phase functions

2 participants