Skip to content

refactor(node): generate the trivial metric recorders with a macro (#1247) - #1263

Merged
thiras merged 3 commits into
mainfrom
refactor/1247-metric-recorder-macro
Jul 17, 2026
Merged

thiras merged 3 commits into
mainfrom
refactor/1247-metric-recorder-macro

Conversation

@thiras

@thiras thiras commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1247.

Problem

impl Metrics hand-wrote 134 recorders whose entire body was a single forwarding call to one field on self.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:

  • 45 recorders have a name that differs from their field (probe_request→probe_requests, connection_opened→active_connections, rate_bounds_clamped→rate_bounds_clamp_events). A one-identifier macro can't express this.
  • Cardinality isn't 1:1 in either direction. 18 fields have no trivial recorder; active_connections and dispatch_in_flight each back two recorders (the inc/dec pairs). A per-field macro can't emit two methods for one field.
  • Field docs and recorder docs are different text for different audiences — field docs become operator-facing OpenMetrics # HELP output via the derive; recorder docs are developer rationale. One "doc" param can't serve both.
  • A "doc" string literal can't express the 85 multi-line docs (up to 15 lines of ADR/issue rationale).

So DecdnMetrics is untouched — derive, # HELP text, 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:

$(#[$meta:meta])*
$method:ident $(($arg:ident: $ty:ty))? => $field:ident . $op:ident ( $($val:expr)? ) ;
  • Both names always spelled out. Fields deliberately omit the _total suffix the encoder appends, so any synthesis rule emits ..._total_total or binds the wrong series.
  • Docs pass through as $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.)
  • No Counter/Gauge argument — the type system already rejects a mismatched op, since Counter has no dec().
  • No 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 saturating usize→i64 gauge conversion that 10 methods inlined — lands in its own commit first, deliberately: the macro commit's evidence is a cargo expand diff that must be empty, and folding sat in 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:

  1. Gate (a) — a script parsed the parent commit's AST into (docs, method, arg, field, op, val) tuples, re-rendered them in the original hand-written shape, and diffed against source: 134/134 reproduce exactly.
  2. Gate (b) — cargo expand on the parent commit vs this one, normalized for method order (the macro emits a second impl block) and for the line!() literals tracing bakes 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 main is the 10 sat() 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_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. (An earlier hand-census of mine also miscounted the total as 130 and the name-mismatches as 34.)

Result

  • metrics.rs 3,616 → 3,371 lines (−245 net; −727/+482).
  • No recorder added, removed, or renamed — verified against the expansion, so all 238 call sites, the four sink-trait adapters, ConnectionGuard, and SettleParty are untouched.
  • No hand-written recorder whose body is a single forwarding call remains; every survivor branches, computes, or returns a value.

Cost

rustfmt does not format macro-invocation bodies, so the entry table's layout is now hand-maintained and cargo fmt --check won'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-node is not in the public-api snapshot job, so no regen.

Follow-ups spotted, not fixed here

  • started() is observably a no-op — encode() unconditionally overwrites uptime_seconds at scrape time, so its set(0) never surfaces.
  • The 3 gossip_*(_topic: &str) args are ignored — callers pass a topic that never becomes a label (iroh-metrics 1.x has no label dimension).
  • The 6 watcher *_backoff_started/*_cycle_established methods share an identical body shape across {slash, staker_set, origin_directory} — a plausible second macro family, but they touch Metrics's own Mutex state.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor
    • Streamlined internal metrics recording by consolidating repeated usize→counter/gauge conversions into shared saturation logic to prevent overflow.
    • Reduced duplication by moving many metric publishing helpers to a code-generated pattern, while keeping the same metric semantics and bounds (including existing specialized gauge updates).
    • Preserved existing metric reporting behavior; no changes to exported interfaces or end-user functionality.

thiras and others added 2 commits July 17, 2026 16:48
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]>
Copilot AI review requested due to automatic review settings July 17, 2026 14:28
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 4954884c-a845-42b7-82dd-958ae788b972

📥 Commits

Reviewing files that changed from the base of the PR and between dbc5bb5 and b13a5d1.

📒 Files selected for processing (1)
  • crates/node/src/metrics.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/node/src/metrics.rs

Walkthrough

crates/node/src/metrics.rs centralizes usize-to-i64 metric clamping and replaces many thin handwritten Metrics forwarding methods with recorders!-generated methods. Stateful, bounded, negative-value, and derived metric logic remains manually implemented.

Changes

Metrics recorder consolidation

Layer / File(s) Summary
Conversion helper and retained manual logic
crates/node/src/metrics.rs
Adds sat for overflow-safe gauge conversion, moves early forwarding methods into recorders!, and retains manual handling for complex metric updates including restart windows, negative dispatch gauges, session-ticket peers, and downtime recomputation.
Buyer and settlement recorders
crates/node/src/metrics.rs
Generates prefetch, buyer top-up, and seller settlement lifecycle forwarding methods through recorders!.
Node, DHT, and QUIC recorders
crates/node/src/metrics.rs
Generates forwarding methods for watcher, staking, origin-directory, node pull, serving, limiter, DHT, probe, and QUIC metrics, using sat for usize gauges.

Estimated code review effort: 4 (Complex) | ~45 minutes


Note

🎁 Summarized by CodeRabbit Free

Your 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 @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

github-actions Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 88.92% (2488/2798 lines)
▲ +0.00pp vs base (88.92% → 88.92%)
Run: 29599071439

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

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 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) -> i64 to remove repeated i64::try_from(...).unwrap_or(i64::MAX) patterns for gauge-setting recorders.
  • Introduce recorders! { ... } to generate trivial forwarding Metrics methods (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 Metrics block.

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

@github-actions

github-actions Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.25% (was 81.21%, ▲ +0.04%) — 48011/59090 lines

File Coverage Lines Δ
crates/node/src/metrics.rs 92.93% 815/877 ▲ +5.81%
History
Commit Total Δ vs base
dbc5bb5 81.25% ▲ +0.05%
b13a5d1 (HEAD) 81.25% ▲ +0.04%

@thiras

thiras commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

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]>
@thiras

thiras commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

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 recorders! macro's own doc block — all verified against the code, all prose, no expansion change:

  1. "Recorders that … take a value they transform … stay hand-written" — contradicted by 11 table entries that transform inline (set(sat(used)), set(i64::from(enabled))). Would have misled a maintainer into hand-writing a sat(n) recorder. Reworded to the real line: a single field.op(expr) body belongs in the table; only multi-statement/branching/Mutex bodies stay hand-written.
  2. "fields omit the _total suffix the encoder appends" given as a cause of the 45 divergences — it isn't (0 of 45 diverge for that reason; 3 fields in the table actually carry _total). Moved to a parenthetical clarifying it governs the exported name, not the method→field mapping.
  3. "the type system already rejects a mismatched op" — overstated; Counter has set(), so only dec() on a counter is rejected. Narrowed to that.

Noted, not changed (disclosed trade-offs)

  • The 134-row table is hand-maintained and no tool enforces the 100-col rule inside a macro-invocation body (rustfmt skips it, clippy doesn't check width). Currently clean; the guardrail is the doc warning, which is the right mitigation.
  • $op:ident/$field:ident accept any same-type combination, so a same-kind typo would still compile — identical to the hand-written code it replaces, and backstopped by the golden-bytes test and the cargo expand proof.

Clean

  • silent-failure-hunter: no diff-introduced silent failures; sat() byte-identical at all 10 sites, the 4 u64 encode() conversions correctly left inline, every error-surfacing method kept hand-written.
  • No comment rot in the 134 moved recorder docs; sat() doc accurate; doc-passthrough claim accurate.

@thiras
thiras merged commit a4ca28b into main Jul 17, 2026
23 checks passed
@thiras
thiras deleted the refactor/1247-metric-recorder-macro branch July 17, 2026 17:21
thiras added a commit that referenced this pull request Jul 17, 2026
…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]>
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.

refactor(node): generate the ~125 one-liner metric recorders with a macro

2 participants