CodeSampleX

Beispiel

go.opentelemetry.io/otel/trace v1.24.0: ContextWithSpanContext, LinkFromContext, ValidateSpanKind

Verifiziertes Beispiel für golang go.opentelemetry.io/otel/trace v1.24.0: ContextWithSpanContext, LinkFromContext, ValidateSpanKind. Der Vertrag lief auf go…

sha256:b0deb4d1c4022ee60203a2df97414bdb0a2de6f7d17e04118bacf1435d7f77cb

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 linux 24 · ubuntu · glibc 2.39 x64 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-02

Fall

HOW
Ziel
verify pkg:golang/go.opentelemetry.io/otel/trace@v1.24.0
Pakete
Symbole
  • go.opentelemetry.io/otel/trace.ContextWithSpanContext
  • go.opentelemetry.io/otel/trace.LinkFromContext
  • go.opentelemetry.io/otel/trace.ValidateSpanKind
Erstellt
2026-09-02T22:36:25Z

Contract

  1. ContextWithSpanContext stores SpanContext in context yielding a non-recording span and SpanContextFromContext recovers it
  2. LinkFromContext extracts valid SpanContext from populated context and attaches attributes to the Link
  3. LinkFromContext on an uninstrumented context yields Link with invalid SpanContext while preserving attributes
  4. ValidateSpanKind preserves standard span kinds while coercing SpanKindUnspecified and out-of-range values to SpanKindInternal

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

NOTES.md
# OpenTelemetry Go Trace Context, LinkFromContext, and SpanKind Validation

## Search Known Solution Result
- `search_known_solution` returned `NO_SAFE_MATCH` for `ContextWithSpanContext`, `LinkFromContext`, and `ValidateSpanKind`.
- Existing samples focus on W3C `TraceState` limits, `TextMapPropagator` baggage propagation, and `Tracer` span starting options.
- **Why this sample is distinct**: This sample demonstrates:
  1. `trace.ContextWithSpanContext` attaches a `SpanContext` to `context.Context` without activating a live recording span, allowing `trace.SpanContextFromContext` to recover it and `trace.SpanFromContext` to return a non-recording placeholder span.
  2. `trace.LinkFromContext` extracts the active or attached `SpanContext` from a context and packages it into a `trace.Link` alongside custom attributes. When called on an uninstrumented context, it produces a Link with an invalid `SpanContext` while preserving provided attributes.
  3. `trace.ValidateSpanKind` preserves recognized span kinds (`SpanKindInternal`, `SpanKindServer`, `SpanKindClient`, `SpanKindProducer`, `SpanKindConsumer`), while coercing `SpanKindUnspecified` and unrecognized out-of-range values to `SpanKindInternal`.

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

## Observed Behaviour
1. `ContextWithSpanContext` produces an unrecorded span accessible via `SpanFromContext` whose `SpanContext()` matches the input.
2. `LinkFromContext` correctly extracts the `SpanContext` from context and attaches key-value attributes.
3. `ValidateSpanKind` normalizes invalid and unspecified kinds into `SpanKindInternal`.
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/otel/trace@v1.24.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel/trace@v1.24.0
Demonstrate these symbols/APIs:
  - go.opentelemetry.io/otel/trace.ContextWithSpanContext
  - go.opentelemetry.io/otel/trace.LinkFromContext
  - go.opentelemetry.io/otel/trace.ValidateSpanKind

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:755eaa98eeca2cc100ecc4e88fca3f9d2514365f0b9ae6d567056fa40893c581","contract":["ContextWithSpanContext stores SpanContext in context yielding a non-recording span and SpanContextFromContext recovers it","LinkFromContext extracts valid SpanContext from populated context and attaches attributes to the Link","LinkFromContext on an uninstrumented context yields Link with invalid SpanContext while preserving attributes","ValidateSpanKind preserves standard span kinds while coercing SpanKindUnspecified and out-of-range values to SpanKindInternal"],"goal":"verify pkg:golang/go.opentelemetry.io/otel/trace@v1.24.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/trace@v1.24.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/otel/trace.ContextWithSpanContext","go.opentelemetry.io/otel/trace.LinkFromContext","go.opentelemetry.io/otel/trace.ValidateSpanKind"]},"contractCommand":["go","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/otel/trace@v1.24.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/trace@v1.24.0","symbols":["go.opentelemetry.io/otel/trace.ContextWithSpanContext","go.opentelemetry.io/otel/trace.LinkFromContext","go.opentelemetry.io/otel/trace.ValidateSpanKind"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require (
	go.opentelemetry.io/otel v1.24.0
	go.opentelemetry.io/otel/trace v1.24.0
)
go.sum
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI=
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/go.opentelemetry.io/otel/trace@v1.24.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/trace@v1.24.0"
  ],
  "symbols": [
    "go.opentelemetry.io/otel/trace.ContextWithSpanContext",
    "go.opentelemetry.io/otel/trace.LinkFromContext",
    "go.opentelemetry.io/otel/trace.ValidateSpanKind"
  ]
}
trace_test.go
package sample_test

import (
	"context"
	"testing"

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

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

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

	sc := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID,
		SpanID:     spanID,
		TraceFlags: trace.FlagsSampled,
	})
	if !sc.IsValid() {
		t.Fatalf("expected valid SpanContext")
	}

	ctxWithSC := trace.ContextWithSpanContext(ctx, sc)

	// SpanContextFromContext recovers the exact stored SpanContext
	recoveredSC := trace.SpanContextFromContext(ctxWithSC)
	if !recoveredSC.Equal(sc) {
		t.Fatalf("recovered SpanContext did not match original: got %+v, want %+v", recoveredSC, sc)
	}

	// SpanFromContext on context populated with ContextWithSpanContext returns a non-recording span preserving the SpanContext
	span := trace.SpanFromContext(ctxWithSC)
	if span == nil {
		t.Fatalf("SpanFromContext returned nil")
	}
	if span.IsRecording() {
		t.Fatalf("SpanFromContext for ContextWithSpanContext must return a non-recording span")
	}
	if !span.SpanContext().Equal(sc) {
		t.Fatalf("span SpanContext did not match original: got %+v, want %+v", span.SpanContext(), sc)
	}
}

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

	// Empty context produces Link with invalid SpanContext while preserving attributes
	untracedLink := trace.LinkFromContext(ctx, attribute.String("meta", "orphan"))
	if untracedLink.SpanContext.IsValid() {
		t.Fatalf("LinkFromContext on empty context must have invalid SpanContext")
	}
	if len(untracedLink.Attributes) != 1 || untracedLink.Attributes[0].Key != "meta" || untracedLink.Attributes[0].Value.AsString() != "orphan" {
		t.Fatalf("LinkFromContext failed to preserve attributes on untraced context: %+v", untracedLink.Attributes)
	}

	// Populated context produces Link with matching valid SpanContext and attributes
	traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
	sc := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID,
		SpanID:     spanID,
		TraceFlags: trace.FlagsSampled,
	})
	ctxWithSC := trace.ContextWithSpanContext(ctx, sc)

	link := trace.LinkFromContext(ctxWithSC,
		attribute.String("link.relation", "parent"),
		attribute.Int("link.sequence", 1),
	)

	if !link.SpanContext.IsValid() {
		t.Fatalf("expected valid SpanContext in link")
	}
	if !link.SpanContext.Equal(sc) {
		t.Fatalf("link SpanContext does not match context SpanContext: got %+v, want %+v", link.SpanContext, sc)
	}
	if len(link.Attributes) != 2 {
		t.Fatalf("expected 2 attributes on link, got %d", len(link.Attributes))
	}
	if link.Attributes[0].Key != "link.relation" || link.Attributes[0].Value.AsString() != "parent" {
		t.Fatalf("unexpected attribute 0: %+v", link.Attributes[0])
	}
	if link.Attributes[1].Key != "link.sequence" || link.Attributes[1].Value.AsInt64() != 1 {
		t.Fatalf("unexpected attribute 1: %+v", link.Attributes[1])
	}
}

func TestValidateSpanKind(t *testing.T) {
	// Standard span kinds are preserved as-is
	tests := []struct {
		input    trace.SpanKind
		expected trace.SpanKind
	}{
		{trace.SpanKindInternal, trace.SpanKindInternal},
		{trace.SpanKindServer, trace.SpanKindServer},
		{trace.SpanKindClient, trace.SpanKindClient},
		{trace.SpanKindProducer, trace.SpanKindProducer},
		{trace.SpanKindConsumer, trace.SpanKindConsumer},
	}

	for _, tc := range tests {
		got := trace.ValidateSpanKind(tc.input)
		if got != tc.expected {
			t.Errorf("ValidateSpanKind(%v) = %v; want %v", tc.input, got, tc.expected)
		}
	}

	// Unspecified and invalid out-of-range kinds are coerced to SpanKindInternal
	coercedTests := []trace.SpanKind{
		trace.SpanKindUnspecified,
		trace.SpanKind(-1),
		trace.SpanKind(99),
		trace.SpanKind(1000),
	}

	for _, input := range coercedTests {
		got := trace.ValidateSpanKind(input)
		if got != trace.SpanKindInternal {
			t.Errorf("ValidateSpanKind(%v) = %v; want SpanKindInternal (%v)", input, got, trace.SpanKindInternal)
		}
	}
}

Ursprungs-Seeder

anonym