CodeSampleX

Пример

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

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

sha256:6ed6ec525eabf1ec355a21088f4f6a750b0b5ed86001424a7db681307f4d3da0

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

Контракт

  1. NumberDataPoint represents scalar metric values as 64-bit integer or double-precision floating point via its oneof Value field and typed getters.
  2. NumberDataPoint associates timestamps for both start time and observation time in nanoseconds alongside key-value attributes uniquely identifying the timeseries.
  3. NumberDataPoint captures diagnostic exemplars with filtered attributes, timestamps, and optional trace or span IDs alongside data point flags.
  4. NumberDataPoint getters safely handle nil receivers and unpopulated instances without panicking, returning default zero values.
  5. NumberDataPoint serializes to and deserializes from binary Protobuf wire format without data loss, satisfying proto.Equal.
  6. NumberDataPoint serializes to and deserializes from protojson format, preserving field names, 64-bit integer strings, and nested structures.
  7. proto.Clone produces an isolated deep copy of NumberDataPoint where mutating nested attributes, exemplars, or values 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.NumberDataPoint 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.NumberDataPoint

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:87bca718e7631ae53cadf97ffa18e477a0b72c5d45c87f16de0106817a9cbb13","contract":["NumberDataPoint represents scalar metric values as 64-bit integer or double-precision floating point via its oneof Value field and typed getters.","NumberDataPoint associates timestamps for both start time and observation time in nanoseconds alongside key-value attributes uniquely identifying the timeseries.","NumberDataPoint captures diagnostic exemplars with filtered attributes, timestamps, and optional trace or span IDs alongside data point flags.","NumberDataPoint getters safely handle nil receivers and unpopulated instances without panicking, returning default zero values.","NumberDataPoint serializes to and deserializes from binary Protobuf wire format without data loss, satisfying proto.Equal.","NumberDataPoint serializes to and deserializes from protojson format, preserving field names, 64-bit integer strings, and nested structures.","proto.Clone produces an isolated deep copy of NumberDataPoint where mutating nested attributes, exemplars, or values does not affect the original."],"goal":"verify go.opentelemetry.io/proto/otlp/metrics/v1.NumberDataPoint 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.NumberDataPoint"]},"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.NumberDataPoint"],"verifierAdapter":"golang@1"}
go.mod
module example.com/otlpnumberdatapoint

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.NumberDataPoint 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.NumberDataPoint"
  ]
}
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: NumberDataPoint represents scalar metric values as 64-bit integer or double-precision floating point via its oneof Value field and typed getters.
	{
		intPoint := &metricspb.NumberDataPoint{
			Value: &metricspb.NumberDataPoint_AsInt{AsInt: 1042},
		}
		assert(intPoint.GetAsInt() == 1042, "expected AsInt 1042")
		assert(intPoint.GetAsDouble() == 0.0, "expected default AsDouble 0.0 for integer point")
		assert(intPoint.GetValue() != nil, "expected non-nil Value")

		doublePoint := &metricspb.NumberDataPoint{
			Value: &metricspb.NumberDataPoint_AsDouble{AsDouble: 3.14159},
		}
		assert(doublePoint.GetAsDouble() == 3.14159, "expected AsDouble 3.14159")
		assert(doublePoint.GetAsInt() == 0, "expected default AsInt 0 for double point")
		assert(doublePoint.GetValue() != nil, "expected non-nil Value")
	}

	// Assertion 2: NumberDataPoint associates timestamps for both start time and observation time in nanoseconds alongside key-value attributes uniquely identifying the timeseries.
	{
		point := &metricspb.NumberDataPoint{
			StartTimeUnixNano: 1700000000000000000,
			TimeUnixNano:      1700000060000000000,
			Attributes: []*commonpb.KeyValue{
				{
					Key:   "http.status_code",
					Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_IntValue{IntValue: 200}},
				},
				{
					Key:   "http.method",
					Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "GET"}},
				},
			},
			Value: &metricspb.NumberDataPoint_AsInt{AsInt: 1},
		}
		assert(point.GetStartTimeUnixNano() == 1700000000000000000, "expected StartTimeUnixNano 1700000000000000000")
		assert(point.GetTimeUnixNano() == 1700000060000000000, "expected TimeUnixNano 1700000060000000000")
		assert(len(point.GetAttributes()) == 2, "expected 2 attributes")
		assert(point.GetAttributes()[0].GetKey() == "http.status_code", "expected key 'http.status_code'")
		assert(point.GetAttributes()[0].GetValue().GetIntValue() == 200, "expected status code 200")
		assert(point.GetAttributes()[1].GetKey() == "http.method", "expected key 'http.method'")
		assert(point.GetAttributes()[1].GetValue().GetStringValue() == "GET", "expected method 'GET'")
	}

	// Assertion 3: NumberDataPoint captures diagnostic exemplars with filtered attributes, timestamps, and optional trace or span IDs alongside data point flags.
	{
		spanID := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}
		traceID := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}
		point := &metricspb.NumberDataPoint{
			Flags: uint32(metricspb.DataPointFlags_DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK),
			Exemplars: []*metricspb.Exemplar{
				{
					TimeUnixNano: 1700000055000000000,
					Value:        &metricspb.Exemplar_AsDouble{AsDouble: 99.5},
					SpanId:       spanID,
					TraceId:      traceID,
					FilteredAttributes: []*commonpb.KeyValue{
						{
							Key:   "user.id",
							Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "user-123"}},
						},
					},
				},
			},
			Value: &metricspb.NumberDataPoint_AsDouble{AsDouble: 100.0},
		}
		assert(point.GetFlags() == uint32(metricspb.DataPointFlags_DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK), "expected flag NO_RECORDED_VALUE_MASK")
		assert(len(point.GetExemplars()) == 1, "expected 1 exemplar")
		assert(point.GetExemplars()[0].GetTimeUnixNano() == 1700000055000000000, "expected exemplar TimeUnixNano")
		assert(point.GetExemplars()[0].GetAsDouble() == 99.5, "expected exemplar AsDouble 99.5")
		assert(bytes.Equal(point.GetExemplars()[0].GetSpanId(), spanID), "expected matching exemplar SpanId")
		assert(bytes.Equal(point.GetExemplars()[0].GetTraceId(), traceID), "expected matching exemplar TraceId")
		assert(len(point.GetExemplars()[0].GetFilteredAttributes()) == 1, "expected 1 filtered attribute")
	}

	// Assertion 4: NumberDataPoint getters safely handle nil receivers and unpopulated instances without panicking, returning default zero values.
	{
		var nilPoint *metricspb.NumberDataPoint
		assert(nilPoint.GetAttributes() == nil, "nil NumberDataPoint GetAttributes must return nil")
		assert(nilPoint.GetStartTimeUnixNano() == 0, "nil NumberDataPoint GetStartTimeUnixNano must return 0")
		assert(nilPoint.GetTimeUnixNano() == 0, "nil NumberDataPoint GetTimeUnixNano must return 0")
		assert(nilPoint.GetValue() == nil, "nil NumberDataPoint GetValue must return nil")
		assert(nilPoint.GetAsInt() == 0, "nil NumberDataPoint GetAsInt must return 0")
		assert(nilPoint.GetAsDouble() == 0.0, "nil NumberDataPoint GetAsDouble must return 0.0")
		assert(nilPoint.GetExemplars() == nil, "nil NumberDataPoint GetExemplars must return nil")
		assert(nilPoint.GetFlags() == 0, "nil NumberDataPoint GetFlags must return 0")

		emptyPoint := &metricspb.NumberDataPoint{}
		assert(emptyPoint.GetAttributes() == nil, "empty NumberDataPoint GetAttributes must return nil")
		assert(emptyPoint.GetStartTimeUnixNano() == 0, "empty NumberDataPoint GetStartTimeUnixNano must return 0")
		assert(emptyPoint.GetTimeUnixNano() == 0, "empty NumberDataPoint GetTimeUnixNano must return 0")
		assert(emptyPoint.GetValue() == nil, "empty NumberDataPoint GetValue must return nil")
		assert(emptyPoint.GetAsInt() == 0, "empty NumberDataPoint GetAsInt must return 0")
		assert(emptyPoint.GetAsDouble() == 0.0, "empty NumberDataPoint GetAsDouble must return 0.0")
		assert(emptyPoint.GetExemplars() == nil, "empty NumberDataPoint GetExemplars must return nil")
		assert(emptyPoint.GetFlags() == 0, "empty NumberDataPoint GetFlags must return 0")
	}

	// Assertion 5: NumberDataPoint serializes to and deserializes from binary Protobuf wire format without data loss, satisfying proto.Equal.
	{
		orig := &metricspb.NumberDataPoint{
			StartTimeUnixNano: 1700000000000000000,
			TimeUnixNano:      1700000060000000000,
			Value:             &metricspb.NumberDataPoint_AsInt{AsInt: 8443},
			Flags:             1,
			Attributes: []*commonpb.KeyValue{
				{
					Key:   "service.name",
					Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "payment-service"}},
				},
			},
			Exemplars: []*metricspb.Exemplar{
				{
					TimeUnixNano: 1700000059000000000,
					Value:        &metricspb.Exemplar_AsInt{AsInt: 8440},
					SpanId:       []byte{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11, 0x22},
				},
			},
		}

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

		unmarshaled := &metricspb.NumberDataPoint{}
		err = proto.Unmarshal(wire, unmarshaled)
		assert(err == nil, "proto.Unmarshal failed")
		assert(proto.Equal(orig, unmarshaled), "proto.Equal returned false for protobuf round-trip")
	}

	// Assertion 6: NumberDataPoint serializes to and deserializes from protojson format, preserving field names, 64-bit integer strings, and nested structures.
	{
		orig := &metricspb.NumberDataPoint{
			StartTimeUnixNano: 1700000000000000000,
			TimeUnixNano:      1700000060000000000,
			Value:             &metricspb.NumberDataPoint_AsDouble{AsDouble: 99.99},
			Attributes: []*commonpb.KeyValue{
				{
					Key:   "endpoint",
					Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "/checkout"}},
				},
			},
		}

		jsonBytes, err := protojson.Marshal(orig)
		assert(err == nil, "protojson.Marshal failed")
		assert(bytes.Contains(jsonBytes, []byte(`"timeUnixNano"`)), "json must contain 'timeUnixNano'")
		assert(bytes.Contains(jsonBytes, []byte(`"asDouble"`)), "json must contain 'asDouble'")
		assert(bytes.Contains(jsonBytes, []byte(`"attributes"`)), "json must contain 'attributes'")

		jsonUnmarshaled := &metricspb.NumberDataPoint{}
		err = protojson.Unmarshal(jsonBytes, jsonUnmarshaled)
		assert(err == nil, "protojson.Unmarshal failed")
		assert(proto.Equal(orig, jsonUnmarshaled), "proto.Equal returned false for protojson round-trip")
	}

	// Assertion 7: proto.Clone produces an isolated deep copy of NumberDataPoint where mutating nested attributes, exemplars, or values does not affect the original.
	{
		orig := &metricspb.NumberDataPoint{
			TimeUnixNano: 1700000060000000000,
			Value:        &metricspb.NumberDataPoint_AsInt{AsInt: 50},
			Attributes: []*commonpb.KeyValue{
				{
					Key:   "cluster",
					Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "us-central1"}},
				},
			},
			Exemplars: []*metricspb.Exemplar{
				{
					TimeUnixNano: 1700000050000000000,
					Value:        &metricspb.Exemplar_AsInt{AsInt: 45},
				},
			},
		}

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

		// Mutate cloned fields
		cloned.TimeUnixNano = 1800000000000000000
		cloned.Value = &metricspb.NumberDataPoint_AsInt{AsInt: 999}
		cloned.Attributes[0].Key = "mutated-cluster"
		cloned.Attributes = append(cloned.Attributes, &commonpb.KeyValue{
			Key:   "new-attr",
			Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "value"}},
		})
		cloned.Exemplars[0].TimeUnixNano = 1800000000000000000

		// Verify original remains untouched
		assert(orig.GetTimeUnixNano() == 1700000060000000000, "original TimeUnixNano was mutated")
		assert(orig.GetAsInt() == 50, "original Value was mutated")
		assert(len(orig.GetAttributes()) == 1, "original Attributes length was modified")
		assert(orig.GetAttributes()[0].GetKey() == "cluster", "original Attribute key was mutated")
		assert(orig.GetExemplars()[0].GetTimeUnixNano() == 1700000050000000000, "original Exemplar was mutated")
	}

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

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

аноним