Repository navigation
feat(cli): add decdn node drain --wait for zero-payment-loss upgrades (#604) - #662
Conversation
…es (#604) Operators currently have no CLI-driven way to block until graceful shutdown completes — `admin_v1_drain` is fire-and-forget and the admin server is intentionally one of the first surfaces to stop (ADR 025), so a naive client polling admin would observe ECONNREFUSED long before in-flight client streams finish in `router.shutdown`. This change adds an opt-in seam: `DrainRequest { wait_admin: bool }` flows through `admin_v1_drain` and a new `wait_admin: AtomicBool` on `DrainTrigger` (Release/Acquire-paired with the runtime reader). When set, the runtime defers the admin stop signal from before `router.shutdown` to after it returns, keeping admin alive for the CLI's polling loop. `HealthResponse` gains `in_flight_streams: u64` (serde-default 0) sourced from `Metrics::dispatch_in_flight_value()`, which reads the existing `dispatch_in_flight` gauge so the value is always consistent with the permit RAII pair. The CLI gains `--wait` / `--wait-timeout-secs` (default 30) / `--wait-poll-ms` (default 250). With `--wait`, it calls drain with `wait_admin=true` and polls `health()` until `in_flight_streams == 0` or admin closes (ECONNREFUSED — both terminal success). On wall-clock overrun, it prints `drain_timeout=true in_flight_streams=N` to stderr and exits non-zero so operator scripts can fail closed on stuck rolling upgrades. All new fields are `#[serde(default)]` so an old client calling a new server (and vice versa) round-trip cleanly with the original SIGTERM-equivalent ordering. SIGTERM/SIGINT and plain `decdn node drain` (no `--wait`) keep the original ADR-025 ordering exactly. Verification: cargo build, cargo clippy --workspace --all-targets -- -D warnings, cargo nextest run (940/940 pass including 4 new tests covering server-side flag ordering, gauge wiring, CLI idle success, and CLI timeout diagnostic), cargo fmt --check, pre-commit hooks. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Coverage reportTotal: 90.04% (was 90.05%, ▼ 0.01%) — 17439/19368 lines
History
|
There was a problem hiding this comment.
Code Review
This pull request introduces a --wait flag to the decdn node drain command, enabling graceful shutdown by polling the node's health until all in-flight streams are closed. Key changes include updating the drain RPC to accept a DrainRequest, adding in_flight_streams tracking via metrics, and reordering the runtime shutdown sequence when the wait flag is active. Reviewers identified a breaking change in the RPC signature and recommended using an optional parameter for backward compatibility. Additionally, feedback was provided regarding schema inconsistencies in the CLI's JSON output during the final stages of the drain process.
There was a problem hiding this comment.
Pull request overview
Adds an opt-in decdn node drain --wait mode to support CLI-driven graceful rolling upgrades by keeping the admin surface alive through router.shutdown and exposing a health signal (in_flight_streams) that reaches zero when all handler streams have completed.
Changes:
- Extend the admin drain RPC to accept a request (
DrainRequest { wait_admin }) and extend health responses within_flight_streams. - Reorder runtime shutdown so admin can be kept alive through
router.shutdownwhenwait_adminis requested. - Add CLI flags (
--wait,--wait-timeout-secs,--wait-poll-ms) and tests covering the--waitbehavior.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/runtime/mod.rs | Defers admin shutdown until after router.shutdown() when wait_admin is set. |
| crates/node/src/metrics.rs | Adds a helper to read the dispatch in-flight gauge as u64 for health reporting. |
| crates/node/src/admin.rs | Wires metrics into admin_v1_health, adds wait_admin side-channel on drain trigger, and updates drain RPC signature. |
| crates/common/src/cli/node.rs | Adds new CLI flags and help text for decdn node drain --wait. |
| crates/common/src/admin.rs | Adds DrainRequest + HealthResponse.in_flight_streams and updates the AdminRpc::drain method signature. |
| crates/cli/src/commands/node.rs | Implements --wait polling loop and timeout diagnostics in the drain command. |
| crates/cli/tests/admin_peers.rs | Updates existing admin/CLI tests and adds new --wait behavior tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Address review on #662 (gemini-code-assist + Copilot): - Wire compatibility: changing `drain(&self)` to `drain(&self, req: DrainRequest)` was breaking for any caller that sent `params: []` or omitted `params` entirely (jsonrpsee's proc-macro uses `next()` for required params and would return `InvalidParams`). The trait now declares `req: Option<DrainRequest>`, which jsonrpsee maps to `optional_next()` (see `render_server.rs:378`); the server impl normalizes `None` to `DrainRequest::default()`. Verified by a new regression test that calls `admin_v1_drain` with `rpc_params![]` via the raw `client.request(...)` path and asserts the trigger still fires. - Cross-version safety: `--wait` previously treated an immediate ECONNREFUSED as drain completion, which would falsely report success against an older server that closes admin early. Added `wait_admin_honored: bool` (serde-default false) to `DrainResponse`. The server sets it to `req.wait_admin` only when it actually plans to keep admin alive. The CLI refuses to enter the polling loop when `args.wait && !resp.wait_admin_honored`, returning an actionable error mentioning the missing ack. - JSON schema consistency: the two terminal-success branches in `--wait` mode (polled-to-zero and ECONNREFUSED) previously emitted unrelated JSON shapes. Both now emit `{drain_complete: true, in_flight_streams: 0, admin_closed: <bool>}` via a shared `emit_drain_complete()` helper, with `admin_closed` the only varying field. Verification: cargo build, cargo clippy --workspace --all-targets -- -D warnings, cargo nextest run (943/943 pass; +3 new tests: `admin_drain_with_no_params_still_triggers`, `admin_v1_drain_with_empty_params_still_triggers`, `cli_drain_wait_refuses_unhonored_server`), cargo fmt --check, pre-commit hooks. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Multi-agent review of #662 surfaced four critical, seven important, and several smaller issues. This commit addresses all of them in one self-contained pass: Critical - C1: split CLI polling-loop error arms so RequestTimeout and non-ECONNREFUSED Transport hiccups retry until the wall-clock deadline rather than collapsing the wait budget after one tick. - C2: dispatch_in_flight_value now logs `error!` + debug_assert on the negative-gauge clamp so a permit-pair imbalance can't silently produce a false "drain complete" signal. - C3: extract `admin_stop_order(signal, &drain_trigger)` helper + free function so the two-branch ordering decision is unit-tested in isolation (4 tests covering default, wait_admin, SIGINT override, SIGTERM override). A refactor inverting the branches now fails a test instead of silently breaking zero-payment-loss. - C4: cli_drain_wait_treats_econnrefused_as_complete — fake server honors wait_admin, returns in_flight=1 on the first health poll, then closes; CLI must observe ECONNREFUSED on the next poll and return Ok. Covers the late-stop success terminal. Important - I1: docstrings now correctly attribute cross-thread visibility of wait_admin to the Notify::notify_one→notified() edge, not the AtomicBool ordering. The atomic ordering is belt-and-braces. - I2 + I5 + I4: `DrainTrigger::set_wait_admin` is gone; `fire(bool)` now atomically sets-and-fires via `OnceLock<bool>` (first writer wins) and returns the effective value for the response ack. This closes both the set-after-fire footgun (I4) and the concurrent- drain race where the response could lie about wait_admin_honored (I5). Late-stop `tracing::warn!` upgraded to `tracing::error!` with the right context (I2) — that path now means an invariant violation, not an expected race. - Signal-gated wait_admin read in the runtime: SIGINT/SIGTERM always pick `AdminStopOrder::Early` even if a stale wait_admin=true is set on the trigger. Operator's stated intent wins. - I3: wait_admin_honored=false error now acknowledges drain is already in progress server-side and points operators at process- exit / `decdn node health` for completion observation. - I6: pure-serde compat tests for DrainResponse and HealthResponse assert that legacy server payloads (missing wait_admin_honored / in_flight_streams) deserialize with the default-false / default-0 values the cross-version guards depend on. - I7: emit_drain_complete refactored to `&mut impl io::Write`; inline tests assert exact JSON and plain-text shapes for both admin_closed branches. Suggestions - is_admin_closed_transport_error matches ConnectionRefused, ConnectionReset, ConnectionAborted, UnexpectedEof — the polling loop survives race-window closes mid-response. The narrower is_connection_refused stays for the non-wait classify path. - Ctrl-C-cancellable sleep: a long --wait-poll-ms no longer wedges the operator; `tokio::select!` between sleep and ctrl_c lets them exit cleanly with a "drain continues server-side" stderr note. - writeln! / writeln to stderr.lock() everywhere on the wait path so BrokenPipe (e.g. `decdn node drain --wait | head -1`) doesn't panic the process. - NonZeroU64 for wait_timeout_secs / wait_poll_ms: clap rejects 0 at parse time, runtime ensure! checks removed. - Comment rot fixes: drop the `:378` line-number citation on jsonrpsee (will rot on next bump), drop the "Now at 9 params" AdminState comment. Verification: cargo build, cargo clippy --workspace --all-targets -- -D warnings, cargo nextest run (957/957 pass — 14 new tests: drain_trigger_fire_is_first_writer_wins, admin_stop_order_* x4, drain_response_legacy_shape_*, health_response_legacy_shape_*, drain_request_empty_object_*, emit_drain_complete_* x3, is_admin_closed_transport_error_*, is_connection_refused_only_*, cli_drain_wait_treats_econnrefused_as_complete), cargo fmt --check, pre-commit hooks. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
--waitmode todecdn node drainthat blocks until all in-flight client streams complete (or a configurable timeout expires), enabling CLI-driven zero-payment-loss rolling upgrades.decdn node drain(no--wait) keep the original ADR-025 shutdown ordering exactly.cargo nextest run(940/940),cargo clippy --workspace --all-targets -- -D warnings,cargo fmt --check, andpre-commit.Why this shape
admin_v1_drainis fire-and-forget by design — admin is intentionally one of the first surfaces to stop during drain (crates/common/src/admin.rs:319-331pre-#604) — so a naive client polling admin seesECONNREFUSEDlong beforerouter.shutdownfinishes awaiting in-flight handlers. To support--waithonestly, the runtime needs to keep admin alive throughrouter.shutdownon the opt-in path; otherwise the CLI can't observein_flight_streamsreach 0.The change adds:
DrainRequest { wait_admin: bool }— opt-in viaadmin_v1_drainparameter,#[serde(default)]for backward compat.DrainTrigger.wait_admin: AtomicBool— set by the RPC handler beforefire(), read by the runtime afterwait()resolves (Release/Acquire pair).HealthResponse.in_flight_streams: u64— sourced fromMetrics::dispatch_in_flight_value(), which reads the existingdispatch_in_flightgauge. Always consistent with the dispatch limiter'sPermitRAII pair.wait_adminis true, the admin stop signal is deferred from beforerouter.shutdownto after it returns. Default path is byte-identical to pre-Add a decdn node drain --wait flag that blocks until all in-flight streams complete before the node exits #604 behavior.--wait,--wait-timeout-secs(default 30),--wait-poll-ms(default 250). Polling loop terminates onin_flight_streams == 0orECONNREFUSED(both are terminal success); on wall-clock overrun, printsdrain_timeout=true in_flight_streams=Nto stderr and returnsErrso operator scripts can fail closed.Backwards compatibility
decdnCLI calling new server: sends no params →DrainRequest::default()→wait_admin: false→ original SIGTERM-equivalent ordering. Preserved.decdnCLI without--wait: same path. Preserved.decdnCLI calling old server (if that ever existed in the wild): old server doesn't exposein_flight_streams, so it deserializes as 0 via#[serde(default)]and the polling loop would terminate immediately. The early admin close still producesECONNREFUSEDand is treated as terminal success.Test plan
cargo build && cargo clippy --workspace --all-targets -- -D warningscargo nextest run— 940/940 pass, including:admin_drain_with_wait_admin_sets_flag_before_fire— verifies the trigger'swait_adminflag is set beforefire()so the runtime reader sees ithealth_reports_in_flight_streams_from_dispatch_gauge— acquires a realConnectionLimiter::Permitand assertshealth()reports 1, drops, asserts 0cli_drain_wait_returns_immediately_when_idle—--waitreturns success on first health() tick when the gauge is 0cli_drain_wait_times_out_on_stuck_stream— holds a permit indefinitely, asserts the CLI exits withdrain_timeout=trueand "1 stream(s) still in flight" in the errorcargo fmt --checkpre-commiton changed files (all hooks pass)decdn-node run, hold a slow probe to occupy a dispatch permit, rundecdn node drain --wait --wait-timeout-secs 60 --jsonfrom another shell and confirm pretty JSON within_flight_streams: 0on success /drain_timeout=true in_flight_streams=1on a stuck stream with--wait-timeout-secs 1.🤖 Generated with Claude Code