Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -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.**
Expand Down
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion buckets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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", ""))

Expand Down
39 changes: 35 additions & 4 deletions prometheus/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//
Expand All @@ -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)
Expand Down Expand Up @@ -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 {
Expand All @@ -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()))
}
}

Expand All @@ -136,13 +156,24 @@ 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
}
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 {
Expand Down Expand Up @@ -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 {
Expand Down
9 changes: 5 additions & 4 deletions prometheus/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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)}},
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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++ {
Expand Down
63 changes: 51 additions & 12 deletions prometheus/metric.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand All @@ -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)
}

Expand All @@ -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)
}
}
}
Expand All @@ -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++
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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,
})

Expand All @@ -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,
})
}
Expand All @@ -385,15 +424,15 @@ 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{
mtype: entry.mtype,
scope: entry.scope,
name: entry.count,
help: entry.help,
value: float64(state.count),
value: value(float64(state.count)),
labels: state.labels,
},
)
Expand Down
Loading
Loading