CodeSampleX

示例

go.opentelemetry.io/otel/trace v1.37.0: ParseTraceState, TraceState.Insert, TraceState.Delete

已验证示例 — golang go.opentelemetry.io/otel/trace v1.37.0: ParseTraceState, TraceState.Insert, TraceState.Delete. contract 在 go 1.26 · linux debian/x64 · docker…

sha256:6dc068dc1ea45965011fd0aae42902114329bf2b5fa762c5c587937e95ce536e

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 go linux 24 · ubuntu · glibc 2.39 x64 go go gomod

验证运行环境

环境 契约 阶段 运行日期
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-16

案例

HOW
目标
verify pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0
包
符号
  • go.opentelemetry.io/otel/trace.ParseTraceState
  • go.opentelemetry.io/otel/trace.TraceState.Insert
  • go.opentelemetry.io/otel/trace.TraceState.Delete
  • go.opentelemetry.io/otel/trace.NewSpanContext
  • go.opentelemetry.io/otel/trace.ContextWithRemoteSpanContext
  • go.opentelemetry.io/otel/trace.SpanFromContext
环境
go
创建时间
2026-09-16T12:17:19Z

契约

  1. ParseTraceState enforces W3C syntax and fails when exceeding 32 members, while Insert prepends new entries, moves updated keys to the head, and silently drops tail entries exceeding the 32-member limit
  2. Delete removes targeted key while preserving remaining member order, and deleting nonexistent keys returns identical copy
  3. NewSpanContext requires non-zero TraceID and SpanID for validity, preserving TraceFlags, TraceState, and Remote status
  4. ContextWithRemoteSpanContext stores remote span context in context.Context and SpanFromContext returns a non-recording span preserving the remote context

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# OpenTelemetry Go Trace Context and TraceState Lifecycle (v1.37.0)

## Search Known Solution Result
- `search_known_solution` returned existing OpenTelemetry samples for v1.35.0 (`sha256:69235f0b6d4fce1faa220931dd41851a39f3a4da531c09b34cb2c0b78aedecaa`) and v1.45.0 (`sha256:754781c365eac75c8696c1c32b0184086b76a32bfc2e42ecdcf75496a3940a73`).
- **Why this sample is distinct**: This sample targets and proves the exact lifecycle, immutability, and W3C limits for `go.opentelemetry.io/otel/trace` pinned to `v1.37.0`:
  1. `trace.ParseTraceState` strictly enforces W3C syntax rules and returns an error when the input exceeds the 32-member list limit.
  2. `TraceState.Insert` prepends new keys to index 0, updates existing keys by moving them to index 0 (MRU order), and caps the list at 32 members by silently evicting the least recently updated tail member without returning an error.
  3. `TraceState.Delete` removes specific members while preserving the relative ordering of remaining entries, and deleting nonexistent keys returns an unchanged copy.
  4. `trace.NewSpanContext` requires non-zero values for both `TraceID` and `SpanID` for `IsValid()` to return true.
  5. `trace.ContextWithRemoteSpanContext` stores a remote `SpanContext` into `context.Context` without activating a span, allowing `trace.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. **TraceState Parsing vs Insertion Limits**:
   - `trace.ParseTraceState` strictly validates member count; providing 33 or more comma-separated entries fails with an error.
   - `TraceState.Insert` dynamically caps member count at 32. Inserting a 33rd key succeeds, prepending the new key to the head and dropping the oldest member at the tail.
   - Inserting an existing key updates its value and relocates that key to the head of the list.
2. **TraceState Deletion and Empty Representation**:
   - `TraceState.Delete` removes the specified key and keeps the remaining list elements in their existing order.
   - Deleting a key that is not present leaves the `TraceState` unmodified.
   - An empty `TraceState` has a length of 0 and serializes to `""`.
3. **SpanContext Construction and Validity**:
   - A `SpanContext` is valid (`IsValid() == true`) if and only if both `TraceID` and `SpanID` are non-zero.
   - Modifiers (`WithRemote`, `WithTraceFlags`, `WithTraceState`) create updated copies without mutating the original instance.
4. **Context Propagation**:
   - `trace.ContextWithRemoteSpanContext` attaches a remote `SpanContext` to Go context.
   - `trace.SpanFromContext` on such a context returns a non-recording span (`IsRecording() == false`) whose `SpanContext()` matches the remote `SpanContext` (including `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 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

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:7173e2ec220bc31fc42f7a4e505ee4da3acbe6f50cd009a451f170b1b74c7908","contract":["ParseTraceState enforces W3C syntax and fails when exceeding 32 members, while Insert prepends new entries, moves updated keys to the head, and silently drops tail entries exceeding the 32-member limit","Delete removes targeted key while preserving remaining member order, and deleting nonexistent keys returns identical copy","NewSpanContext requires non-zero TraceID and SpanID for validity, preserving TraceFlags, TraceState, and Remote status","ContextWithRemoteSpanContext stores remote span context in context.Context and SpanFromContext returns a non-recording span preserving the remote context"],"goal":"verify 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.ParseTraceState","go.opentelemetry.io/otel/trace.TraceState.Insert","go.opentelemetry.io/otel/trace.TraceState.Delete","go.opentelemetry.io/otel/trace.NewSpanContext","go.opentelemetry.io/otel/trace.ContextWithRemoteSpanContext","go.opentelemetry.io/otel/trace.SpanFromContext"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"gomod","runtime":"go","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.ParseTraceState","go.opentelemetry.io/otel/trace.TraceState.Insert","go.opentelemetry.io/otel/trace.TraceState.Delete","go.opentelemetry.io/otel/trace.NewSpanContext","go.opentelemetry.io/otel/trace.ContextWithRemoteSpanContext","go.opentelemetry.io/otel/trace.SpanFromContext"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

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 pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/trace@v1.37.0"
  ]
}
trace_test.go
package sample_test

import (
	"context"
	"fmt"
	"strings"
	"testing"

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

func TestTraceStateLifecycleAndLimits(t *testing.T) {
	// Parse valid W3C TraceState header
	ts, err := trace.ParseTraceState("vendor1=alpha,tenant1@system=beta")
	if err != nil {
		t.Fatalf("ParseTraceState failed: %v", err)
	}
	if ts.Len() != 2 {
		t.Fatalf("expected length 2, got %d", ts.Len())
	}
	if ts.Get("vendor1") != "alpha" || ts.Get("tenant1@system") != "beta" {
		t.Fatalf("unexpected values: vendor1=%s, tenant1@system=%s", ts.Get("vendor1"), ts.Get("tenant1@system"))
	}
	if ts.String() != "vendor1=alpha,tenant1@system=beta" {
		t.Fatalf("unexpected serialized tracestate: %s", ts.String())
	}

	// Reject invalid syntax and characters
	if _, err := trace.ParseTraceState("INVALID_KEY=val"); err == nil {
		t.Errorf("ParseTraceState must reject uppercase keys")
	}
	if _, err := trace.ParseTraceState("@invalid=val"); err == nil {
		t.Errorf("ParseTraceState must reject keys starting with @")
	}
	if _, err := trace.ParseTraceState("key=\x00"); err == nil {
		t.Errorf("ParseTraceState must reject control characters in values")
	}

	// Reject headers with more than 32 members
	var over32 []string
	for i := 0; i < 33; i++ {
		over32 = append(over32, fmt.Sprintf("k%d=v%d", i, i))
	}
	if _, err := trace.ParseTraceState(strings.Join(over32, ",")); err == nil {
		t.Errorf("ParseTraceState must reject tracestate with >32 members")
	}

	// Insert prepends new member to head
	tsPrepended, err := ts.Insert("vendor3", "gamma")
	if err != nil {
		t.Fatalf("Insert failed: %v", err)
	}
	if tsPrepended.Len() != 3 || tsPrepended.String() != "vendor3=gamma,vendor1=alpha,tenant1@system=beta" {
		t.Fatalf("expected vendor3 at head, got %s", tsPrepended.String())
	}

	// Insert existing key updates value and moves key to head (MRU)
	tsUpdated, err := tsPrepended.Insert("tenant1@system", "beta_updated")
	if err != nil {
		t.Fatalf("Insert failed: %v", err)
	}
	if tsUpdated.Len() != 3 || tsUpdated.String() != "tenant1@system=beta_updated,vendor3=gamma,vendor1=alpha" {
		t.Fatalf("expected updated key at head, got %s", tsUpdated.String())
	}

	// Insert maintains 32-member cap by silently dropping oldest tail member
	var fullTS trace.TraceState
	for i := 0; i < 32; i++ {
		var err error
		fullTS, err = fullTS.Insert(fmt.Sprintf("k%02d", i), fmt.Sprintf("v%02d", i))
		if err != nil {
			t.Fatalf("Insert failed at index %d: %v", i, err)
		}
	}
	if fullTS.Len() != 32 {
		t.Fatalf("expected length 32, got %d", fullTS.Len())
	}

	fullTS, err = fullTS.Insert("k32", "v32")
	if err != nil {
		t.Fatalf("Insert on full TraceState should succeed: %v", err)
	}
	if fullTS.Len() != 32 {
		t.Fatalf("expected length to remain 32, got %d", fullTS.Len())
	}
	if fullTS.Get("k32") != "v32" {
		t.Fatalf("expected k32 at head")
	}
	if fullTS.Get("k00") != "" {
		t.Fatalf("expected oldest k00 to be evicted from tail")
	}

	// Delete removes member while preserving remaining order
	tsDeleted := ts.Delete("vendor1")
	if tsDeleted.Len() != 1 || tsDeleted.String() != "tenant1@system=beta" {
		t.Fatalf("expected tenant1@system=beta after delete, got %s", tsDeleted.String())
	}

	// Deleting nonexistent member returns identical copy
	tsUnchanged := tsDeleted.Delete("missing")
	if tsUnchanged.Len() != 1 || tsUnchanged.String() != "tenant1@system=beta" {
		t.Fatalf("expected unchanged TraceState on missing key deletion")
	}
}

func TestSpanContextConstructionAndImmutability(t *testing.T) {
	// Zero SpanContext is invalid
	var zeroSC trace.SpanContext
	if zeroSC.IsValid() {
		t.Errorf("zero SpanContext must be invalid")
	}
	if zeroSC.TraceID().IsValid() || zeroSC.SpanID().IsValid() {
		t.Errorf("zero IDs must not be valid")
	}

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

	// Requires both TraceID and SpanID to be valid
	scTraceOnly := trace.NewSpanContext(trace.SpanContextConfig{TraceID: traceID})
	if scTraceOnly.IsValid() {
		t.Errorf("SpanContext with only TraceID must be invalid")
	}
	scSpanOnly := trace.NewSpanContext(trace.SpanContextConfig{SpanID: spanID})
	if scSpanOnly.IsValid() {
		t.Errorf("SpanContext with only SpanID must be invalid")
	}

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

	if !sc.IsValid() {
		t.Fatalf("SpanContext with valid TraceID and SpanID must be valid")
	}
	if !sc.IsRemote() {
		t.Errorf("SpanContext must retain Remote flag")
	}
	if !sc.IsSampled() || sc.TraceFlags() != trace.FlagsSampled {
		t.Errorf("SpanContext must retain TraceFlags")
	}
	if sc.TraceState().String() != "vendor=test" {
		t.Errorf("SpanContext must retain TraceState")
	}

	// Modifiers return updated copies without mutating receiver
	scLocal := sc.WithRemote(false)
	if scLocal.IsRemote() || !sc.IsRemote() {
		t.Errorf("WithRemote should produce non-remote copy without mutating original")
	}

	scUnsampled := sc.WithTraceFlags(0x00)
	if scUnsampled.IsSampled() || !sc.IsSampled() {
		t.Errorf("WithTraceFlags should produce unsampled copy without mutating original")
	}

	emptyTS := trace.TraceState{}
	scEmptyTS := sc.WithTraceState(emptyTS)
	if scEmptyTS.TraceState().String() != "" || sc.TraceState().String() != "vendor=test" {
		t.Errorf("WithTraceState should produce updated copy without mutating original")
	}
}

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

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

	traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
	ts, _ := trace.ParseTraceState("role=worker")
	remoteSC := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID,
		SpanID:     spanID,
		TraceFlags: trace.FlagsSampled,
		TraceState: ts,
		Remote:     true,
	})

	// ContextWithRemoteSpanContext stores remote span context
	remoteCtx := trace.ContextWithRemoteSpanContext(ctx, remoteSC)

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

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

原始种子者

匿名