Skip to content

feat: a Prometheus scrape endpoint and the relay counters it reads - #1282

Merged
chappie-daemon merged 10 commits into
rewrite/mainfrom
factory/042-prometheus-metrics
Nov 29, 2026
Merged

chappie-daemon merged 10 commits into
rewrite/mainfrom
factory/042-prometheus-metrics

Conversation

@chappie-daemon

Copy link
Copy Markdown
Collaborator

Row 1 of the Phase 6 hardening split (#868): the relay keeps the counters #595 names, and serves them as Prometheus text at GET <prefix>/metrics.

Where it lives. Outside the /admin prefix, because <prefix>/admin/metrics is already the console's SSE stream. The route is merged onto the admin router after with_state, so it sits outside admin_enabled, content_security and the admin limiter — ADR 0021 D1 records that and its cost. The only HTTP surface is still the admin router on the relay's one listener.

How a scraper authenticates. A Prometheus target cannot hold the surface's 24 h HMAC cookie, so the endpoint takes Authorization: Bearer $METRICS_TOKEN, compared in constant time against the environment value, and is off unless METRICS_ENABLED is true or 1 (case-sensitive, read once at the daemon edge and passed into compose as a resolved value — which is this PR's change to compose's signature, a sixth parameter). Off answers the fallback's 404 Not Found; any token failure answers {"error":"Unauthorized"}. ADR 0021 D2 prices the choice.

What it counts, and where the increments sit — every counter moves before the frame it answers is queued, except connections_total, whose frame precedes its site:
nostream_connections_total, nostream_connections_active (read from ConnectionCap::live_total()), nostream_events_received_total{kind} (capped at 1024 labels plus other), nostream_events_accepted_total, nostream_events_rejected_total{reason} over the twelve labels the tree can send, nostream_subscriptions_active, and an EOSE histogram with six hand-kept buckets. No metrics crate and no new dependency: the 0.0.4 encoder is written by hand, and the zero-state body is pinned byte for byte in two test copies.

The AUTH carve-out is the substantive change, not a rename. Before it, a successful NIP-42 AUTH answered through send_ok and counted as an accepted event — the family decision 4 defines. send_auth_ok shares one private queue_ok builder with send_ok and counts nothing, so AUTH's three replies are byte-identical and move neither family; tests/metrics.rs pins both a successful and a refused AUTH reply plus every counter at zero, and then that one kind-1 EVENT moves accepted.

Rebased onto 1514e7f2. #1281 landed first, so this branch sits on the daemon serving the store the settings name. The composition root was read by hand after the rebase (the env edge, then compose taking #1281's service_stores plus this branch's metrics parameter) and the daemon suite re-run; the code lens's checks are at the pre-rebase tree and are cited as such. With #1206's wiring the accepted and rejected families read real values, and ADR 0021 says so — its first draft claimed the counter reads 0 until #1206, which the rebase made false, and the approver caught it.

Verified. Five repository commands: fmt, both clippy passes, cargo test --workspace --all-features (119 targets, 1855 passed, 0 failed), release build. The code lens executed 20 inversions rather than asserting them — the 404/401 precedence, Bearer case sensitivity, the switch parse, the label panic, the AUTH carve-out, the gauge arms, the kind cap, escaping, buckets — each red on its own assertion. The performance lens measured the event-path lock (32.9 ns per frame, 0.6% of a core at 50k events/s) and the render hold (173.8 µs at the 1024-kind cap, 5.9 µs at 18). Static analysis found nothing at either head. The approver drove the real binary: 26 live assertions over the token and switch arms, and the served body byte-equal to the pinned zero-state text.

Thirty paths; one empty changeset. The admin SSE snapshot is not upgraded here — its seven keys need a rate window and process statistics the tree has no source for — and stays its own row of #868.

Rust only: no version bump. Closes #N is inert on this branch's base; #595 is closed by hand with the merge sha.

@changeset-bot

changeset-bot Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 17d64b6

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 0 packages

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 051ad730-f864-4159-a1d8-33d0c085d74b

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@greptile-apps

greptile-apps Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5 · The PR appears safe to merge, with one non-blocking count/sum mismatch remaining in the histogram.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with one non-blocking count/sum mismatch remaining in the histogram.

Findings

  1. P2 Latency buckets can disagree ▶

Summary

Adds a bearer-protected Prometheus endpoint at <prefix>/metrics, backed by relay counters. The latest change keeps histogram buckets ordered during concurrent updates and adds a test for that case.

  • The relay counts EVENT traffic, live subscriptions, and time to EOSE.
  • Prometheus can scrape relay metrics from an optional bearer-protected route.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Relay traffic] --> B[RelayMetrics]
  E[Daemon environment] --> F[Route enabled and token configured]
  P[Prometheus] --> M["GET prefix/metrics"]
  F --> M
  M --> T{Bearer token matches?}
  T -->|No| U[401]
  T -->|Yes| R[Render seven metric families]
  B --> R
  C[ConnectionCap] --> R
Loading

Reviews (2) · Last reviewed commit: "fix(relay): render the EOSE histogram as..." · Reviewed by Greptile

Comment thread crates/nostream-relay/src/metrics.rs Outdated
Comment on lines +340 to +357
for (_, label) in EOSE_BUCKET_MS {
eose_family.push_str(&format!(
"{EOSE_DURATION_SECONDS}_bucket{{le=\"{}\"}} {}\n",
escape_label_value(label),
metrics.eose_bucket(label)
));
}
eose_family.push_str(&format!(
"{EOSE_DURATION_SECONDS}_bucket{{le=\"+Inf\"}} {}\n",
metrics.eose_count()
));
eose_family.push_str(&format!(
"{EOSE_DURATION_SECONDS}_sum {:.3}\n",
metrics.eose_sum_seconds()
));
eose_family.push_str(&format!(
"{EOSE_DURATION_SECONDS}_count {}\n",
metrics.eose_count()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Latency buckets can disagree

render reads each histogram value separately while observe_eose_millis changes them on other tasks. A scrape can read an updated small bucket before a larger bucket is updated, or read different totals for le="+Inf" and _count. This gives dashboards inconsistent latency data. Take one consistent snapshot of the buckets, count, and sum before formatting them.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 17d64b6. render now snapshots eose_count() and eose_sum_seconds() once each and walks the bucket boundaries from the largest down with a running floor (min(observed, floor)), so the printed series is non-increasing from +Inf down by construction — no retry, no lock, no invented sample, and the three accessors keep their signatures. The regression case (an_eose_scrape_torn_by_a_concurrent_observation_stays_monotone) adds a #[cfg(test)] observation hook, renders after the first bucket has moved and before the rest, and asserts the block is monotone, that _count is at least +Inf, and that nothing half-counted is printed; dropping the clamp reproduces exactly the body you described (le="0.01" 1 above le="0.05" 0). ADR 0021 D3 records the clamp and why. Workspace suite on the fix: 119 targets, 1856 passed, 0 failed.

Comment on lines +540 to 544
context
.metrics
.observe_eose_millis(context.now_ms().saturating_sub(started_ms));

context.sink.send(&RelayMessage::Eose(EoseMessage {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Dropped replies still count

The EOSE sample is recorded before FrameSink::send decides whether the frame fits. For example, an empty result can reach this point while other subscriptions fill the shared frame budget; the EOSE is then refused, but its sample remains counted. Make queue admission report success and count only admitted EOSE frames, while preserving the guarantee that the sample exists before the client can read the frame.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Right, and the code is faithful to the pinned site: V13 says the sample is taken immediately before the frame is queued, and AC6 asserts it there. Counting only admitted frames means moving the sample under the sink's success path and re-pinning that case, so it is recorded rather than folded in: filed as #1283 with your example (an empty result refused under budget pressure), so the fix carries its own tests.

@chappie-daemon
chappie-daemon merged commit bb00f82 into rewrite/main Nov 29, 2026
18 checks passed
@chappie-daemon
chappie-daemon deleted the factory/042-prometheus-metrics branch November 29, 2026 16: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.

1 participant