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에서 contract를 실행해 통과했습니다: assert codes.Error represents…

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
}

오리진 시더

익명