CodeSampleX

Пример

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

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

sha256:4595ddb6e8f127e626da1b78758176203ddf26dcb462f0c4c9fc680f8ada191a

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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.Metric_Gauge in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
Пакеты
Символы
  • go.opentelemetry.io/proto/otlp/metrics/v1.Metric_Gauge
Создан
2026-09-05T19:54:23Z

Контракт

  1. Metric_Gauge implements the Metric Data oneof interface to represent instantaneous gauge measurements wrapping a Gauge message.
  2. Metric.GetGauge returns the wrapped Gauge pointer when Data is Metric_Gauge and returns nil when Data is unset or another metric type.
  3. Metric_Gauge supports Gauge data points containing integer or double scalar values, timestamps, and key-value attributes.
  4. Metric with Metric_Gauge serializes to and deserializes from binary Protobuf wire format without data loss, satisfying proto.Equal.
  5. Metric with Metric_Gauge serializes to and deserializes from protojson format with the gauge oneof field and data points preserved.
  6. proto.Clone creates an independent deep copy of Metric with Metric_Gauge where mutating cloned data points does not affect the original.

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/main.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.Metric_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.Metric_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:0cf18f172dd28beb7893293985024b2fe0709f6e5dbb78fe6d73fa21bf556d98","contract":["Metric_Gauge implements the Metric Data oneof interface to represent instantaneous gauge measurements wrapping a Gauge message.","Metric.GetGauge returns the wrapped Gauge pointer when Data is Metric_Gauge and returns nil when Data is unset or another metric type.","Metric_Gauge supports Gauge data points containing integer or double scalar values, timestamps, and key-value attributes.","Metric with Metric_Gauge serializes to and deserializes from binary Protobuf wire format without data loss, satisfying proto.Equal.","Metric with Metric_Gauge serializes to and deserializes from protojson format with the gauge oneof field and data points preserved.","proto.Clone creates an independent deep copy of Metric with Metric_Gauge where mutating cloned data points does not affect the original."],"goal":"verify go.opentelemetry.io/proto/otlp/metrics/v1.Metric_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.Metric_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.Metric_Gauge"],"verifierAdapter":"golang@1"}
go.mod
module example.com/otlpmetricgauge

go 1.26.6

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=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/proto/otlp/metrics/v1.Metric_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.Metric_Gauge"
  ]
}
test/main.go
package main

import (
	"bytes"
	"fmt"
	"os"

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

func assert(condition bool, message string) {
	if !condition {
		fmt.Fprintf(os.Stderr, "assertion failed: %s\n", message)
		os.Exit(1)
	}
}

func main() {
	// Assertion 1: Metric_Gauge implements the Metric Data oneof interface to represent instantaneous gauge measurements wrapping a Gauge message
	{
		gauge := &metricspb.Gauge{
			DataPoints: []*metricspb.NumberDataPoint{
				{
					TimeUnixNano: 1700000000000000000,
					Value:        &metricspb.NumberDataPoint_AsDouble{AsDouble: 73.5},
				},
			},
		}
		metricGauge := &metricspb.Metric_Gauge{
			Gauge: gauge,
		}
		metric := &metricspb.Metric{
			Name:        "system.cpu.utilization",
			Description: "Current CPU utilization percentage",
			Unit:        "1",
			Data:        metricGauge,
		}

		assert(metric.Data != nil, "expected non-nil metric Data")
		assert(metric.GetGauge() != nil, "expected non-nil Gauge from GetGauge()")
		assert(metric.GetGauge() == gauge, "expected GetGauge() to match assigned gauge instance")
	}

	// Assertion 2: Metric.GetGauge returns the wrapped Gauge pointer when Data is Metric_Gauge and returns nil when Data is unset or another metric type
	{
		var nilMetric *metricspb.Metric
		assert(nilMetric.GetGauge() == nil, "nil Metric GetGauge must return nil")

		emptyMetric := &metricspb.Metric{}
		assert(emptyMetric.GetGauge() == nil, "Metric without Data GetGauge must return nil")
		assert(emptyMetric.GetData() == nil, "Metric without Data GetData must return nil")

		sumMetric := &metricspb.Metric{
			Name: "http.requests.total",
			Data: &metricspb.Metric_Sum{
				Sum: &metricspb.Sum{},
			},
		}
		assert(sumMetric.GetGauge() == nil, "Metric with Metric_Sum Data must return nil for GetGauge()")
		assert(sumMetric.GetSum() != nil, "Metric with Metric_Sum Data must return non-nil for GetSum()")
	}

	// Assertion 3: Metric_Gauge supports Gauge data points containing integer or double scalar values, timestamps, and key-value attributes
	{
		dpInt := &metricspb.NumberDataPoint{
			TimeUnixNano:      1700000001000000000,
			StartTimeUnixNano: 1700000000000000000,
			Value:             &metricspb.NumberDataPoint_AsInt{AsInt: 1024},
			Attributes: []*commonpb.KeyValue{
				{
					Key:   "device",
					Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "/dev/sda1"}},
				},
			},
		}

		dpDouble := &metricspb.NumberDataPoint{
			TimeUnixNano: 1700000002000000000,
			Value:        &metricspb.NumberDataPoint_AsDouble{AsDouble: 85.25},
			Attributes: []*commonpb.KeyValue{
				{
					Key:   "status",
					Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "active"}},
				},
			},
		}

		metric := &metricspb.Metric{
			Name: "system.disk.operations",
			Data: &metricspb.Metric_Gauge{
				Gauge: &metricspb.Gauge{
					DataPoints: []*metricspb.NumberDataPoint{dpInt, dpDouble},
				},
			},
		}

		pts := metric.GetGauge().GetDataPoints()
		assert(len(pts) == 2, "expected 2 data points")
		assert(pts[0].GetAsInt() == 1024, "expected first point AsInt 1024")
		assert(pts[0].GetAsDouble() == 0, "expected first point AsDouble default 0")
		assert(pts[0].GetAttributes()[0].GetKey() == "device", "expected attribute key 'device'")
		assert(pts[0].GetAttributes()[0].GetValue().GetStringValue() == "/dev/sda1", "expected attribute value '/dev/sda1'")

		assert(pts[1].GetAsDouble() == 85.25, "expected second point AsDouble 85.25")
		assert(pts[1].GetAsInt() == 0, "expected second point AsInt default 0")
		assert(pts[1].GetAttributes()[0].GetKey() == "status", "expected attribute key 'status'")
	}

	// Assertion 4: Metric with Metric_Gauge serializes to and deserializes from binary Protobuf wire format without data loss, satisfying proto.Equal
	{
		orig := &metricspb.Metric{
			Name:        "memory.free",
			Description: "Available physical memory in bytes",
			Unit:        "By",
			Data: &metricspb.Metric_Gauge{
				Gauge: &metricspb.Gauge{
					DataPoints: []*metricspb.NumberDataPoint{
						{
							TimeUnixNano: 1700000005000000000,
							Value:        &metricspb.NumberDataPoint_AsInt{AsInt: 8589934592},
							Attributes: []*commonpb.KeyValue{
								{
									Key:   "node.id",
									Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "worker-01"}},
								},
							},
						},
					},
				},
			},
		}

		wire, err := proto.Marshal(orig)
		assert(err == nil, "proto.Marshal failed")
		assert(len(wire) > 0, "marshaled wire length is 0")

		unmarshaled := &metricspb.Metric{}
		err = proto.Unmarshal(wire, unmarshaled)
		assert(err == nil, "proto.Unmarshal failed")
		assert(proto.Equal(orig, unmarshaled), "proto.Equal returned false for protobuf round-trip")
		assert(unmarshaled.GetGauge() != nil, "unmarshaled GetGauge() must not be nil")
		assert(unmarshaled.GetGauge().GetDataPoints()[0].GetAsInt() == 8589934592, "unmarshaled point value mismatch")
	}

	// Assertion 5: Metric with Metric_Gauge serializes to and deserializes from protojson format with the gauge oneof field and data points preserved
	{
		orig := &metricspb.Metric{
			Name: "temperature.sensor",
			Data: &metricspb.Metric_Gauge{
				Gauge: &metricspb.Gauge{
					DataPoints: []*metricspb.NumberDataPoint{
						{
							TimeUnixNano: 1700000010000000000,
							Value:        &metricspb.NumberDataPoint_AsDouble{AsDouble: 23.8},
							Attributes: []*commonpb.KeyValue{
								{
									Key:   "location",
									Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "rack-b"}},
								},
							},
						},
					},
				},
			},
		}

		jsonBytes, err := protojson.Marshal(orig)
		assert(err == nil, "protojson.Marshal failed")
		assert(bytes.Contains(jsonBytes, []byte(`"gauge"`)), "json must contain 'gauge' key")
		assert(bytes.Contains(jsonBytes, []byte(`"dataPoints"`)), "json must contain 'dataPoints' key")
		assert(bytes.Contains(jsonBytes, []byte(`23.8`)), "json must contain '23.8'")

		jsonUnmarshaled := &metricspb.Metric{}
		err = protojson.Unmarshal(jsonBytes, jsonUnmarshaled)
		assert(err == nil, "protojson.Unmarshal failed")
		assert(proto.Equal(orig, jsonUnmarshaled), "proto.Equal returned false for protojson round-trip")
		assert(jsonUnmarshaled.GetGauge().GetDataPoints()[0].GetAsDouble() == 23.8, "protojson round-trip value mismatch")
	}

	// Assertion 6: proto.Clone creates an independent deep copy of Metric with Metric_Gauge where mutating cloned data points does not affect the original
	{
		orig := &metricspb.Metric{
			Name: "thread.count",
			Data: &metricspb.Metric_Gauge{
				Gauge: &metricspb.Gauge{
					DataPoints: []*metricspb.NumberDataPoint{
						{
							TimeUnixNano: 1700000020000000000,
							Value:        &metricspb.NumberDataPoint_AsInt{AsInt: 16},
						},
					},
				},
			},
		}

		cloned := proto.Clone(orig).(*metricspb.Metric)
		assert(proto.Equal(orig, cloned), "cloned Metric must equal original")

		// Mutate cloned metric and gauge data
		cloned.GetGauge().GetDataPoints()[0].Value = &metricspb.NumberDataPoint_AsInt{AsInt: 64}
		cloned.GetGauge().DataPoints = append(cloned.GetGauge().DataPoints, &metricspb.NumberDataPoint{
			TimeUnixNano: 1700000021000000000,
			Value:        &metricspb.NumberDataPoint_AsInt{AsInt: 128},
		})

		// Verify original remains unchanged
		origPoints := orig.GetGauge().GetDataPoints()
		assert(len(origPoints) == 1, "original Metric gauge data point count was modified")
		assert(origPoints[0].GetAsInt() == 16, "original Metric gauge data point value was modified")
	}

	fmt.Println("PASS: all go.opentelemetry.io/proto/otlp/metrics/v1.Metric_Gauge contract assertions verified")
}

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

аноним