Skip to content

feat(node): surface ChainStakerSet watcher drift via metrics (#783) - #788

Merged
thiras merged 2 commits into
mainfrom
fix/783-watcher-drift-metric
Jun 3, 2026
Merged

thiras merged 2 commits into
mainfrom
fix/783-watcher-drift-metric

Conversation

@thiras

@thiras thiras commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Closes #783

Summary

The ChainStakerSet watcher (crates/node/src/dht/chain_staker_set.rs) documents that a mid-run watcher RPC outage lets the cached active-staker set drift from chain state, and the only operator-visible signal was a warn! log line — explicitly not covered by decdn_rpc_healthy (a different watchdog). Since #757 (probe-time stake-lane reservation) this drift is revenue-impacting: a stale active set decides which probes are shed and gates DHT Store admission. A "documented degradation" is only acceptable if it's alertable.

This PR adds Prometheus metrics so the drift window is dashboard-visible and alertable. Observability only — no control-flow change; the watcher's resync logic is untouched (the getActiveNodes resync-on-extended-outage path remains a separate follow-up).

New metrics (in DecdnMetrics, crates/node/src/metrics.rs), emitted from the watcher task which now takes Arc<Metrics>:

  • decdn_staker_set_watcher_restarts_total (counter) — bumped in watcher_loop's Err arm each time filters are re-established after an error. A clean stream end (filter expiry / provider rotation) is not a restart.
  • decdn_staker_set_watcher_down_seconds (gauge) — seconds since the last established event-stream cycle. Recomputed at scrape time from a monotonic Instant, mirroring uptime_seconds, so it climbs through the exponential backoff for sustained-outage alerts (a gauge updated only on events would read stale across the exact window we need to surface).
  • decdn_staker_set_active_count (gauge) — cached active-set size, sampled on bootstrap and on each real membership change (no-op changes leave it untouched).

Registry + recommended alert thresholds added to adr/appendix-observability.md (new "Active-Staker Set Watcher Metrics" subsection), with a cross-reference from the RPC-unreachable runbook entry (docs/runbook.md).

Review

Ran the pr-review-toolkit lenses (code-reviewer, silent-failure-hunter, pr-test-analyzer, type-design-analyzer, comment-analyzer) over the diff before committing.

  • Critical / Important: none.
  • Addressed during implementation:
    • silent-failure-hunter: a poisoned staker_set_watcher_last_event lock reports 0 down-seconds. The only holders are an assignment and a read (neither can panic), so poison is effectively unreachable; the "report 0" degradation is documented on the field and the emitter. Down-seconds is sampled under the lock and the active-count gauge is sampled while holding the set's write lock, so neither can observe a torn view.
    • pr-test-analyzer: added 4 tests — counter/gauge start-at-zero + increment, active-count moves only on real membership changes, down-seconds resets to 0 on cycle_established. The error-restart accounting is exercised via the metric call the Err arm makes (the live run_watcher_once path needs a chain endpoint).
    • comment-analyzer: updated the module's # Failure model doc to list the three metrics and verified the appendix/runbook anchors resolve.
  • Declined (with rationale):
    • Marking the two watcher-health metrics M-tier without shipping matching rules in monitoring/prometheus-alerts.yml. The appendix explicitly scopes those files as "an onboarding starting point, not a normative deliverable" and "Deliberately not exhaustive," and decdn_blacklist_sync_lag_seconds is the M-tier precedent for a chain-poll-lag gauge without (yet) a firing alert. Adding monitoring YAML is out of scope for this issue.

Multi-agent review follow-up (post-#783, fixed in 88dfa67)

A second multi-agent review pass over the merged-shape diff caught three issues, all now fixed on this branch (observability-only; watcher control flow untouched):

  • CRITICAL — decdn_staker_set_watcher_down_seconds measured cycle AGE, not downtime. Because a healthy filter stream persists indefinitely, the gauge climbed to hours on a perfectly healthy watcher and tripped the appendix's >120s/>600s alerts with no real outage. Resolution: inverted to true downtime via down_since: Option<Instant> — stamped on entry to error/backoff, cleared on successful (re)establishment — so it reads exactly 0 for the whole life of any cycle and climbs only during an actual outage. Poison-lock fallback flipped from 0 to i64::MAX so it never masks an in-progress outage.
  • HIGH — apply_operator_change silently dropped a membership change on nodeIdOf RPC failure, moving no metric (the exact silent drift this PR exists to surface). Resolution: added decdn_staker_set_watcher_resolve_failures_total, registered in the appendix with a nonzero-rate alert and referenced from the module failure-model doc.
  • MEDIUM — restart counter over-counted backoff iterations within one continuous outage, contradicting its "each restart brackets a drift window" doc. Resolution: made it edge-triggered on the transition INTO the error state (same down_since.is_none() edge), so it counts exactly one per drift window; doc wording retained.

Tests added/updated: down_seconds reads 0 across a backdated long healthy cycle and climbs only after an error; resolve-failure counter increments on a nodeIdOf failure; restart counter counts one-per-window across two distinct outages. cargo build, cargo clippy --workspace --all-targets, cargo nextest run -p decdn-node, cargo fmt -- --check all green.

Verification

cargo build, cargo clippy --workspace --all-targets, cargo nextest run -p decdn-node, and cargo fmt -- --check all green. Pre-commit hooks (fmt, clippy, doc, deny, ADR hygiene) passed.

🤖 Generated with Claude Code

The ChainStakerSet watcher documents that a mid-run RPC outage lets the
cached active-staker set drift from chain state, and the only
operator-visible signal was a warn! log — explicitly not covered by
decdn_rpc_healthy. Since #757 (probe-time stake-lane reservation) that
drift is revenue-impacting: a stale active set decides which probes are
shed and gates DHT Store admission.

Add three Prometheus metrics (observability only, no control-flow change):
- decdn_staker_set_watcher_restarts_total (counter) — error-driven filter
  re-establishments in watcher_loop.
- decdn_staker_set_watcher_down_seconds (gauge) — seconds since the last
  established event-stream cycle; recomputed at scrape time like
  uptime_seconds, so it climbs through backoff for sustained-outage alerts.
- decdn_staker_set_active_count (gauge) — cached active-set size, sampled
  on bootstrap and each real membership change.

Register the rows + recommended alert thresholds in
adr/appendix-observability.md and cross-reference from the RPC-unreachable
runbook entry.

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

@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 new metrics (restarts, down-seconds, and active count) to monitor the active-staker set watcher and detect cache drift during RPC outages. The review feedback identifies a critical logical issue where the decdn_staker_set_watcher_down_seconds metric would continuously climb during healthy operations, leading to false-positive alerts. The reviewer provides actionable suggestions to track the outage start time (staker_set_watcher_down_since) instead of the last established cycle time, ensuring the metric only reports non-zero values during actual outages.

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/metrics.rs Resolved
Comment thread crates/node/src/metrics.rs Resolved
Comment thread crates/node/src/metrics.rs Resolved
Comment thread crates/node/src/metrics.rs Resolved
@github-actions

github-actions Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 86.55% (was 86.58%, ▼ 0.03%) — 26139/30201 lines

File Coverage Lines Δ
crates/node/src/dht/chain_staker_set.rs 34.60% 118/341 ▲ +14.28%
crates/node/src/metrics.rs 85.66% 496/579 ▲ +2.03%
crates/node/src/runtime/mod.rs 45.70% 515/1127 ▼ 0.16%
History
Commit Total Δ vs base
98e2ef0 86.53% ▼ 0.04%
88dfa67 (HEAD) 86.55% ▼ 0.03%

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 adds operator-visible Prometheus/OpenMetrics instrumentation for the ChainStakerSet watcher so that drift risk (when the watcher can’t follow on-chain membership events) becomes dashboardable and alertable, rather than only visible via warn! logs. It wires the node Metrics handle into the watcher, exports three new metric series, and documents the operational interpretation in the runbook and observability appendix.

Changes:

  • Adds decdn_staker_set_watcher_restarts_total, decdn_staker_set_watcher_down_seconds, and decdn_staker_set_active_count to DecdnMetrics, plus helper methods and tests.
  • Passes Arc<Metrics> into ChainStakerSet::bootstrap() and emits the new metrics from the watcher task.
  • Updates adr/appendix-observability.md and docs/runbook.md with metric registry entries, recommended thresholds, and runbook cross-references.

Reviewed changes

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

Show a summary per file
File Description
docs/runbook.md Adds runbook guidance for diagnosing staker-set watcher outages using the new metrics.
crates/node/src/runtime/mod.rs Wires Arc<Metrics> into ChainStakerSet::bootstrap() from runtime bring-up.
crates/node/src/metrics.rs Defines/registers new metrics, adds scrape-time computation, and adds unit tests.
crates/node/src/dht/chain_staker_set.rs Emits the new metrics from the watcher loop and publishes active-set size changes.
adr/appendix-observability.md Registers the new metrics and documents recommended alert thresholds/actions.

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

Comment thread crates/node/src/metrics.rs Resolved
Comment thread crates/node/src/metrics.rs Resolved
Comment thread crates/node/src/metrics.rs Resolved
Comment thread crates/node/src/metrics.rs Resolved
…e failures (#788 review)

Three findings from multi-agent review of #783's watcher-drift metrics:

1. CRITICAL: decdn_staker_set_watcher_down_seconds measured cycle AGE,
   not downtime — a healthy persistent filter stream made the gauge
   climb to hours and trip the >120s/>600s alerts on healthy nodes.
   Invert to true downtime via a down_since: Option<Instant>: stamped
   Some(now) when a cycle ends in error/backoff, cleared to None on
   successful (re)establishment. Reads exactly 0 for the whole life of
   any established cycle and climbs only during backoff. Poison-lock
   fallback flipped to i64::MAX (alerting) so it never masks an outage.

2. HIGH: apply_operator_change dropped a membership change on nodeIdOf
   RPC failure, moving no metric. Add edge counter
   decdn_staker_set_watcher_resolve_failures_total, registered in the
   appendix with a nonzero-rate alert and referenced from the module
   failure-model doc.

3. MEDIUM: restart counter over-counted backoff iterations. Make it
   edge-triggered on the transition INTO the error state (down_since
   was None), so it genuinely counts one per drift window; keep the
   "each restart brackets a drift window" wording.

Tests: down_seconds reads 0 across a backdated long healthy cycle and
climbs only after an error; resolve-failure counter increments;
restart counter counts one per window across two distinct outages.

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

@alpergundogdu alpergundogdu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review — ChainStakerSet watcher drift metrics

Observability-only, watcher control flow untouched, and the metric semantics are right. No blocking issues.

The standout is the down_seconds correction: measuring true downtime via down_since: Option<Instant> (stamped on the edge into error/backoff, cleared on cycle_established) rather than cycle age is the correct model — a healthy filter stream persists indefinitely, so an age-based gauge would have tripped the >120s/>600s alerts on a perfectly healthy watcher. The regression guard staker_set_watcher_down_seconds_reads_zero_across_a_long_healthy_cycle (backdating started_at an hour and asserting down-seconds stays 0 while uptime reads 3600) precisely locks that semantic in. 👍

Other correct choices:

  • Edge-triggered restart counter (down_since.is_none() guard) so one continuous outage with N backoff iterations counts as one drift window — matches the "each increment brackets exactly one window" doc and is tested across two distinct outages.
  • resolve_failures counter for the nodeIdOf drop in apply_operator_change — that's a genuine silent-drift path that trips no stream-level restart, so it earns its own counter.
  • Poison-lock fallback flipped to i64::MAX (conservative — never masks an in-progress outage) and documented; cycle_established/backoff_started treat poison as skip-the-update with the gauge still climbing in the safe direction.
  • active_count sampled while holding the set's write lock (no torn view), republished only on a real membership change, and seeded at bootstrap so the gauge isn't (no data) before the first event.
  • Field names lack the _total suffix (encoder appends it) and the start-at-zero test asserts the suffixed exported name, guarding the ..._total_total footgun.

The appendix-observability registry + recommended alerts and the runbook cross-reference are appropriately scoped (you correctly declined to add firing rules to monitoring/prometheus-alerts.yml, consistent with the decdn_blacklist_sync_lag_seconds precedent). LGTM.


Generated by Claude Code

@thiras
thiras merged commit 2826365 into main Jun 3, 2026
47 of 57 checks passed
@thiras
thiras deleted the fix/783-watcher-drift-metric branch June 3, 2026 13:40
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.

Observability: surface ChainStakerSet watcher drift via a metric (not just a warn! log)

3 participants