Repository navigation
fix(metrics): prime counters for startup exposure - #1343
Conversation
The OpenTelemetry Prometheus exporter only emits a counter time series after the counter records its first measurement. ncps' counters (ncps_nar_served_total, ncps_narinfo_served_total, the LRU eviction counters, lock counters, and the migration counter) are only incremented on real events, so a freshly started or idle instance scraped at /metrics is missing every counter the docs promise (GitHub issue #1337). Add an exported PrimeMetrics(ctx) to pkg/cache, pkg/lock, and pkg/ncps that records a zero-valued Add(ctx, 0) on each Int64Counter, and call all three from serve.go once the global meter provider is installed (when OTel or Prometheus is enabled). Adding zero forces each series to be exported at value 0 without affecting counts: the first real event still advances the counter from 0 to 1. Observable gauges and histograms are unaffected (gauges already export via callbacks). Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
This change is part of the following stack: Change managed by git-spice. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (13)
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR addresses missing Prometheus counter metrics at startup by implementing counter "priming." After the OpenTelemetry meter provider is installed, ChangesMetrics Priming Implementation
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request addresses issue #1337 by priming all OpenTelemetry counter instruments to zero at startup, ensuring they are immediately visible in the /metrics endpoint. This is achieved by introducing a PrimeMetrics function in the pkg/cache, pkg/lock, and pkg/ncps packages, which are invoked in serve.go once the global meter provider is installed. Comprehensive unit and integration tests have been added to verify that priming works correctly, preserves counting semantics, and is a safe no-op when metrics are disabled. No review comments were provided, so there is no additional 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.
|
Documentation Updates 2 document(s) were updated by changes in this PR: OpenTelemetry Instrumentation and MetricsView Changes@@ -70,6 +70,13 @@
The `/metrics` endpoint is available on the server's HTTP address (default `:8501`) and can be scraped by Prometheus or queried directly for metrics [[source]](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/cmd/serve.go#L255-L529).
+#### Counter Initialization Behavior
+All OpenTelemetry counter instruments are primed to value `0` at startup after the global meter provider is installed. This ensures that documented counters—including `ncps_nar_served_total`, `ncps_narinfo_served_total`, LRU eviction counters, lock counters, and migration counters—are present in the `/metrics` output from the moment the Prometheus exporter is active, even on idle instances that have not processed any events yet.
+
+Previously, counters only appeared in the `/metrics` output after their first measurement due to the OpenTelemetry → Prometheus exporter implementation. With counter priming, all counters are initialized to `0` by recording a zero-valued measurement (`Add(ctx, 0)`) on each counter instrument defined in `pkg/cache`, `pkg/lock`, and `pkg/ncps`. This priming occurs in `serve.go` once metrics exporters are configured.
+
+The priming does not affect counting semantics: the first real event still increments the counter from `0` to `1`. When metrics are disabled, the priming is a harmless no-op.
+
### pprof Profiling Support
The pprof profiling server enables CPU and memory profiling for performance analysis and troubleshooting. Profiling is disabled by default for security and must be explicitly enabled using the `--pprof-addr` flag.
@@ -145,6 +152,13 @@
#### Background Operations Metrics
- `ncps_background_migration_objects_total`: Counter tracking the number of objects migrated from legacy storage to the database in background operations.
+- `ncps_migration_objects_total`: Counter tracking the total number of objects migrated. This counter is distinct from `ncps_background_migration_objects_total` and includes all migration operations.
+
+#### Lock Operations Metrics
+
+- `ncps_lock_acquisitions_total`: Counter tracking the total number of lock acquisition attempts, with attributes for lock type and mode.
+- `ncps_lock_failures_total`: Counter tracking the total number of lock acquisition failures, with attributes for lock type, mode, and failure reason.
+- `ncps_lock_retry_attempts_total`: Counter tracking the total number of lock retry attempts, with attributes for lock type.
### Tracing Spans for NAR and NarInfo Operations
In addition to tracing spans for NAR and NarInfo operations, lock operations are now instrumented with OpenTelemetry metrics. Both local and distributed (Redis-based) lock implementations record metrics for acquisition attempts, contention, failures (with detailed reasons), retry attempts, and lock hold durations. While lock operations do not create tracing spans, the emitted metrics provide fine-grained observability into lock behavior, including contention events and failure diagnostics for distributed systems.Prometheus Metrics IntegrationView Changes@@ -23,7 +23,7 @@
- `ncps_nar_served_total`: Counts the number of NAR (Nix ARchive) files served by the cache. This counter includes `result` and `status` attributes.
- `ncps_narinfo_served_total`: Counts the number of NarInfo files served. This counter includes `result`, `status`, and `source` attributes.
-Both metrics are OpenTelemetry counters and are incremented each time a NAR or NarInfo is served. Each counter is enriched with attributes for detailed analysis:
+Both metrics are OpenTelemetry counters and are incremented each time a NAR or NarInfo is served. These counters are initialized to `0` at startup when the Prometheus exporter is active, ensuring they appear in `/metrics` output immediately, even before any NAR or NarInfo has been served. Each counter is enriched with attributes for detailed analysis:
- `result`: Indicates whether the request was a cache `hit` or `miss`.
- `status`: Indicates the outcome, such as `success` or `error`.
@@ -47,6 +47,8 @@
- `ncps_lru_chunks_evicted_total`: Count of chunks evicted by the LRU process (relevant when CDC is enabled).
- `ncps_lru_bytes_freed_total`: Total bytes freed by LRU eviction operations.
+All LRU eviction counters are initialized to `0` at startup when the Prometheus exporter is active, ensuring they are present in the `/metrics` output before any eviction occurs.
+
These metrics help track cache cleanup activity and understand how effectively the LRU policy is managing disk space.
**Pinned Closures and LRU Eviction**: Pinned closures and all their transitive references are automatically excluded from LRU eviction candidates. When a closure is pinned via `POST /pin/{hash}.narinfo`, the narinfo and all packages it references (recursively) are protected from eviction. The LRU eviction metrics above count only items that were successfully evicted and do not include any pinned items that were skipped during the eviction process. If the LRU process is unable to meet its cleanup size targets, this may indicate that too many closures are pinned, leaving insufficient reclaimable space in the cache.
@@ -69,7 +71,7 @@
- `ncps_background_migration_objects_total`: Count of objects (narinfos) migrated from legacy storage to the database in the background.
-This counter tracks the progress of background migration operations for legacy narinfo storage [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/cache/cache.go#L1-L1887).
+This counter is initialized to `0` at startup when the Prometheus exporter is active, ensuring it is present in the `/metrics` output before any migration activity occurs. This counter tracks the progress of background migration operations for legacy narinfo storage [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/cache/cache.go#L1-L1887).
#### Monitoring Pinned Closures
@@ -84,6 +86,8 @@
### Instrumentation with OpenTelemetry
Metrics are instrumented using OpenTelemetry. The project initializes a global OpenTelemetry MeterProvider, which is configured to export metrics to Prometheus when the `--prometheus-enabled` flag is set. The integration is handled by the `SetupPrometheusMetrics` function, which creates a Prometheus exporter and registry, and sets the MeterProvider globally for all instrumentation [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/prometheus/prometheus.go#L15-L49).
+
+All documented counter metrics are initialized to `0` at startup by recording a zero-valued measurement after the MeterProvider is installed. This ensures counters appear in the `/metrics` output immediately when the Prometheus exporter is active, rather than only appearing after their first event. The initialization does not inflate counts—adding `0` preserves counting semantics, so the first real event still advances the counter from `0` to `1`.
In addition to custom counters, the server uses OpenTelemetry middleware to track HTTP request duration, in-flight requests, and response sizes, providing a comprehensive view of server performance.
|
## Summary The `[Unreleased]` section was populated in #1309 but skewed toward the recent CDC-drain, in-flight-staging, and Ent-migration work, omitting several user-facing features and fixes that also landed since v0.9.4. This backfills the missing notable changes, each cross-referenced by PR. **Added** - `ncps fsck` command + Helm fsck CronJob (#975, #996, #998, #999, #1000, #1004, #1006, #1176) - Closure pinning HTTP endpoints `POST`/`DELETE /pin/{hash}.narinfo`, `GET /pins` (#1108) - pprof server via `--pprof-addr` (#1063) - CDC lazy chunking as a feature + `--cache-cdc-lazy-cleanup-schedule` + recovery cron (#1082, #1083, #1089, #1096) - Helm: auto `GOMEMLIMIT` (#1061), configurable temp volume / `volumeClaimTemplate` (#1074, #1077), SQLite `Recreate` strategy (#1012) - Startup storage reporting + deprecated-narinfo warning (#959, #961) - `docker-dev` image (#1097) **Fixed** - `store/tmp` no longer wiped on startup (#1313) - `nix-hash` NAR verification (#1101) - Prometheus counters primed at startup (#1337, #1343) - 404 on un-reassemblable chunked NARs (#1319), purged narinfo no longer 500 (#1318), fail-fast tmp validation (#1086) - Further CDC/cache reliability fixes (#1317, #1346, #1341, #1342, #1331, #1347) **Changed** - CDC config now persisted in the DB config table (#971) Dependency bumps, CI/test-only changes, and the internal Ent-conversion PRs are intentionally excluded; the existing Ent-migration entry already covers that work. ## Test plan - [x] `nix fmt` reports no changes (docs-only edit) - [x] CHANGELOG section structure intact (Added/Fixed/Changed/Removed/Migration/CI)
Summary
Fixes #1337. Documented counters (
ncps_nar_served_total,ncps_narinfo_served_total, the LRU eviction counters, the lockcounters, and the migration counter) were absent from
GET /metricson a freshly started or idle instance.
Root cause: the OpenTelemetry → Prometheus exporter only emits a
counter time series after the counter records its first measurement.
These counters only increment on real events, so until a NAR/narinfo
was served (or an eviction/migration fired) the series simply did not
exist — contradicting the docs that promise them and breaking
dashboards/alerts that reference them from the start.
Fix: add an exported
PrimeMetrics(ctx)topkg/cache,pkg/lock, andpkg/ncpsthat records a zero-valuedAdd(ctx, 0)oneach
Int64Counter, and call all three fromserve.goonce the globalmeter provider is installed (when OTel or Prometheus is enabled).
Adding zero forces each series to export at value
0without affectingcounts: the first real event still advances the counter from 0 to 1.
Observable gauges and histograms are unaffected (gauges already export
via callbacks).
Test plan
task fmt,task lint(0 issues),task test(race detector) all passpkg/ncps/metrics_prime_test.godrives the real Prometheusgatherer and asserts all 13 counters appear at
0before anytraffic, plus a 0→1 increment check proving priming does not inflate
pkg/cacheandpkg/lockno-op-without-provider tests confirmpriming is safe when metrics are disabled