From 6f0bdd705ab0efdc8d1a7e85d15ca10e08778d9e Mon Sep 17 00:00:00 2001 From: Richard Luong Date: Thu, 10 Sep 2026 19:22:55 -0700 Subject: [PATCH] Expose native histograms on Scope Scope.NativeValueHistogram(name) and Scope.NativeDurationHistogram(name) return the native histogram for a name. Both follow Histogram at every site: the lookup-then-create path, the report loop, the cached path, subscope creation, clearMetrics, and the snapshot. Values and durations get separate lookup namespaces rather than separate mutexes or slices. The two variants are views over one accumulator type, so everything past the record call -- draining, reporting, snapshotting -- is identical, and only the create-and-find path needs to know which kind it is holding. A name registered as both yields two accumulators reporting under it, exactly as Counter("x") and Gauge("x") already do; tally does not arbitrate cross-type name collisions and this does not add a new kind of them. Two new ScopeOptions: NativeHistogramFactory supplies the accumulator behind each native histogram on this scope and its subscopes. DefaultNativeHistogramMaxBuckets the bucket budget for every native histogram on this scope. Defaults to DefaultNativeHistogramMaxBuckets, 160. The budget is configured on the scope rather than passed per call. It follows from the encoding and the cost an application has signed up for, which is a deployment-wide decision, and these objects are memoized: the accumulator is built on the first call for a name and every later call returns it, so a per-call budget was silently ignored everywhere except the call that happened to run first. A nil factory falls back to defaultNativeHistogramFactory, so both methods are always safe to call. Without a real factory the metric is counted and never reported, rather than panicking or emitting an empty payload -- an application that has not chosen an encoding has nothing meaningful to put on the wire. Snapshot gains NativeHistograms(), with both variants in the one map the way Histograms() already carries value and duration histograms together. Only the sample count is exposed: the distribution lives in an application-supplied accumulator whose encoding tally does not interpret, so there is nothing generic to show. tally still has no dependency on any histogram implementation. The factory is the entire seam. --- native_histogram_test.go | 254 +++++++++++++++++++++++++++++++++++++++ scope.go | 208 ++++++++++++++++++++++++++++++-- scope_registry.go | 26 ++-- types.go | 19 +++ 4 files changed, 484 insertions(+), 23 deletions(-) diff --git a/native_histogram_test.go b/native_histogram_test.go index deefdd8..5e25a55 100644 --- a/native_histogram_test.go +++ b/native_histogram_test.go @@ -23,6 +23,7 @@ package tally import ( "errors" "fmt" + "strings" "testing" "time" @@ -328,3 +329,256 @@ func TestDefaultNativeHistogramDataIsInert(t *testing.T) { func TestDefaultNativeHistogramMaxBucketsValue(t *testing.T) { assert.Equal(t, 160, DefaultNativeHistogramMaxBuckets) } + +// testNativeHistogramFactory records the bucket budget it is handed for each +// native histogram a scope creates, and hands back accumulators the test can +// inspect. +type testNativeHistogramFactory struct { + maxBuckets []int + data []*testNativeHistogramData +} + +func (f *testNativeHistogramFactory) New(maxBuckets int) NativeHistogramData { + d := newTestNativeHistogramData() + f.maxBuckets = append(f.maxBuckets, maxBuckets) + f.data = append(f.data, d) + return d +} + +// getNativeHistograms mirrors testStatsReporter's other accessors, keying by +// bare metric name. +func (r *testStatsReporter) getNativeHistograms() map[string]*testNativeHistogramValue { + r.mtx.Lock() + defer r.mtx.Unlock() + + dst := make(map[string]*testNativeHistogramValue, len(r.nativeHistograms)) + for k, v := range r.nativeHistograms { + var ( + parts = strings.Split(k, "+") + name string + ) + if len(parts) > 0 { + name = parts[0] + } + + dst[name] = v + } + + return dst +} + +func TestScopeNativeHistogram(t *testing.T) { + r := newTestStatsReporter() + f := &testNativeHistogramFactory{} + + root, closer := NewRootScope(ScopeOptions{ + Reporter: r, + NativeHistogramFactory: f.New, + OmitCardinalityMetrics: true, + }, 0) + defer closer.Close() + + s := root.(*scope) + + r.nhg.Add(2) + s.NativeValueHistogram("payload_bytes").RecordValue(1) + s.NativeDurationHistogram("latency").RecordDuration(2 * time.Second) + + s.report(r) + r.WaitAll() + + bytes := r.getNativeHistograms()["payload_bytes"] + require.NotNil(t, bytes) + assert.Equal(t, []byte("[1]"), bytes.payload) + assert.Equal(t, uint64(1), bytes.samples) + + latency := r.getNativeHistograms()["latency"] + require.NotNil(t, latency) + assert.Equal(t, []byte("[2]"), latency.payload, "durations report as seconds") + assert.Equal(t, uint64(1), latency.samples) +} + +func TestScopeNativeHistogramCachedReporter(t *testing.T) { + r := newTestStatsReporter() + f := &testNativeHistogramFactory{} + + root, closer := NewRootScope(ScopeOptions{ + CachedReporter: r, + NativeHistogramFactory: f.New, + OmitCardinalityMetrics: true, + }, 0) + defer closer.Close() + + s := root.(*scope) + + r.nhg.Add(1) + s.NativeValueHistogram("latency").RecordValue(42) + + s.cachedReport() + r.WaitAll() + + nh := r.getNativeHistograms()["latency"] + require.NotNil(t, nh) + assert.Equal(t, []byte("[42]"), nh.payload) + assert.Equal(t, uint64(1), nh.samples) +} + +func TestScopeNativeHistogramMaxBuckets(t *testing.T) { + tests := []struct { + name string + scopeMax int + expectedTo int + }{ + { + name: "an unset scope default falls back to the package default", + expectedTo: DefaultNativeHistogramMaxBuckets, + }, + { + name: "a configured scope default is honoured", + scopeMax: 64, + expectedTo: 64, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := &testNativeHistogramFactory{} + + root, closer := NewRootScope(ScopeOptions{ + Reporter: NullStatsReporter, + NativeHistogramFactory: f.New, + DefaultNativeHistogramMaxBuckets: tt.scopeMax, + OmitCardinalityMetrics: true, + }, 0) + defer closer.Close() + + root.NativeValueHistogram("payload_bytes") + root.NativeDurationHistogram("latency") + + require.Equal(t, 2, len(f.maxBuckets)) + assert.Equal(t, tt.expectedTo, f.maxBuckets[0]) + assert.Equal(t, tt.expectedTo, f.maxBuckets[1], + "both variants honour the same budget") + }) + } +} + +// A scope with no NativeHistogramFactory must stay usable: values are counted +// but nothing is ever reported. +func TestScopeNativeHistogramWithoutFactory(t *testing.T) { + r := newTestStatsReporter() + + root, closer := NewRootScope(ScopeOptions{ + Reporter: r, + OmitCardinalityMetrics: true, + }, 0) + defer closer.Close() + + s := root.(*scope) + + values := s.NativeValueHistogram("payload_bytes").(nativeValueHistogram) + durations := s.NativeDurationHistogram("latency").(nativeDurationHistogram) + values.RecordValue(1) + durations.RecordDuration(time.Second) + + require.Equal(t, uint64(1), values.snapshot(), "values are counted") + require.Equal(t, uint64(1), durations.snapshot()) + + s.report(r) + r.WaitAll() + + assert.Empty(t, r.getNativeHistograms(), "but nothing is reported") + assert.Equal(t, uint64(0), values.snapshot(), "and the failed marshal clears") + assert.Equal(t, uint64(0), durations.snapshot()) +} + +func TestScopeNativeHistogramSubscopesInheritFactory(t *testing.T) { + r := newTestStatsReporter() + f := &testNativeHistogramFactory{} + + root, closer := NewRootScope(ScopeOptions{ + Reporter: r, + NativeHistogramFactory: f.New, + DefaultNativeHistogramMaxBuckets: 64, + OmitCardinalityMetrics: true, + }, 0) + defer closer.Close() + + sub := root.SubScope("requests").Tagged(map[string]string{"env": "test"}) + + r.nhg.Add(1) + sub.NativeValueHistogram("latency").RecordValue(7) + + root.(*scope).registry.Report(r) + r.WaitAll() + + require.Equal(t, 1, len(f.maxBuckets)) + assert.Equal(t, 64, f.maxBuckets[0], "subscope inherits the scope default") + + nh := r.getNativeHistograms()["requests.latency"] + require.NotNil(t, nh) + assert.Equal(t, []byte("[7]"), nh.payload) + assert.Equal(t, uint64(1), nh.samples) + assert.Equal(t, map[string]string{"env": "test"}, nh.tags) +} + +func TestScopeNativeHistogramReturnsSameInstance(t *testing.T) { + f := &testNativeHistogramFactory{} + + root, closer := NewRootScope(ScopeOptions{ + Reporter: NullStatsReporter, + NativeHistogramFactory: f.New, + OmitCardinalityMetrics: true, + }, 0) + defer closer.Close() + + first := root.NativeValueHistogram("latency") + second := root.NativeValueHistogram("latency") + + assert.Equal(t, first, second) + assert.Equal(t, 1, len(f.maxBuckets), "the accumulator is only built once") +} + +// Values and durations are separate metrics, so one name in both yields two +// accumulators -- and two payloads reported under that name, the same way +// Counter("x") and Gauge("x") already both report as x. +func TestScopeNativeHistogramVariantsAreSeparateMetrics(t *testing.T) { + f := &testNativeHistogramFactory{} + + root, closer := NewRootScope(ScopeOptions{ + Reporter: NullStatsReporter, + NativeHistogramFactory: f.New, + OmitCardinalityMetrics: true, + }, 0) + defer closer.Close() + + root.NativeValueHistogram("latency").RecordValue(1) + root.NativeDurationHistogram("latency").RecordDuration(time.Second) + + require.Equal(t, 2, len(f.maxBuckets), "one accumulator per variant") + require.Equal(t, 2, len(f.data)) + assert.Equal(t, []float64{1}, f.data[0].values) + assert.Equal(t, []float64{1}, f.data[1].values, + "a second of duration, not the raw value") +} + +func TestScopeNativeHistogramSnapshot(t *testing.T) { + s := NewTestScope("prefix", map[string]string{"env": "test"}) + + s.NativeDurationHistogram("latency").RecordDuration(time.Second) + s.NativeDurationHistogram("latency").RecordDuration(2 * time.Second) + s.NativeValueHistogram("other").RecordValue(3) + + snap := s.Snapshot().NativeHistograms() + require.Equal(t, 2, len(snap), "both variants land in the one map") + + latency := snap[KeyForPrefixedStringMap("prefix.latency", map[string]string{"env": "test"})] + require.NotNil(t, latency) + assert.Equal(t, "prefix.latency", latency.Name()) + assert.Equal(t, map[string]string{"env": "test"}, latency.Tags()) + assert.Equal(t, uint64(2), latency.Samples()) + + other := snap[KeyForPrefixedStringMap("prefix.other", map[string]string{"env": "test"})] + require.NotNil(t, other) + assert.Equal(t, uint64(1), other.Samples()) +} diff --git a/scope.go b/scope.go index 733cd4e..0f9893b 100644 --- a/scope.go +++ b/scope.go @@ -70,12 +70,16 @@ type scope struct { defaultBuckets Buckets sanitizer Sanitizer + nativeHistogramFactory func(maxBuckets int) NativeHistogramData + defaultNativeHistogramMaxBucket int + registry *scopeRegistry - cm sync.RWMutex - gm sync.RWMutex - tm sync.RWMutex - hm sync.RWMutex + cm sync.RWMutex + gm sync.RWMutex + tm sync.RWMutex + hm sync.RWMutex + nhm sync.RWMutex counters map[string]*counter countersSlice []*counter @@ -83,7 +87,13 @@ type scope struct { gaugesSlice []*gauge histograms map[string]*histogram histogramsSlice []*histogram - timers map[string]*timer + // Values and durations are separate metrics, so they get separate lookup + // namespaces. The slice is shared: the cached report path walks + // accumulators and never needs to know which kind produced one. + nativeValueHistograms map[string]*nativeHistogram + nativeDurationHistograms map[string]*nativeHistogram + nativeHistogramsSlice []*nativeHistogram + timers map[string]*timer // nb: deliberately skipping timersSlice as we report timers immediately, // no buffering is involved. @@ -107,6 +117,17 @@ type ScopeOptions struct { OmitCardinalityMetrics bool CardinalityMetricsTags map[string]string + // NativeHistogramFactory supplies the accumulator backing each native + // histogram created on this scope and its subscopes. Leaving it nil makes + // the native histogram methods safe to call, but values are merely counted and + // never reported. + NativeHistogramFactory func(maxBuckets int) NativeHistogramData + + // DefaultNativeHistogramMaxBuckets is the bucket budget for every native + // histogram created on this scope and its subscopes. Defaults to + // DefaultNativeHistogramMaxBuckets. + DefaultNativeHistogramMaxBuckets int + testScope bool registryShardCount uint } @@ -163,6 +184,13 @@ func newRootScope(opts ScopeOptions, interval time.Duration) *scope { opts.DefaultBuckets = defaultScopeBuckets } + if opts.NativeHistogramFactory == nil { + opts.NativeHistogramFactory = defaultNativeHistogramFactory + } + if opts.DefaultNativeHistogramMaxBuckets < 1 { + opts.DefaultNativeHistogramMaxBuckets = DefaultNativeHistogramMaxBuckets + } + s := &scope{ baseReporter: baseReporter, bucketCache: newBucketCache(), @@ -182,6 +210,12 @@ func newRootScope(opts ScopeOptions, interval time.Duration) *scope { timers: make(map[string]*timer), root: true, testScope: opts.testScope, + + nativeHistogramFactory: opts.NativeHistogramFactory, + defaultNativeHistogramMaxBucket: opts.DefaultNativeHistogramMaxBuckets, + nativeValueHistograms: make(map[string]*nativeHistogram), + nativeDurationHistograms: make(map[string]*nativeHistogram), + nativeHistogramsSlice: make([]*nativeHistogram, 0, _defaultInitialSliceSize), } // NB(r): Take a copy of the tags on creation @@ -223,6 +257,15 @@ func (s *scope) report(r StatsReporter) { histogram.report(s.fullyQualifiedName(name), s.tags, r) } s.hm.RUnlock() + + s.nhm.RLock() + for name, nativeHistogram := range s.nativeValueHistograms { + nativeHistogram.report(s.fullyQualifiedName(name), s.tags, r) + } + for name, nativeHistogram := range s.nativeDurationHistograms { + nativeHistogram.report(s.fullyQualifiedName(name), s.tags, r) + } + s.nhm.RUnlock() } func (s *scope) cachedReport() { @@ -245,6 +288,12 @@ func (s *scope) cachedReport() { histogram.cachedReport() } s.hm.RUnlock() + + s.nhm.RLock() + for _, nativeHistogram := range s.nativeHistogramsSlice { + nativeHistogram.cachedReport() + } + s.nhm.RUnlock() } // reportLoop is used by the root scope for periodic reporting @@ -438,6 +487,67 @@ func (s *scope) histogram(sanitizedName string) (Histogram, bool) { return h, ok } +func (s *scope) NativeValueHistogram(name string) NativeValueHistogram { + return nativeValueHistogram{ + s.nativeHistogram(s.nativeValueHistograms, name), + } +} + +func (s *scope) NativeDurationHistogram(name string) NativeDurationHistogram { + return nativeDurationHistogram{ + s.nativeHistogram(s.nativeDurationHistograms, name), + } +} + +// nativeHistogram returns the accumulator registered under name in kind, +// creating it if this is the first call. Callers wrap it in the variant that +// matches the map they passed. +func (s *scope) nativeHistogram( + kind map[string]*nativeHistogram, + name string, +) *nativeHistogram { + name = s.sanitizer.Name(name) + if h, ok := s.lookupNativeHistogram(kind, name); ok { + return h + } + + s.nhm.Lock() + defer s.nhm.Unlock() + + if h, ok := kind[name]; ok { + return h + } + + maxBuckets := s.defaultNativeHistogramMaxBucket + + var cachedNativeHistogram CachedNativeHistogram + if s.cachedReporter != nil { + cachedNativeHistogram = s.cachedReporter.AllocateNativeHistogram( + s.fullyQualifiedName(name), s.tags, maxBuckets, + ) + } + + h := newNativeHistogram( + s.nativeHistogramFactory(maxBuckets), + cachedNativeHistogram, + ) + kind[name] = h + s.nativeHistogramsSlice = append(s.nativeHistogramsSlice, h) + + return h +} + +func (s *scope) lookupNativeHistogram( + kind map[string]*nativeHistogram, + sanitizedName string, +) (*nativeHistogram, bool) { + s.nhm.RLock() + defer s.nhm.RUnlock() + + h, ok := kind[sanitizedName] + return h, ok +} + func (s *scope) Tagged(tags map[string]string) Scope { return s.subscope(s.prefix, tags) } @@ -513,6 +623,22 @@ func (s *scope) Snapshot() Snapshot { } } ss.hm.RUnlock() + ss.nhm.RLock() + for _, kind := range []map[string]*nativeHistogram{ + ss.nativeValueHistograms, + ss.nativeDurationHistograms, + } { + for key, h := range kind { + name := ss.fullyQualifiedName(key) + id := KeyForPrefixedStringMap(name, tags) + snap.nativeHistograms[id] = &nativeHistogramSnapshot{ + name: name, + tags: tags, + samples: h.snapshot(), + } + } + } + ss.nhm.RUnlock() }) return snap @@ -542,10 +668,12 @@ func (s *scope) clearMetrics() { s.gm.Lock() s.tm.Lock() s.hm.Lock() + s.nhm.Lock() defer s.cm.Unlock() defer s.gm.Unlock() defer s.tm.Unlock() defer s.hm.Unlock() + defer s.nhm.Unlock() for k := range s.counters { delete(s.counters, k) @@ -565,6 +693,15 @@ func (s *scope) clearMetrics() { delete(s.histograms, k) } s.histogramsSlice = nil + + for k := range s.nativeValueHistograms { + delete(s.nativeValueHistograms, k) + } + + for k := range s.nativeDurationHistograms { + delete(s.nativeDurationHistograms, k) + } + s.nativeHistogramsSlice = nil } // NB(prateek): We assume concatenation of sanitized inputs is @@ -615,6 +752,10 @@ type Snapshot interface { // Histograms returns a snapshot of histogram samples since last report execution Histograms() map[string]HistogramSnapshot + + // NativeHistograms returns a snapshot of native histogram sample counts + // since last report execution + NativeHistograms() map[string]NativeHistogramSnapshot } // CounterSnapshot is a snapshot of a counter @@ -668,6 +809,23 @@ type HistogramSnapshot interface { Durations() map[time.Duration]int64 } +// NativeHistogramSnapshot is a snapshot of a native histogram. +// +// Only the sample count is exposed: the distribution itself lives in an +// application-supplied NativeHistogramData whose encoding tally does not +// interpret. +type NativeHistogramSnapshot interface { + // Name returns the name + Name() string + + // Tags returns the tags + Tags() map[string]string + + // Samples returns the number of values accumulated since last report + // execution + Samples() uint64 +} + // mergeRightTags merges 2 sets of tags with the tags from tagsRight overriding values from tagsLeft func mergeRightTags(tagsLeft, tagsRight map[string]string) map[string]string { if tagsLeft == nil && tagsRight == nil { @@ -691,18 +849,20 @@ func mergeRightTags(tagsLeft, tagsRight map[string]string) map[string]string { } type snapshot struct { - counters map[string]CounterSnapshot - gauges map[string]GaugeSnapshot - timers map[string]TimerSnapshot - histograms map[string]HistogramSnapshot + counters map[string]CounterSnapshot + gauges map[string]GaugeSnapshot + timers map[string]TimerSnapshot + histograms map[string]HistogramSnapshot + nativeHistograms map[string]NativeHistogramSnapshot } func newSnapshot() *snapshot { return &snapshot{ - counters: make(map[string]CounterSnapshot), - gauges: make(map[string]GaugeSnapshot), - timers: make(map[string]TimerSnapshot), - histograms: make(map[string]HistogramSnapshot), + counters: make(map[string]CounterSnapshot), + gauges: make(map[string]GaugeSnapshot), + timers: make(map[string]TimerSnapshot), + histograms: make(map[string]HistogramSnapshot), + nativeHistograms: make(map[string]NativeHistogramSnapshot), } } @@ -722,6 +882,10 @@ func (s *snapshot) Histograms() map[string]HistogramSnapshot { return s.histograms } +func (s *snapshot) NativeHistograms() map[string]NativeHistogramSnapshot { + return s.nativeHistograms +} + type counterSnapshot struct { name string tags map[string]string @@ -798,3 +962,21 @@ func (s *histogramSnapshot) Values() map[float64]int64 { func (s *histogramSnapshot) Durations() map[time.Duration]int64 { return s.durations } + +type nativeHistogramSnapshot struct { + name string + tags map[string]string + samples uint64 +} + +func (s *nativeHistogramSnapshot) Name() string { + return s.name +} + +func (s *nativeHistogramSnapshot) Tags() map[string]string { + return s.tags +} + +func (s *nativeHistogramSnapshot) Samples() uint64 { + return s.samples +} diff --git a/scope_registry.go b/scope_registry.go index 1692829..f59ea2f 100644 --- a/scope_registry.go +++ b/scope_registry.go @@ -247,16 +247,22 @@ func (r *scopeRegistry) Subscope(parent *scope, prefix string, tags map[string]s sanitizer: parent.sanitizer, registry: parent.registry, - counters: make(map[string]*counter), - countersSlice: make([]*counter, 0, _defaultInitialSliceSize), - gauges: make(map[string]*gauge), - gaugesSlice: make([]*gauge, 0, _defaultInitialSliceSize), - histograms: make(map[string]*histogram), - histogramsSlice: make([]*histogram, 0, _defaultInitialSliceSize), - timers: make(map[string]*timer), - bucketCache: parent.bucketCache, - done: make(chan struct{}), - testScope: parent.testScope, + nativeHistogramFactory: parent.nativeHistogramFactory, + defaultNativeHistogramMaxBucket: parent.defaultNativeHistogramMaxBucket, + + counters: make(map[string]*counter), + countersSlice: make([]*counter, 0, _defaultInitialSliceSize), + gauges: make(map[string]*gauge), + gaugesSlice: make([]*gauge, 0, _defaultInitialSliceSize), + histograms: make(map[string]*histogram), + histogramsSlice: make([]*histogram, 0, _defaultInitialSliceSize), + nativeValueHistograms: make(map[string]*nativeHistogram), + nativeDurationHistograms: make(map[string]*nativeHistogram), + nativeHistogramsSlice: make([]*nativeHistogram, 0, _defaultInitialSliceSize), + timers: make(map[string]*timer), + bucketCache: parent.bucketCache, + done: make(chan struct{}), + testScope: parent.testScope, } subscopeBucket.s[sanitizedKey] = subscope if _, ok := r.lockedLookup(subscopeBucket, unsanitizedKey); !ok { diff --git a/types.go b/types.go index e51c4b4..778a20d 100644 --- a/types.go +++ b/types.go @@ -54,6 +54,25 @@ type Scope interface { // You can use tally.MustMakeExponentialDurationBuckets(start, factor, count) for exponential durations. Histogram(name string, buckets Buckets) Histogram + // NativeValueHistogram returns the NativeValueHistogram object + // corresponding to the name. + // + // Unlike Histogram, bucket boundaries are derived from the observations + // rather than declared up front, and the distribution is reported as a + // single serialized payload. The bucket budget is + // ScopeOptions.DefaultNativeHistogramMaxBuckets. Requires + // ScopeOptions.NativeHistogramFactory to be set; without it the metric + // accumulates but is never reported. + NativeValueHistogram(name string) NativeValueHistogram + + // NativeDurationHistogram is NativeValueHistogram for durations, which it + // records as seconds. + // + // Durations are a separate metric from values, not another way to write to + // the same one, so a name used for both yields two distributions reported + // under it -- as Counter and Gauge already do. + NativeDurationHistogram(name string) NativeDurationHistogram + // Tagged returns a new child scope with the given tags and current tags. Tagged(tags map[string]string) Scope