CodeSampleX

Exemplo

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

Amostra verificada para golang go.opentelemetry.io/proto/otlp v1.9.0: v1.Metric. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou.

sha256:aad9584ff1d236616b9eb9b219780f0a421094d3d8ed4907015a43d17bcec14b

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
verify go.opentelemetry.io/proto/otlp/metrics/v1.Metric in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
Pacotes
Símbolos
  • go.opentelemetry.io/proto/otlp/metrics/v1.Metric
Criado
2026-09-05T16:50:23Z

Contrato

  1. Metric holds core metadata fields (Name, Description, Unit) and supports Metadata KeyValue attributes.
  2. Metric with Metric_Gauge data encapsulates Gauge and NumberDataPoint with timestamp and float64 value.
  3. Metric with Metric_Sum data encapsulates Sum with aggregation temporality, monotonicity, and int64 value.
  4. Metric with Metric_Histogram data encapsulates Histogram with explicit bucket counts and bounds.
  5. Metric provides oneof Data discrimination where the active variant accessor returns non-nil and inactive variant accessors return nil.
  6. Metric serializes to and deserializes from protobuf binary format preserving all fields.

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 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

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:f994fd566b3ab1984dce5979356f562f23c5248de80758590e24834aa3814ac0","contract":["Metric holds core metadata fields (Name, Description, Unit) and supports Metadata KeyValue attributes.","Metric with Metric_Gauge data encapsulates Gauge and NumberDataPoint with timestamp and float64 value.","Metric with Metric_Sum data encapsulates Sum with aggregation temporality, monotonicity, and int64 value.","Metric with Metric_Histogram data encapsulates Histogram with explicit bucket counts and bounds.","Metric provides oneof Data discrimination where the active variant accessor returns non-nil and inactive variant accessors return nil.","Metric serializes to and deserializes from protobuf binary format preserving all fields."],"goal":"verify go.opentelemetry.io/proto/otlp/metrics/v1.Metric 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"]},"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"],"verifierAdapter":"golang@1"}
go.mod
module sample

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=
main.go
package main

import (
	"fmt"
	"time"

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

// NewGaugeMetric constructs an OTLP Metric configured as a Gauge.
func NewGaugeMetric(name, description, unit string, timestamp uint64, val float64) *metricspb.Metric {
	return &metricspb.Metric{
		Name:        name,
		Description: description,
		Unit:        unit,
		Data: &metricspb.Metric_Gauge{
			Gauge: &metricspb.Gauge{
				DataPoints: []*metricspb.NumberDataPoint{
					{
						TimeUnixNano: timestamp,
						Value: &metricspb.NumberDataPoint_AsDouble{
							AsDouble: val,
						},
					},
				},
			},
		},
	}
}

// NewSumMetric constructs an OTLP Metric configured as a monotonic cumulative Sum.
func NewSumMetric(name, description, unit string, startTime, timestamp uint64, val int64) *metricspb.Metric {
	return &metricspb.Metric{
		Name:        name,
		Description: description,
		Unit:        unit,
		Data: &metricspb.Metric_Sum{
			Sum: &metricspb.Sum{
				AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,
				IsMonotonic:            true,
				DataPoints: []*metricspb.NumberDataPoint{
					{
						StartTimeUnixNano: startTime,
						TimeUnixNano:      timestamp,
						Value: &metricspb.NumberDataPoint_AsInt{
							AsInt: val,
						},
						Attributes: []*commonv1.KeyValue{
							{
								Key: "host.id",
								Value: &commonv1.AnyValue{
									Value: &commonv1.AnyValue_StringValue{StringValue: "node-1"},
								},
							},
						},
					},
				},
			},
		},
	}
}

func main() {
	now := uint64(time.Now().UnixNano())

	gauge := NewGaugeMetric("system.memory.usage", "Current memory utilization", "By", now, 4294967296.0)
	fmt.Printf("Metric: %s (Unit: %s)\n", gauge.GetName(), gauge.GetUnit())
	if g := gauge.GetGauge(); g != nil && len(g.GetDataPoints()) > 0 {
		fmt.Printf("  Gauge value: %f\n", g.GetDataPoints()[0].GetAsDouble())
	}

	sum := NewSumMetric("http.server.request_count", "Total HTTP requests received", "{request}", now-1000000000, now, 12050)
	fmt.Printf("Metric: %s (Monotonic: %t)\n", sum.GetName(), sum.GetSum().GetIsMonotonic())
	if s := sum.GetSum(); s != nil && len(s.GetDataPoints()) > 0 {
		fmt.Printf("  Sum count: %d\n", s.GetDataPoints()[0].GetAsInt())
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/proto/otlp/metrics/v1.Metric 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"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"

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

func main() {
	// Contract 1: Metric holds core metadata fields (Name, Description, Unit) and supports Metadata KeyValue attributes
	{
		m := &metricspb.Metric{
			Name:        "system.cpu.load",
			Description: "Average system CPU load over 1 minute",
			Unit:        "1",
			Metadata: []*commonv1.KeyValue{
				{
					Key: "environment",
					Value: &commonv1.AnyValue{
						Value: &commonv1.AnyValue_StringValue{StringValue: "staging"},
					},
				},
			},
		}

		if m.GetName() != "system.cpu.load" {
			fmt.Fprintf(os.Stderr, "Contract 1 fail: expected Name 'system.cpu.load', got %q\n", m.GetName())
			os.Exit(1)
		}
		if m.GetDescription() != "Average system CPU load over 1 minute" {
			fmt.Fprintf(os.Stderr, "Contract 1 fail: expected Description 'Average system CPU load over 1 minute', got %q\n", m.GetDescription())
			os.Exit(1)
		}
		if m.GetUnit() != "1" {
			fmt.Fprintf(os.Stderr, "Contract 1 fail: expected Unit '1', got %q\n", m.GetUnit())
			os.Exit(1)
		}
		if len(m.GetMetadata()) != 1 || m.GetMetadata()[0].GetKey() != "environment" {
			fmt.Fprintf(os.Stderr, "Contract 1 fail: metadata key mismatch\n")
			os.Exit(1)
		}
		if m.GetMetadata()[0].GetValue().GetStringValue() != "staging" {
			fmt.Fprintf(os.Stderr, "Contract 1 fail: metadata string value mismatch\n")
			os.Exit(1)
		}
	}

	// Contract 2: Metric with Metric_Gauge data encapsulates Gauge and NumberDataPoint with timestamp and float64 value
	{
		timestamp := uint64(1700000000000000000)
		m := &metricspb.Metric{
			Name: "system.memory.usage_ratio",
			Data: &metricspb.Metric_Gauge{
				Gauge: &metricspb.Gauge{
					DataPoints: []*metricspb.NumberDataPoint{
						{
							TimeUnixNano: timestamp,
							Value: &metricspb.NumberDataPoint_AsDouble{
								AsDouble: 0.85,
							},
						},
					},
				},
			},
		}

		g := m.GetGauge()
		if g == nil {
			fmt.Fprintf(os.Stderr, "Contract 2 fail: GetGauge() returned nil\n")
			os.Exit(1)
		}
		if len(g.GetDataPoints()) != 1 {
			fmt.Fprintf(os.Stderr, "Contract 2 fail: expected 1 data point, got %d\n", len(g.GetDataPoints()))
			os.Exit(1)
		}
		dp := g.GetDataPoints()[0]
		if dp.GetTimeUnixNano() != timestamp {
			fmt.Fprintf(os.Stderr, "Contract 2 fail: expected TimeUnixNano %d, got %d\n", timestamp, dp.GetTimeUnixNano())
			os.Exit(1)
		}
		if dp.GetAsDouble() != 0.85 {
			fmt.Fprintf(os.Stderr, "Contract 2 fail: expected AsDouble 0.85, got %f\n", dp.GetAsDouble())
			os.Exit(1)
		}
	}

	// Contract 3: Metric with Metric_Sum data encapsulates Sum with aggregation temporality, monotonicity, and int64 value
	{
		startTime := uint64(1700000000000000000)
		timestamp := uint64(1700000060000000000)
		m := &metricspb.Metric{
			Name: "http.server.request_count",
			Data: &metricspb.Metric_Sum{
				Sum: &metricspb.Sum{
					AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,
					IsMonotonic:            true,
					DataPoints: []*metricspb.NumberDataPoint{
						{
							StartTimeUnixNano: startTime,
							TimeUnixNano:      timestamp,
							Value: &metricspb.NumberDataPoint_AsInt{
								AsInt: 5042,
							},
						},
					},
				},
			},
		}

		s := m.GetSum()
		if s == nil {
			fmt.Fprintf(os.Stderr, "Contract 3 fail: GetSum() returned nil\n")
			os.Exit(1)
		}
		if s.GetAggregationTemporality() != metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE {
			fmt.Fprintf(os.Stderr, "Contract 3 fail: expected cumulative temporality, got %v\n", s.GetAggregationTemporality())
			os.Exit(1)
		}
		if !s.GetIsMonotonic() {
			fmt.Fprintf(os.Stderr, "Contract 3 fail: expected IsMonotonic true\n")
			os.Exit(1)
		}
		if len(s.GetDataPoints()) != 1 {
			fmt.Fprintf(os.Stderr, "Contract 3 fail: expected 1 data point, got %d\n", len(s.GetDataPoints()))
			os.Exit(1)
		}
		dp := s.GetDataPoints()[0]
		if dp.GetStartTimeUnixNano() != startTime {
			fmt.Fprintf(os.Stderr, "Contract 3 fail: expected StartTimeUnixNano %d, got %d\n", startTime, dp.GetStartTimeUnixNano())
			os.Exit(1)
		}
		if dp.GetAsInt() != 5042 {
			fmt.Fprintf(os.Stderr, "Contract 3 fail: expected AsInt 5042, got %d\n", dp.GetAsInt())
			os.Exit(1)
		}
	}

	// Contract 4: Metric with Metric_Histogram data encapsulates Histogram with explicit bucket counts and bounds
	{
		m := &metricspb.Metric{
			Name: "http.server.duration",
			Unit: "ms",
			Data: &metricspb.Metric_Histogram{
				Histogram: &metricspb.Histogram{
					AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA,
					DataPoints: []*metricspb.HistogramDataPoint{
						{
							Count:          100,
							BucketCounts:   []uint64{20, 50, 30},
							ExplicitBounds: []float64{10.0, 50.0},
						},
					},
				},
			},
		}

		h := m.GetHistogram()
		if h == nil {
			fmt.Fprintf(os.Stderr, "Contract 4 fail: GetHistogram() returned nil\n")
			os.Exit(1)
		}
		if h.GetAggregationTemporality() != metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA {
			fmt.Fprintf(os.Stderr, "Contract 4 fail: expected delta temporality, got %v\n", h.GetAggregationTemporality())
			os.Exit(1)
		}
		if len(h.GetDataPoints()) != 1 {
			fmt.Fprintf(os.Stderr, "Contract 4 fail: expected 1 data point, got %d\n", len(h.GetDataPoints()))
			os.Exit(1)
		}
		hdp := h.GetDataPoints()[0]
		if hdp.GetCount() != 100 {
			fmt.Fprintf(os.Stderr, "Contract 4 fail: expected Count 100, got %d\n", hdp.GetCount())
			os.Exit(1)
		}
		if len(hdp.GetBucketCounts()) != 3 || hdp.GetBucketCounts()[1] != 50 {
			fmt.Fprintf(os.Stderr, "Contract 4 fail: bucket counts mismatch\n")
			os.Exit(1)
		}
		if len(hdp.GetExplicitBounds()) != 2 || hdp.GetExplicitBounds()[0] != 10.0 {
			fmt.Fprintf(os.Stderr, "Contract 4 fail: explicit bounds mismatch\n")
			os.Exit(1)
		}
	}

	// Contract 5: Metric provides oneof Data discrimination where the active variant accessor returns non-nil and inactive variant accessors return nil
	{
		gaugeMetric := &metricspb.Metric{
			Name: "test.gauge",
			Data: &metricspb.Metric_Gauge{
				Gauge: &metricspb.Gauge{},
			},
		}

		if gaugeMetric.GetGauge() == nil {
			fmt.Fprintf(os.Stderr, "Contract 5 fail: GetGauge() should be non-nil\n")
			os.Exit(1)
		}
		if gaugeMetric.GetSum() != nil {
			fmt.Fprintf(os.Stderr, "Contract 5 fail: GetSum() should be nil for Gauge\n")
			os.Exit(1)
		}
		if gaugeMetric.GetHistogram() != nil {
			fmt.Fprintf(os.Stderr, "Contract 5 fail: GetHistogram() should be nil for Gauge\n")
			os.Exit(1)
		}
		if gaugeMetric.GetExponentialHistogram() != nil {
			fmt.Fprintf(os.Stderr, "Contract 5 fail: GetExponentialHistogram() should be nil for Gauge\n")
			os.Exit(1)
		}
		if gaugeMetric.GetSummary() != nil {
			fmt.Fprintf(os.Stderr, "Contract 5 fail: GetSummary() should be nil for Gauge\n")
			os.Exit(1)
		}
	}

	// Contract 6: Metric serializes to and deserializes from protobuf binary format preserving all fields
	{
		orig := &metricspb.Metric{
			Name:        "system.network.io",
			Description: "Network ingress bytes",
			Unit:        "By",
			Data: &metricspb.Metric_Sum{
				Sum: &metricspb.Sum{
					AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,
					IsMonotonic:            true,
					DataPoints: []*metricspb.NumberDataPoint{
						{
							TimeUnixNano: 1700000000000000000,
							Value: &metricspb.NumberDataPoint_AsInt{
								AsInt: 1048576,
							},
						},
					},
				},
			},
		}

		wire, err := proto.Marshal(orig)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Contract 6 fail: proto.Marshal failed: %v\n", err)
			os.Exit(1)
		}

		var restored metricspb.Metric
		if err := proto.Unmarshal(wire, &restored); err != nil {
			fmt.Fprintf(os.Stderr, "Contract 6 fail: proto.Unmarshal failed: %v\n", err)
			os.Exit(1)
		}

		if restored.GetName() != orig.GetName() {
			fmt.Fprintf(os.Stderr, "Contract 6 fail: Name mismatch: got %q, want %q\n", restored.GetName(), orig.GetName())
			os.Exit(1)
		}
		if restored.GetDescription() != orig.GetDescription() {
			fmt.Fprintf(os.Stderr, "Contract 6 fail: Description mismatch: got %q, want %q\n", restored.GetDescription(), orig.GetDescription())
			os.Exit(1)
		}
		if restored.GetUnit() != orig.GetUnit() {
			fmt.Fprintf(os.Stderr, "Contract 6 fail: Unit mismatch: got %q, want %q\n", restored.GetUnit(), orig.GetUnit())
			os.Exit(1)
		}
		if restored.GetSum() == nil || len(restored.GetSum().GetDataPoints()) != 1 {
			fmt.Fprintf(os.Stderr, "Contract 6 fail: Sum data points mismatch\n")
			os.Exit(1)
		}
		if restored.GetSum().GetDataPoints()[0].GetAsInt() != 1048576 {
			fmt.Fprintf(os.Stderr, "Contract 6 fail: AsInt value mismatch: got %d, want 1048576\n", restored.GetSum().GetDataPoints()[0].GetAsInt())
			os.Exit(1)
		}
	}

	fmt.Println("All contracts passed.")
}

Seeder de origem

anônimo