CodeSampleX

샘플

go.opentelemetry.io/otel/metric v1.24.0: WithAttributes

검증된 샘플 — golang go.opentelemetry.io/otel/metric v1.24.0: WithAttributes. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:a8da6655e826184ad3be5a36a48186758d07ff6d5125969adb653a0281f7f157

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 go linux 24 · ubuntu · glibc 2.39 x64 go go go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-03

케이스

HOW
목표
verify go.opentelemetry.io/otel/metric.WithAttributes in pkg:golang/go.opentelemetry.io/otel/metric@v1.24.0
패키지
심벌
  • go.opentelemetry.io/otel/metric.WithAttributes
환경
go
생성일
2026-09-03T13:48:38Z

컨트랙트

  1. metric.WithAttributes returns a MeasurementOption that implements AddOption, RecordOption, and ObserveOption interfaces.
  2. metric.WithAttributes populates Attributes on AddConfig, RecordConfig, and ObserveConfig with the provided key-value pairs.
  3. metric.WithAttributes with no arguments yields an empty attribute set without modifying existing attributes.
  4. metric.WithAttributes makes an internal copy of input attributes ensuring mutation safety and concurrent execution safety.
  5. metric.WithAttributes merges multiple options sequentially where duplicate keys retain the last specified value and distinct keys are combined.
  6. metric.WithAttributes supports recording measurements across synchronous counters, histograms, and asynchronous observer callbacks.

파일

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • with_attributes_test.go

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# OpenTelemetry Metric Attributes (`metric.WithAttributes`)

This sample tests and verifies measurement attribute handling in `go.opentelemetry.io/otel/metric` pinned to release `v1.24.0`.

## Verified Semantics

1. **MeasurementOption Interface Conformance**:
   - `metric.WithAttributes` returns a `MeasurementOption`, which simultaneously satisfies `AddOption`, `RecordOption`, and `ObserveOption`.

2. **Config Attribute Population**:
   - When passed into `NewAddConfig`, `NewRecordConfig`, or `NewObserveConfig`, the key-value attributes are accessible via `.Attributes()`.

3. **Empty Attribute Invocation**:
   - Invoking `metric.WithAttributes()` with no arguments returns an option that maintains an empty attribute set and does not alter previously merged attributes.

4. **Mutation and Concurrency Safety**:
   - `metric.WithAttributes` internally copies slice elements before constructing the attribute set, guarding against subsequent mutations to the input slice and allowing concurrent usage.

5. **Sequential Attribute Merging and Overriding**:
   - Merging multiple `WithAttributes` options combines distinct keys and ensures duplicate keys resolve to the last passed value.

6. **Instrument Measurement Integration**:
   - `metric.WithAttributes` works cleanly with synchronous counter additions, histogram recordings, up-down counter increments/decrements, and asynchronous observer callbacks.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify go.opentelemetry.io/otel/metric.WithAttributes in pkg:golang/go.opentelemetry.io/otel/metric@v1.24.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel/metric@v1.24.0
Demonstrate these symbols/APIs:
  - go.opentelemetry.io/otel/metric.WithAttributes

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:9e8161a6120ee6568663396bc2028df8d07046bc8d7d3a7f971d5da4b7f48281","contract":["metric.WithAttributes returns a MeasurementOption that implements AddOption, RecordOption, and ObserveOption interfaces.","metric.WithAttributes populates Attributes on AddConfig, RecordConfig, and ObserveConfig with the provided key-value pairs.","metric.WithAttributes with no arguments yields an empty attribute set without modifying existing attributes.","metric.WithAttributes makes an internal copy of input attributes ensuring mutation safety and concurrent execution safety.","metric.WithAttributes merges multiple options sequentially where duplicate keys retain the last specified value and distinct keys are combined.","metric.WithAttributes supports recording measurements across synchronous counters, histograms, and asynchronous observer callbacks."],"goal":"verify go.opentelemetry.io/otel/metric.WithAttributes in pkg:golang/go.opentelemetry.io/otel/metric@v1.24.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/metric@v1.24.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/otel/metric.WithAttributes"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/otel/metric@v1.24.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/metric@v1.24.0","symbols":["go.opentelemetry.io/otel/metric.WithAttributes"],"verifierAdapter":"golang@1"}
go.mod
module example.com/metric_attributes

go 1.26.6

require (
	go.opentelemetry.io/otel v1.24.0
	go.opentelemetry.io/otel/metric v1.24.0
)
go.sum
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI=
go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco=
go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI=
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/otel/metric.WithAttributes in pkg:golang/go.opentelemetry.io/otel/metric@v1.24.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/metric@v1.24.0"
  ],
  "symbols": [
    "go.opentelemetry.io/otel/metric.WithAttributes"
  ]
}
with_attributes_test.go
package metric_attributes_test

import (
	"context"
	"sync"
	"testing"

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

// Contract 1: metric.WithAttributes returns a MeasurementOption that implements AddOption, RecordOption, and ObserveOption.
func TestMeasurementOptionInterfaces(t *testing.T) {
	opt := metric.WithAttributes(attribute.String("key", "val"))

	var _ metric.MeasurementOption = opt
	var _ metric.AddOption = opt
	var _ metric.RecordOption = opt
	var _ metric.ObserveOption = opt
}

// Contract 2: metric.WithAttributes populates Attributes on AddConfig, RecordConfig, and ObserveConfig with the provided key-value pairs.
func TestConfigAttributesPopulated(t *testing.T) {
	attr1 := attribute.String("env", "prod")
	attr2 := attribute.Int("version", 2)

	opt := metric.WithAttributes(attr1, attr2)

	// AddConfig
	addCfg := metric.NewAddConfig([]metric.AddOption{opt})
	addAttrs := addCfg.Attributes()
	if addAttrs.Len() != 2 {
		t.Fatalf("expected 2 attributes on AddConfig, got %d", addAttrs.Len())
	}
	val, ok := addAttrs.Value("env")
	if !ok || val.AsString() != "prod" {
		t.Errorf("expected env=prod on AddConfig, got %v (ok=%v)", val, ok)
	}

	// RecordConfig
	recordCfg := metric.NewRecordConfig([]metric.RecordOption{opt})
	recAttrs := recordCfg.Attributes()
	if recAttrs.Len() != 2 {
		t.Fatalf("expected 2 attributes on RecordConfig, got %d", recAttrs.Len())
	}
	val, ok = recAttrs.Value("version")
	if !ok || val.AsInt64() != 2 {
		t.Errorf("expected version=2 on RecordConfig, got %v (ok=%v)", val, ok)
	}

	// ObserveConfig
	obsCfg := metric.NewObserveConfig([]metric.ObserveOption{opt})
	obsAttrs := obsCfg.Attributes()
	if obsAttrs.Len() != 2 {
		t.Fatalf("expected 2 attributes on ObserveConfig, got %d", obsAttrs.Len())
	}
	val, ok = obsAttrs.Value("env")
	if !ok || val.AsString() != "prod" {
		t.Errorf("expected env=prod on ObserveConfig, got %v (ok=%v)", val, ok)
	}
}

// Contract 3: metric.WithAttributes with no arguments yields an empty attribute set without modifying existing attributes.
func TestEmptyAttributes(t *testing.T) {
	emptyOpt := metric.WithAttributes()
	cfg := metric.NewAddConfig([]metric.AddOption{emptyOpt})
	attrs := cfg.Attributes()
	if attrs.Len() != 0 {
		t.Errorf("expected empty attributes, got %d", attrs.Len())
	}

	// Applying empty after existing retains existing
	baseOpt := metric.WithAttributes(attribute.String("service", "billing"))
	mergedCfg := metric.NewAddConfig([]metric.AddOption{baseOpt, emptyOpt})
	mergedAttrs := mergedCfg.Attributes()
	if mergedAttrs.Len() != 1 {
		t.Fatalf("expected 1 attribute retained, got %d", mergedAttrs.Len())
	}
	val, ok := mergedAttrs.Value("service")
	if !ok || val.AsString() != "billing" {
		t.Errorf("expected service=billing retained, got %v", val)
	}
}

// Contract 4: metric.WithAttributes makes an internal copy of input attributes ensuring mutation safety and concurrent execution safety.
func TestMutationAndConcurrencySafety(t *testing.T) {
	src := []attribute.KeyValue{
		attribute.String("region", "us-west"),
		attribute.Int("code", 200),
	}

	opt := metric.WithAttributes(src...)

	// Mutate original slice after passing to WithAttributes
	src[0] = attribute.String("region", "eu-central")
	src[1] = attribute.Int("code", 500)

	cfg := metric.NewRecordConfig([]metric.RecordOption{opt})
	attrs := cfg.Attributes()
	val, ok := attrs.Value("region")
	if !ok || val.AsString() != "us-west" {
		t.Errorf("expected region=us-west (mutation safety), got %v", val)
	}
	val, ok = attrs.Value("code")
	if !ok || val.AsInt64() != 200 {
		t.Errorf("expected code=200 (mutation safety), got %v", val)
	}

	// Concurrent invocations
	var wg sync.WaitGroup
	for i := 0; i < 8; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			o := metric.WithAttributes(src...)
			_ = metric.NewAddConfig([]metric.AddOption{o})
			_ = metric.NewRecordConfig([]metric.RecordOption{o})
			_ = metric.NewObserveConfig([]metric.ObserveOption{o})
		}()
	}
	wg.Wait()
}

// Contract 5: metric.WithAttributes merges multiple options sequentially where duplicate keys retain the last specified value and distinct keys are combined.
func TestSequentialMergingAndDeduplication(t *testing.T) {
	opt1 := metric.WithAttributes(
		attribute.String("tenant", "alpha"),
		attribute.String("status", "pending"),
		attribute.Int("retries", 1),
	)
	opt2 := metric.WithAttributes(
		attribute.String("status", "success"),
		attribute.String("region", "apac"),
	)

	cfg := metric.NewAddConfig([]metric.AddOption{opt1, opt2})
	attrs := cfg.Attributes()

	if attrs.Len() != 4 {
		t.Fatalf("expected 4 attributes after merge, got %d", attrs.Len())
	}

	// Status was overridden by opt2
	val, ok := attrs.Value("status")
	if !ok || val.AsString() != "success" {
		t.Errorf("expected status=success, got %v", val)
	}

	// Tenant from opt1 preserved
	val, ok = attrs.Value("tenant")
	if !ok || val.AsString() != "alpha" {
		t.Errorf("expected tenant=alpha, got %v", val)
	}

	// Region from opt2 included
	val, ok = attrs.Value("region")
	if !ok || val.AsString() != "apac" {
		t.Errorf("expected region=apac, got %v", val)
	}

	// Retries from opt1 preserved
	val, ok = attrs.Value("retries")
	if !ok || val.AsInt64() != 1 {
		t.Errorf("expected retries=1, got %v", val)
	}
}

// Contract 6: metric.WithAttributes works seamlessly when recording measurements on synchronous counters, histograms, and asynchronous gauges.
func TestRecordingMeasurements(t *testing.T) {
	ctx := context.Background()
	provider := noop.NewMeterProvider()
	meter := provider.Meter("test-meter")

	// Counter Add with WithAttributes
	counter, err := meter.Int64Counter("requests_total")
	if err != nil {
		t.Fatalf("unexpected error creating counter: %v", err)
	}
	counter.Add(ctx, 1, metric.WithAttributes(
		attribute.String("endpoint", "/api/v1/resource"),
		attribute.Int("status_code", 200),
	))

	// Histogram Record with WithAttributes
	hist, err := meter.Float64Histogram("latency_seconds")
	if err != nil {
		t.Fatalf("unexpected error creating histogram: %v", err)
	}
	hist.Record(ctx, 0.042, metric.WithAttributes(
		attribute.String("method", "GET"),
	))

	// UpDownCounter Add with WithAttributes
	upDown, err := meter.Int64UpDownCounter("active_connections")
	if err != nil {
		t.Fatalf("unexpected error creating updown counter: %v", err)
	}
	upDown.Add(ctx, -1, metric.WithAttributes(
		attribute.String("pool", "primary"),
	))

	// Gauge Observe callback with WithAttributes
	observed := false
	gauge, err := meter.Int64ObservableGauge("cpu_utilization",
		metric.WithInt64Callback(func(c context.Context, obsrv metric.Int64Observer) error {
			obsrv.Observe(75, metric.WithAttributes(
				attribute.String("core", "0"),
			))
			observed = true
			return nil
		}),
	)
	if err != nil {
		t.Fatalf("unexpected error creating observable gauge: %v", err)
	}
	if gauge == nil {
		t.Fatal("expected gauge to not be nil")
	}

	// Trigger callback via manual Meter callback registration test
	reg, err := meter.RegisterCallback(func(c context.Context, obs metric.Observer) error {
		obs.ObserveInt64(gauge, 80, metric.WithAttributes(attribute.String("core", "1")))
		return nil
	}, gauge)
	if err != nil {
		t.Fatalf("unexpected error registering callback: %v", err)
	}
	_ = reg.Unregister()
	_ = observed
}

오리진 시더

익명