CodeSampleX

Exemple

go.opentelemetry.io/otel/sdk/metric v1.45.0: metricdata.Sum

Échantillon vérifié pour golang go.opentelemetry.io/otel/sdk/metric v1.45.0: metricdata.Sum. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker…

sha256:35a9d85fb3473323b5debdc25ef42a102c46414b66bf7261a3d4df11b54544cd

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-16

Cas

HOW
Objectif
verify go.opentelemetry.io/otel/sdk/metric/metricdata.Sum in pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.45.0
Paquets
Symboles
  • go.opentelemetry.io/otel/sdk/metric/metricdata.Sum
Environnement
go 1.26
Créé
2026-09-16T09:23:09Z

Contrat

  1. Sum[N int64 | float64] encapsulates aggregated sum data points with temporality and monotonicity
  2. Sum implements Aggregation interface for embedding in Metrics record
  3. Int64Counter collections yield metricdata.Sum[int64] with CumulativeTemporality and IsMonotonic true
  4. Sum support for float64 values with DeltaTemporality and non-monotonic measurements

Fichiers

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • sum.go
  • test/contract_test.go

Télécharger l’artefact source (tar.gz)

Code source

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/sdk/metric/metricdata.Sum in pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.45.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.45.0
Demonstrate these symbols/APIs:
  - go.opentelemetry.io/otel/sdk/metric/metricdata.Sum

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:4618a4300383b199dc5045d009f77c3166987459481a9fecf0826e9c1b5c1329","contract":["Sum[N int64 | float64] encapsulates aggregated sum data points with temporality and monotonicity","Sum implements Aggregation interface for embedding in Metrics record","Int64Counter collections yield metricdata.Sum[int64] with CumulativeTemporality and IsMonotonic true","Sum support for float64 values with DeltaTemporality and non-monotonic measurements"],"goal":"verify go.opentelemetry.io/otel/sdk/metric/metricdata.Sum in pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.45.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.45.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/otel/sdk/metric/metricdata.Sum"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","moduleSystem":"go.mod","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","runtimeVersion":"1.26","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.45.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.45.0","symbols":["go.opentelemetry.io/otel/sdk/metric/metricdata.Sum"],"verifierAdapter":"golang@1"}
go.mod
module example.com/otel-metric-sum

go 1.25.0

require (
	go.opentelemetry.io/otel v1.45.0
	go.opentelemetry.io/otel/metric v1.45.0
	go.opentelemetry.io/otel/sdk/metric v1.45.0
)

require (
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/go-logr/logr v1.4.4 // indirect
	github.com/go-logr/stdr v1.2.2 // indirect
	github.com/google/uuid v1.6.0 // indirect
	go.opentelemetry.io/auto/sdk v1.2.1 // indirect
	go.opentelemetry.io/otel/sdk v1.45.0 // indirect
	go.opentelemetry.io/otel/trace v1.45.0 // indirect
	golang.org/x/sys v0.47.0 // indirect
)
go.sum
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
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.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/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.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
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=
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
go.opentelemetry.io/otel/metric/x v0.67.0 h1:PcicCNZFkZ4bXfSooXdo3WN7RBOVOtjVdo1wD358Uns=
go.opentelemetry.io/otel/metric/x v0.67.0/go.mod h1:FBjCWZe6wgcqxcMtjdGiClDKXb2YxxXii0CXftE4QtI=
go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
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/sdk/metric/metricdata.Sum in pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.45.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.45.0"
  ],
  "symbols": [
    "go.opentelemetry.io/otel/sdk/metric/metricdata.Sum"
  ]
}
sum.go
package sample

import (
	"context"
	"fmt"

	"go.opentelemetry.io/otel/attribute"
	otelmetric "go.opentelemetry.io/otel/metric"
	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/metric/metricdata"
)

// NewInt64CumulativeSum constructs a metricdata.Sum[int64] representing cumulative monotonic sum data points.
func NewInt64CumulativeSum(points []metricdata.DataPoint[int64], isMonotonic bool) metricdata.Sum[int64] {
	return metricdata.Sum[int64]{
		DataPoints:  points,
		Temporality: metricdata.CumulativeTemporality,
		IsMonotonic: isMonotonic,
	}
}

// NewFloat64DeltaSum constructs a metricdata.Sum[float64] representing delta sum data points.
func NewFloat64DeltaSum(points []metricdata.DataPoint[float64], isMonotonic bool) metricdata.Sum[float64] {
	return metricdata.Sum[float64]{
		DataPoints:  points,
		Temporality: metricdata.DeltaTemporality,
		IsMonotonic: isMonotonic,
	}
}

// WrapInMetrics wraps an Aggregation (such as Sum[int64] or Sum[float64]) in a metricdata.Metrics descriptor.
func WrapInMetrics(name, desc, unit string, agg metricdata.Aggregation) metricdata.Metrics {
	return metricdata.Metrics{
		Name:        name,
		Description: desc,
		Unit:        unit,
		Data:        agg,
	}
}

// CollectCounterSum produces metricdata.ResourceMetrics by exercising an Int64Counter via a ManualReader.
func CollectCounterSum(ctx context.Context, counterName string, val int64, attrs ...attribute.KeyValue) (*metricdata.ResourceMetrics, error) {
	reader := sdkmetric.NewManualReader()
	mp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
	defer func() {
		_ = mp.Shutdown(ctx)
	}()

	meter := mp.Meter("example.com/otel-metric-sum")
	counter, err := meter.Int64Counter(counterName)
	if err != nil {
		return nil, fmt.Errorf("failed to create counter: %w", err)
	}

	counter.Add(ctx, val, otelmetric.WithAttributes(attrs...))

	var rm metricdata.ResourceMetrics
	if err := reader.Collect(ctx, &rm); err != nil {
		return nil, fmt.Errorf("failed to collect metrics: %w", err)
	}

	return &rm, nil
}
test/contract_test.go
package test

import (
	"context"
	"testing"
	"time"

	sample "example.com/otel-metric-sum"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/sdk/metric/metricdata"
)

func TestMetricdataSumContract(t *testing.T) {
	ctx := context.Background()
	now := time.Now()

	// 1. Sum[N int64 | float64] encapsulates aggregated sum data points with temporality and monotonicity
	int64Points := []metricdata.DataPoint[int64]{
		{
			Attributes: attribute.NewSet(attribute.String("status", "ok")),
			StartTime:  now.Add(-time.Minute),
			Time:       now,
			Value:      42,
		},
	}
	sumInt64 := sample.NewInt64CumulativeSum(int64Points, true)
	if !sumInt64.IsMonotonic {
		t.Fatal("expected sumInt64.IsMonotonic to be true")
	}
	if sumInt64.Temporality != metricdata.CumulativeTemporality {
		t.Fatalf("expected CumulativeTemporality, got %v", sumInt64.Temporality)
	}
	if len(sumInt64.DataPoints) != 1 || sumInt64.DataPoints[0].Value != 42 {
		t.Fatalf("unexpected data points: %v", sumInt64.DataPoints)
	}

	// 2. Sum implements Aggregation interface for embedding in Metrics record
	metricRecord := sample.WrapInMetrics("requests_total", "Total requests", "1", sumInt64)
	if metricRecord.Name != "requests_total" {
		t.Fatalf("expected metric name requests_total, got %s", metricRecord.Name)
	}
	aggSum, ok := metricRecord.Data.(metricdata.Sum[int64])
	if !ok {
		t.Fatalf("expected metricRecord.Data to be metricdata.Sum[int64], got %T", metricRecord.Data)
	}
	if aggSum.DataPoints[0].Value != 42 {
		t.Fatalf("expected data point value 42, got %d", aggSum.DataPoints[0].Value)
	}

	// 3. Int64Counter collections yield metricdata.Sum[int64] with CumulativeTemporality and IsMonotonic true
	rm, err := sample.CollectCounterSum(ctx, "items_processed_total", 10, attribute.String("env", "prod"))
	if err != nil {
		t.Fatalf("CollectCounterSum failed: %v", err)
	}
	if len(rm.ScopeMetrics) == 0 || len(rm.ScopeMetrics[0].Metrics) == 0 {
		t.Fatal("expected at least one collected metric in ScopeMetrics")
	}
	collectedMetric := rm.ScopeMetrics[0].Metrics[0]
	if collectedMetric.Name != "items_processed_total" {
		t.Fatalf("expected metric name items_processed_total, got %s", collectedMetric.Name)
	}
	sdkSum, ok := collectedMetric.Data.(metricdata.Sum[int64])
	if !ok {
		t.Fatalf("expected collected Data to be metricdata.Sum[int64], got %T", collectedMetric.Data)
	}
	if !sdkSum.IsMonotonic {
		t.Fatal("expected sdkSum to be monotonic for counter")
	}
	if sdkSum.Temporality != metricdata.CumulativeTemporality {
		t.Fatalf("expected CumulativeTemporality for sdkSum, got %v", sdkSum.Temporality)
	}
	if len(sdkSum.DataPoints) != 1 || sdkSum.DataPoints[0].Value != 10 {
		t.Fatalf("expected single data point with value 10, got %v", sdkSum.DataPoints)
	}

	// 4. Sum support for float64 values with DeltaTemporality and non-monotonic measurements
	floatPoints := []metricdata.DataPoint[float64]{
		{
			Attributes: attribute.NewSet(attribute.String("direction", "in")),
			StartTime:  now.Add(-time.Second),
			Time:       now,
			Value:      3.14159,
		},
	}
	sumFloat64 := sample.NewFloat64DeltaSum(floatPoints, false)
	if sumFloat64.IsMonotonic {
		t.Fatal("expected sumFloat64.IsMonotonic to be false")
	}
	if sumFloat64.Temporality != metricdata.DeltaTemporality {
		t.Fatalf("expected DeltaTemporality, got %v", sumFloat64.Temporality)
	}
	if len(sumFloat64.DataPoints) != 1 || sumFloat64.DataPoints[0].Value != 3.14159 {
		t.Fatalf("unexpected float64 data point value: %v", sumFloat64.DataPoints)
	}
	floatRecord := sample.WrapInMetrics("bandwidth_delta", "Delta bandwidth usage", "bytes", sumFloat64)
	aggFloatSum, ok := floatRecord.Data.(metricdata.Sum[float64])
	if !ok {
		t.Fatalf("expected metricRecord.Data to be metricdata.Sum[float64], got %T", floatRecord.Data)
	}
	if aggFloatSum.DataPoints[0].Value != 3.14159 {
		t.Fatalf("expected float64 data point 3.14159, got %f", aggFloatSum.DataPoints[0].Value)
	}
}

Seeder d'origine

anonyme