CodeSampleX

示例

go.opentelemetry.io/otel/trace v1.39.0: WithLinks

已验证示例 — golang go.opentelemetry.io/otel/trace v1.39.0: WithLinks. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: WithLinks creates a SpanStartOption…

sha256:b9ee9031e8d5b1bcbac36c00a09d65313c35dc92e4439e7523e2fbd430c619ab

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

执行证据

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

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

验证运行环境

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

案例

HOW
目标
verify go.opentelemetry.io/otel/trace.WithLinks in pkg:golang/go.opentelemetry.io/otel/trace@v1.39.0
包
符号
  • go.opentelemetry.io/otel/trace.WithLinks
创建时间
2026-10-11T01:37:21Z

契约

  1. WithLinks creates a SpanStartOption configuring links on a SpanConfig retrievable via Links()
  2. WithLinks options accumulate cumulatively without overwriting when multiple WithLinks calls are provided
  3. WithLinks preserves slice isolation where modifying the source slice after configuration does not alter SpanConfig links
  4. WithLinks accepts empty or zero SpanContext links at configuration time without panicking
  5. WithLinks interoperates with LinkFromContext to preserve trace context and attributes from active contexts
  6. WithLinks passes SpanStartOption through Tracer.Start for tracer implementations to consume via SpanConfig

文件

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

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

源代码

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.WithLinks in pkg:golang/go.opentelemetry.io/otel/trace@v1.39.0
Kind: HOW

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

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:a16093698a2804f065593f7fb04c52c4779c01a0f51826a95f7ee59fbe36d8df","contract":["WithLinks creates a SpanStartOption configuring links on a SpanConfig retrievable via Links()","WithLinks options accumulate cumulatively without overwriting when multiple WithLinks calls are provided","WithLinks preserves slice isolation where modifying the source slice after configuration does not alter SpanConfig links","WithLinks accepts empty or zero SpanContext links at configuration time without panicking","WithLinks interoperates with LinkFromContext to preserve trace context and attributes from active contexts","WithLinks passes SpanStartOption through Tracer.Start for tracer implementations to consume via SpanConfig"],"goal":"verify go.opentelemetry.io/otel/trace.WithLinks in pkg:golang/go.opentelemetry.io/otel/trace@v1.39.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/trace@v1.39.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/otel/trace.WithLinks"]},"contractCommand":["go","run","./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.39.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/trace@v1.39.0","symbols":["go.opentelemetry.io/otel/trace.WithLinks"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require (
	go.opentelemetry.io/otel v1.39.0
	go.opentelemetry.io/otel/trace v1.39.0
)

require github.com/cespare/xxhash/v2 v2.3.0 // indirect
go.sum
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
main.go
package main

import (
	"context"
	"fmt"

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

func main() {
	// Generate valid trace IDs and span IDs for cross-trace linkage
	traceID1, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	spanID1, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
	traceID2, _ := trace.TraceIDFromHex("0af7651916cd43dd8448eb211c80319c")
	spanID2, _ := trace.SpanIDFromHex("b7ad6b7169203331")

	// Create linked SpanContexts
	sc1 := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID1,
		SpanID:     spanID1,
		TraceFlags: trace.FlagsSampled,
		Remote:     true,
	})
	sc2 := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID2,
		SpanID:     spanID2,
		TraceFlags: trace.FlagsSampled,
		Remote:     false,
	})

	// Construct links with attributes
	link1 := trace.Link{
		SpanContext: sc1,
		Attributes: []attribute.KeyValue{
			attribute.String("link.type", "parent_request"),
			attribute.Int("batch.seq", 1),
		},
	}
	link2 := trace.Link{
		SpanContext: sc2,
		Attributes: []attribute.KeyValue{
			attribute.String("link.type", "enqueued_job"),
			attribute.Int("batch.seq", 2),
		},
	}

	// 1. WithLinks with multiple links
	startOpt := trace.WithLinks(link1, link2)
	cfg := trace.NewSpanStartConfig(startOpt)
	fmt.Printf("Configured %d links via WithLinks\n", len(cfg.Links()))

	// 2. Cumulative WithLinks
	cfgCumulative := trace.NewSpanStartConfig(
		trace.WithLinks(link1),
		trace.WithLinks(link2),
	)
	fmt.Printf("Cumulative WithLinks resulted in %d links\n", len(cfgCumulative.Links()))

	// 3. Start a span using a Tracer with WithLinks
	tp := noop.NewTracerProvider()
	tracer := tp.Tracer("demo-tracer")
	ctx, span := tracer.Start(
		context.Background(),
		"process_batch_item",
		trace.WithLinks(link1, link2),
	)
	defer span.End()

	fmt.Printf("Started span with WithLinks: isRecording=%v\n", span.IsRecording())
	_ = ctx
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/otel/trace.WithLinks in pkg:golang/go.opentelemetry.io/otel/trace@v1.39.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/trace@v1.39.0"
  ],
  "symbols": [
    "go.opentelemetry.io/otel/trace.WithLinks"
  ]
}
test/contract.go
package main

import (
	"context"
	"fmt"
	"os"

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

// recordingMockTracer captures SpanConfig generated by SpanStartOptions including WithLinks.
type recordingMockTracer struct {
	embedded.Tracer
	capturedConfig trace.SpanConfig
}

func (m *recordingMockTracer) Start(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
	m.capturedConfig = trace.NewSpanStartConfig(opts...)
	span := noop.NewTracerProvider().Tracer("mock").Start
	return span(ctx, name, opts...)
}

func main() {
	traceID1, err := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to parse traceID1: %v\n", err)
		os.Exit(1)
	}
	spanID1, err := trace.SpanIDFromHex("00f067aa0ba902b7")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to parse spanID1: %v\n", err)
		os.Exit(1)
	}

	traceID2, err := trace.TraceIDFromHex("0af7651916cd43dd8448eb211c80319c")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to parse traceID2: %v\n", err)
		os.Exit(1)
	}
	spanID2, err := trace.SpanIDFromHex("b7ad6b7169203331")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to parse spanID2: %v\n", err)
		os.Exit(1)
	}

	sc1 := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID1,
		SpanID:     spanID1,
		TraceFlags: trace.FlagsSampled,
		Remote:     true,
	})
	sc2 := trace.NewSpanContext(trace.SpanContextConfig{
		TraceID:    traceID2,
		SpanID:     spanID2,
		TraceFlags: trace.FlagsSampled,
		Remote:     false,
	})

	link1 := trace.Link{
		SpanContext: sc1,
		Attributes: []attribute.KeyValue{
			attribute.String("link.purpose", "upstream-job"),
			attribute.Int("link.id", 101),
		},
	}
	link2 := trace.Link{
		SpanContext: sc2,
		Attributes: []attribute.KeyValue{
			attribute.String("link.purpose", "peer-message"),
			attribute.Int("link.id", 102),
		},
	}

	// Assertion 1: WithLinks creates a SpanStartOption that configures links on a SpanConfig retrievable via Links().
	cfg1 := trace.NewSpanStartConfig(trace.WithLinks(link1, link2))
	gotLinks1 := cfg1.Links()
	if len(gotLinks1) != 2 {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 1]: expected 2 links, got %d\n", len(gotLinks1))
		os.Exit(1)
	}
	if !gotLinks1[0].SpanContext.Equal(sc1) {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 1]: link 0 SpanContext mismatch\n")
		os.Exit(1)
	}
	if !gotLinks1[1].SpanContext.Equal(sc2) {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 1]: link 1 SpanContext mismatch\n")
		os.Exit(1)
	}
	if len(gotLinks1[0].Attributes) != 2 || gotLinks1[0].Attributes[0].Value.AsString() != "upstream-job" {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 1]: link 0 attributes mismatch\n")
		os.Exit(1)
	}

	// Assertion 2: WithLinks options accumulate cumulatively without overwriting when multiple WithLinks calls are provided.
	cfg2 := trace.NewSpanStartConfig(
		trace.WithLinks(link1),
		trace.WithLinks(link2),
	)
	gotLinks2 := cfg2.Links()
	if len(gotLinks2) != 2 {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 2]: expected 2 accumulated links, got %d\n", len(gotLinks2))
		os.Exit(1)
	}
	if !gotLinks2[0].SpanContext.Equal(sc1) || !gotLinks2[1].SpanContext.Equal(sc2) {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 2]: accumulated links order or SpanContext mismatch\n")
		os.Exit(1)
	}

	// Assertion 3: WithLinks preserves slice isolation where modifying the source slice after configuration does not alter SpanConfig links.
	linkSlice := []trace.Link{link1, link2}
	cfg3 := trace.NewSpanStartConfig(trace.WithLinks(linkSlice...))
	// Mutate underlying slice
	linkSlice[0] = trace.Link{SpanContext: trace.SpanContext{}}
	gotLinks3 := cfg3.Links()
	if !gotLinks3[0].SpanContext.Equal(sc1) {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 3]: slice mutation mutated SpanConfig links\n")
		os.Exit(1)
	}

	// Assertion 4: WithLinks accepts empty or zero SpanContext links at configuration time without panicking.
	emptyLink := trace.Link{}
	cfg4 := trace.NewSpanStartConfig(trace.WithLinks(emptyLink))
	gotLinks4 := cfg4.Links()
	if len(gotLinks4) != 1 {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 4]: expected 1 link in SpanConfig, got %d\n", len(gotLinks4))
		os.Exit(1)
	}
	if gotLinks4[0].SpanContext.IsValid() {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 4]: expected invalid SpanContext for empty link\n")
		os.Exit(1)
	}

	// Assertion 5: WithLinks interoperates with LinkFromContext to preserve trace context and attributes from active contexts.
	ctxWithRemote := trace.ContextWithRemoteSpanContext(context.Background(), sc1)
	linkFromCtx := trace.LinkFromContext(ctxWithRemote, attribute.String("rpc.system", "grpc"))
	cfg5 := trace.NewSpanStartConfig(trace.WithLinks(linkFromCtx))
	gotLinks5 := cfg5.Links()
	if len(gotLinks5) != 1 {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 5]: expected 1 link from context, got %d\n", len(gotLinks5))
		os.Exit(1)
	}
	if !gotLinks5[0].SpanContext.Equal(sc1) {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 5]: link from context SpanContext mismatch\n")
		os.Exit(1)
	}
	if len(gotLinks5[0].Attributes) != 1 || gotLinks5[0].Attributes[0].Value.AsString() != "grpc" {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 5]: link from context attributes mismatch\n")
		os.Exit(1)
	}

	// Assertion 6: WithLinks passes SpanStartOption through Tracer.Start for tracer implementations to consume via SpanConfig.
	mockTracer := &recordingMockTracer{}
	ctx, span := mockTracer.Start(context.Background(), "test-span", trace.WithLinks(link1, link2))
	if span == nil || ctx == nil {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 6]: mockTracer.Start returned nil span or context\n")
		os.Exit(1)
	}
	span.End()

	capturedLinks := mockTracer.capturedConfig.Links()
	if len(capturedLinks) != 2 {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 6]: expected mockTracer to capture 2 links, got %d\n", len(capturedLinks))
		os.Exit(1)
	}
	if !capturedLinks[0].SpanContext.Equal(sc1) || !capturedLinks[1].SpanContext.Equal(sc2) {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 6]: captured links SpanContext mismatch\n")
		os.Exit(1)
	}

	// Also verify noop tracer handles WithLinks cleanly
	noopTracer := noop.NewTracerProvider().Tracer("noop-test")
	noopCtx, noopSpan := noopTracer.Start(context.Background(), "noop-span", trace.WithLinks(link1))
	if noopSpan == nil || noopCtx == nil {
		fmt.Fprintf(os.Stderr, "FAIL [Assertion 6]: noopTracer.Start returned nil\n")
		os.Exit(1)
	}
	noopSpan.End()

	fmt.Println("PASS: all trace.WithLinks contract assertions passed.")
}

原始种子者

匿名