CodeSampleX

Exemplo

github.com/go-logr/logr v1.4.2

Amostra verificada para golang github.com/go-logr/logr v1.4.2. O contrato rodou em go 1.26 · linux alpine/x64 · docker e passou.

sha256:346c114b883d0544fe7a3a2293307ba18923940f030598c407b540f15f1786f0

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-24
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-07

Caso

HOW
Objetivo
verify pkg:golang/github.com/go-logr/logr@v1.4.2
Pacotes
Criado
2026-08-24T20:14:21Z

Contrato

  1. logr.New initializes a Logger with custom LogSink implementation
  2. LogSink.Info and LogSink.Error receive structured log parameters and error objects
  3. logr.Logger.WithSink and logr.Logger.GetSink swap and inspect the underlying LogSink
  4. logr.Logger.WithCallDepth configures stack frame offset on CallDepthLogSink
  5. logr.Logger.IsZero returns true for uninitialized or discard loggers and false for active sinks

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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/github.com/go-logr/logr@v1.4.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-logr/logr@v1.4.2
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:719ce8c29add69caf1e23d2b3241fc80aad6dc53066e654e760d81c9a929a466","contract":["logr.New initializes a Logger with custom LogSink implementation","LogSink.Info and LogSink.Error receive structured log parameters and error objects","logr.Logger.WithSink and logr.Logger.GetSink swap and inspect the underlying LogSink","logr.Logger.WithCallDepth configures stack frame offset on CallDepthLogSink","logr.Logger.IsZero returns true for uninitialized or discard loggers and false for active sinks"],"goal":"verify pkg:golang/github.com/go-logr/logr@v1.4.2","kind":"HOW","packages":["pkg:golang/github.com/go-logr/logr@v1.4.2"],"schemaVersion":1},"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/github.com/go-logr/logr@v1.4.2"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-logr/logr@v1.4.2","verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require github.com/go-logr/logr v1.4.2
go.sum
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
main.go
package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/go-logr/logr"
)

// CustomLogSink implements logr.LogSink and logr.CallDepthLogSink.
type CustomLogSink struct {
	name      string
	values    []any
	callDepth int
}

func (s *CustomLogSink) Init(info logr.RuntimeInfo) {
	s.callDepth = info.CallDepth
}

func (s *CustomLogSink) Enabled(level int) bool {
	return true
}

func (s *CustomLogSink) Info(level int, msg string, keysAndValues ...any) {
	allValues := append(s.values, keysAndValues...)
	fmt.Printf("[INFO] name=%q depth=%d msg=%q kv=%v\n", s.name, s.callDepth, msg, allValues)
}

func (s *CustomLogSink) Error(err error, msg string, keysAndValues ...any) {
	allValues := append(s.values, keysAndValues...)
	fmt.Fprintf(os.Stderr, "[ERROR] name=%q depth=%d msg=%q err=%v kv=%v\n", s.name, s.callDepth, msg, err, allValues)
}

func (s *CustomLogSink) WithValues(keysAndValues ...any) logr.LogSink {
	newVals := make([]any, 0, len(s.values)+len(keysAndValues))
	newVals = append(newVals, s.values...)
	newVals = append(newVals, keysAndValues...)
	return &CustomLogSink{
		name:      s.name,
		values:    newVals,
		callDepth: s.callDepth,
	}
}

func (s *CustomLogSink) WithName(name string) logr.LogSink {
	newName := s.name
	if newName != "" {
		newName += "." + name
	} else {
		newName = name
	}
	return &CustomLogSink{
		name:      newName,
		values:    s.values,
		callDepth: s.callDepth,
	}
}

func (s *CustomLogSink) WithCallDepth(depth int) logr.LogSink {
	return &CustomLogSink{
		name:      s.name,
		values:    s.values,
		callDepth: s.callDepth + depth,
	}
}

func main() {
	sink := &CustomLogSink{}
	logger := logr.New(sink)

	logger.Info("application starting", "version", "1.0.0")
	logger.WithName("subsystem").WithValues("module", "worker").Info("processing job", "jobId", 42)

	err := errors.New("resource unavailable")
	logger.Error(err, "operation failed", "retryCount", 3)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/go-logr/logr@v1.4.2",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-logr/logr@v1.4.2"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/go-logr/logr"
)

type recordedEvent struct {
	level     int
	isError   bool
	err       error
	msg       string
	name      string
	values    []any
	callDepth int
}

type testSink struct {
	events    *[]recordedEvent
	name      string
	values    []any
	callDepth int
	inited    bool
}

func newTestSink(events *[]recordedEvent) *testSink {
	return &testSink{
		events: events,
	}
}

func (s *testSink) Init(info logr.RuntimeInfo) {
	s.inited = true
	s.callDepth = info.CallDepth
}

func (s *testSink) Enabled(level int) bool {
	return level <= 2
}

func (s *testSink) Info(level int, msg string, keysAndValues ...any) {
	allVals := append(s.values, keysAndValues...)
	*s.events = append(*s.events, recordedEvent{
		level:     level,
		isError:   false,
		msg:       msg,
		name:      s.name,
		values:    allVals,
		callDepth: s.callDepth,
	})
}

func (s *testSink) Error(err error, msg string, keysAndValues ...any) {
	allVals := append(s.values, keysAndValues...)
	*s.events = append(*s.events, recordedEvent{
		level:     0,
		isError:   true,
		err:       err,
		msg:       msg,
		name:      s.name,
		values:    allVals,
		callDepth: s.callDepth,
	})
}

func (s *testSink) WithValues(keysAndValues ...any) logr.LogSink {
	newVals := make([]any, 0, len(s.values)+len(keysAndValues))
	newVals = append(newVals, s.values...)
	newVals = append(newVals, keysAndValues...)
	return &testSink{
		events:    s.events,
		name:      s.name,
		values:    newVals,
		callDepth: s.callDepth,
		inited:    s.inited,
	}
}

func (s *testSink) WithName(name string) logr.LogSink {
	newName := s.name
	if newName != "" {
		newName += "." + name
	} else {
		newName = name
	}
	return &testSink{
		events:    s.events,
		name:      newName,
		values:    s.values,
		callDepth: s.callDepth,
		inited:    s.inited,
	}
}

func (s *testSink) WithCallDepth(depth int) logr.LogSink {
	return &testSink{
		events:    s.events,
		name:      s.name,
		values:    s.values,
		callDepth: s.callDepth + depth,
		inited:    s.inited,
	}
}

func main() {
	// Contract 1: logr.New initializes a Logger with custom LogSink implementation
	{
		var events []recordedEvent
		sink := newTestSink(&events)
		logger := logr.New(sink)

		if logger.IsZero() {
			fmt.Fprintln(os.Stderr, "FAIL: logr.New produced zero-value logger")
			os.Exit(1)
		}

		if !sink.inited {
			fmt.Fprintln(os.Stderr, "FAIL: logr.New did not call Init on LogSink")
			os.Exit(1)
		}

		retrievedSink := logger.GetSink()
		if retrievedSink == nil {
			fmt.Fprintln(os.Stderr, "FAIL: logger.GetSink() returned nil")
			os.Exit(1)
		}
	}

	// Contract 2: LogSink.Info and LogSink.Error receive structured log parameters and error objects
	{
		var events []recordedEvent
		sink := newTestSink(&events)
		logger := logr.New(sink)

		childLogger := logger.WithName("service").WithValues("tenant", "acme")
		childLogger.Info("operation successful", "records", 100)

		testErr := errors.New("timeout reached")
		childLogger.Error(testErr, "operation failed", "attempt", 3)

		if len(events) != 2 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 2 events, got %d\n", len(events))
			os.Exit(1)
		}

		infoEv := events[0]
		if infoEv.isError || infoEv.msg != "operation successful" || infoEv.name != "service" {
			fmt.Fprintf(os.Stderr, "FAIL: invalid Info event: %+v\n", infoEv)
			os.Exit(1)
		}

		errEv := events[1]
		if !errEv.isError || !errors.Is(errEv.err, testErr) || errEv.msg != "operation failed" {
			fmt.Fprintf(os.Stderr, "FAIL: invalid Error event: %+v\n", errEv)
			os.Exit(1)
		}
	}

	// Contract 3: logr.Logger.WithSink and logr.Logger.GetSink swap and inspect the underlying LogSink
	{
		var events1, events2 []recordedEvent
		sink1 := newTestSink(&events1)
		sink2 := newTestSink(&events2)

		logger1 := logr.New(sink1).WithName("logger1")
		logger2 := logger1.WithSink(sink2)

		logger2.Info("hello sink2")

		if len(events1) != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: events recorded to sink1 after WithSink: %d\n", len(events1))
			os.Exit(1)
		}
		if len(events2) != 1 || events2[0].msg != "hello sink2" {
			fmt.Fprintf(os.Stderr, "FAIL: events not recorded to sink2: %+v\n", events2)
			os.Exit(1)
		}
		if logger2.GetSink() != sink2 {
			fmt.Fprintln(os.Stderr, "FAIL: logger2.GetSink() did not return sink2")
			os.Exit(1)
		}
	}

	// Contract 4: logr.Logger.WithCallDepth configures stack frame offset on CallDepthLogSink
	{
		var events []recordedEvent
		sink := newTestSink(&events)
		logger := logr.New(sink)

		depthLogger := logger.WithCallDepth(2)
		depthLogger.Info("depth test")

		if len(events) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 1 depth event, got %d\n", len(events))
			os.Exit(1)
		}
		if events[0].callDepth != 3 {
			fmt.Fprintf(os.Stderr, "FAIL: expected callDepth 3, got %d\n", events[0].callDepth)
			os.Exit(1)
		}
	}

	// Contract 5: logr.Logger.IsZero returns true for uninitialized or discard loggers and false for active sinks
	{
		var uninitLogger logr.Logger
		if !uninitLogger.IsZero() {
			fmt.Fprintln(os.Stderr, "FAIL: zero-value logger reported IsZero() == false")
			os.Exit(1)
		}

		discardLogger := logr.Discard()
		if !discardLogger.IsZero() {
			fmt.Fprintln(os.Stderr, "FAIL: discard logger reported IsZero() == false")
			os.Exit(1)
		}

		var events []recordedEvent
		configuredLogger := logr.New(newTestSink(&events))
		if configuredLogger.IsZero() {
			fmt.Fprintln(os.Stderr, "FAIL: configured logger reported IsZero() == true")
			os.Exit(1)
		}
	}

	fmt.Println("PASS: github.com/go-logr/logr contract passed")
}

Seeder de origem

anônimo