Skip to content

fix(metrics): prime counters for startup exposure - #1343

Merged
kalbasit merged 1 commit into
mainfrom
user/wnasreddine/fix-issue-1337
Jun 7, 2026
Merged

kalbasit merged 1 commit into
mainfrom
user/wnasreddine/fix-issue-1337

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes #1337. Documented counters (ncps_nar_served_total,
ncps_narinfo_served_total, the LRU eviction counters, the lock
counters, and the migration counter) were absent from GET /metrics
on 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) 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 export 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).

Test plan

  • task fmt, task lint (0 issues), task test (race detector) all pass
  • New pkg/ncps/metrics_prime_test.go drives the real Prometheus
    gatherer and asserts all 13 counters appear at 0 before any
    traffic, plus a 0→1 increment check proving priming does not inflate
  • pkg/cache and pkg/lock no-op-without-provider tests confirm
    priming is safe when metrics are disabled

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

kalbasit commented Jun 7, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. go Pull requests that update go code labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 16870669-350c-4c37-bf50-e2cb9cf46204

📥 Commits

Reviewing files that changed from the base of the PR and between 10b0fab and 4a53dce.

📒 Files selected for processing (13)
  • openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/.openspec.yaml
  • openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/design.md
  • openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/proposal.md
  • openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/specs/metrics-exposure/spec.md
  • openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/tasks.md
  • openspec/specs/metrics-exposure/spec.md
  • pkg/cache/cache.go
  • pkg/cache/metrics_prime_test.go
  • pkg/lock/metrics.go
  • pkg/lock/metrics_prime_test.go
  • pkg/ncps/metrics.go
  • pkg/ncps/metrics_prime_test.go
  • pkg/ncps/serve.go

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Counter metrics now appear in the /metrics endpoint immediately at startup with a value of 0, rather than only appearing after the first real event. This improves observability visibility from process launch.
  • Documentation

    • Added metrics exposure specification defining counter initialization behavior and requirements.

Walkthrough

This PR addresses missing Prometheus counter metrics at startup by implementing counter "priming." After the OpenTelemetry meter provider is installed, PrimeMetrics(ctx) functions across cache, lock, and ncps packages record zero-valued measurements to ensure documented counters appear in the /metrics endpoint immediately, with value 0, rather than remaining absent until the first real event.

Changes

Metrics Priming Implementation

Layer / File(s) Summary
Specification and Design
openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/.openspec.yaml, openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/design.md, openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/proposal.md, openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/specs/metrics-exposure/spec.md, openspec/changes/archive/2026-06-06-fix-prometheus-counter-priming/tasks.md, openspec/specs/metrics-exposure/spec.md
Complete specification documenting counter priming behavior, requirements (counters at 0 after meter provider installation via Add(ctx, 0)), scope exclusions (gauges/histograms), and integration points via per-package PrimeMetrics(ctx) functions called during pkg/ncps/serve.go startup.
Cache Package Metrics Priming
pkg/cache/cache.go, pkg/cache/metrics_prime_test.go
Exported PrimeMetrics(ctx) iterates over cache's Int64Counter instruments (served/eviction/migration/download coordination) and records zero measurements for each non-nil counter; parallel test verifies safe no-op when no meter provider is configured.
Lock Package Metrics Priming
pkg/lock/metrics.go, pkg/lock/metrics_prime_test.go
Exported PrimeMetrics(ctx) records zero measurements for lock acquisition, failure, and retry counters, skipping nil instruments; parallel test confirms safe no-op without meter provider.
NCPS Package Priming and Startup Wiring
pkg/ncps/metrics.go, pkg/ncps/metrics_prime_test.go, pkg/ncps/serve.go
Exported PrimeMetrics(ctx) primes the migration objects counter; serveAction startup (guarded by otel-enabled or prometheus-enabled) calls all three package priming functions after meter provider installation; integration test verifies counters exposed at zero and that priming preserves counting semantics (first real increment yields total 1).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested labels

bug, go

Poem

🐇 At startup's dawn, the counters wake,
Priming themselves with measures fake,
Add zero, they whisper, for all to see—
Prometheus shows what will soon be!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(metrics): prime counters for startup exposure' clearly and concisely describes the main change: fixing a metrics issue by priming counters to ensure they appear on startup.
Description check ✅ Passed The description is well-written and directly related to the changeset, explaining the root cause, the fix, and test coverage for the counter priming implementation.
Linked Issues check ✅ Passed The PR fully addresses issue #1337 by implementing counter priming to expose documented Prometheus metrics (ncps_nar_served_total, ncps_narinfo_served_total, cache/lock counters) immediately on startup.
Out of Scope Changes check ✅ Passed All changes are directly in scope: PrimeMetrics functions in pkg/cache, pkg/lock, pkg/ncps with corresponding tests, spec documentation, and serve.go integration to call priming functions.
Docstring Coverage ✅ Passed Docstring coverage is 81.82% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot 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.

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.

@dosubot

dosubot Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Documentation Updates

2 document(s) were updated by changes in this PR:

OpenTelemetry Instrumentation and Metrics
View 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 Integration
View 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.
 

How did I do? Any feedback?  Join Discord

@kalbasit
kalbasit merged commit 244b6cf into main Jun 7, 2026
38 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-issue-1337 branch June 7, 2026 05:19
kalbasit added a commit that referenced this pull request Jun 8, 2026
## 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Missing prometheus metrics

1 participant