CodeSampleX

Beispiel

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

Verifiziertes Beispiel für golang go.opentelemetry.io/proto/otlp v1.9.0: v1.TracesData. Der Vertrag lief auf go 1.26 · linux debian/x64 · docker und bestand.

sha256:6f2e2c4a6e3d21a400842dea659984f4acc94bc653bce365978552e0bc1aa584

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung go linux 24 · ubuntu · glibc 2.39 x64 go go go

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
verify pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
Pakete
Symbole
  • go.opentelemetry.io/proto/otlp/trace/v1.TracesData
Umgebung
go
Erstellt
2026-09-05T09:11:04Z

Contract

  1. TracesData constructs and holds valid ResourceSpans with Resource, ScopeSpans, and Spans
  2. TracesData marshals to and unmarshals from binary protobuf wire format without data loss
  3. TracesData marshals to and unmarshals from JSON format preserving span attributes, events, and status
  4. TracesData preserves trace ID, span ID, parent span ID, and span kind across serialization
  5. TracesData preserves span timestamps, status code, and event metadata across serialization
  6. TracesData handles multiple ResourceSpans with multiple ScopeSpans and multiple Spans

Dateien

  • PROMPT.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json

Quellartefakt herunterladen (tar.gz)

Quelltext

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 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/trace/v1.TracesData

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.
contract_test.go
package sample

import (
	"bytes"
	"strings"
	"testing"

	tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
)

func TestTracesDataContract(t *testing.T) {
	traceID := [16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}
	spanID := [8]byte{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}
	parentSpanID := [8]byte{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11}

	// 1. TracesData constructs and holds valid ResourceSpans with Resource, ScopeSpans, and Spans
	t.Run("ConstructValidTracesData", func(t *testing.T) {
		span1 := NewSpan(
			traceID,
			spanID,
			parentSpanID,
			"/api/checkout",
			tracepb.Span_SPAN_KIND_SERVER,
			1700000000000000000,
			1700000000500000000,
			tracepb.Status_STATUS_CODE_OK,
			"request processed",
			StringAttribute("http.method", "POST"),
			IntAttribute("http.status_code", 200),
			BoolAttribute("auth.success", true),
			DoubleAttribute("response_time_ms", 50.5),
			BytesAttribute("request.id_hash", []byte{0xaa, 0xbb, 0xcc, 0xdd}),
		)
		resSpans := NewResourceSpans("order-service", "sample/tracer", "1.0.0", []*tracepb.Span{span1})
		tracesData := NewTracesData(resSpans)

		if len(tracesData.GetResourceSpans()) != 1 {
			t.Fatalf("expected 1 ResourceSpans, got %d", len(tracesData.GetResourceSpans()))
		}
		rs := tracesData.GetResourceSpans()[0]
		if rs.GetResource() == nil || len(rs.GetResource().GetAttributes()) == 0 {
			t.Fatalf("expected resource attributes to be present")
		}
		if rs.GetResource().GetAttributes()[0].GetKey() != "service.name" ||
			rs.GetResource().GetAttributes()[0].GetValue().GetStringValue() != "order-service" {
			t.Fatalf("unexpected resource attribute: %v", rs.GetResource().GetAttributes()[0])
		}
		if len(rs.GetScopeSpans()) != 1 {
			t.Fatalf("expected 1 ScopeSpans, got %d", len(rs.GetScopeSpans()))
		}
		ss := rs.GetScopeSpans()[0]
		if ss.GetScope().GetName() != "sample/tracer" || ss.GetScope().GetVersion() != "1.0.0" {
			t.Fatalf("unexpected scope: %v", ss.GetScope())
		}
		if len(ss.GetSpans()) != 1 {
			t.Fatalf("expected 1 Span, got %d", len(ss.GetSpans()))
		}
	})

	// 2. TracesData marshals to and unmarshals from binary protobuf wire format without data loss
	// 4. TracesData preserves trace ID, span ID, parent span ID, and span kind across serialization
	// 5. TracesData preserves span timestamps, status code, and event metadata across serialization
	t.Run("ProtobufSerializationRoundtrip", func(t *testing.T) {
		span1 := NewSpan(
			traceID,
			spanID,
			parentSpanID,
			"/api/checkout",
			tracepb.Span_SPAN_KIND_SERVER,
			1700000000000000000,
			1700000000500000000,
			tracepb.Status_STATUS_CODE_OK,
			"request processed",
			StringAttribute("http.method", "POST"),
			IntAttribute("http.status_code", 200),
		)
		span1.Events = []*tracepb.Span_Event{
			NewSpanEvent(1700000000200000000, "database_query", StringAttribute("db.table", "orders")),
		}
		resSpans := NewResourceSpans("order-service", "sample/tracer", "1.0.0", []*tracepb.Span{span1})
		tracesData := NewTracesData(resSpans)

		data, err := MarshalProto(tracesData)
		if err != nil {
			t.Fatalf("failed to marshal traces data to protobuf: %v", err)
		}
		if len(data) == 0 {
			t.Fatalf("marshaled protobuf wire format is empty")
		}

		unmarshaledTraces, err := UnmarshalProto(data)
		if err != nil {
			t.Fatalf("failed to unmarshal traces data from protobuf: %v", err)
		}
		if len(unmarshaledTraces.GetResourceSpans()) != 1 {
			t.Fatalf("unmarshaled traces data missing ResourceSpans")
		}
		uSpan := unmarshaledTraces.GetResourceSpans()[0].GetScopeSpans()[0].GetSpans()[0]
		if uSpan.GetName() != "/api/checkout" {
			t.Fatalf("unmarshaled span name mismatch: got %q, want '/api/checkout'", uSpan.GetName())
		}
		if !bytes.Equal(uSpan.GetTraceId(), traceID[:]) {
			t.Fatalf("trace ID mismatch after proto roundtrip: got %x, want %x", uSpan.GetTraceId(), traceID)
		}
		if !bytes.Equal(uSpan.GetSpanId(), spanID[:]) {
			t.Fatalf("span ID mismatch after proto roundtrip: got %x, want %x", uSpan.GetSpanId(), spanID)
		}
		if !bytes.Equal(uSpan.GetParentSpanId(), parentSpanID[:]) {
			t.Fatalf("parent span ID mismatch after proto roundtrip: got %x, want %x", uSpan.GetParentSpanId(), parentSpanID)
		}
		if uSpan.GetKind() != tracepb.Span_SPAN_KIND_SERVER {
			t.Fatalf("span kind mismatch: got %v, want %v", uSpan.GetKind(), tracepb.Span_SPAN_KIND_SERVER)
		}
		if uSpan.GetStartTimeUnixNano() != 1700000000000000000 {
			t.Fatalf("startTimeUnixNano mismatch: got %d, want 1700000000000000000", uSpan.GetStartTimeUnixNano())
		}
		if uSpan.GetEndTimeUnixNano() != 1700000000500000000 {
			t.Fatalf("endTimeUnixNano mismatch: got %d, want 1700000000500000000", uSpan.GetEndTimeUnixNano())
		}
		if uSpan.GetStatus().GetCode() != tracepb.Status_STATUS_CODE_OK {
			t.Fatalf("status code mismatch: got %v, want %v", uSpan.GetStatus().GetCode(), tracepb.Status_STATUS_CODE_OK)
		}
		if uSpan.GetStatus().GetMessage() != "request processed" {
			t.Fatalf("status message mismatch: got %q, want 'request processed'", uSpan.GetStatus().GetMessage())
		}
		if len(uSpan.GetEvents()) != 1 || uSpan.GetEvents()[0].GetName() != "database_query" {
			t.Fatalf("span event mismatch: got %v", uSpan.GetEvents())
		}
	})

	// 3. TracesData marshals to and unmarshals from JSON format preserving span attributes, events, and status
	t.Run("JSONSerializationRoundtrip", func(t *testing.T) {
		span1 := NewSpan(
			traceID,
			spanID,
			parentSpanID,
			"/api/checkout",
			tracepb.Span_SPAN_KIND_SERVER,
			1700000000000000000,
			1700000000500000000,
			tracepb.Status_STATUS_CODE_OK,
			"request processed",
			StringAttribute("http.method", "POST"),
		)
		span1.Events = []*tracepb.Span_Event{
			NewSpanEvent(1700000000200000000, "cache_lookup"),
		}
		resSpans := NewResourceSpans("order-service", "sample/tracer", "1.0.0", []*tracepb.Span{span1})
		tracesData := NewTracesData(resSpans)

		jsonData, err := MarshalJSON(tracesData)
		if err != nil {
			t.Fatalf("failed to marshal traces data to JSON: %v", err)
		}
		jsonStr := string(jsonData)
		if !strings.Contains(jsonStr, "order-service") || !strings.Contains(jsonStr, "/api/checkout") || !strings.Contains(jsonStr, "cache_lookup") {
			t.Fatalf("JSON output missing expected fields: %s", jsonStr)
		}

		jsonTraces, err := UnmarshalJSON(jsonData)
		if err != nil {
			t.Fatalf("failed to unmarshal traces data from JSON: %v", err)
		}
		if len(jsonTraces.GetResourceSpans()) != 1 {
			t.Fatalf("JSON unmarshaled traces data missing ResourceSpans")
		}
		uSpan := jsonTraces.GetResourceSpans()[0].GetScopeSpans()[0].GetSpans()[0]
		if uSpan.GetName() != "/api/checkout" {
			t.Fatalf("JSON unmarshaled span name mismatch: got %q, want '/api/checkout'", uSpan.GetName())
		}
		if uSpan.GetStatus().GetCode() != tracepb.Status_STATUS_CODE_OK {
			t.Fatalf("JSON unmarshaled status code mismatch: got %v, want %v", uSpan.GetStatus().GetCode(), tracepb.Status_STATUS_CODE_OK)
		}
	})

	// 6. TracesData handles multiple ResourceSpans with multiple ScopeSpans and multiple Spans
	t.Run("MultipleResourceSpansHandling", func(t *testing.T) {
		multiTraces := NewTracesData(
			NewResourceSpans("frontend-service", "sample/fe", "1.0.0", []*tracepb.Span{
				NewSpan(traceID, [8]byte{1}, [8]byte{}, "GET /", tracepb.Span_SPAN_KIND_SERVER, 100, 200, tracepb.Status_STATUS_CODE_OK, "ok"),
				NewSpan(traceID, [8]byte{2}, [8]byte{1}, "render", tracepb.Span_SPAN_KIND_INTERNAL, 110, 190, tracepb.Status_STATUS_CODE_OK, "ok"),
			}),
			NewResourceSpans("backend-service", "sample/be", "2.0.0", []*tracepb.Span{
				NewSpan(traceID, [8]byte{3}, [8]byte{1}, "rpc /call", tracepb.Span_SPAN_KIND_SERVER, 120, 180, tracepb.Status_STATUS_CODE_OK, "ok"),
			}),
		)

		multiData, err := MarshalProto(multiTraces)
		if err != nil {
			t.Fatalf("failed to marshal multi-resource traces: %v", err)
		}
		multiUnmarshaled, err := UnmarshalProto(multiData)
		if err != nil {
			t.Fatalf("failed to unmarshal multi-resource traces: %v", err)
		}
		if len(multiUnmarshaled.GetResourceSpans()) != 2 {
			t.Fatalf("expected 2 ResourceSpans, got %d", len(multiUnmarshaled.GetResourceSpans()))
		}
		if len(multiUnmarshaled.GetResourceSpans()[0].GetScopeSpans()[0].GetSpans()) != 2 {
			t.Fatalf("expected 2 Spans in first ResourceSpans, got %d", len(multiUnmarshaled.GetResourceSpans()[0].GetScopeSpans()[0].GetSpans()))
		}
		if len(multiUnmarshaled.GetResourceSpans()[1].GetScopeSpans()[0].GetSpans()) != 1 {
			t.Fatalf("expected 1 Span in second ResourceSpans, got %d", len(multiUnmarshaled.GetResourceSpans()[1].GetScopeSpans()[0].GetSpans()))
		}
	})
}
csx.json
{"case":{"caseId":"case:sha256:fbb278edf7812a974bb82ca6a0649590aa4e5a372d6abdacc46eb12b3600f883","contract":["TracesData constructs and holds valid ResourceSpans with Resource, ScopeSpans, and Spans","TracesData marshals to and unmarshals from binary protobuf wire format without data loss","TracesData marshals to and unmarshals from JSON format preserving span attributes, events, and status","TracesData preserves trace ID, span ID, parent span ID, and span kind across serialization","TracesData preserves span timestamps, status code, and event metadata across serialization","TracesData handles multiple ResourceSpans with multiple ScopeSpans and multiple Spans"],"goal":"verify 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/trace/v1.TracesData"]},"contractCommand":["go","test","-mod=readonly","-count=1","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"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/trace/v1.TracesData"],"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.11
)
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.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
sample.go
package sample

import (
	commonpb "go.opentelemetry.io/proto/otlp/common/v1"
	resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
	tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
)

// StringAttribute creates a string KeyValue attribute.
func StringAttribute(key, value string) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_StringValue{
				StringValue: value,
			},
		},
	}
}

// IntAttribute creates an int64 KeyValue attribute.
func IntAttribute(key string, value int64) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_IntValue{
				IntValue: value,
			},
		},
	}
}

// BoolAttribute creates a boolean KeyValue attribute.
func BoolAttribute(key string, value bool) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_BoolValue{
				BoolValue: value,
			},
		},
	}
}

// DoubleAttribute creates a float64 KeyValue attribute.
func DoubleAttribute(key string, value float64) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_DoubleValue{
				DoubleValue: value,
			},
		},
	}
}

// BytesAttribute creates a byte slice KeyValue attribute.
func BytesAttribute(key string, value []byte) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_BytesValue{
				BytesValue: value,
			},
		},
	}
}

// NewSpanEvent creates a Span_Event with a name, timestamp, and optional attributes.
func NewSpanEvent(timeUnixNano uint64, name string, attributes ...*commonpb.KeyValue) *tracepb.Span_Event {
	return &tracepb.Span_Event{
		TimeUnixNano: timeUnixNano,
		Name:         name,
		Attributes:   attributes,
	}
}

// NewSpan constructs a Span with trace context, timing, status, and attributes.
func NewSpan(
	traceID [16]byte,
	spanID [8]byte,
	parentSpanID [8]byte,
	name string,
	kind tracepb.Span_SpanKind,
	startTimeUnixNano uint64,
	endTimeUnixNano uint64,
	statusCode tracepb.Status_StatusCode,
	statusMsg string,
	attributes ...*commonpb.KeyValue,
) *tracepb.Span {
	var traceIDSlice []byte
	var spanIDSlice []byte
	var parentSpanIDSlice []byte
	if traceID != [16]byte{} {
		traceIDSlice = traceID[:]
	}
	if spanID != [8]byte{} {
		spanIDSlice = spanID[:]
	}
	if parentSpanID != [8]byte{} {
		parentSpanIDSlice = parentSpanID[:]
	}

	return &tracepb.Span{
		TraceId:           traceIDSlice,
		SpanId:            spanIDSlice,
		ParentSpanId:      parentSpanIDSlice,
		Name:              name,
		Kind:              kind,
		StartTimeUnixNano: startTimeUnixNano,
		EndTimeUnixNano:   endTimeUnixNano,
		Attributes:        attributes,
		Status: &tracepb.Status{
			Code:    statusCode,
			Message: statusMsg,
		},
	}
}

// NewResourceSpans constructs ResourceSpans with resource attributes and scope spans.
func NewResourceSpans(
	serviceName string,
	scopeName string,
	scopeVersion string,
	spans []*tracepb.Span,
) *tracepb.ResourceSpans {
	return &tracepb.ResourceSpans{
		Resource: &resourcepb.Resource{
			Attributes: []*commonpb.KeyValue{
				StringAttribute("service.name", serviceName),
			},
		},
		ScopeSpans: []*tracepb.ScopeSpans{
			{
				Scope: &commonpb.InstrumentationScope{
					Name:    scopeName,
					Version: scopeVersion,
				},
				Spans: spans,
			},
		},
	}
}

// NewTracesData wraps ResourceSpans into a TracesData container.
func NewTracesData(resSpans ...*tracepb.ResourceSpans) *tracepb.TracesData {
	return &tracepb.TracesData{
		ResourceSpans: resSpans,
	}
}

// MarshalProto serializes TracesData to protobuf wire format.
func MarshalProto(traces *tracepb.TracesData) ([]byte, error) {
	return proto.Marshal(traces)
}

// UnmarshalProto deserializes TracesData from protobuf wire format.
func UnmarshalProto(data []byte) (*tracepb.TracesData, error) {
	traces := &tracepb.TracesData{}
	if err := proto.Unmarshal(data, traces); err != nil {
		return nil, err
	}
	return traces, nil
}

// MarshalJSON serializes TracesData to JSON.
func MarshalJSON(traces *tracepb.TracesData) ([]byte, error) {
	return protojson.Marshal(traces)
}

// UnmarshalJSON deserializes TracesData from JSON.
func UnmarshalJSON(data []byte) (*tracepb.TracesData, error) {
	traces := &tracepb.TracesData{}
	if err := protojson.Unmarshal(data, traces); err != nil {
		return nil, err
	}
	return traces, nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify 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/trace/v1.TracesData"
  ]
}

Ursprungs-Seeder

anonym