CodeSampleX

Пример

go.opentelemetry.io/otel v1.44.0: codes.Error

Проверенный пример — golang go.opentelemetry.io/otel v1.44.0: codes.Error. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:fb6b5f483e1c180db67e415af53b3fefbc265aacd607a35dd2b6f85ddf22d467

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-20

Кейс

HOW
Цель
verify go.opentelemetry.io/otel/codes.Error in pkg:golang/go.opentelemetry.io/otel@v1.44.0
Пакеты
Символы
  • go.opentelemetry.io/otel/codes.Error
Окружение
go 1.26.6
Создан
2026-09-20T00:09:08Z

Контракт

  1. assert codes.Error represents failure with numerical value 1 and string representation Error
  2. assert NewErrorStatus returns codes.Error with non-nil error and codes.Unset with nil error
  3. assert IsError accurately identifies codes.Error while rejecting codes.Ok and codes.Unset
  4. assert codes.Code pointer receiver MarshalJSON encodes to string Error and unmarshals back to codes.Error

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Notes

- **search_known_solution result**: The network returned a COMPATIBLE sample targeting OpenTelemetry v1.45.0 on musl with 0 contract passes. This clean-room sample targets `pkg:golang/go.opentelemetry.io/otel@v1.44.0` directly on Linux glibc with contract verification.
- **What a model would write instead**: A model frequently assumes `codes.Error` is `2` (confusing Go SDK internal code representation with OTLP wire specification where Error is 2 and Ok is 1), or assumes struct fields of value type `codes.Code` automatically serialize to JSON string `"Error"`. In Go SDK, `codes.Error` is `1` (uint32), and `MarshalJSON()` is defined on a pointer receiver `(*Code)`, so serializing value types directly falls back to the underlying integer `1`.
- **How the wrong version fails**: Marshaling a struct containing value-type `codes.Code` into JSON yields `{"code":1}` instead of `{"code":"Error"}`, causing downstream API consumers and tracing ingestion pipelines that expect textual status enum strings to fail schema validation or misclassify errors.
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/codes.Error in pkg:golang/go.opentelemetry.io/otel@v1.44.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel@v1.44.0
Demonstrate these symbols/APIs:
  - go.opentelemetry.io/otel/codes.Error
Required runtime conditions:
  - ecosystem: golang
  - language: go
  - packageManager: go@1.26.6
  - runtime: go@1.26.6

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:12c5b933959474651e2f8d0a702d9230dcb2050276d9b9b8cd9c333747eace68","contract":["assert codes.Error represents failure with numerical value 1 and string representation Error","assert NewErrorStatus returns codes.Error with non-nil error and codes.Unset with nil error","assert IsError accurately identifies codes.Error while rejecting codes.Ok and codes.Unset","assert codes.Code pointer receiver MarshalJSON encodes to string Error and unmarshals back to codes.Error"],"goal":"verify go.opentelemetry.io/otel/codes.Error in pkg:golang/go.opentelemetry.io/otel@v1.44.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel@v1.44.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/otel/codes.Error"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/otel@v1.44.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel@v1.44.0","symbols":["go.opentelemetry.io/otel/codes.Error"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require go.opentelemetry.io/otel v1.44.0
go.sum
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
sample.go
package sample

import (
	"encoding/json"

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

// Status represents an operation status with an OpenTelemetry code and description.
type Status struct {
	Code        codes.Code `json:"code"`
	Description string     `json:"description,omitempty"`
}

// NewStatus creates a new Status.
func NewStatus(code codes.Code, description string) Status {
	return Status{
		Code:        code,
		Description: description,
	}
}

// NewErrorStatus creates a Status initialized with codes.Error.
func NewErrorStatus(err error) Status {
	if err == nil {
		return Status{
			Code:        codes.Unset,
			Description: "",
		}
	}
	return Status{
		Code:        codes.Error,
		Description: err.Error(),
	}
}

// IsError checks whether the status code matches codes.Error.
func IsError(code codes.Code) bool {
	return code == codes.Error
}

// FormatCode returns the string representation of the given code.
func FormatCode(code codes.Code) string {
	return code.String()
}

// MarshalCodeJSON demonstrates the pointer receiver requirement:
// codes.Code.MarshalJSON has a pointer receiver (*Code), so serializing as string "Error" requires &code.
func MarshalCodeJSON(code codes.Code) ([]byte, error) {
	return (&code).MarshalJSON()
}

// UnmarshalCodeJSON parses a JSON string into a codes.Code.
func UnmarshalCodeJSON(data []byte) (codes.Code, error) {
	var c codes.Code
	err := json.Unmarshal(data, &c)
	return c, err
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/otel/codes.Error in pkg:golang/go.opentelemetry.io/otel@v1.44.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel@v1.44.0"
  ],
  "symbols": [
    "go.opentelemetry.io/otel/codes.Error"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.6",
    "runtime": "go@1.26.6"
  }
}
test/contract.go
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"os"

	"go.opentelemetry.io/otel/codes"
	"sample"
)

func main() {
	if err := runContractTests(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract test failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All OpenTelemetry codes.Error contract tests passed successfully.")
}

func runContractTests() error {
	// 1. codes.Error represents failure with numerical value 1 and string representation "Error"
	if codes.Error != 1 {
		return fmt.Errorf("expected codes.Error to have uint32 value 1, got %d", uint32(codes.Error))
	}
	if codes.Error.String() != "Error" {
		return fmt.Errorf("expected codes.Error.String() to be %q, got %q", "Error", codes.Error.String())
	}
	if sample.FormatCode(codes.Error) != "Error" {
		return fmt.Errorf("expected sample.FormatCode(codes.Error) to be %q, got %q", "Error", sample.FormatCode(codes.Error))
	}

	// 2. NewErrorStatus returns codes.Error with non-nil error and codes.Unset with nil error
	testErr := errors.New("operation timed out")
	errStatus := sample.NewErrorStatus(testErr)
	if errStatus.Code != codes.Error {
		return fmt.Errorf("expected error status code to be codes.Error, got %v", errStatus.Code)
	}
	if errStatus.Description != "operation timed out" {
		return fmt.Errorf("expected error status description 'operation timed out', got %q", errStatus.Description)
	}

	nilStatus := sample.NewErrorStatus(nil)
	if nilStatus.Code != codes.Unset {
		return fmt.Errorf("expected nil error to produce codes.Unset, got %v", nilStatus.Code)
	}
	if nilStatus.Description != "" {
		return fmt.Errorf("expected empty description for nil error, got %q", nilStatus.Description)
	}

	// 3. IsError accurately identifies codes.Error while rejecting codes.Ok and codes.Unset
	if !sample.IsError(codes.Error) {
		return fmt.Errorf("expected sample.IsError(codes.Error) to be true")
	}
	if sample.IsError(codes.Ok) {
		return fmt.Errorf("expected sample.IsError(codes.Ok) to be false")
	}
	if sample.IsError(codes.Unset) {
		return fmt.Errorf("expected sample.IsError(codes.Unset) to be false")
	}

	// 4. codes.Code MarshalJSON requires pointer receiver and round-trips correctly for codes.Error
	c := codes.Error
	encoded, err := sample.MarshalCodeJSON(c)
	if err != nil {
		return fmt.Errorf("failed to marshal codes.Error: %w", err)
	}
	if string(encoded) != `"Error"` {
		return fmt.Errorf("expected marshaled code to be %q, got %q", `"Error"`, string(encoded))
	}

	decoded, err := sample.UnmarshalCodeJSON(encoded)
	if err != nil {
		return fmt.Errorf("failed to unmarshal code: %w", err)
	}
	if decoded != codes.Error {
		return fmt.Errorf("expected unmarshaled code to be codes.Error, got %v", decoded)
	}

	// Also verify standard json.Marshal directly on pointer to codes.Code produces `"Error"`
	ptrEncoded, err := json.Marshal(&c)
	if err != nil {
		return fmt.Errorf("failed to marshal &codes.Error: %w", err)
	}
	if string(ptrEncoded) != `"Error"` {
		return fmt.Errorf("expected &c marshaled code to be %q, got %q", `"Error"`, string(ptrEncoded))
	}

	return nil
}

Исходный сидер

аноним