Repository navigation
refactor(node): generate the trivial metric recorders with a macro (#1247) - #1263
Conversation
Ten recorders in `impl Metrics` each inlined the same `i64::try_from(n).unwrap_or(i64::MAX)` saturating conversion, which rustfmt then split across three lines apiece. Collapse them onto a private `sat()` helper. Behavior-preserving: same saturating semantics, same call sites, same exported series. Nine of the ten are the `usize -> set` recorders that the macro in the follow-up commit will consume; the tenth (`note_session_ticket_peer`) stays hand-written but shares the shape, so it moves too rather than leaving an inline copy beside the helper. Landed separately from the macro on purpose: the macro's acceptance evidence is a `cargo expand` diff that must be *empty*. Folding the `sat()` rewrite into that commit would leave nine expected-but-differing lines in the expansion, turning an mechanical check back into a human judgement call — on exactly the nine methods where a mis-transcribed argument is plausible. The `u64`-typed conversions in `encode()` are a different type and are left alone. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…1247) `impl Metrics` hand-wrote 134 recorders whose entire body was a single forwarding call to one field on `self.decdn`. Their only content was field-name repetition across ~700 lines. Collapse them onto a declarative `recorders!` table: one line per metric, docs attached. `DecdnMetrics` is untouched — the `MetricsGroup` derive, the field docs that become OpenMetrics `# HELP` text, and rustfmt/IDE coverage of the 1,117-line struct all stay as they were. Only the recorder layer moves. Not the shape the issue proposed. `metric!(field, Counter, "doc")` would generate the field and its recorder from one identifier, which the data cannot support: 45 recorders have a name that differs from their field, and the cardinality is not 1:1 in either direction — 18 fields have no trivial recorder, while `active_connections` and `dispatch_in_flight` each back *two* recorders (the `inc`/`dec` pairs). Field docs and recorder docs are also different text for different audiences, so one doc parameter cannot serve both. Each entry spells out both names. Fields deliberately omit the `_total` suffix the encoder appends, so any synthesis rule would emit `..._total_total` or bind the wrong series. Docs pass through as `$meta`, which keeps multi-line rationale byte-identical and preserves call-site spans for clippy and rustdoc. No `Counter`/`Gauge` argument: the type system already rejects a mismatched op, since `Counter` has no `dec()`. Behavior-preserving, and checked rather than asserted. Both the mapping table and the deletion were produced by script from the previous commit's AST — nothing was transcribed by hand, because only 30 of these recorders are named by any test, so a mis-wired field would compile, pass the suite, and silently corrupt an operator-facing series. Proof is a `cargo expand` diff against the parent commit, normalized for method order and for the `line!()` literals `tracing` bakes into a surviving method: token-identical across all 152 methods. Two recorders were nearly missed by eye and found only by the script: `serve_stream_rejected_cooperative_close_signed` and `dht_batch_store_hashes_deferred_rate_limit` have field names long enough that rustfmt chained the call across three lines, so they don't read as one-liners in the source. rustfmt does not format macro-invocation bodies, so the table's layout is now hand-maintained and `cargo fmt --check` will not police it. That is the one real cost, noted in the macro's own docs. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Walkthrough
ChangesMetrics recorder consolidation
Estimated code review effort: 4 (Complex) | ~45 minutes Note 🎁 Summarized by CodeRabbit FreeYour 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 |
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 88.92% (2488/2798 lines) |
There was a problem hiding this comment.
Code Review
This pull request refactors the metrics recording implementation in 'crates/node/src/metrics.rs'. It introduces a 'recorders!' macro to automatically generate trivial forwarding recorder methods, which significantly reduces boilerplate code. It also adds a 'sat' helper function for saturating 'usize' to 'i64' conversions. There are no review comments, so I have no feedback to provide.
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.
There was a problem hiding this comment.
Pull request overview
This PR refactors the decdn-node metrics recorder layer by generating the previously hand-written one-liner “forwarding” recorder methods via a macro_rules! macro, while keeping the underlying DecdnMetrics registration/HELP text unchanged. It also introduces a small helper (sat) to centralize saturating usize -> i64 conversions for gauges.
Changes:
- Add
sat(usize) -> i64to remove repeatedi64::try_from(...).unwrap_or(i64::MAX)patterns for gauge-setting recorders. - Introduce
recorders! { ... }to generate trivial forwardingMetricsmethods (including doc passthrough) and delete the now-redundant hand-written methods. - Keep non-trivial recorders (branching / mutex state / computed values) hand-written in the main
impl Metricsblock.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 81.25% (was 81.21%, ▲ +0.04%) — 48011/59090 lines
History
|
|
Follow-ups filed from findings in this refactor, all deliberately out of scope here:
|
…oc (#1247) Review of #1263 caught the macro's own doc block overstating three things about the table beneath it. All three are prose-only; the generated code is unchanged (verified: the normalized `cargo expand` output is identical). - "Recorders that ... take a value they transform ... stay hand-written" is contradicted by 11 table entries that transform their argument inline (`set(sat(used))`, `set(i64::from(enabled))`). The real dividing line is a single `field.op(expr)` body — a one-expression transform is fine in the table; only multi-statement/branching/Mutex bodies stay hand-written. Reworded so a maintainer doesn't wrongly hand-write a `sat(n)` recorder. - "fields omit the `_total` suffix the encoder appends" was given as a cause of the 45 method-vs-field divergences. It isn't: none of the 45 diverge for that reason (they are singular/plural or semantic renames), and 3 of the fields in the table in fact carry `_total`. The suffix convention governs the exported name, not the method-to-field mapping; moved to a parenthetical that says so. - "the type system already rejects a mismatched op" overstates. `Counter` has `set()`, so a wrong `set`/`inc` on the right kind compiles; only `dec()` on a `Counter` is rejected. Narrowed to that true guarantee. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Review summary (3 agents: code, comments, silent-failure)Ran a multi-agent review. The code is correct and behavior-preserving — two agents independently re-derived that (161 recorder methods on both sides, empty set-difference, zero field/op miswiring, the 45 method↔field divergences confirmed). No critical or important code findings. Fixed in b13a5d1 (doc-only)The comment-analyzer found three inaccurate claims in the
Noted, not changed (disclosed trade-offs)
Clean
|
…nd macro family (#1266) (#1276) * refactor(node): generate the 6 watcher downtime recorders with a macro (#1266) Collapse the three chain watchers' (slash, staker_set, origin_directory) byte-identical backoff/cycle-established recorder pairs onto a second table-macro, `watcher_downtime_recorders!`. These couldn't join #1263's `recorders!` because their bodies branch and touch `Metrics`'s own `Mutex<Option<Instant>>` state; the new macro carries the lock/edge-trigger shape once, with each row spelling out both method names (production hooks call them by exact name) and labelling the three struct-field idents. Behaviour-neutral: normalized `cargo expand` of the metrics module is token-identical for all six methods (differing only by the extra impl-block wrapper). encode()'s down-seconds recompute is left for a follow-up commit. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * refactor(node): fold encode()'s 3 down-seconds recomputes into the watcher macro (#1266) Extend `watcher_downtime_recorders!` to also emit a private `refresh_watcher_down_seconds` that recomputes every watcher's `*_down_seconds` gauge from its `down_since` (poisoned lock -> i64::MAX, the alerting direction). encode() now calls it once instead of hand-repeating the three byte-identical recompute blocks, so adding a fourth watcher is one table row. Unlike the method collapse in the previous commit, this changes encode()'s tokens (the three inline blocks weren't uniform — different local names and wrapping), so it is gated by the down-seconds tests rather than an empty `cargo expand` diff. Adds the missing origin_directory down-seconds test to match the staker_set and slash guards and to exercise the shared recompute. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test(node): guard the poisoned-lock down-seconds fallback + clarify macro doc (#1266) PR-review follow-ups. Adds `poisoned_down_since_reports_i64_max_not_zero`, which poisons a `*_watcher_down_since` lock (spawn+join, the `dispatch::tests` pattern) and asserts the shared `refresh_watcher_down_seconds` reports `i64::MAX` — the load-bearing "never mask an outage" invariant that was documented but unenforced across all three watchers before #1266 unified the recompute. It also pins single-scrape isolation: the two healthy gauges still read 0 in the same encode(). Also corrects the macro doc's "three struct-field idents" to note that only `down_since` lives on `Metrics`; `restarts`/`down_seconds` are on `self.decdn`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(node): correct poison-case wording — gauge reads i64::MAX, not "keeps climbing" (#1276 review) The three "keeps climbing" phrasings attached to the *poison* case were imprecise: a poisoned `down_since` lock is sticky, so `refresh_watcher_down_seconds` hits its `Err(_) => i64::MAX` arm on every scrape and the gauge is pinned at `i64::MAX` — "keeps climbing" describes the distinct healthy-lock ongoing-outage path where `elapsed()` grows. Reword the macro doc, the slash backoff doc, and the staker_set cycle-established doc to say the poison fallback reports `i64::MAX`, matching the already-correct staker_set backoff doc, the field docs, and the `poisoned_down_since_reports_i64_max_not_zero` test. Doc-only; no behaviour or metric-series change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Closes #1247.
Problem
impl Metricshand-wrote 134 recorders whose entire body was a single forwarding call to one field onself.decdn—self.decdn.probe_requests.inc();and 133 siblings. Their only content was field-name repetition, across ~700 lines.Registration was already macro-generated (
#[derive(MetricsGroup)]); only the recorder layer was hand-copied.Scope note — not the shape the issue proposed
The issue proposed
metric!(field, Counter, "doc")generating the struct field and its recorder together. The data can't support that:probe_request→probe_requests,connection_opened→active_connections,rate_bounds_clamped→rate_bounds_clamp_events). A one-identifier macro can't express this.active_connectionsanddispatch_in_flighteach back two recorders (theinc/decpairs). A per-field macro can't emit two methods for one field.# HELPoutput via the derive; recorder docs are developer rationale. One"doc"param can't serve both."doc"string literal can't express the 85 multi-line docs (up to 15 lines of ADR/issue rationale).So
DecdnMetricsis untouched — derive,# HELPtext, and rustfmt/IDE coverage of the 1,117-line struct all stay as they were. The macro generates only recorders.Design
One arm, one repetition, no recursion:
_totalsuffix the encoder appends, so any synthesis rule emits..._total_totalor binds the wrong series.$meta— multi-line rationale stays byte-identical and keeps its call-site span for clippy/rustdoc. (Note: this is not a lint-coverage argument — a#[doc = $lit]param lints identically. The case is multi-line ergonomics and byte-preservation.)Counter/Gaugeargument — the type system already rejects a mismatched op, sinceCounterhas nodec().paste(transitive-only; adding it is a dependency-policy change) and no TT-muncher (134 entries would blow the default 128 recursion limit).sat()— the saturatingusize→i64gauge conversion that 10 methods inlined — lands in its own commit first, deliberately: the macro commit's evidence is acargo expanddiff that must be empty, and foldingsatin would leave 10 expected-but-differing lines, turning a mechanical check back into a judgement call on exactly the methods where a mis-transcribed argument is plausible.Correctness — checked, not asserted
Only 30 of these 134 recorders are named by any test. A mis-wired field would compile (all are
Counter/Gauge), pass all 805 tests, and silently corrupt an operator-facing series. So nothing was transcribed by hand:(docs, method, arg, field, op, val)tuples, re-rendered them in the original hand-written shape, and diffed against source: 134/134 reproduce exactly.cargo expandon the parent commit vs this one, normalized for method order (the macro emits a secondimplblock) and for theline!()literalstracingbakes into a surviving method: token-identical across all 152 methods.The two are independent: (a) validates the extractor against source, (b) validates the macro against the extractor.
End-to-end, the branch's entire semantic delta vs
mainis the 10sat()rewrites in commit 1. The 134 recorders moving into a macro is provably a no-op.Two recorders were nearly missed by eye and found only by the script:
serve_stream_rejected_cooperative_close_signedanddht_batch_store_hashes_deferred_rate_limithave field names long enough that rustfmt chained the call across three lines, so they don't read as one-liners in the source. (An earlier hand-census of mine also miscounted the total as 130 and the name-mismatches as 34.)Result
metrics.rs3,616 → 3,371 lines (−245 net; −727/+482).ConnectionGuard, andSettlePartyare untouched.Cost
rustfmtdoes not format macro-invocation bodies, so the entry table's layout is now hand-maintained andcargo fmt --checkwon't police it. Noted in the macro's own docs. Worth it for −245 lines; it would not have been worth it for the issue's version, which would have put the whole 1,117-line struct outside rustfmt's reach.Verification
cargo fmt --check,cargo clippy --workspace --all-targets -- -D warnings,RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --document-private-items,cargo nextest run -p decdn-node(805/805),cargo test --doc -p decdn-node— all clean.decdn-nodeis not in the public-api snapshot job, so no regen.Follow-ups spotted, not fixed here
started()is observably a no-op —encode()unconditionally overwritesuptime_secondsat scrape time, so itsset(0)never surfaces.gossip_*(_topic: &str)args are ignored — callers pass a topic that never becomes a label (iroh-metrics 1.x has no label dimension).*_backoff_started/*_cycle_establishedmethods share an identical body shape across{slash, staker_set, origin_directory}— a plausible second macro family, but they touchMetrics's ownMutexstate.🤖 Generated with Claude Code
Summary by CodeRabbit
usize→counter/gauge conversions into shared saturation logic to prevent overflow.