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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
Set `OTEL_GO_X_METRIC_EXPORT_BATCH_SIZE=<max_size>` to enable for all periodic readers.
See `go.opentelemetry.io/otel/sdk/metric/internal/x` for feature documentation. (#8071)
- Add `WithDefaultAttributes` to `go.opentelemetry.io/otel/metric/x` to support setting default attributes on instruments. (#8135)
- Add `Resettable` to `go.opentelemetry.io/otel/metric/x` to allow reusing attribute options. (#8178)

### Changed

Expand Down
11 changes: 11 additions & 0 deletions attribute/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ func hashKVs(kvs []KeyValue) uint64 {
return h.Sum64()
}

// hashKVsWithFilter returns a new xxHash64 hash of kvs, applying the filter.
func hashKVsWithFilter(kvs []KeyValue, filter Filter) uint64 {
h := xxhash.New()
for _, kv := range kvs {
if filter(kv) {
h = hashKV(h, kv)
}
}
return h.Sum64()
}

// hashKV returns the xxHash64 hash of kv with h as the base.
func hashKV(h xxhash.Hash, kv KeyValue) xxhash.Hash {
h = h.String(string(kv.Key))
Expand Down
55 changes: 55 additions & 0 deletions attribute/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,61 @@ func NewSet(kvs ...KeyValue) Set {
return s
}

// SortAndDedup sorts and de-duplicates the passed attributes in-place.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

is this called in hot path, when when using WithUnsafeAttributes API?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes. Because we don't every copy the slice, I have to sort and dedup within the WithUnsafeAttributes function to avoid concurrent modification of the slice later when it is used or re-used.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Given that sort+dedup still has to run on every call, does WithUnsafeAttributes provide enough of a performance boost over the existing API to warrant new public API surface (especially one with "Unsafe" semantics)?

For reference, both the .NET and Rust OTel SDKs achieve zero-allocation, zero-sort hot paths without any new API — the optimization is entirely internal to the SDK. The approach: store each attribute combination in the hashmap under two keys — one in the caller-provided order and one in sorted+deduped order. Since a given callsite almost always passes attributes in the same order, the unsorted lookup hits, skipping sort+dedup entirely. The sorted lookup only kicks in on a miss (i.e new KV slice never seen before), and the extra map entry per unique combination is likely negligible overhead.

A similar approach in Go could deliver the same (or better) performance gains through the existing WithAttributes path itself.

(I am not very familiar with Go implementation, so feel free to discard if this is not applicable/feasible)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Right now, WithAttributes makes a copy of the provided attributes for safety. If a user provides a slice of attributes today using WithAttributes, it is safe for them to modify the slice afterwards without issue. I've opted to call it WithUnsafeAttributes to indicate that it is no longer safe for users to modify the slice of attributes passed to the option. We could have adopted that stance from the beginning, and we wouldn't need to introduce a second option.

Your point about being able to skip sort + dedup is a good one. We could definitely implement that to provide a further speed-up. The cost of sorting + deduping doesn't seem to be too substantial (sorting + deduping + hashing seems to take ~30ns at 10 attributes). I've focused this PoC primarily on avoiding allocations.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The dual-insertion approach would also avoid allocations on the hot path — the SDK can hash the incoming slice as-is (no copy, no sort) and look up in the sync.Map. Only on a miss does it need to sort, dedup, and copy. So it gives you both: zero allocation and zero sort, using the existing WithAttributes API.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Because of how our options pattern works, we can't do that without changing our safety guarantees around WithAttributes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah! Got it. (Thanks for explaining this!)

// Duplicate keys are eliminated by taking the last value.
// It returns the slice containing the unique attributes.
func SortAndDedup(kvs []KeyValue) []KeyValue {
if len(kvs) == 0 {
return kvs
}

// Stable sort so the following de-duplication can implement
// last-value-wins semantics.
slices.SortStableFunc(kvs, func(a, b KeyValue) int {
return cmp.Compare(a.Key, b.Key)
})

position := len(kvs) - 1
offset := position - 1

// De-duplicate with last-value-wins semantics.
for ; offset >= 0; offset-- {
if kvs[offset].Key == kvs[position].Key {
continue
}
position--
kvs[offset], kvs[position] = kvs[position], kvs[offset]
}
return kvs[position:]
}

// NewDistinctFromSorted returns a Distinct identifier for the passed attributes.
// The passed attributes must already be sorted and de-duplicated.
func NewDistinctFromSorted(kvs []KeyValue) Distinct {
if len(kvs) == 0 {
return Distinct{hash: emptySet.hash}
}
return Distinct{hash: hashKVs(kvs)}
}

// NewDistinctFromSortedWithFilter returns a Distinct identifier for the passed attributes,
// applying the filter to ignore attributes that don't pass.
// The passed attributes must already be sorted and de-duplicated.
func NewDistinctFromSortedWithFilter(kvs []KeyValue, filter Filter) Distinct {
if len(kvs) == 0 || filter == nil {
return NewDistinctFromSorted(kvs)
}
return Distinct{hash: hashKVsWithFilter(kvs, filter)}
}

// NewDistinct returns a Distinct identifier for the passed attributes.
// It may modify the passed slice to sort and de-duplicate the attributes.
// Duplicate keys are eliminated by taking the last value.
func NewDistinct(kvs []KeyValue) Distinct {
kvs = SortAndDedup(kvs)
return NewDistinctFromSorted(kvs)
}

// NewSetWithSortable returns a new Set. See the documentation for
// NewSetWithSortableFiltered for more details.
//
Expand Down
43 changes: 43 additions & 0 deletions attribute/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -599,3 +599,46 @@ func BenchmarkNewSetStringAttrs(b *testing.B) {
})
}
}

func TestNewDistinct(t *testing.T) {
cases := []struct {
name string
kvs []attribute.KeyValue
}{
{
name: "empty",
kvs: nil,
},
{
name: "unique",
kvs: []attribute.KeyValue{attribute.String("A", "B"), attribute.String("C", "D")},
},
{
name: "duplicate",
kvs: []attribute.KeyValue{attribute.String("A", "B"), attribute.String("A", "C")},
},
{
name: "mixed",
kvs: []attribute.KeyValue{
attribute.String("C", "D"),
attribute.String("A", "B"),
attribute.String("A", "C"),
},
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
kvsCopy1 := make([]attribute.KeyValue, len(tc.kvs))
copy(kvsCopy1, tc.kvs)

kvsCopy2 := make([]attribute.KeyValue, len(tc.kvs))
copy(kvsCopy2, tc.kvs)

distinct := attribute.NewDistinct(kvsCopy1)
set := attribute.NewSet(kvsCopy2...)

assert.Equal(t, set.Equivalent(), distinct, "Distinct should match Set.Equivalent()")
})
}
}
14 changes: 9 additions & 5 deletions metric/instrument.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,10 @@ type attrOpt struct {
set attribute.Set
}

func (o *attrOpt) Reset(set attribute.Set) {
o.set = set
}

// mergeSets returns the union of keys between a and b. Any duplicate keys will
// use the value associated with b.
func mergeSets(a, b attribute.Set) attribute.Set {
Expand All @@ -322,7 +326,7 @@ func mergeSets(a, b attribute.Set) attribute.Set {
return attribute.NewSet(merged...)
}

func (o attrOpt) applyAdd(c AddConfig) AddConfig {
func (o *attrOpt) applyAdd(c AddConfig) AddConfig {
switch {
case o.set.Len() == 0:
case c.attrs.Len() == 0:
Expand All @@ -333,7 +337,7 @@ func (o attrOpt) applyAdd(c AddConfig) AddConfig {
return c
}

func (o attrOpt) applyRecord(c RecordConfig) RecordConfig {
func (o *attrOpt) applyRecord(c RecordConfig) RecordConfig {
switch {
case o.set.Len() == 0:
case c.attrs.Len() == 0:
Expand All @@ -344,7 +348,7 @@ func (o attrOpt) applyRecord(c RecordConfig) RecordConfig {
return c
}

func (o attrOpt) applyObserve(c ObserveConfig) ObserveConfig {
func (o *attrOpt) applyObserve(c ObserveConfig) ObserveConfig {
switch {
case o.set.Len() == 0:
case c.attrs.Len() == 0:
Expand All @@ -362,7 +366,7 @@ func (o attrOpt) applyObserve(c ObserveConfig) ObserveConfig {
// attributes will be merged together in the order they are passed. Attributes
// with duplicate keys will use the last value passed.
func WithAttributeSet(attributes attribute.Set) MeasurementOption {
return attrOpt{set: attributes}
return &attrOpt{set: attributes}
}

// WithAttributes converts attributes into an attribute Set and sets the Set to
Expand All @@ -383,5 +387,5 @@ func WithAttributeSet(attributes attribute.Set) MeasurementOption {
func WithAttributes(attributes ...attribute.KeyValue) MeasurementOption {
cp := make([]attribute.KeyValue, len(attributes))
copy(cp, attributes)
return attrOpt{set: attribute.NewSet(cp...)}
return &attrOpt{set: attribute.NewSet(cp...)}
}
32 changes: 32 additions & 0 deletions metric/instrument_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"go.opentelemetry.io/otel/attribute"
)
Expand Down Expand Up @@ -127,3 +128,34 @@ func TestWithAttributesConcurrentSafe(*testing.T) {

wg.Wait()
}

func TestResettableOptions(t *testing.T) {
type resettable interface {
Reset(attribute.Set)
}

aliceAttr := attribute.String("user", "Alice")
alice := attribute.NewSet(aliceAttr)
bobAttr := attribute.String("user", "Bob")
bob := attribute.NewSet(bobAttr)

t.Run("WithAttributeSet", func(t *testing.T) {
opt := WithAttributeSet(alice)
r, ok := opt.(resettable)
require.True(t, ok, "WithAttributeSet option does not implement resettable")

r.Reset(bob)
c := NewAddConfig([]AddOption{opt.(AddOption)})
assert.Equal(t, bob, c.Attributes())
})

t.Run("WithAttributes", func(t *testing.T) {
opt := WithAttributes(aliceAttr)
r, ok := opt.(resettable)
require.True(t, ok, "WithAttributes option does not implement resettable")

r.Reset(bob)
c := NewAddConfig([]AddOption{opt.(AddOption)})
assert.Equal(t, bob, c.Attributes())
})
}
8 changes: 7 additions & 1 deletion metric/x/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,17 @@ module go.opentelemetry.io/otel/metric/x
go 1.25.0

require (
github.com/stretchr/testify v1.11.1
go.opentelemetry.io/otel v1.43.0
go.opentelemetry.io/otel/metric v1.43.0
)

require github.com/cespare/xxhash/v2 v2.3.0 // indirect
require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

replace go.opentelemetry.io/otel/metric => ../../metric

Expand Down
2 changes: 2 additions & 0 deletions metric/x/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
53 changes: 53 additions & 0 deletions metric/x/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,56 @@ func (o defaultAttributesOption) AllowedKeys() []attribute.Key {
func WithDefaultAttributes(keys ...attribute.Key) metric.InstrumentOption {
return defaultAttributesOption{keys: keys}
}

type unsafeAttributesOption struct {
metric.MeasurementOption
kvs []attribute.KeyValue
}

// Experimental prevents the API from panicking when the option is used.
func (*unsafeAttributesOption) Experimental() {}

// RawAttributes returns the raw key-values associated with the option.
func (o *unsafeAttributesOption) RawAttributes() []attribute.KeyValue {
return o.kvs
}

// Reset resets the attributes.
func (o *unsafeAttributesOption) Reset(kvs []attribute.KeyValue) {
o.kvs = kvs
}

// WithUnsafeAttributes returns a metric.MeasurementOption that stores the raw attributes
// and associates them with a measurement without making a copy.
// The caller must not modify the attributes slice after passing it to this function.
func WithUnsafeAttributes(kvs ...attribute.KeyValue) metric.MeasurementOption {
kvs = attribute.SortAndDedup(kvs)
return &unsafeAttributesOption{kvs: kvs}
}

// Resettable is an optional interface that Options can implement
// to allow reuse without additional allocations.
//
// Example usage with sync.Pool:
//
// var optionPool = sync.Pool{
// New: func() any {
// return metric.WithAttributeSet(*attribute.EmptySet())
// },
// }
//
// func record(ctx context.Context, counter metric.Int64Counter, set attribute.Set) {
// opt := optionPool.Get().(metric.MeasurementOption)
// defer optionPool.Put(opt)
//
// if r, ok := opt.(x.Resettable[attribute.Set]); ok {
// r.Reset(set)
// }
// counter.Add(ctx, 1, opt)
// }
//
// WARNING: It is the user's responsibility to ensure that the option is not
// concurrently reset while being passed to the API or used by another goroutine.
type Resettable[T any] interface {
Reset(T)
}
21 changes: 21 additions & 0 deletions metric/x/options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package x

import (
"testing"

"github.com/stretchr/testify/assert"

"go.opentelemetry.io/otel/attribute"
)

func TestWithUnsafeAttributes(t *testing.T) {
kvs := []attribute.KeyValue{attribute.String("A", "B")}
opt := WithUnsafeAttributes(kvs...)

unsafeOpt, ok := opt.(*unsafeAttributesOption)
assert.True(t, ok, "expected *unsafeAttributesOption")
assert.Equal(t, kvs, unsafeOpt.RawAttributes(), "expected stored attributes to match")
}
Loading
Loading