CodeSampleX

Sample

go.opentelemetry.io/otel/trace v1.32.0: Tracer creates spans with custom SpanKind, attributes, events, links, status codes, and error recording, supporting WithNewRoot and timestamp options

Verified sample for golang go.opentelemetry.io/otel/trace v1.32.0: Tracer creates spans with custom SpanKind, attributes, events, links, status codes, and…

sha256:34df8b53185bce49adbc1ffc2d5113075c6cd0b5a5110e6337a3cd9a04a1eac5

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 go

Verification-run environments

Environment Contract Stages Run
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

Case

HOW
Goal
Tracer creates spans with custom SpanKind, attributes, events, links, status codes, and error recording, supporting WithNewRoot and timestamp options
Packages
Symbols
  • trace.Span
  • trace.Tracer
  • trace.WithAttributes
  • trace.WithLinks
  • trace.WithNewRoot
  • trace.WithSpanKind
  • trace.WithStackTrace
  • trace.WithTimestamp
Created
2026-08-27T10:12:33Z

Contract

  1. NewSpanStartConfig resolves WithSpanKind, WithAttributes, WithNewRoot, WithTimestamp, and WithLinks into a SpanConfig
  2. NewSpanEndConfig and NewEventConfig record timestamps, attributes, and stack trace flags for span termination and events
  3. Tracer starts spans with configured start options, attaches spans to context via ContextWithSpan, and records events, errors, status, and attributes across the span lifecycle
  4. NoopTracerProvider and NoopTracer safely handle all start options, attributes, events, error records, and status updates as non-recording spans

Files

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

Download the source artifact (tar.gz)

Source

NOTES.md
# OpenTelemetry Go Trace Tracer and Span Lifecycle

## Search Known Solution Result
- `search_known_solution` returned `NO_SAFE_MATCH` for the combination of `trace.Tracer`, `trace.Span`, `trace.WithSpanKind`, `trace.WithAttributes`, `trace.WithLinks`, `trace.WithNewRoot`, `trace.WithTimestamp`, `trace.WithStackTrace`.
- Existing samples focus on W3C `TraceState` limits and `TextMapPropagator` baggage propagation.
- **Why this sample is distinct**: This sample demonstrates the span lifecycle, span options evaluation, and interface contracts for OpenTelemetry Go tracing:
  1. `trace.NewSpanStartConfig` resolves `WithSpanKind`, `WithAttributes`, `WithNewRoot`, `WithTimestamp`, and `WithLinks` into a configured `SpanConfig`.
  2. `trace.NewSpanEndConfig` and `trace.NewEventConfig` configure timestamps, attributes, and stack trace capture options (`WithStackTrace`) for span termination and event recording.
  3. `trace.Tracer.Start` activates a span and propagates it into Go `context.Context` via `trace.ContextWithSpan`, allowing retrieval through `trace.SpanFromContext`.
  4. Spans support runtime mutation via `SetAttributes`, `AddEvent`, `RecordError`, `SetStatus`, and `End`.
  5. `noop.NewTracerProvider` and `noop.Tracer` provide non-recording span implementations that safely accept all span lifecycle operations without panicking.

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

## Observed Behaviour
1. **Span Start Options**:
   - `trace.WithSpanKind` configures the role of the span (e.g., Server, Client, Producer, Consumer).
   - `trace.WithNewRoot` explicitly detaches a span from any parent span in context.
   - `trace.WithTimestamp` sets explicit start/end/event timestamps.
   - `trace.WithLinks` associates zero or more external span contexts with custom attributes.
2. **Span Lifecycle & Error Recording**:
   - `span.RecordError` records an exception event with type and message attributes.
   - `span.SetStatus` sets the final status code (`codes.Error`, `codes.Ok`, `codes.Unset`) and description.
   - `span.End` accepts `WithTimestamp` and `WithStackTrace` options and marks the span as non-recording.
3. **Noop Behavior**:
   - `noop.Tracer.Start` produces a non-recording span (`IsRecording() == false`) with an invalid `SpanContext`.
   - Calling mutations (`SetAttributes`, `AddEvent`, `RecordError`, `SetStatus`, `End`) on a noop span safely executes without panicking.
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: Tracer creates spans with custom SpanKind, attributes, events, links, status codes, and error recording, supporting WithNewRoot and timestamp options
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel/trace@v1.32.0
Demonstrate these symbols/APIs:
  - trace.Span
  - trace.Tracer
  - trace.WithAttributes
  - trace.WithLinks
  - trace.WithNewRoot
  - trace.WithSpanKind
  - trace.WithStackTrace
  - trace.WithTimestamp

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:dab493631bdd150f6e3ecc09de3e1ac614b4a0e6cbd5caab588dfdfa8ed6816f","contract":["NewSpanStartConfig resolves WithSpanKind, WithAttributes, WithNewRoot, WithTimestamp, and WithLinks into a SpanConfig","NewSpanEndConfig and NewEventConfig record timestamps, attributes, and stack trace flags for span termination and events","Tracer starts spans with configured start options, attaches spans to context via ContextWithSpan, and records events, errors, status, and attributes across the span lifecycle","NoopTracerProvider and NoopTracer safely handle all start options, attributes, events, error records, and status updates as non-recording spans"],"goal":"Tracer creates spans with custom SpanKind, attributes, events, links, status codes, and error recording, supporting WithNewRoot and timestamp options","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/trace@v1.32.0"],"schemaVersion":1,"symbols":["trace.Span","trace.Tracer","trace.WithAttributes","trace.WithLinks","trace.WithNewRoot","trace.WithSpanKind","trace.WithStackTrace","trace.WithTimestamp"]},"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.32.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/trace@v1.32.0","symbols":["trace.Span","trace.Tracer","trace.WithAttributes","trace.WithLinks","trace.WithNewRoot","trace.WithSpanKind","trace.WithStackTrace","trace.WithTimestamp"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require (
	go.opentelemetry.io/otel v1.32.0
	go.opentelemetry.io/otel/trace v1.32.0
)
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.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
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.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U=
go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg=
go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM=
go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8=
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": "Tracer creates spans with custom SpanKind, attributes, events, links, status codes, and error recording, supporting WithNewRoot and timestamp options",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/trace@v1.32.0"
  ],
  "symbols": [
    "trace.Span",
    "trace.Tracer",
    "trace.WithAttributes",
    "trace.WithLinks",
    "trace.WithNewRoot",
    "trace.WithSpanKind",
    "trace.WithStackTrace",
    "trace.WithTimestamp"
  ]
}
trace_test.go
package sample_test

import (
	"context"
	"errors"
	"testing"
	"time"

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

// customSpan implements trace.Span to record start and runtime configurations
type customSpan struct {
	noop.Span
	startConfig trace.SpanConfig
	endConfig   trace.SpanConfig
	attributes  []attribute.KeyValue
	events      []customEvent
	status      codes.Code
	statusDesc  string
	ended       bool
}

type customEvent struct {
	name   string
	config trace.EventConfig
}

func (s *customSpan) End(options ...trace.SpanEndOption) {
	s.endConfig = trace.NewSpanEndConfig(options...)
	s.ended = true
}

func (s *customSpan) AddEvent(name string, options ...trace.EventOption) {
	s.events = append(s.events, customEvent{
		name:   name,
		config: trace.NewEventConfig(options...),
	})
}

func (s *customSpan) RecordError(err error, options ...trace.EventOption) {
	if err == nil {
		return
	}
	opts := append([]trace.EventOption{
		trace.WithAttributes(
			attribute.String("exception.type", "error"),
			attribute.String("exception.message", err.Error()),
		),
	}, options...)
	s.AddEvent("exception", opts...)
}

func (s *customSpan) SetStatus(code codes.Code, description string) {
	s.status = code
	s.statusDesc = description
}

func (s *customSpan) SetAttributes(kv ...attribute.KeyValue) {
	s.attributes = append(s.attributes, kv...)
}

func (s *customSpan) IsRecording() bool {
	return !s.ended
}

// customTracer implements trace.Tracer to instantiate customSpan with SpanStartOptions
type customTracer struct {
	noop.Tracer
}

func (t *customTracer) Start(ctx context.Context, spanName string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
	cfg := trace.NewSpanStartConfig(opts...)
	span := &customSpan{
		startConfig: cfg,
	}
	return trace.ContextWithSpan(ctx, span), span
}

func TestSpanStartOptionsResolution(t *testing.T) {
	startTime := time.Date(2026, time.August, 27, 10, 0, 0, 0, time.UTC)
	linkTraceID := trace.TraceID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
	linkSpanID := trace.SpanID{1, 2, 3, 4, 5, 6, 7, 8}
	linkSC := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID: linkTraceID,
		SpanID:  linkSpanID,
	})

	link := trace.Link{
		SpanContext: linkSC,
		Attributes:  []attribute.KeyValue{attribute.String("rel", "follows_from")},
	}

	opts := []trace.SpanStartOption{
		trace.WithSpanKind(trace.SpanKindServer),
		trace.WithAttributes(
			attribute.String("component", "http_server"),
			attribute.Int("http.status_code", 200),
		),
		trace.WithNewRoot(),
		trace.WithTimestamp(startTime),
		trace.WithLinks(link),
	}

	cfg := trace.NewSpanStartConfig(opts...)

	if cfg.SpanKind() != trace.SpanKindServer {
		t.Fatalf("expected SpanKindServer, got %v", cfg.SpanKind())
	}
	if !cfg.NewRoot() {
		t.Fatalf("expected NewRoot to be true")
	}
	if !cfg.Timestamp().Equal(startTime) {
		t.Fatalf("expected timestamp %v, got %v", startTime, cfg.Timestamp())
	}
	if len(cfg.Attributes()) != 2 {
		t.Fatalf("expected 2 attributes, got %d", len(cfg.Attributes()))
	}
	if len(cfg.Links()) != 1 {
		t.Fatalf("expected 1 link, got %d", len(cfg.Links()))
	}
	if !cfg.Links()[0].SpanContext.Equal(linkSC) {
		t.Fatalf("expected link SpanContext to match")
	}
}

func TestSpanEndAndEventOptions(t *testing.T) {
	endTime := time.Date(2026, time.August, 27, 10, 5, 0, 0, time.UTC)
	endCfg := trace.NewSpanEndConfig(
		trace.WithTimestamp(endTime),
		trace.WithStackTrace(true),
	)

	if !endCfg.Timestamp().Equal(endTime) {
		t.Fatalf("expected end timestamp %v, got %v", endTime, endCfg.Timestamp())
	}
	if !endCfg.StackTrace() {
		t.Fatalf("expected end stack trace to be true")
	}

	eventTime := time.Date(2026, time.August, 27, 10, 2, 0, 0, time.UTC)
	eventCfg := trace.NewEventConfig(
		trace.WithTimestamp(eventTime),
		trace.WithAttributes(attribute.String("event.type", "cache_hit")),
		trace.WithStackTrace(false),
	)

	if !eventCfg.Timestamp().Equal(eventTime) {
		t.Fatalf("expected event timestamp %v, got %v", eventTime, eventCfg.Timestamp())
	}
	if eventCfg.StackTrace() {
		t.Fatalf("expected event stack trace to be false")
	}
	if len(eventCfg.Attributes()) != 1 || eventCfg.Attributes()[0].Key != "event.type" {
		t.Fatalf("unexpected event attributes: %v", eventCfg.Attributes())
	}
}

func TestTracerAndSpanLifecycle(t *testing.T) {
	tracer := &customTracer{}
	ctx := context.Background()

	startTime := time.Date(2026, time.August, 27, 10, 0, 0, 0, time.UTC)
	ctx, span := tracer.Start(ctx, "ProcessOrder",
		trace.WithSpanKind(trace.SpanKindConsumer),
		trace.WithAttributes(attribute.String("order.id", "ord-1234")),
		trace.WithNewRoot(),
		trace.WithTimestamp(startTime),
	)

	// Verify span in context
	extractedSpan := trace.SpanFromContext(ctx)
	if extractedSpan != span {
		t.Fatalf("SpanFromContext did not retrieve the active span")
	}
	if !span.IsRecording() {
		t.Fatalf("span must be recording before End()")
	}

	// Add event
	eventTime := time.Date(2026, time.August, 27, 10, 1, 0, 0, time.UTC)
	span.AddEvent("validation_passed",
		trace.WithTimestamp(eventTime),
		trace.WithAttributes(attribute.Bool("validated", true)),
	)

	// Record error with stack trace
	errTime := time.Date(2026, time.August, 27, 10, 2, 0, 0, time.UTC)
	testErr := errors.New("insufficient inventory")
	span.RecordError(testErr,
		trace.WithTimestamp(errTime),
		trace.WithStackTrace(true),
	)
	span.SetStatus(codes.Error, "order failed")

	// Set extra attributes
	span.SetAttributes(attribute.Int("retry_count", 2))

	// End span
	endTime := time.Date(2026, time.August, 27, 10, 3, 0, 0, time.UTC)
	span.End(
		trace.WithTimestamp(endTime),
		trace.WithStackTrace(true),
	)

	if span.IsRecording() {
		t.Fatalf("span must not be recording after End()")
	}

	cs := span.(*customSpan)
	if cs.startConfig.SpanKind() != trace.SpanKindConsumer {
		t.Fatalf("expected SpanKindConsumer, got %v", cs.startConfig.SpanKind())
	}
	if !cs.startConfig.NewRoot() {
		t.Fatalf("expected startConfig.NewRoot() true")
	}
	if len(cs.events) != 2 {
		t.Fatalf("expected 2 events, got %d", len(cs.events))
	}
	if cs.events[0].name != "validation_passed" {
		t.Fatalf("expected event 0 'validation_passed', got %s", cs.events[0].name)
	}
	if cs.events[1].name != "exception" {
		t.Fatalf("expected event 1 'exception', got %s", cs.events[1].name)
	}
	if !cs.events[1].config.StackTrace() {
		t.Fatalf("expected exception event stacktrace true")
	}
	if cs.status != codes.Error || cs.statusDesc != "order failed" {
		t.Fatalf("unexpected status: %v (%s)", cs.status, cs.statusDesc)
	}
	if !cs.endConfig.Timestamp().Equal(endTime) || !cs.endConfig.StackTrace() {
		t.Fatalf("unexpected end configuration")
	}
}

func TestNoopTracerAndSpan(t *testing.T) {
	// Standard library noop TracerProvider and Tracer
	noopTP := noop.NewTracerProvider()
	noopTracer := noopTP.Tracer("noop-tracer")

	ctx := context.Background()
	ctx, span := noopTracer.Start(ctx, "noop-op",
		trace.WithSpanKind(trace.SpanKindClient),
		trace.WithAttributes(attribute.String("k", "v")),
		trace.WithNewRoot(),
		trace.WithTimestamp(time.Now()),
	)

	if span.IsRecording() {
		t.Fatalf("noop span should never be recording")
	}
	sc := span.SpanContext()
	if sc.IsValid() {
		t.Fatalf("noop span without parent should have invalid SpanContext")
	}

	// Invoking all methods on noop span should safely no-op without panicking
	span.SetAttributes(attribute.Int("count", 1))
	span.AddEvent("noop_event", trace.WithTimestamp(time.Now()), trace.WithStackTrace(true))
	span.RecordError(errors.New("ignored error"), trace.WithStackTrace(true))
	span.SetStatus(codes.Ok, "all good")
	span.SetName("renamed-op")
	span.End(trace.WithTimestamp(time.Now()), trace.WithStackTrace(true))

	// SpanFromContext on context with noop span returns non-recording span
	fromCtx := trace.SpanFromContext(ctx)
	if fromCtx.IsRecording() {
		t.Fatalf("SpanFromContext should return a non-recording span")
	}
	if fromCtx.SpanContext().IsValid() {
		t.Fatalf("SpanFromContext should have invalid SpanContext")
	}
}

Origin Seeder

anonymous