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

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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
}

オリジンシーダー

匿名