CodeSampleX

サンプル

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

検証済みサンプル — golang go.opentelemetry.io/proto/otlp v1.9.0: v1.Metric_Sum. go 1.26 · linux debian/x64 · docker で contract を実行し、成功しました.

sha256:6b1b8246bd79974b8b8d721dfb1471135d67bd62b855b376c7261ad10a15077a

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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_Sum in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
パッケージ
シンボル
  • go.opentelemetry.io/proto/otlp/metrics/v1.Metric_Sum
作成日
2026-09-05T18:16:18Z

コントラクト

  1. Metric_Sum wraps a Sum message as the oneof data variant for an OTLP Metric.
  2. Metric.GetSum returns the wrapped Sum pointer when Metric_Sum is assigned and nil when another variant or no data is set.
  3. Metric.GetSum safely returns nil on nil receiver, unpopulated Metric, or when Metric_Sum has a nil Sum pointer.
  4. Metric with Metric_Sum roundtrips through Protobuf binary wire format without data loss, satisfying proto.Equal.
  5. Metric with Metric_Sum roundtrips through protojson format preserving JSON field names and nested data points.
  6. proto.Clone creates an isolated deep copy of Metric containing Metric_Sum where mutating the cloned Sum does not affect the original.

ファイル

  • 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.Metric_Sum 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_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:37491038f2d18e2b41e76542a6f7e43f2b5e3ac8b99bc0bcae266a38fb2efd2f","contract":["Metric_Sum wraps a Sum message as the oneof data variant for an OTLP Metric.","Metric.GetSum returns the wrapped Sum pointer when Metric_Sum is assigned and nil when another variant or no data is set.","Metric.GetSum safely returns nil on nil receiver, unpopulated Metric, or when Metric_Sum has a nil Sum pointer.","Metric with Metric_Sum roundtrips through Protobuf binary wire format without data loss, satisfying proto.Equal.","Metric with Metric_Sum roundtrips through protojson format preserving JSON field names and nested data points.","proto.Clone creates an isolated deep copy of Metric containing Metric_Sum where mutating the cloned Sum does not affect the original."],"goal":"verify go.opentelemetry.io/proto/otlp/metrics/v1.Metric_Sum 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_Sum"]},"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_Sum"],"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"

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

// NewSumMetric constructs an OTLP Metric containing a Metric_Sum data payload.
func NewSumMetric(name, unit string, isMonotonic bool, temporality metricspb.AggregationTemporality) *metricspb.Metric {
	return &metricspb.Metric{
		Name: name,
		Unit: unit,
		Data: &metricspb.Metric_Sum{
			Sum: &metricspb.Sum{
				IsMonotonic:            isMonotonic,
				AggregationTemporality: temporality,
			},
		},
	}
}

// ExtractSum retrieves the underlying Sum message from a Metric if the variant is Metric_Sum.
func ExtractSum(m *metricspb.Metric) (*metricspb.Sum, bool) {
	if m == nil {
		return nil, false
	}
	if s, ok := m.GetData().(*metricspb.Metric_Sum); ok {
		return s.Sum, true
	}
	return nil, false
}

func main() {
	m := NewSumMetric("http_requests_total", "1", true, metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE)
	sum, ok := ExtractSum(m)
	fmt.Printf("Metric name=%s hasSum=%v monotonic=%v\n", m.GetName(), ok, sum.GetIsMonotonic())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/proto/otlp/metrics/v1.Metric_Sum 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_Sum"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"

	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_Sum wraps a Sum message as the oneof data variant for an OTLP Metric.
	{
		sumPayload := &metricspb.Sum{
			AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,
			IsMonotonic:            true,
		}
		metricSum := &metricspb.Metric_Sum{
			Sum: sumPayload,
		}
		m := &metricspb.Metric{
			Name: "http_requests_total",
			Data: metricSum,
		}

		assert(m.GetData() != nil, "expected non-nil Data")
		extracted, ok := m.GetData().(*metricspb.Metric_Sum)
		assert(ok, "expected Data to be *metricspb.Metric_Sum")
		assert(extracted.Sum == sumPayload, "expected extracted Sum pointer to match original")
		assert(extracted.Sum.GetIsMonotonic() == true, "expected IsMonotonic true")
		assert(extracted.Sum.GetAggregationTemporality() == metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE, "expected CUMULATIVE temporality")
	}

	// Assertion 2: Metric.GetSum returns the wrapped Sum pointer when Metric_Sum is assigned and nil when another variant or no data is set.
	{
		sum := &metricspb.Sum{
			IsMonotonic:            false,
			AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA,
		}
		metricWithSum := &metricspb.Metric{
			Data: &metricspb.Metric_Sum{Sum: sum},
		}
		assert(metricWithSum.GetSum() == sum, "GetSum should return sum pointer")
		assert(metricWithSum.GetGauge() == nil, "GetGauge should return nil when Data is Metric_Sum")
		assert(metricWithSum.GetHistogram() == nil, "GetHistogram should return nil when Data is Metric_Sum")

		gaugeMetric := &metricspb.Metric{
			Data: &metricspb.Metric_Gauge{Gauge: &metricspb.Gauge{}},
		}
		assert(gaugeMetric.GetSum() == nil, "GetSum should return nil when Data is Metric_Gauge")

		emptyMetric := &metricspb.Metric{}
		assert(emptyMetric.GetSum() == nil, "GetSum should return nil when Data is unset")
	}

	// Assertion 3: Metric.GetSum safely returns nil on nil receiver, unpopulated Metric, or when Metric_Sum has a nil Sum pointer.
	{
		var nilMetric *metricspb.Metric
		assert(nilMetric.GetSum() == nil, "nil Metric GetSum must return nil")
		assert(nilMetric.GetData() == nil, "nil Metric GetData must return nil")

		emptyMetric := &metricspb.Metric{}
		assert(emptyMetric.GetSum() == nil, "empty Metric GetSum must return nil")

		metricWithNilSum := &metricspb.Metric{
			Data: &metricspb.Metric_Sum{Sum: nil},
		}
		assert(metricWithNilSum.GetSum() == nil, "Metric with nil Metric_Sum.Sum must return nil")
	}

	// Assertion 4: Metric with Metric_Sum roundtrips through Protobuf binary wire format without data loss, satisfying proto.Equal.
	{
		orig := &metricspb.Metric{
			Name:        "process_cpu_seconds_total",
			Description: "Total user and system CPU time spent in seconds",
			Unit:        "s",
			Data: &metricspb.Metric_Sum{
				Sum: &metricspb.Sum{
					AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,
					IsMonotonic:            true,
					DataPoints: []*metricspb.NumberDataPoint{
						{
							TimeUnixNano: 1700000000000000000,
							Value: &metricspb.NumberDataPoint_AsDouble{
								AsDouble: 123.456,
							},
						},
						{
							TimeUnixNano: 1700000060000000000,
							Value: &metricspb.NumberDataPoint_AsInt{
								AsInt: 789,
							},
						},
					},
				},
			},
		}

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

		var decoded metricspb.Metric
		err = proto.Unmarshal(wire, &decoded)
		assert(err == nil, "proto.Unmarshal failed")
		assert(proto.Equal(orig, &decoded), "proto.Equal returned false for protobuf round-trip")
		assert(decoded.GetSum() != nil, "decoded GetSum returned nil")
		assert(len(decoded.GetSum().GetDataPoints()) == 2, "decoded DataPoints length mismatch")
		assert(decoded.GetSum().GetDataPoints()[0].GetAsDouble() == 123.456, "decoded AsDouble mismatch")
		assert(decoded.GetSum().GetDataPoints()[1].GetAsInt() == 789, "decoded AsInt mismatch")
	}

	// Assertion 5: Metric with Metric_Sum roundtrips through protojson format preserving JSON field names and nested data points.
	{
		orig := &metricspb.Metric{
			Name: "system_memory_usage_bytes",
			Unit: "By",
			Data: &metricspb.Metric_Sum{
				Sum: &metricspb.Sum{
					AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,
					IsMonotonic:            false,
					DataPoints: []*metricspb.NumberDataPoint{
						{
							TimeUnixNano: 1700000000000000000,
							Value: &metricspb.NumberDataPoint_AsInt{
								AsInt: 1048576,
							},
						},
					},
				},
			},
		}

		jsonBytes, err := protojson.Marshal(orig)
		assert(err == nil, "protojson.Marshal failed")
		assert(bytes.Contains(jsonBytes, []byte(`"sum"`)), "json must contain 'sum'")
		assert(bytes.Contains(jsonBytes, []byte(`"dataPoints"`)) || bytes.Contains(jsonBytes, []byte(`"data_points"`)), "json must contain data points")

		var jsonDecoded metricspb.Metric
		err = protojson.Unmarshal(jsonBytes, &jsonDecoded)
		assert(err == nil, "protojson.Unmarshal failed")
		assert(proto.Equal(orig, &jsonDecoded), "proto.Equal returned false for protojson round-trip")
		assert(jsonDecoded.GetSum() != nil, "jsonDecoded GetSum returned nil")
		assert(jsonDecoded.GetSum().GetDataPoints()[0].GetAsInt() == 1048576, "jsonDecoded AsInt mismatch")
	}

	// Assertion 6: proto.Clone creates an isolated deep copy of Metric containing Metric_Sum where mutating the cloned Sum does not affect the original.
	{
		orig := &metricspb.Metric{
			Name: "requests_count",
			Data: &metricspb.Metric_Sum{
				Sum: &metricspb.Sum{
					IsMonotonic: true,
					DataPoints: []*metricspb.NumberDataPoint{
						{
							TimeUnixNano: 1700000000000000000,
							Value: &metricspb.NumberDataPoint_AsInt{
								AsInt: 10,
							},
						},
					},
				},
			},
		}

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

		// Mutate cloned Sum and its data points
		cloned.GetSum().IsMonotonic = false
		cloned.GetSum().GetDataPoints()[0].Value = &metricspb.NumberDataPoint_AsInt{AsInt: 999}
		cloned.GetSum().DataPoints = append(cloned.GetSum().DataPoints, &metricspb.NumberDataPoint{
			TimeUnixNano: 1700000060000000000,
			Value: &metricspb.NumberDataPoint_AsInt{
				AsInt: 20,
			},
		})

		// Verify original remains unmodified
		assert(orig.GetSum().GetIsMonotonic() == true, "original IsMonotonic was mutated")
		assert(len(orig.GetSum().GetDataPoints()) == 1, "original DataPoints length was mutated")
		assert(orig.GetSum().GetDataPoints()[0].GetAsInt() == 10, "original DataPoint value was mutated")
	}

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

オリジンシーダー

匿名