CodeSampleX

Пример

go.opentelemetry.io/proto/otlp v1.9.0: v1.Gauge

Проверенный пример — golang go.opentelemetry.io/proto/otlp v1.9.0: v1.Gauge. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:7d417186ae5650d5debb77321139784268c6fa5602b14870c7dbb3b9113f4af3

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 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-05

Кейс

HOW
Цель
verify go.opentelemetry.io/proto/otlp/metrics/v1.Gauge in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
Пакеты
Символы
  • go.opentelemetry.io/proto/otlp/metrics/v1.Gauge
Создан
2026-09-05T19:23:54Z

Контракт

  1. Gauge GetDataPoints returns empty slice when initialized without data points
  2. Gauge holds NumberDataPoints recording floating point measurements with timestamps
  3. Gauge holds NumberDataPoints recording integer measurements with key-value attributes
  4. Metric GetData returns Metric_Gauge wrapper and GetGauge provides underlying Gauge
  5. Metric GetGauge returns nil when metric contains non-gauge data
  6. Gauge Reset clears all recorded data points
  7. Gauge marshals and unmarshals with protobuf binary wire format preserving data points

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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/proto/otlp/metrics/v1.Gauge in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
Demonstrate these symbols/APIs:
  - go.opentelemetry.io/proto/otlp/metrics/v1.Gauge

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:36a925b22ffb2588dd3bcd714dec361d4bb787f60c64d267f45c22879aee26f7","contract":["Gauge GetDataPoints returns empty slice when initialized without data points","Gauge holds NumberDataPoints recording floating point measurements with timestamps","Gauge holds NumberDataPoints recording integer measurements with key-value attributes","Metric GetData returns Metric_Gauge wrapper and GetGauge provides underlying Gauge","Metric GetGauge returns nil when metric contains non-gauge data","Gauge Reset clears all recorded data points","Gauge marshals and unmarshals with protobuf binary wire format preserving data points"],"goal":"verify go.opentelemetry.io/proto/otlp/metrics/v1.Gauge in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/proto/otlp/metrics/v1.Gauge"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0","symbols":["go.opentelemetry.io/proto/otlp/metrics/v1.Gauge"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.23.0

require (
	go.opentelemetry.io/proto/otlp v1.9.0
	google.golang.org/protobuf v1.36.10
)
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
main.go
package main

import (
	"fmt"
	"time"

	v1 "go.opentelemetry.io/proto/otlp/common/v1"
	metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
)

func main() {
	// Create a NumberDataPoint representing a gauge observation
	point := &metricspb.NumberDataPoint{
		TimeUnixNano: uint64(time.Now().UnixNano()),
		Value: &metricspb.NumberDataPoint_AsDouble{
			AsDouble: 42.5,
		},
		Attributes: []*v1.KeyValue{
			{
				Key: "device_id",
				Value: &v1.AnyValue{
					Value: &v1.AnyValue_StringValue{StringValue: "sensor-01"},
				},
			},
		},
	}

	// Construct Gauge with data points
	gauge := &metricspb.Gauge{
		DataPoints: []*metricspb.NumberDataPoint{point},
	}

	// Wrap Gauge in Metric
	metric := &metricspb.Metric{
		Name:        "temperature_celsius",
		Description: "Current temperature reading in Celsius",
		Unit:        "Cel",
		Data: &metricspb.Metric_Gauge{
			Gauge: gauge,
		},
	}

	fmt.Printf("Metric: %s, DataPoints count: %d\n", metric.GetName(), len(metric.GetGauge().GetDataPoints()))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/proto/otlp/metrics/v1.Gauge in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0"
  ],
  "symbols": [
    "go.opentelemetry.io/proto/otlp/metrics/v1.Gauge"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"

	v1 "go.opentelemetry.io/proto/otlp/common/v1"
	metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
	"google.golang.org/protobuf/proto"
)

func main() {
	// 1. Gauge GetDataPoints returns empty slice when initialized without data points
	emptyGauge := &metricspb.Gauge{}
	if pts := emptyGauge.GetDataPoints(); len(pts) != 0 {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: expected 0 points, got %d\n", len(pts))
		os.Exit(1)
	}

	// 2. Gauge holds NumberDataPoints recording floating point measurements with timestamps
	dpDouble := &metricspb.NumberDataPoint{
		TimeUnixNano: 1725540000000000000,
		Value: &metricspb.NumberDataPoint_AsDouble{
			AsDouble: 73.5,
		},
	}
	gaugeWithDouble := &metricspb.Gauge{
		DataPoints: []*metricspb.NumberDataPoint{dpDouble},
	}
	if len(gaugeWithDouble.GetDataPoints()) != 1 {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: expected 1 point\n")
		os.Exit(1)
	}
	if gaugeWithDouble.GetDataPoints()[0].GetAsDouble() != 73.5 {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: expected 73.5, got %f\n", gaugeWithDouble.GetDataPoints()[0].GetAsDouble())
		os.Exit(1)
	}
	if gaugeWithDouble.GetDataPoints()[0].GetTimeUnixNano() != 1725540000000000000 {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: timestamp mismatch\n")
		os.Exit(1)
	}

	// 3. Gauge holds NumberDataPoints recording integer measurements with key-value attributes
	dpInt := &metricspb.NumberDataPoint{
		TimeUnixNano: 1725540001000000000,
		Value: &metricspb.NumberDataPoint_AsInt{
			AsInt: 42,
		},
		Attributes: []*v1.KeyValue{
			{
				Key: "host",
				Value: &v1.AnyValue{
					Value: &v1.AnyValue_StringValue{StringValue: "server-01"},
				},
			},
		},
	}
	gaugeWithInt := &metricspb.Gauge{
		DataPoints: []*metricspb.NumberDataPoint{dpInt},
	}
	if gaugeWithInt.GetDataPoints()[0].GetAsInt() != 42 {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: expected int 42, got %d\n", gaugeWithInt.GetDataPoints()[0].GetAsInt())
		os.Exit(1)
	}
	if len(gaugeWithInt.GetDataPoints()[0].GetAttributes()) != 1 || gaugeWithInt.GetDataPoints()[0].GetAttributes()[0].GetKey() != "host" {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: attribute mismatch\n")
		os.Exit(1)
	}

	// 4. Metric GetData returns Metric_Gauge wrapper and GetGauge provides underlying Gauge
	metric := &metricspb.Metric{
		Name:        "memory_usage_bytes",
		Description: "Current memory usage in bytes",
		Unit:        "By",
		Data: &metricspb.Metric_Gauge{
			Gauge: gaugeWithDouble,
		},
	}
	if metric.GetGauge() == nil {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: Metric.GetGauge returned nil\n")
		os.Exit(1)
	}
	if metric.GetGauge().GetDataPoints()[0].GetAsDouble() != 73.5 {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: metric gauge data point mismatch\n")
		os.Exit(1)
	}
	if _, ok := metric.GetData().(*metricspb.Metric_Gauge); !ok {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: Metric.GetData is not *Metric_Gauge\n")
		os.Exit(1)
	}

	// 5. Metric GetGauge returns nil when metric contains non-gauge data
	sumMetric := &metricspb.Metric{
		Name: "requests_total",
		Data: &metricspb.Metric_Sum{
			Sum: &metricspb.Sum{},
		},
	}
	if sumMetric.GetGauge() != nil {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: Metric.GetGauge should return nil for Sum data\n")
		os.Exit(1)
	}

	// 6. Gauge Reset clears all recorded data points
	gaugeToReset := &metricspb.Gauge{
		DataPoints: []*metricspb.NumberDataPoint{dpDouble, dpInt},
	}
	gaugeToReset.Reset()
	if len(gaugeToReset.GetDataPoints()) != 0 {
		fmt.Fprintf(os.Stderr, "assertion 6 failed: Reset did not clear data points\n")
		os.Exit(1)
	}

	// 7. Gauge marshals and unmarshals with protobuf binary wire format preserving data points
	origGauge := &metricspb.Gauge{
		DataPoints: []*metricspb.NumberDataPoint{dpDouble, dpInt},
	}
	data, err := proto.Marshal(origGauge)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 7 failed: proto.Marshal error: %v\n", err)
		os.Exit(1)
	}
	deserializedGauge := &metricspb.Gauge{}
	if err := proto.Unmarshal(data, deserializedGauge); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 7 failed: proto.Unmarshal error: %v\n", err)
		os.Exit(1)
	}
	if len(deserializedGauge.GetDataPoints()) != 2 {
		fmt.Fprintf(os.Stderr, "assertion 7 failed: expected 2 points, got %d\n", len(deserializedGauge.GetDataPoints()))
		os.Exit(1)
	}
	if deserializedGauge.GetDataPoints()[0].GetAsDouble() != 73.5 {
		fmt.Fprintf(os.Stderr, "assertion 7 failed: double value mismatch after roundtrip\n")
		os.Exit(1)
	}
	if deserializedGauge.GetDataPoints()[1].GetAsInt() != 42 {
		fmt.Fprintf(os.Stderr, "assertion 7 failed: int value mismatch after roundtrip\n")
		os.Exit(1)
	}

	fmt.Println("All contract assertions passed.")
}

Исходный сидер

аноним