CodeSampleX

Ejemplo

go.opentelemetry.io/otel/trace v1.37.0: SpanContext

Muestra verificada para golang go.opentelemetry.io/otel/trace v1.37.0: SpanContext. El contrato se ejecutó en go 1.26 · linux debian/x64 · docker y pasó.

sha256:1c59b323eac8c0b3c10d35471d951997119d22705527f49c85507a6e9e702ea0

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 gomod

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-19

Caso

HOW
Objetivo
verify go.opentelemetry.io/otel/trace.SpanContext in pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0
Paquetes
Símbolos
  • go.opentelemetry.io/otel/trace.SpanContext
Creado
2026-09-17T15:29:48Z

Contrato

  1. NewSpanContext requires non-zero TraceID and SpanID for IsValid to return true, reporting HasTraceID, HasSpanID, and IsSampled accurately
  2. WithRemote, WithTraceFlags, and WithTraceState return updated copies without mutating the original SpanContext instance
  3. SpanContext Equal validates TraceID, SpanID, TraceFlags, TraceState, and Remote status
  4. ContextWithRemoteSpanContext stores remote SpanContext in context.Context and SpanFromContext returns a non-recording placeholder span preserving remote context properties

Archivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • trace_test.go

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# OpenTelemetry Go SpanContext Lifecycle and Immutability

## Search Known Solution Result
- `search_known_solution` returned `REVERIFY` for `verify go.opentelemetry.io/otel/trace.SpanContext in pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0` (existing samples were pinned to v1.32.0 and v1.24.0).
- **Why this sample is distinct**: Validates and pins the `go.opentelemetry.io/otel/trace.SpanContext` contract directly against `v1.37.0`:
  1. `NewSpanContext` requires non-zero values for both `TraceID` and `SpanID` for `IsValid()` to return true. If either is missing or zero, `IsValid()` evaluates to false while `HasTraceID()` and `HasSpanID()` isolate individual field presence.
  2. Modifiers `WithRemote`, `WithTraceFlags`, and `WithTraceState` follow strict value immutability, returning modified copies without mutating original instances.
  3. `SpanContext.Equal` compares all components (`TraceID`, `SpanID`, `TraceFlags`, `TraceState`, and `Remote`).
  4. `ContextWithRemoteSpanContext` stores a remote `SpanContext` into `context.Context` without activating a span, allowing `SpanFromContext` to return a non-recording placeholder span that preserves the remote context properties.

## Pinned Release
- `go.opentelemetry.io/otel/trace v1.37.0`

## Observed Behaviour
1. **SpanContext Construction and Validity**:
   - A zero `SpanContext` is invalid (`IsValid() == false`).
   - `NewSpanContext` with only `TraceID` or only `SpanID` returns an invalid `SpanContext`.
   - Both `TraceID` and `SpanID` must be valid for `IsValid()` to return true.
2. **Immutable Modifiers**:
   - `WithRemote(bool)` updates the remote status on a returned copy.
   - `WithTraceFlags(TraceFlags)` updates flags on a returned copy.
   - `WithTraceState(TraceState)` updates the trace state on a returned copy.
3. **Equality**:
   - `Equal` evaluates true only if `TraceID`, `SpanID`, `TraceFlags`, `TraceState`, and `Remote` match identically.
4. **Context Propagation**:
   - `ContextWithRemoteSpanContext` attaches a remote `SpanContext` to a Go `context.Context`.
   - `SpanFromContext` returns a non-recording span (`IsRecording() == false`) whose `SpanContext()` matches the remote `SpanContext` (`IsRemote() == true`).
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/otel/trace.SpanContext in pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0
Demonstrate these symbols/APIs:
  - go.opentelemetry.io/otel/trace.SpanContext

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:a34fca41722b9a1c2ffea5f56af9f66b7ffdf2afee4250684ffce11b22b33cc0","contract":["NewSpanContext requires non-zero TraceID and SpanID for IsValid to return true, reporting HasTraceID, HasSpanID, and IsSampled accurately","WithRemote, WithTraceFlags, and WithTraceState return updated copies without mutating the original SpanContext instance","SpanContext Equal validates TraceID, SpanID, TraceFlags, TraceState, and Remote status","ContextWithRemoteSpanContext stores remote SpanContext in context.Context and SpanFromContext returns a non-recording placeholder span preserving remote context properties"],"goal":"verify go.opentelemetry.io/otel/trace.SpanContext in pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/otel/trace.SpanContext"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"gomod","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0","symbols":["go.opentelemetry.io/otel/trace.SpanContext"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.23.0

require go.opentelemetry.io/otel/trace v1.37.0

require go.opentelemetry.io/otel v1.37.0 // indirect
go.sum
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/otel/trace.SpanContext in pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0"
  ],
  "symbols": [
    "go.opentelemetry.io/otel/trace.SpanContext"
  ]
}
trace_test.go
package sample_test

import (
	"context"
	"testing"

	"go.opentelemetry.io/otel/trace"
)

func TestSpanContextValidityAndProperties(t *testing.T) {
	// Zero SpanContext is invalid
	var zeroSC trace.SpanContext
	if zeroSC.IsValid() {
		t.Errorf("zero SpanContext must be invalid")
	}
	if zeroSC.HasTraceID() {
		t.Errorf("zero SpanContext must not have valid TraceID")
	}
	if zeroSC.HasSpanID() {
		t.Errorf("zero SpanContext must not have valid SpanID")
	}
	if zeroSC.IsSampled() {
		t.Errorf("zero SpanContext must not be sampled")
	}
	if zeroSC.IsRemote() {
		t.Errorf("zero SpanContext must not be remote")
	}

	traceID, err := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	if err != nil {
		t.Fatalf("TraceIDFromHex failed: %v", err)
	}
	spanID, err := trace.SpanIDFromHex("00f067aa0ba902b7")
	if err != nil {
		t.Fatalf("SpanIDFromHex failed: %v", err)
	}

	// SpanContext requires both non-zero TraceID and non-zero SpanID to be valid
	scOnlyTrace := trace.NewSpanContext(trace.SpanContextConfig{TraceID: traceID})
	if scOnlyTrace.IsValid() {
		t.Errorf("SpanContext with zero SpanID must be invalid")
	}
	if !scOnlyTrace.HasTraceID() || scOnlyTrace.HasSpanID() {
		t.Errorf("SpanContext with only TraceID must report HasTraceID=true and HasSpanID=false")
	}

	scOnlySpan := trace.NewSpanContext(trace.SpanContextConfig{SpanID: spanID})
	if scOnlySpan.IsValid() {
		t.Errorf("SpanContext with zero TraceID must be invalid")
	}
	if scOnlySpan.HasTraceID() || !scOnlySpan.HasSpanID() {
		t.Errorf("SpanContext with only SpanID must report HasTraceID=false and HasSpanID=true")
	}

	ts, err := trace.ParseTraceState("vendor=alpha")
	if err != nil {
		t.Fatalf("ParseTraceState failed: %v", err)
	}

	sc := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID,
		SpanID:     spanID,
		TraceFlags: trace.FlagsSampled,
		TraceState: ts,
		Remote:     true,
	})

	if !sc.IsValid() {
		t.Fatalf("SpanContext with non-zero TraceID and SpanID must be valid")
	}
	if !sc.HasTraceID() || !sc.HasSpanID() {
		t.Errorf("SpanContext must report HasTraceID=true and HasSpanID=true")
	}
	if !sc.IsRemote() {
		t.Errorf("SpanContext must report IsRemote=true")
	}
	if !sc.IsSampled() {
		t.Errorf("SpanContext must report IsSampled=true")
	}
	if sc.TraceFlags() != trace.FlagsSampled {
		t.Errorf("expected TraceFlags %v, got %v", trace.FlagsSampled, sc.TraceFlags())
	}
	if sc.TraceState().String() != "vendor=alpha" {
		t.Errorf("expected TraceState 'vendor=alpha', got %s", sc.TraceState().String())
	}
}

func TestSpanContextImmutableModifiers(t *testing.T) {
	traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
	ts, _ := trace.ParseTraceState("env=prod")

	orig := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID,
		SpanID:     spanID,
		TraceFlags: trace.FlagsSampled,
		TraceState: ts,
		Remote:     true,
	})

	// WithRemote returns a copy with updated remote status, leaving original untouched
	localCopy := orig.WithRemote(false)
	if localCopy.IsRemote() {
		t.Errorf("localCopy must have Remote=false")
	}
	if !orig.IsRemote() {
		t.Errorf("original SpanContext must retain Remote=true")
	}

	// WithTraceFlags returns a copy with updated flags, leaving original untouched
	unsampledCopy := orig.WithTraceFlags(0x00)
	if unsampledCopy.IsSampled() {
		t.Errorf("unsampledCopy must have IsSampled=false")
	}
	if !orig.IsSampled() {
		t.Errorf("original SpanContext must retain IsSampled=true")
	}

	// WithTraceState returns a copy with updated TraceState, leaving original untouched
	newTS, _ := trace.ParseTraceState("env=dev,tier=frontend")
	updatedTSCopy := orig.WithTraceState(newTS)
	if updatedTSCopy.TraceState().String() != "env=dev,tier=frontend" {
		t.Errorf("updatedTSCopy must have new TraceState")
	}
	if orig.TraceState().String() != "env=prod" {
		t.Errorf("original SpanContext must retain original TraceState")
	}
}

func TestSpanContextEquality(t *testing.T) {
	traceID1, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	traceID2, _ := trace.TraceIDFromHex("0123456789abcdef0123456789abcdef")
	spanID1, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
	spanID2, _ := trace.SpanIDFromHex("fedcba9876543210")
	ts1, _ := trace.ParseTraceState("k=v1")
	ts2, _ := trace.ParseTraceState("k=v2")

	sc1 := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID1,
		SpanID:     spanID1,
		TraceFlags: trace.FlagsSampled,
		TraceState: ts1,
		Remote:     true,
	})

	sc1Duplicate := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID1,
		SpanID:     spanID1,
		TraceFlags: trace.FlagsSampled,
		TraceState: ts1,
		Remote:     true,
	})

	if !sc1.Equal(sc1Duplicate) {
		t.Errorf("identical SpanContext instances must be Equal")
	}

	// Equal checks TraceID, SpanID, TraceFlags, TraceState, and Remote
	if sc1.Equal(sc1.WithRemote(false)) {
		t.Errorf("SpanContext with different Remote flag must not be Equal")
	}
	if sc1.Equal(sc1.WithTraceFlags(0x00)) {
		t.Errorf("SpanContext with different TraceFlags must not be Equal")
	}
	if sc1.Equal(sc1.WithTraceState(ts2)) {
		t.Errorf("SpanContext with different TraceState must not be Equal")
	}

	scDiffTraceID := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID2,
		SpanID:     spanID1,
		TraceFlags: trace.FlagsSampled,
		TraceState: ts1,
		Remote:     true,
	})
	if sc1.Equal(scDiffTraceID) {
		t.Errorf("SpanContext with different TraceID must not be Equal")
	}

	scDiffSpanID := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID1,
		SpanID:     spanID2,
		TraceFlags: trace.FlagsSampled,
		TraceState: ts1,
		Remote:     true,
	})
	if sc1.Equal(scDiffSpanID) {
		t.Errorf("SpanContext with different SpanID must not be Equal")
	}
}

func TestContextRemoteSpanContextAndSpanFromContext(t *testing.T) {
	ctx := context.Background()

	// Empty context returns non-recording span with invalid SpanContext
	emptySpan := trace.SpanFromContext(ctx)
	if emptySpan == nil {
		t.Fatalf("SpanFromContext must never return nil")
	}
	if emptySpan.IsRecording() {
		t.Errorf("SpanFromContext on untraced context must not be recording")
	}
	if emptySpan.SpanContext().IsValid() {
		t.Errorf("SpanFromContext on untraced context must have invalid SpanContext")
	}

	// Create valid remote SpanContext
	traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
	ts, _ := trace.ParseTraceState("tenant=alpha")
	remoteSC := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID,
		SpanID:     spanID,
		TraceFlags: trace.FlagsSampled,
		TraceState: ts,
		Remote:     true,
	})

	// ContextWithRemoteSpanContext stores remote SpanContext in Context
	remoteCtx := trace.ContextWithRemoteSpanContext(ctx, remoteSC)

	extractedSC := trace.SpanContextFromContext(remoteCtx)
	if !extractedSC.Equal(remoteSC) {
		t.Fatalf("SpanContextFromContext did not retrieve identical SpanContext")
	}

	spanFromCtx := trace.SpanFromContext(remoteCtx)
	if spanFromCtx == nil {
		t.Fatalf("SpanFromContext on remote context must not be nil")
	}
	if spanFromCtx.IsRecording() {
		t.Fatalf("SpanFromContext on remote context must return a non-recording placeholder span")
	}
	if !spanFromCtx.SpanContext().Equal(remoteSC) {
		t.Fatalf("SpanFromContext SpanContext does not match remote SpanContext")
	}
	if !spanFromCtx.SpanContext().IsRemote() {
		t.Fatalf("SpanFromContext SpanContext must retain remote status")
	}
}

Seeder de origen

anónimo