Skip to content
Merged
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
47 changes: 44 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,18 +74,59 @@ mean := snap.Mean()
count, sum := snap.Total()
```

### Export to Prometheus
### Register with Prometheus

A histogram can be registered with a Prometheus registry via
`ToPrometheusCollector`. Recording is done directly on the histogram;
the collector only participates in the scrape path.

```go
ph := snap.ToPrometheusHistogram() // *prometheusgo.Histogram
h := goodhistogram.New(goodhistogram.Params{
Lo: 500,
Hi: 60e9,
ErrorBound: 0.10,
})

desc := prometheus.NewDesc("request_duration_ns", "Request duration in nanoseconds", nil, nil)
prometheus.MustRegister(h.ToPrometheusCollector(desc))

// Hot path — record directly on the histogram.
h.Record(durationNs)
```

The returned proto includes both conventional cumulative buckets (for
The collector exports both conventional cumulative buckets (for
backward compatibility with classic Prometheus) and native histogram
sparse fields (schema, spans, deltas). Because the internal bucket
indices are Prometheus bucket keys by construction, export is a direct
copy with no remapping.

### Labeled histograms (HistogramVec)

For multi-dimensional histograms partitioned by label values, use
`HistogramVec`. It implements `prometheus.Collector` so the entire
vec can be registered with a registry.

```go
vec := goodhistogram.NewHistogramVec(
goodhistogram.Params{Lo: 500, Hi: 60e9, ErrorBound: 0.10},
"request_duration_ns", "Request duration in nanoseconds",
[]string{"method", "path"},
)
prometheus.MustRegister(vec)

// Hot path — WithLabelValues returns a *Histogram for direct recording.
vec.WithLabelValues("GET", "/api").Record(durationNs)
```

### Export to Prometheus proto

If you need the proto directly (e.g. for remote write or custom
export), use `ToPrometheusHistogram` on a snapshot:

```go
ph := snap.ToPrometheusHistogram() // *prometheusgo.Histogram
```


## How it works

Expand Down
53 changes: 53 additions & 0 deletions collector.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2026 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0

package goodhistogram

import (
"github.com/prometheus/client_golang/prometheus"
prometheusgo "github.com/prometheus/client_model/go"
)

// PrometheusCollector wraps a Histogram as a prometheus.Collector, allowing it
// to be registered with a Prometheus registry for scraping. Recording is done
// directly on the Histogram; the collector only participates in the export path.
type PrometheusCollector struct {
h *Histogram
desc *prometheus.Desc
}

// ToPrometheusCollector returns a PrometheusCollector that exposes this
// histogram to a Prometheus registry. The returned collector implements
// prometheus.Collector and can be passed to prometheus.MustRegister.
func (h *Histogram) ToPrometheusCollector(desc *prometheus.Desc) *PrometheusCollector {
return &PrometheusCollector{h: h, desc: desc}
}

// Describe implements prometheus.Collector.
func (p *PrometheusCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- p.desc
}

// Collect implements prometheus.Collector. A fresh histogramMetric is
// created per scrape so the Collector and Metric roles are separate.
func (p *PrometheusCollector) Collect(ch chan<- prometheus.Metric) {
ch <- &histogramMetric{
desc: p.desc,
h: p.h,
}
}

// ToPrometheusMetric returns a point-in-time snapshot as a
// prometheusgo.Metric. This bridges to CockroachDB's PrometheusExportable
// interface without going through the Collector/Metric channel path.
func (p *PrometheusCollector) ToPrometheusMetric() *prometheusgo.Metric {
snap := p.h.Snapshot()
return &prometheusgo.Metric{
Histogram: snap.ToPrometheusHistogram(),
}
}
66 changes: 66 additions & 0 deletions collector_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright 2026 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0

package goodhistogram

import (
"testing"

"github.com/prometheus/client_golang/prometheus"
prometheusgo "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/require"
)

func TestPrometheusCollectorRegistration(t *testing.T) {
h := New(Params{Lo: 100, Hi: 1e9})
desc := prometheus.NewDesc("test_hist", "test", nil, nil)
collector := h.ToPrometheusCollector(desc)

reg := prometheus.NewRegistry()
require.NoError(t, reg.Register(collector))

h.Record(500)
h.Record(1000)
h.Record(2000)

families, err := reg.Gather()
require.NoError(t, err)
require.Len(t, families, 1)
require.Equal(t, "test_hist", *families[0].Name)

metrics := families[0].Metric
require.Len(t, metrics, 1)
require.Equal(t, uint64(3), *metrics[0].Histogram.SampleCount)
require.Equal(t, float64(3500), *metrics[0].Histogram.SampleSum)
}

func TestPrometheusCollectorMatchesSnapshot(t *testing.T) {
h := New(Params{Lo: 100, Hi: 1e9})
for _, v := range []int64{150, 999, 5000, 100000, 5000000} {
h.Record(v)
}

// Collect via the PrometheusCollector and extract the metric.
desc := prometheus.NewDesc("test_hist", "test", nil, nil)
collector := h.ToPrometheusCollector(desc)
ch := make(chan prometheus.Metric, 1)
collector.Collect(ch)
metric := <-ch
var collected prometheusgo.Metric
require.NoError(t, metric.Write(&collected))

// Export directly via Snapshot.
snap := h.Snapshot()
direct := snap.ToPrometheusHistogram()

require.Equal(t, direct.GetSampleCount(), collected.Histogram.GetSampleCount())
require.Equal(t, direct.GetSampleSum(), collected.Histogram.GetSampleSum())
require.Equal(t, direct.GetSchema(), collected.Histogram.GetSchema())
require.Equal(t, len(direct.GetBucket()), len(collected.Histogram.GetBucket()))
require.Equal(t, len(direct.GetPositiveSpan()), len(collected.Histogram.GetPositiveSpan()))
}
20 changes: 20 additions & 0 deletions histogram.go
Original file line number Diff line number Diff line change
Expand Up @@ -440,3 +440,23 @@ func (s *Snapshot) Merge(other *Snapshot) Snapshot {
}
return merged
}

// Sub returns a new Snapshot whose counts are the element-wise difference
// of s minus other. Both snapshots must share the same config. This is used
// to compute windowed views by subtracting a baseline snapshot from a
// current cumulative snapshot.
func (s *Snapshot) Sub(other *Snapshot) Snapshot {
diff := Snapshot{
cfg: s.cfg,
Counts: make([]uint64, len(s.Counts)),
ZeroCount: s.ZeroCount - other.ZeroCount,
Underflow: s.Underflow - other.Underflow,
Overflow: s.Overflow - other.Overflow,
TotalCount: s.TotalCount - other.TotalCount,
TotalSum: s.TotalSum - other.TotalSum,
}
for i := range s.Counts {
diff.Counts[i] = s.Counts[i] - other.Counts[i]
}
return diff
}
151 changes: 151 additions & 0 deletions vec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// Copyright 2026 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0

package goodhistogram

import (
"fmt"
"strings"
"sync"

"github.com/prometheus/client_golang/prometheus"
prometheusgo "github.com/prometheus/client_model/go"
)

// HistogramVec is a collection of Histograms partitioned by label values.
// It implements prometheus.Collector so the entire vec can be registered
// with a Prometheus registry. Recording is done on the individual
// *Histogram returned by WithLabelValues.
type HistogramVec struct {
params Params
desc *prometheus.Desc
labelNames []string

mu struct {
sync.RWMutex
histograms map[string]*labeledHistogram
}
}

type labeledHistogram struct {
h *Histogram
labelPairs []*prometheusgo.LabelPair
}

// NewHistogramVec creates a new HistogramVec. All child histograms share the
// same Params. The desc is created internally from name, help, and labelNames.
func NewHistogramVec(p Params, name, help string, labelNames []string) *HistogramVec {
v := &HistogramVec{
params: p,
desc: prometheus.NewDesc(name, help, labelNames, nil),
labelNames: labelNames,
}
v.mu.histograms = make(map[string]*labeledHistogram)
return v
}

// WithLabelValues returns the Histogram for the given label values,
// creating it if it doesn't exist. Panics if the number of values
// doesn't match the number of label names.
func (v *HistogramVec) WithLabelValues(lvs ...string) *Histogram {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

do we need cardinality protection here?

In CockroachDB, this is a known concern — HighCardinalityHistogram in aggmetric/histogram.go uses cache-based eviction with configurable MaxLabelValues (default 5000). The SQLHistogram similarly has cardinality controls.

Without any limit, a caller passing user-controlled label values (e.g., SQL query fingerprints, user IDs) could cause unbounded memory growth. Consider:

  • Adding a MaxChildren option to HistogramVec with a default cap.
  • Alternatively, documenting that callers must ensure bounded cardinality, since this is a library not directly exposed to user input.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Prometheus doesn't do bounding on cardinality (link), does it feel okay to match that pattern, and push bounding up to the consumers of the library?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ah cool, yeah that sounds fine

if len(lvs) != len(v.labelNames) {
panic(fmt.Sprintf(
"goodhistogram: expected %d label values, got %d",
len(v.labelNames), len(lvs),
))
}
key := strings.Join(lvs, "\xff")

v.mu.RLock()
if lh, ok := v.mu.histograms[key]; ok {
v.mu.RUnlock()
return lh.h
}
v.mu.RUnlock()

v.mu.Lock()
defer v.mu.Unlock()
if lh, ok := v.mu.histograms[key]; ok {
return lh.h
}
h := New(v.params)
v.mu.histograms[key] = &labeledHistogram{
h: h,
labelPairs: makeLabelPairs(v.labelNames, lvs),
}
return h
}

// DeleteLabelValues removes the Histogram for the given label values.
// Returns true if the entry existed. Panics if the number of values
// doesn't match the number of label names.
func (v *HistogramVec) DeleteLabelValues(lvs ...string) bool {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Do we need the same len(lvs) len(v.labelNames) panic/check here as we have in WithLabelValues?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We do! adding it now

if len(lvs) != len(v.labelNames) {
panic(fmt.Sprintf(
"goodhistogram: expected %d label values, got %d",
len(v.labelNames), len(lvs),
))
}
key := strings.Join(lvs, "\xff")
v.mu.Lock()
defer v.mu.Unlock()
_, ok := v.mu.histograms[key]
delete(v.mu.histograms, key)
return ok
}

// Reset removes all child histograms.
func (v *HistogramVec) Reset() {
v.mu.Lock()
defer v.mu.Unlock()
v.mu.histograms = make(map[string]*labeledHistogram)
}

// Describe implements prometheus.Collector.
func (v *HistogramVec) Describe(ch chan<- *prometheus.Desc) {
ch <- v.desc
}

// Collect implements prometheus.Collector.
func (v *HistogramVec) Collect(ch chan<- prometheus.Metric) {
v.mu.RLock()
defer v.mu.RUnlock()
for _, lh := range v.mu.histograms {
ch <- &histogramMetric{
desc: v.desc,
h: lh.h,
labelPairs: lh.labelPairs,
}
}
}

// histogramMetric implements prometheus.Metric for a single labeled histogram.
type histogramMetric struct {
desc *prometheus.Desc
h *Histogram
labelPairs []*prometheusgo.LabelPair
}

func (m *histogramMetric) Desc() *prometheus.Desc { return m.desc }

func (m *histogramMetric) Write(out *prometheusgo.Metric) error {
snap := m.h.Snapshot()
out.Histogram = snap.ToPrometheusHistogram()
out.Label = m.labelPairs
return nil
}

func makeLabelPairs(names, values []string) []*prometheusgo.LabelPair {
pairs := make([]*prometheusgo.LabelPair, len(names))
for i := range names {
n := names[i]
v := values[i]
pairs[i] = &prometheusgo.LabelPair{Name: &n, Value: &v}
}
return pairs
}
Loading
Loading