Skip to content

feat(node): hot-reload mutable config fields on sighup - #367

Merged
thiras merged 7 commits into
mainfrom
feat/sighup-config-reload
Apr 30, 2026
Merged

thiras merged 7 commits into
mainfrom
feat/sighup-config-reload

Conversation

@thiras

@thiras thiras commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

Summary

  • SIGHUP triggers a config-reload pass that re-reads the TOML file and applies changes to two fields safely reloadable without rebinding sockets:
    • payment.rate_per_mb (now backed by a shared Arc<AtomicU64> consulted by ProbeHandler on every probe).
    • observability.log_level (via a tracing_subscriber::reload::Layer wrapping the EnvFilter).
  • Every other changed field is logged with a requires restart notice — operators never miss a silent drop.
  • CLI flag precedence is preserved across reloads (CLI > file > default), matching startup semantics.
  • SIGINT/SIGTERM still trigger graceful shutdown; the runtime now loops the signal select! so SIGHUP can fire repeatedly.

Test plan

  • cargo fmt -- --check
  • cargo clippy --workspace --all-targets -- -D warnings
  • cargo nextest run -p decdn-node (139 tests, 5 new in runtime::reload::tests):
    • reload_applies_rate_and_log_level — TOML edit takes effect
    • reload_skips_log_level_when_unchanged — no-op rebuild avoided
    • reload_rejects_invalid_rate_and_keeps_previous — bad reload retains old value
    • reload_returns_error_on_missing_file — best-effort, prior values intact
    • reload_preserves_cli_override — CLI flag still wins after SIGHUP
  • cargo deny check
  • pre-commit run --all-files

The SIGHUP wiring itself is a single tokio::select! arm in runtime::run. Per the issue plan a focused unit test of reload_runtime_config is acceptable; the full signal-delivery path is left to manual operator testing because spinning up the iroh endpoint just to send a signal would be disproportionate.

Closes #236

Wire SIGHUP to a config-reload pass that re-reads the TOML file and
applies changes to the two fields that are safe to update without
rebinding sockets or rebuilding the iroh router:

- payment.rate_per_mb (now backed by a shared Arc<AtomicU64> read by
  ProbeHandler on every probe)
- observability.log_level (via a tracing_subscriber::reload::Layer
  wrapping the EnvFilter)

All other fields that change in the file are logged with a "requires
restart" notice so operators don't silently miss that the change
needs a process restart. CLI-flag precedence is preserved across
reloads — flags set at launch keep winning until restart.

The signal arm of the runtime select loop now branches: SIGHUP triggers
reload_runtime_config (errors are logged, never propagated), while
SIGINT/SIGTERM still break the loop and trigger graceful shutdown.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Closes #236
Copilot AI review requested due to automatic review settings April 30, 2026 20:17

@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 implements hot-reloading for payment.rate_per_mb and observability.log_level upon receiving a SIGHUP signal. Key changes include the introduction of a RuntimeReloadState for shared mutable configuration, the use of tracing_subscriber::reload for dynamic log filtering, and the addition of a signal handling loop in the runtime. Review feedback suggests minor improvements to error handling for mutex poisoning and more explicit logic for checking admin_port changes to avoid conflating missing configurations with ephemeral port settings.

Comment thread crates/node/src/runtime/reload.rs Resolved
Comment thread crates/node/src/runtime/reload.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 SIGHUP-driven hot-reload support in the node runtime for a small set of “safe to change without rebinding sockets” configuration fields, so operators can adjust runtime behavior without dropping connections.

Changes:

  • Introduces runtime::reload with RuntimeReloadState and reload_runtime_config() to re-read TOML and apply reloadable fields.
  • Makes payment.rate_per_mb hot-reloadable by backing it with a shared Arc<AtomicU64> read by ProbeHandler.
  • Makes observability.log_level hot-reloadable via a tracing_subscriber::reload::Layer, and updates the runtime to listen for SIGHUP in its signal loop.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
crates/node/src/runtime/reload.rs New reload module: reload state, config re-read, apply/warn logic, unit tests.
crates/node/src/runtime/mod.rs Wires SIGHUP into the runtime loop and passes reload state/config path through run().
crates/node/src/handlers/probe.rs Switches probe rate from u64 to Arc<AtomicU64> for live updates.
crates/node/src/commands/mod.rs init_tracing() now returns a log-level setter; constructs and passes RuntimeReloadState into runtime.
crates/node/src/config/mod.rs Exposes config helpers as pub(crate) for reuse by reload module.
crates/node/src/cli/run.rs Derives Clone for args structs so CLI overrides can be stored in reload state.
crates/node/tests/probe_loopback.rs Updates tests for new ProbeHandler::new(..) signature using Arc<AtomicU64>.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/node/src/runtime/reload.rs Resolved
Comment thread crates/node/src/runtime/reload.rs Resolved
Comment thread crates/node/src/runtime/reload.rs Resolved
Comment thread crates/node/src/runtime/mod.rs Resolved
Comment thread crates/node/src/runtime/mod.rs Resolved
thiras and others added 6 commits April 30, 2026 23:39
addresses three correctness bugs in #367 that the existing test suite
didn't cover:

- partial-reload contract: rate_per_mb was swapped before the fallible
  log-level apply, so a setter or mutex error left the rate changed
  while the function returned err. reorder so all fallible work
  (parse, lock, log-level apply) succeeds before the atomic store.
  the store is now the only commit step.
- signal stream races: the select loop recreated `Signal` instances
  each iteration via `tokio::signal::unix::signal(...)`, so SIGHUPs
  delivered during `reload_runtime_config(..).await` could land
  between drops. install both SIGHUP and SIGTERM streams once outside
  the loop (HupStream / ShutdownStreams) and call `.recv()` on the
  persistent receivers inside the select.
- first-reload no-op when RUST_LOG is set: current_log_level seeded
  from initial.observability.log_level, but the live EnvFilter at
  startup may have come from RUST_LOG. seed to None so the first
  reload always applies — what we cache is "what we last applied",
  not "what the resolved config said".

smaller items, also addressed:

- diff-based ignored-section logging (3170650666): warn only when a
  non-reloadable section actually changed since the previous
  successful reload, tracked as per-section serde_json::Value
  snapshots on the state. routine SIGHUPs against an unchanged file
  no longer emit "ignored (requires restart)" lines.
- log-level mutex error (3170639303): replace `.expect(...)` with
  `.map_err(...)?` consistent with the workspace's expect_used lint.
- admin_port option compare (3170639319): treat None and Some(0)
  distinctly instead of collapsing both into 0.
- runtime doc placeholder (3170650702): drop the "ADR-... TODO"
  marker; document the persistent-signal rationale in its place.

new tests:
- reload_keeps_rate_when_log_level_setter_fails (bug 1)
- reload_keeps_rate_when_log_level_mutex_poisoned (bug 1, mutex variant)
- first_reload_applies_log_level_even_when_matching_initial (bug 3)
- reload_is_idempotent_across_repeated_sighups (diff-based logging)

verified: cargo fmt --check, cargo clippy --workspace --all-targets
-D warnings, cargo nextest run -p decdn-node (143 tests pass).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ShutdownSignal is now returned by ShutdownStreams::recv after the
SIGHUP-fixup persistent-signal-stream rework. The doc comment still
referenced the deleted shutdown_signal function and broke
cargo doc -D warnings on CI.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…serde error handling

The reload sequence committed the live tracing filter (via the
log-level setter) before locking `last_file_sections`. A poisoned
snapshot mutex would surface as `Err` *after* the filter had already
been swapped, violating the "previous values retained on error"
contract that callers rely on. Acquire both mutexes up front, then
treat setter + atomic swap + write-back as one infallible commit
block. Adds `reload_keeps_log_level_when_sections_mutex_poisoned`
to nail the regression down.

While in this neighbourhood:

- `HupStream::recv` now branches on `Signal::recv -> None` and parks
  on `pending` instead of resolving immediately forever; the same
  treatment is applied to the SIGTERM arm of `ShutdownStreams::recv`
  so a closed signal stream can't short-circuit the runtime select
  into a busy-loop or a spurious shutdown.
- `serde_json::to_value(...).ok()` snapshot poisoning was silently
  collapsing to `None` (treated as "section absent"), causing
  unchanged reloads to spuriously emit "ignored (requires restart)"
  warnings forever. Funnel every site through `snap_section` which
  logs the failure at `debug!` so an operator chasing phantom
  warnings has a thread to pull.
- Drop `Clone` from `RunArgs`, `IdentityArgs`, `NetworkArgs`,
  `BlockchainArgs`, `CacheArgs`. Only `PaymentArgs` and
  `ObservabilityArgs` are actually cloned (in `commands::run`).
- Fix the `Ordering::Relaxed` justification (rate is a config knob,
  not a monotonic counter) and the post-commit-snapshot rationale
  (`AtomicU64::swap` is infallible, the original "if mutex write
  fails" wording was speculative).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…contract

The unit tests in `runtime::reload` stub out signal delivery and
exercise reload semantics directly. That left two gaps:

1. The transactional guarantees were proven on the *resolution*
   failure paths (invalid rate, failing setter, poisoned mutex) but
   not on the *parse* failure path. Adds
   `reload_returns_error_on_malformed_toml`: a syntactically broken
   TOML body must reject the reload before any side effect — setter
   stays unused, rate atomic stays put, snapshot baseline stays put.

2. Nothing in the test suite raised a real signal. The persistent-
   signal-stream rule (re-installing `Signal` per select-loop
   iteration drops in-flight signals) was prose-enforced. Adds an
   integration test in `tests/sighup_signal.rs` that:
     - installs the same `Signal` API the runtime uses,
     - raises two SIGHUPs in quick succession at a reload loop,
     - asserts both reloads landed in order via the recording setter
       and the rate atomic.
   Also adds `shutdown_streams_recv_resolves_on_sigterm` in
   `runtime::tests` to lock down the post-fixup `ShutdownStreams`
   contract on a real SIGTERM. nextest's per-test process isolation
   keeps the signals from leaking across tests.

`nix` is added as a dev-dependency (signal-only feature, MIT) so we
can call `raise(2)` through a safe wrapper without violating the
workspace `unsafe_code = "forbid"` lint that `libc::raise` would
otherwise force us around. Verified `cargo deny check` passes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…leanup

Convert the free function `reload_runtime_config(path, state)` into
`RuntimeReloadState::reload(&self, path)`. The transactional
"acquire both mutexes before any committing side-effect" rule was
prose-enforced; making `reload` a method puts it next to the state
it guards so callers can't accidentally reorder against external
helpers, and the borrow checker tracks the `&self` lifetime through
the whole transactional block. Updates the runtime select-loop, the
integration test, and all unit tests.

Also:

- Strip the "Bug 1/3" diff-context labels from test doc comments at
  the three regression-suite sites; replace each with an
  intent-stated sentence (fail-stop guarantee / first-reload-applies
  guarantee / transactional contract for the log-level mutex).
- Drop the speculative SIGINT-immediate / SIGTERM-graceful
  parenthetical from the `ShutdownSignal` doc; the operator-grep
  rationale stays since it's the actual contract.

Deferred (intentionally, per the review brief's "stop after method
conversion if the refactor would obscure the load-bearing
invariant"):

- `CommitState` private sub-struct wrapping the two mutexes + the
  rate atomic + the setter. The `RuntimeReloadState::reload` method
  body already enforces the "lock both, then commit" rule
  structurally; pulling the commit half into a sub-struct would add
  an indirection without further compressing the invariant. Tracked
  for follow-up.
- `HupStream` / `ShutdownStreams` collapse into a shared
  `SignalStream` helper. `ShutdownStreams` races SIGTERM against
  `tokio::signal::ctrl_c()` so its `recv` shape isn't a clean fit
  with `HupStream::recv`; collapsing would either re-introduce the
  asymmetry inside the shared helper or leave one of them as an
  outlier. Net LoC saved ≈ 15; not worth the readability tax.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Resolves conflicts with PRs #363/#364/#365/#366 that landed on main while
this branch was in review. Conflict resolution:

- crates/node/Cargo.toml: keep both new dev-deps (nix from this branch
  for SIGHUP integration tests, wiremock from #366 for the rpc-watchdog
  test).
- crates/node/src/runtime/mod.rs: union the test-module clippy allows
  ([unwrap_used, expect_used, panic, indexing_slicing]); keep both new
  test bodies (rpc_watchdog_tracks_endpoint_transitions from #366 plus
  shutdown_streams_recv_resolves_on_sigterm from this branch).
- Test fixtures across config/mod.rs, runtime/reload.rs, and
  tests/sighup_signal.rs gained the rpc_watchdog_interval_sec field
  (Option::None for FileConfig literals; literal 30u64 for ResolvedBlockchain).

Verified post-merge: cargo fmt --check, cargo clippy --workspace
--all-targets -- -D warnings, cargo nextest run -p decdn-node (179/179),
RUSTDOCFLAGS=-D warnings cargo doc --workspace --no-deps --document-private-items,
all clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras merged commit 166ae41 into main Apr 30, 2026
11 checks passed
@thiras
thiras deleted the feat/sighup-config-reload branch April 30, 2026 21:32
alpergundogdu added a commit that referenced this pull request May 1, 2026
)

Expose the same hot-reload path #367 wired to SIGHUP as a JSON-RPC
method on the existing local-admin-http surface. Both call
RuntimeReloadState::reload(); its internal mutex serialises a SIGHUP
racing the RPC, so the two paths queue rather than corrupt state.

The RPC takes no params: the node always reloads the file path it was
started with (admin_v1_reload would otherwise let an operator script
swap in a different config without a restart, which is out of scope
for the SIGHUP-equivalent semantics this method advertises).
- `CONFIG_PATH_UNSET_CODE` (-32_003) when the node was started without
  --config; nothing on disk to re-read.
- `RELOAD_ERROR_CODE` (-32_004) when the underlying reload fails;
  previous values retained, mirroring the SIGHUP "best-effort" contract.
- On success: `{rate_per_mb, log_level}` so operator scripts can
  confirm the post-reload state without scraping logs.

CLI ride-along: `decdn node reload` calls the RPC and prints two
grep-friendly lines (or --json), matching the `decdn node health`
shape.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

Implement config file hot-reload (SIGHUP) for mutable fields such as rate_per_mb and log_level

2 participants