Skip to content

feat(cli): add decdn node drain --wait for zero-payment-loss upgrades (#604) - #662

Merged
alpergundogdu merged 3 commits into
mainfrom
feat/604-drain-wait
May 22, 2026
Merged

alpergundogdu merged 3 commits into
mainfrom
feat/604-drain-wait

Conversation

@thiras

@thiras thiras commented May 22, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Closes Add a decdn node drain --wait flag that blocks until all in-flight streams complete before the node exits #604. Adds an opt-in --wait mode to decdn node drain that blocks until all in-flight client streams complete (or a configurable timeout expires), enabling CLI-driven zero-payment-loss rolling upgrades.
  • New wire fields are serde-default, so old/new clients and servers interoperate cleanly; SIGTERM/SIGINT and plain decdn node drain (no --wait) keep the original ADR-025 shutdown ordering exactly.
  • 4 new tests (server-side flag ordering, gauge wiring, CLI idle success, CLI timeout diagnostic) on top of existing coverage; full workspace passes cargo nextest run (940/940), cargo clippy --workspace --all-targets -- -D warnings, cargo fmt --check, and pre-commit.

Why this shape

admin_v1_drain is fire-and-forget by design — admin is intentionally one of the first surfaces to stop during drain (crates/common/src/admin.rs:319-331 pre-#604) — so a naive client polling admin sees ECONNREFUSED long before router.shutdown finishes awaiting in-flight handlers. To support --wait honestly, the runtime needs to keep admin alive through router.shutdown on the opt-in path; otherwise the CLI can't observe in_flight_streams reach 0.

The change adds:

  • DrainRequest { wait_admin: bool } — opt-in via admin_v1_drain parameter, #[serde(default)] for backward compat.
  • DrainTrigger.wait_admin: AtomicBool — set by the RPC handler before fire(), read by the runtime after wait() resolves (Release/Acquire pair).
  • HealthResponse.in_flight_streams: u64 — sourced from Metrics::dispatch_in_flight_value(), which reads the existing dispatch_in_flight gauge. Always consistent with the dispatch limiter's Permit RAII pair.
  • Runtime ordering: when wait_admin is true, the admin stop signal is deferred from before router.shutdown to 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.
  • CLI flags: --wait, --wait-timeout-secs (default 30), --wait-poll-ms (default 250). Polling loop terminates on in_flight_streams == 0 or ECONNREFUSED (both are terminal success); on wall-clock overrun, prints drain_timeout=true in_flight_streams=N to stderr and returns Err so operator scripts can fail closed.

Backwards compatibility

  • Old decdn CLI calling new server: sends no params → DrainRequest::default() → wait_admin: false → original SIGTERM-equivalent ordering. Preserved.
  • New decdn CLI without --wait: same path. Preserved.
  • New decdn CLI calling old server (if that ever existed in the wild): old server doesn't expose in_flight_streams, so it deserializes as 0 via #[serde(default)] and the polling loop would terminate immediately. The early admin close still produces ECONNREFUSED and is treated as terminal success.

Test plan

  • cargo build && cargo clippy --workspace --all-targets -- -D warnings
  • cargo nextest run — 940/940 pass, including:
    • admin_drain_with_wait_admin_sets_flag_before_fire — verifies the trigger's wait_admin flag is set before fire() so the runtime reader sees it
    • health_reports_in_flight_streams_from_dispatch_gauge — acquires a real ConnectionLimiter::Permit and asserts health() reports 1, drops, asserts 0
    • cli_drain_wait_returns_immediately_when_idle — --wait returns success on first health() tick when the gauge is 0
    • cli_drain_wait_times_out_on_stuck_stream — holds a permit indefinitely, asserts the CLI exits with drain_timeout=true and "1 stream(s) still in flight" in the error
  • cargo fmt --check
  • pre-commit on changed files (all hooks pass)
  • Manual smoke (deferred to reviewer / follow-up): start decdn-node run, hold a slow probe to occupy a dispatch permit, run decdn node drain --wait --wait-timeout-secs 60 --json from another shell and confirm pretty JSON with in_flight_streams: 0 on success / drain_timeout=true in_flight_streams=1 on a stuck stream with --wait-timeout-secs 1.

🤖 Generated with Claude Code

…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]>
Copilot AI review requested due to automatic review settings May 22, 2026 00:58
@github-actions

github-actions Bot commented May 22, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 90.04% (was 90.05%, ▼ 0.01%) — 17439/19368 lines

File Coverage Lines Δ
crates/cli/src/commands/node.rs 80.18% 607/757 ▲ +1.04%
crates/common/src/admin.rs 84.44% 38/45 ▲ +14.88%
crates/node/src/admin.rs 96.58% 763/790 ▲ +0.78%
crates/node/src/metrics.rs 83.49% 354/424 ▼ 0.61%
crates/node/src/runtime/mod.rs 52.34% 437/835 ▲ +1.33%
History
Commit Total Δ vs base
49cb70b 89.97% ▼ 0.08%
d94895d 90.03% ▼ 0.02%
7dedb28 (HEAD) 90.04% ▼ 0.01%

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

Comment thread crates/common/src/admin.rs Resolved
Comment thread crates/node/src/admin.rs Resolved
Comment thread crates/cli/src/commands/node.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

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 with in_flight_streams.
  • Reorder runtime shutdown so admin can be kept alive through router.shutdown when wait_admin is requested.
  • Add CLI flags (--wait, --wait-timeout-secs, --wait-poll-ms) and tests covering the --wait behavior.

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.

Comment thread crates/common/src/admin.rs Resolved
Comment thread crates/cli/src/commands/node.rs Resolved
thiras and others added 2 commits May 22, 2026 04:11
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]>
@thiras
thiras requested a review from alpergundogdu May 22, 2026 01:34
@alpergundogdu
alpergundogdu merged commit 2bf6052 into main May 22, 2026
19 checks passed
@alpergundogdu
alpergundogdu deleted the feat/604-drain-wait branch May 22, 2026 08:42
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.

Add a decdn node drain --wait flag that blocks until all in-flight streams complete before the node exits

3 participants