diff --git a/HISTORY.md b/HISTORY.md index dac7833..4f3d65f 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,30 @@ # History +### v5.12.0 + +**The `prometheus` handler no longer loses the first counts of a new series.** +`increase()` and `rate()` count the change between samples, never a series' +first sample. The handler exposed a new counter at its first value and expired +idle series after `MetricTimeout`, so a counter first scraped at 3 lost those +3, and a series expired and re-created at 1 read as no change at all. Busy +series lose this once per process; sparse, high-cardinality ones lose it every +time they come back. A counter labeled by a per-customer ID, where each series +sees a few requests and goes idle, can read several percent low against the +same counter sent to a statsd backend, while a busy counter on the same process +matches. + +New and re-created counter and histogram series are now published as 0 for +the new `Handler.ZeroPeriod`, 2 minutes by default, before their real value. +The period is measured on the wall clock, not per scrape, so every scraper of +the endpoint sees the zero. Keep it at least twice the scrape interval: a +scrape that runs late, or a target handed to another collector, can otherwise +skip a window only one interval long. Counts are +delayed by up to that long, not lost: a series in its zero period is not +expired, and its value is published for a full `MetricTimeout` afterwards. +Gauges are unchanged. Set a negative `ZeroPeriod` to turn this off. A program +that reads `WriteStats` output right after its first update, as tests often +do, sees 0 unless it does. + ### v5.11.1 **A call-time tag that overrides an engine tag no longer sends a tag twice.** diff --git a/README.md b/README.md index 8114862..3fa8ce2 100644 --- a/README.md +++ b/README.md @@ -203,10 +203,13 @@ http.Handle("/metrics", prometheus.DefaultHandler) `Handler` has no `NewHandler` constructor; `DefaultHandler` is a ready-to-use zero-config instance. Construct your own `&prometheus.Handler{}` literal instead if you need to set -`TrimPrefix`, `MetricTimeout`, or `Buckets`. +`TrimPrefix`, `MetricTimeout`, `ZeroPeriod`, or `Buckets`. Counters are published with a `_total` suffix, and the handler leaves timestamps -off so the scraper assigns scrape time. +off so the scraper assigns scrape time. A new counter or histogram series is +published as 0 for `ZeroPeriod` (2 minutes by default) before its value, so that +`increase()` and `rate()` count its first increments; keep it at least twice +your scrape interval. Histograms need bucket boundaries. Register them with `Engine.SetBuckets`, which takes the same name you pass to `Observe` and derives the registry key from the diff --git a/buckets_test.go b/buckets_test.go index db31c04..d273ad3 100644 --- a/buckets_test.go +++ b/buckets_test.go @@ -99,7 +99,7 @@ func TestEngineSetBucketsKeyMatchesObserve(t *testing.T) { // sub-engine reach the exposition, rather than the metric silently falling // back to the default set. func TestEngineSetBucketsEndToEnd(t *testing.T) { - ph := &prometheus.Handler{} + ph := &prometheus.Handler{ZeroPeriod: -1} e := stats.NewEngine("svc", ph).WithPrefix("sub") e.SetBuckets("latency", 0.1, 0.2, 0.3) diff --git a/engine_test.go b/engine_test.go index 4a68508..7284b14 100644 --- a/engine_test.go +++ b/engine_test.go @@ -709,7 +709,7 @@ func TestPrometheusOverrideTagsUniqueLabels(t *testing.T) { stats.GoVersionReportingEnabled = false defer func() { stats.GoVersionReportingEnabled = initValue }() - h := &prometheus.Handler{} + h := &prometheus.Handler{ZeroPeriod: -1} e := stats.NewEngine("", h, stats.T("service_name", "app")).WithTags(stats.T("service", "cps")) e.Incr("rpc_call", stats.T("method", "POST"), stats.T("service", "")) diff --git a/prometheus/handler.go b/prometheus/handler.go index 39aca27..8996558 100644 --- a/prometheus/handler.go +++ b/prometheus/handler.go @@ -44,6 +44,21 @@ type Handler struct { // The default is to use a 2 minutes metric timeout. MetricTimeout time.Duration + // ZeroPeriod defines how long a new counter or histogram series is + // exposed with a value of zero before its real value. This includes a + // series created again after MetricTimeout expired it. + // + // increase() and rate() never count a series' first sample, so a counter + // whose first scraped value is 3 loses those 3. Starting at zero makes the + // first sample 0. Set it to at least twice the scrape interval of every + // scraper of this handler; counts are delayed by up to this long, not lost. + // Gauges are unaffected. + // + // The default is 2 minutes, twice the common 60s scrape interval, so that + // a late scrape or a target moving between collectors still lands in the + // window. A negative value disables it. + ZeroPeriod time.Duration + // Buckets is the registry of histogram buckets used by the handler, // If nil, stats.Buckets is used instead. // @@ -57,6 +72,7 @@ type Handler struct { // HandleMeasures satisfies the stats.Handler interface. func (h *Handler) HandleMeasures(mtime time.Time, measures ...stats.Measure) { cache := handleMetricPool.Get().(*handleMetricCache) + zeroPeriod := h.zeroPeriod() for _, m := range measures { scope := h.trimPrefix(m.Name) @@ -103,14 +119,18 @@ func (h *Handler) HandleMeasures(mtime time.Time, measures ...stats.Measure) { } } - h.metrics.update(metric{ + point := metric{ mtype: mtype, scope: scope, name: f.Name, value: valueOf(f.Value), time: mtime, labels: cache.labels, - }, buckets) + } + if mtype == counter || mtype == histogram { + point.zeroPeriod = zeroPeriod + } + h.metrics.update(point, buckets) } for i := range cache.labels { @@ -124,7 +144,7 @@ func (h *Handler) HandleMeasures(mtime time.Time, measures ...stats.Measure) { // having memory leaks if the program has generated metrics for a pair of // metric name and labels that won't be seen again. if (h.opcount.Add(1) % 10000) == 0 { - h.metrics.cleanup(time.Now().Add(-h.timeout())) + h.metrics.cleanup(now().Add(-h.timeout())) } } @@ -136,6 +156,10 @@ func (h *Handler) trimPrefix(s string) string { return s } +// now is the wall clock that ZeroPeriod and MetricTimeout are measured on, +// replaced by tests that step through time. +var now = time.Now + func (h *Handler) timeout() time.Duration { if timeout := h.MetricTimeout; timeout != 0 { return timeout @@ -143,6 +167,13 @@ func (h *Handler) timeout() time.Duration { return 2 * time.Minute } +func (h *Handler) zeroPeriod() time.Duration { + if period := h.ZeroPeriod; period != 0 { + return period + } + return 2 * time.Minute +} + // ServeHTTP satisfies the http.Handler interface. func (h *Handler) ServeHTTP(res http.ResponseWriter, req *http.Request) { switch req.Method { @@ -190,7 +221,7 @@ func (h *Handler) WriteStats(w io.Writer) { // the entire scrape fails. declared := make(map[metricKey]struct{}) - metrics := h.metrics.collect(make([]metric, 0, 10000)) + metrics := h.metrics.collect(make([]metric, 0, 10000), now()) sort.Sort(byNameAndLabels(metrics)) for i, m := range metrics { diff --git a/prometheus/handler_test.go b/prometheus/handler_test.go index 5ccda2b..4b12909 100644 --- a/prometheus/handler_test.go +++ b/prometheus/handler_test.go @@ -57,6 +57,7 @@ func TestServeHTTP(t *testing.T) { now := time.Date(2017, 6, 4, 22, 12, 0, 0, time.UTC) handler := &Handler{ + ZeroPeriod: -1, Buckets: map[stats.Key][]stats.Value{ {Field: "C"}: { stats.ValueOf(0.25), @@ -168,7 +169,7 @@ func BenchmarkHandleMetric(b *testing.B) { func TestHistogramWithoutRegisteredBuckets(t *testing.T) { now := time.Date(2017, 6, 4, 22, 12, 0, 0, time.UTC) - handler := &Handler{} // no Buckets registry at all + handler := &Handler{ZeroPeriod: -1} // no Buckets registry at all handler.HandleMeasures(now, stats.Measure{Fields: []stats.Field{stats.MakeField("D", 0.003, stats.Histogram)}}, @@ -291,7 +292,7 @@ func TestTypeDeclarationAcrossAdjacentScopes(t *testing.T) { func TestCounterTotalSuffix(t *testing.T) { now := time.Date(2017, 6, 4, 22, 12, 0, 0, time.UTC) - handler := &Handler{} + handler := &Handler{ZeroPeriod: -1} handler.HandleMeasures(now, stats.Measure{ Name: "svc", Fields: []stats.Field{ @@ -339,7 +340,7 @@ func TestHistogramWithRegisteredInfBoundary(t *testing.T) { // Ending a registered set with +Inf is the idiom used by every bucket set // in httpstats, netstats and procstats. - handler := &Handler{Buckets: stats.HistogramBuckets{}} + handler := &Handler{ZeroPeriod: -1, Buckets: stats.HistogramBuckets{}} handler.Buckets.Set("D", 0.1, 1.0, math.Inf(+1)) handler.HandleMeasures(now, @@ -376,7 +377,7 @@ func TestHistogramWithRegisteredInfBoundary(t *testing.T) { func TestHistogramWithRegisteredInfBoundaryAccumulates(t *testing.T) { now := time.Date(2017, 6, 4, 22, 12, 0, 0, time.UTC) - handler := &Handler{Buckets: stats.HistogramBuckets{}} + handler := &Handler{ZeroPeriod: -1, Buckets: stats.HistogramBuckets{}} handler.Buckets.Set("D", 0.1, 1.0, math.Inf(+1)) for i := 0; i < 5; i++ { diff --git a/prometheus/metric.go b/prometheus/metric.go index 8975f91..9c82e55 100644 --- a/prometheus/metric.go +++ b/prometheus/metric.go @@ -51,6 +51,10 @@ type metric struct { value float64 time time.Time labels labels + + // Input path only: how long a state created by this update publishes zero + // before its real value. See Handler.ZeroPeriod. + zeroPeriod time.Duration } func (m metric) key() metricKey { @@ -110,15 +114,16 @@ func (store *metricStore) lookup(mtype metricType, key metricKey, help string) * func (store *metricStore) update(metric metric, buckets []stats.Value) { entry := store.lookup(metric.mtype, metric.key(), metric.help) - state := entry.lookup(metric.labels) + state := entry.lookup(metric.labels, metric.zeroPeriod) state.update(metric.mtype, metric.value, metric.time, buckets) } -func (store *metricStore) collect(metrics []metric) []metric { +// collect appends the current value of every state, as of now. +func (store *metricStore) collect(metrics []metric, now time.Time) []metric { store.mutex.RLock() for key, entry := range store.entries { - metrics = entry.collect(metrics, store.exposedName(key, entry)) + metrics = entry.collect(metrics, store.exposedName(key, entry), now) } store.mutex.RUnlock() @@ -226,7 +231,11 @@ func hasTotalSuffix(name string) bool { return string(b) == "total" || strings.HasSuffix(string(b), "_total") } -func (entry *metricEntry) lookup(labels labels) *metricState { +// lookup returns the state for labels, creating it if there is none. A state +// created here publishes zero for zeroPeriod, measured on the wall clock rather +// than on the measure's time: engine-reported version metrics carry a zero +// time, and ReportAt takes any time the caller likes. +func (entry *metricEntry) lookup(labels labels, zeroPeriod time.Duration) *metricState { key := labels.hash() entry.mutex.RLock() @@ -238,6 +247,9 @@ func (entry *metricEntry) lookup(labels labels) *metricState { if state = entry.states.find(key, labels); state == nil { state = newMetricState(labels) + if zeroPeriod > 0 { + state.zeroUntil = now().Add(zeroPeriod) + } entry.states.put(key, state) } @@ -247,13 +259,13 @@ func (entry *metricEntry) lookup(labels labels) *metricState { return state } -func (entry *metricEntry) collect(metrics []metric, name string) []metric { +func (entry *metricEntry) collect(metrics []metric, name string, now time.Time) []metric { entry.mutex.RLock() if len(entry.states) != 0 { for _, states := range entry.states { for _, state := range states { - metrics = state.collect(metrics, entry, name) + metrics = state.collect(metrics, entry, name, now) } } } @@ -276,7 +288,12 @@ func (entry *metricEntry) cleanup(exp time.Time, empty func()) { // We expire all entries that have been last updated before exp, // they don't get copied back into the state slice. - if exp.Before(state.time) { + // + // A state still publishing zero, or that stopped doing so less + // than a timeout ago, is kept regardless: its real value has to + // be exposed for as long as any other state's would be, or a + // scrape may never see it. + if exp.Before(state.time) || exp.Before(state.zeroUntil) { states[i] = state i++ } @@ -311,6 +328,18 @@ type metricState struct { sum float64 count uint64 time time.Time + + // Until this time the state publishes zero rather than its value. + // + // Prometheus' increase() and rate() count the change between samples of a + // series, never its first sample. A counter that first appears at 3 has + // lost those 3, and one that expires on MetricTimeout and comes back at 1 + // reads as no change at all. Sparse, high-cardinality series do this + // constantly. Starting every series at 0 for longer than a scrape + // interval makes the first scraped sample 0, so the whole value is + // counted as change. Measured in time rather than per scrape, so that + // every scraper of the endpoint sees the zero. + zeroUntil time.Time } func newMetricState(labels labels) *metricState { @@ -345,9 +374,19 @@ func (state *metricState) update(mtype metricType, value float64, time time.Time state.mutex.Unlock() } -func (state *metricState) collect(metrics []metric, entry *metricEntry, name string) []metric { +func (state *metricState) collect(metrics []metric, entry *metricEntry, name string, now time.Time) []metric { state.mutex.Lock() + // Every value below passes through this, which publishes the series with + // all of its labels and buckets but none of its counts. + zero := now.Before(state.zeroUntil) + value := func(v float64) float64 { + if zero { + return 0 + } + return v + } + // metric.time is deliberately not set here. appendMetric no longer writes // a timestamp, so nothing on the output path reads it; the field stays on // the struct for the input path, where metricStore.update carries it into @@ -359,7 +398,7 @@ func (state *metricState) collect(metrics []metric, entry *metricEntry, name str scope: entry.scope, name: name, help: entry.help, - value: state.value, + value: value(state.value), labels: state.labels, }) @@ -375,7 +414,7 @@ func (state *metricState) collect(metrics []metric, entry *metricEntry, name str scope: entry.scope, name: entry.bucket, help: entry.help, - value: float64(cumulativeCount), + value: value(float64(cumulativeCount)), labels: bucket.labels, }) } @@ -385,7 +424,7 @@ func (state *metricState) collect(metrics []metric, entry *metricEntry, name str scope: entry.scope, name: entry.sum, help: entry.help, - value: state.sum, + value: value(state.sum), labels: state.labels, }, metric{ @@ -393,7 +432,7 @@ func (state *metricState) collect(metrics []metric, entry *metricEntry, name str scope: entry.scope, name: entry.count, help: entry.help, - value: float64(state.count), + value: value(float64(state.count)), labels: state.labels, }, ) diff --git a/prometheus/metric_test.go b/prometheus/metric_test.go index 3b73f46..c78ed63 100644 --- a/prometheus/metric_test.go +++ b/prometheus/metric_test.go @@ -34,7 +34,7 @@ func TestFuzzyDeadlock(t *testing.T) { // 2) race collect vs cleanup once done := make(chan struct{}, 2) go func() { - store.collect(nil) + store.collect(nil, time.Now()) done <- struct{}{} }() go func() { @@ -120,7 +120,7 @@ func TestMetricStore(t *testing.T) { }) } - metrics := store.collect(nil) + metrics := store.collect(nil, time.Now()) sort.Sort(byNameAndLabels(metrics)) expects := []metric{ @@ -254,7 +254,7 @@ func TestMetricStoreCleanup(t *testing.T) { wg.Wait() - metrics := store.collect(nil) + metrics := store.collect(nil, time.Now()) sort.Sort(byNameAndLabels(metrics)) // collect() does not carry state.time onto the collected metric: nothing @@ -379,7 +379,7 @@ func TestCounterTotalSuffixUsesRenderedName(t *testing.T) { // TestCounterTotalSuffixDottedName is the same invariant at the other end: // e.Incr("requests.total") must not publish app_requests_total_total. func TestCounterTotalSuffixDottedName(t *testing.T) { - h := &Handler{} + h := &Handler{ZeroPeriod: -1} // What Incr("requests.total") produces: measure "app.requests", field "total". h.HandleMeasures(time.Now(), stats.Measure{ @@ -408,7 +408,7 @@ func TestCounterTotalSuffixCollision(t *testing.T) { {"hits_total", "hits"}, } { t.Run(strings.Join(order, ","), func(t *testing.T) { - h := &Handler{} + h := &Handler{ZeroPeriod: -1} for _, name := range order { h.HandleMeasures(time.Now(), stats.Measure{ @@ -447,7 +447,7 @@ func TestCounterTotalSuffixCollision(t *testing.T) { // stale and another appearing. func TestCounterTotalSuffixCollisionSurvivesCleanup(t *testing.T) { now := time.Now() - h := &Handler{} + h := &Handler{ZeroPeriod: -1} h.HandleMeasures(now, stats.Measure{ Name: "svc", diff --git a/prometheus/zero_test.go b/prometheus/zero_test.go new file mode 100644 index 0000000..b4f418b --- /dev/null +++ b/prometheus/zero_test.go @@ -0,0 +1,224 @@ +package prometheus + +import ( + "strings" + "testing" + "time" + + "github.com/segmentio/stats/v5" +) + +// setNow points the handler's wall clock at *clock for the rest of the test. +func setNow(t *testing.T, clock *time.Time) { + t.Helper() + prev := now + now = func() time.Time { return *clock } + t.Cleanup(func() { now = prev }) +} + +// seriesKey identifies a collected sample the way a scraper does: by its +// exposed name and its labels. +func seriesKey(m metric) string { + var b strings.Builder + b.WriteString(m.scope + "_" + m.name) + for _, l := range m.labels { + b.WriteString("," + l.name + "=" + l.value) + } + return b.String() +} + +// promIncrease is what increase() over the whole run computes for one series: +// the sum of the changes between consecutive samples, treating a decrease as +// a reset to zero. The first sample is never counted. +func promIncrease(samples []float64) float64 { + var total float64 + for i := 1; i < len(samples); i++ { + if d := samples[i] - samples[i-1]; d >= 0 { + total += d + } else { + total += samples[i] + } + } + return total +} + +// scrapeCounts runs a handler for 30 minutes of simulated time, scraping it +// every 15s, and returns what increase() sums to over every counter and +// histogram _count series, along with the number of increments made. +// +// One series is busy and never expires. Three others, one per workspace, see +// a short burst every few minutes and are expired by MetricTimeout in between +// — the shape of a counter labeled by a per-customer ID. +func scrapeCounts(t *testing.T, zeroPeriod time.Duration) (got, want float64) { + const ( + scrapeInterval = 15 * time.Second + duration = 30 * time.Minute + ) + + clock := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + setNow(t, &clock) + start := clock + + h := &Handler{ZeroPeriod: zeroPeriod, Buckets: stats.HistogramBuckets{}} + samples := map[string][]float64{} + + scrape := func() { + for _, m := range h.metrics.collect(nil, clock) { + if strings.HasSuffix(m.name, "_total") || strings.HasSuffix(m.name, "_count") { + k := seriesKey(m) + samples[k] = append(samples[k], m.value) + } + } + } + + for step := time.Duration(0); step < duration; step += time.Second { + clock = start.Add(step) + + measures := []stats.Measure{{ + Name: "svc.requests", + Fields: []stats.Field{stats.MakeField("count", 1, stats.Counter)}, + }} + for i, ws := range []string{"ws1", "ws2", "ws3"} { + if step%(time.Duration(4+i)*time.Minute) < 3*time.Second { + measures = append(measures, stats.Measure{ + Name: "svc.responses", + Fields: []stats.Field{ + stats.MakeField("count", 1, stats.Counter), + stats.MakeField("rtt", 0.1, stats.Histogram), + }, + Tags: []stats.Tag{stats.T("workspace_id", ws)}, + }) + } + } + for _, m := range measures { + want += float64(len(m.Fields)) + h.HandleMeasures(clock, m) + } + + if step%scrapeInterval == 0 { + // Expire as eagerly as the handler is allowed to, rather than + // every 10K updates, so the result does not depend on traffic. + h.metrics.cleanup(clock.Add(-h.timeout())) + scrape() + } + } + + // Give the last series created time to leave its zero period. + clock = clock.Add(h.zeroPeriod() + scrapeInterval) + scrape() + + for _, s := range samples { + got += promIncrease(s) + } + return got, want +} + +// TestZeroPeriodCountsEveryIncrement reproduces the undercount: increase() +// never counts a series' first sample, so sparse series that MetricTimeout +// keeps expiring and re-creating lose counts each time they come back. +func TestZeroPeriodCountsEveryIncrement(t *testing.T) { + t.Run("disabled", func(t *testing.T) { + got, want := scrapeCounts(t, -1) + if got >= want { + t.Fatalf("increase() = %v of %v; the simulation no longer reproduces the loss", got, want) + } + t.Logf("increase() = %v of %v without a zero period", got, want) + }) + + t.Run("default", func(t *testing.T) { + if got, want := scrapeCounts(t, 0); got != want { + t.Fatalf("increase() = %v, expected %v", got, want) + } + }) +} + +// TestZeroPeriodIsTimeBased checks that every scrape during the zero period +// sees 0, however many there are, so that two scrapers of one endpoint both +// see the series start from zero. +func TestZeroPeriodIsTimeBased(t *testing.T) { + clock := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + setNow(t, &clock) + + h := &Handler{} + h.HandleMeasures(clock, stats.Measure{ + Name: "svc", + Fields: []stats.Field{ + stats.MakeField("hits", 3, stats.Counter), + stats.MakeField("rtt", 0.1, stats.Histogram), + stats.MakeField("level", 7, stats.Gauge), + }, + }) + + write := func() string { + var buf strings.Builder + h.WriteStats(&buf) + return buf.String() + } + + for range 3 { + out := write() + for _, want := range []string{ + "svc_hits_total 0", + `svc_rtt_bucket{le="+Inf"} 0`, + "svc_rtt_count 0", + "svc_rtt_sum 0", + // Gauges carry no history for a scraper to difference. + "svc_level 7", + } { + if !strings.Contains(out, want) { + t.Fatalf("missing %q during the zero period:\n%s", want, out) + } + } + } + + clock = clock.Add(h.zeroPeriod()) + out := write() + for _, want := range []string{ + "svc_hits_total 3", + `svc_rtt_bucket{le="+Inf"} 1`, + "svc_rtt_count 1", + "svc_rtt_sum 0.1", + } { + if !strings.Contains(out, want) { + t.Fatalf("missing %q after the zero period:\n%s", want, out) + } + } +} + +// TestZeroPeriodOutlivesExpiry checks that a state is not expired while it +// publishes zero, nor until it has published its real value for a full +// MetricTimeout, even when it receives no further updates. +func TestZeroPeriodOutlivesExpiry(t *testing.T) { + clock := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + setNow(t, &clock) + created := clock + + h := &Handler{MetricTimeout: 30 * time.Second} + h.HandleMeasures(clock, stats.Measure{ + Name: "svc", + Fields: []stats.Field{stats.MakeField("hits", 1, stats.Counter)}, + }) + + live := func() bool { + h.metrics.cleanup(clock.Add(-h.timeout())) + return len(h.metrics.collect(nil, clock)) != 0 + } + + // Past MetricTimeout since the update, but still in the zero period. + clock = created.Add(45 * time.Second) + if !live() { + t.Fatal("expired during its zero period") + } + + // Value published since created+ZeroPeriod; MetricTimeout of that has not + // passed. + clock = created.Add(h.zeroPeriod() + 29*time.Second) + if !live() { + t.Fatal("expired before its value was published for a full MetricTimeout") + } + + clock = created.Add(h.zeroPeriod() + 31*time.Second) + if live() { + t.Fatal("not expired a MetricTimeout after its zero period") + } +}