CodeSampleX

Ejemplo

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

Muestra verificada para golang github.com/go-logr/logr v1.3.0. El contrato se ejecutó en go 1.26 · linux alpine/x64 · docker y pasó.

sha256:14ea6a1ef895a105124099a4d818fb56ae32868af54241fca41bb80b57a0a0dc

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-28

Caso

HOW
Objetivo
verify pkg:golang/github.com/go-logr/logr@v1.3.0
Paquetes
Creado
2026-08-28T09:26:10Z

Contrato

  1. funcr.New logs structured messages with WithName hierarchical prefixes and WithValues key-value pairs
  2. logger.V filters log messages based on the verbosity threshold configured in funcr.Options
  3. logr.NewContext and logr.FromContext store and retrieve logr.Logger instances across context boundaries
  4. funcr.NewJSON emits valid JSON log entries with timestamp and caller information when enabled
  5. logr.Discard provides a safe no-op logger that disables all verbosity levels and suppresses output

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-logr/logr@v1.3.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:7d1fba7000e94dcf9eadb57289df9f1002e78e437fb3d0ba662eab794b8ebf02","contract":["funcr.New logs structured messages with WithName hierarchical prefixes and WithValues key-value pairs","logger.V filters log messages based on the verbosity threshold configured in funcr.Options","logr.NewContext and logr.FromContext store and retrieve logr.Logger instances across context boundaries","funcr.NewJSON emits valid JSON log entries with timestamp and caller information when enabled","logr.Discard provides a safe no-op logger that disables all verbosity levels and suppresses output"],"goal":"verify pkg:golang/github.com/go-logr/logr@v1.3.0","kind":"HOW","packages":["pkg:golang/github.com/go-logr/logr@v1.3.0"],"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.3.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-logr/logr@v1.3.0","verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

require github.com/go-logr/logr v1.3.0
go.sum
github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY=
github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
main.go
package main

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

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

// TaskProcessor demonstrates structured logging with logr.
type TaskProcessor struct {
	logger logr.Logger
}

// NewTaskProcessor creates a new TaskProcessor with an enriched logger name.
func NewTaskProcessor(logger logr.Logger) *TaskProcessor {
	return &TaskProcessor{
		logger: logger.WithName("processor"),
	}
}

// ProcessTask handles a task within a context, logging steps and errors.
func (p *TaskProcessor) ProcessTask(ctx context.Context, taskID string, retries int) error {
	taskLogger := p.logger.WithValues("taskId", taskID, "retries", retries)
	ctx = logr.NewContext(ctx, taskLogger)

	taskLogger.Info("starting task processing")
	taskLogger.V(1).Info("evaluating processing parameters", "concurrency", 4)

	if retries > 3 {
		err := errors.New("retry limit exceeded")
		taskLogger.Error(err, "task processing aborted")
		return err
	}

	taskLogger.Info("task completed successfully", "status", "success")
	return nil
}

func main() {
	// Standard structured logger using funcr
	logger := funcr.New(func(prefix, args string) {
		if prefix != "" {
			fmt.Fprintf(os.Stdout, "[%s] %s\n", prefix, args)
		} else {
			fmt.Fprintln(os.Stdout, args)
		}
	}, funcr.Options{
		Verbosity: 1,
	})

	processor := NewTaskProcessor(logger)
	ctx := context.Background()

	_ = processor.ProcessTask(ctx, "task-1001", 1)

	// JSON structured logger
	jsonLogger := funcr.NewJSON(func(obj string) {
		var parsed map[string]any
		if err := json.Unmarshal([]byte(obj), &parsed); err == nil {
			fmt.Println("JSON log entry verified:", obj)
		}
	}, funcr.Options{
		LogTimestamp: true,
	})

	jsonLogger.Info("json service event", "event", "start", "code", 200)

	// Discard logger
	discard := logr.Discard()
	discard.Info("this output is discarded")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/go-logr/logr@v1.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-logr/logr@v1.3.0"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"strings"
	"sync"

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

func main() {
	// Contract 1: funcr.New logs structured messages with WithName hierarchical prefixes and WithValues key-value pairs
	{
		var buf bytes.Buffer
		var mu sync.Mutex
		logger := funcr.New(func(prefix, args string) {
			mu.Lock()
			defer mu.Unlock()
			if prefix != "" {
				buf.WriteString(prefix + ": ")
			}
			buf.WriteString(args + "\n")
		}, funcr.Options{})

		subLogger := logger.WithName("service").WithName("worker").WithValues("env", "staging", "workerId", 7)
		subLogger.Info("job started", "jobId", "job-99")

		out := buf.String()
		if !strings.Contains(out, "service/worker") && !strings.Contains(out, "service") {
			fmt.Fprintf(os.Stderr, "FAIL: expected name prefix in output: %s\n", out)
			os.Exit(1)
		}
		if !strings.Contains(out, `"jobId"="job-99"`) && !strings.Contains(out, `job-99`) {
			fmt.Fprintf(os.Stderr, "FAIL: expected jobId key-value in output: %s\n", out)
			os.Exit(1)
		}
		if !strings.Contains(out, `"workerId"=7`) && !strings.Contains(out, `workerId=7`) {
			fmt.Fprintf(os.Stderr, "FAIL: expected workerId key-value in output: %s\n", out)
			os.Exit(1)
		}
	}

	// Contract 2: logger.V filters log messages based on the verbosity threshold configured in funcr.Options
	{
		var lines []string
		var mu sync.Mutex
		logger := funcr.New(func(prefix, args string) {
			mu.Lock()
			defer mu.Unlock()
			lines = append(lines, args)
		}, funcr.Options{
			Verbosity: 2,
		})

		logger.V(0).Info("level 0 info")
		logger.V(1).Info("level 1 info")
		logger.V(2).Info("level 2 debug")
		logger.V(3).Info("level 3 trace - should be omitted")

		mu.Lock()
		count := len(lines)
		mu.Unlock()

		if count != 3 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 3 lines for verbosity 2, got %d\n", count)
			os.Exit(1)
		}
		if !logger.V(2).Enabled() {
			fmt.Fprintf(os.Stderr, "FAIL: V(2) should be enabled\n")
			os.Exit(1)
		}
		if logger.V(3).Enabled() {
			fmt.Fprintf(os.Stderr, "FAIL: V(3) should be disabled\n")
			os.Exit(1)
		}
	}

	// Contract 3: logr.NewContext and logr.FromContext store and retrieve logr.Logger instances across context boundaries
	{
		var captured string
		customLogger := funcr.New(func(prefix, args string) {
			captured = args
		}, funcr.Options{})

		ctx := logr.NewContext(context.Background(), customLogger)
		retrieved, err := logr.FromContext(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected error from FromContext: %v\n", err)
			os.Exit(1)
		}

		retrieved.Info("context logging verified")
		if !strings.Contains(captured, "context logging verified") {
			fmt.Fprintf(os.Stderr, "FAIL: retrieved logger failed to log: %s\n", captured)
			os.Exit(1)
		}

		emptyLogger, err := logr.FromContext(context.Background())
		if err == nil {
			fmt.Fprintf(os.Stderr, "FAIL: expected error retrieving from empty context\n")
			os.Exit(1)
		}
		_ = emptyLogger

		discardRetrieved := logr.FromContextOrDiscard(context.Background())
		discardRetrieved.Info("discarded from empty context")
	}

	// Contract 4: funcr.NewJSON emits valid JSON log entries with timestamp and caller information when enabled
	{
		var jsonEntries []map[string]any
		var mu sync.Mutex
		jsonLogger := funcr.NewJSON(func(obj string) {
			mu.Lock()
			defer mu.Unlock()
			var parsed map[string]any
			if err := json.Unmarshal([]byte(obj), &parsed); err != nil {
				fmt.Fprintf(os.Stderr, "FAIL: invalid JSON emitted: %s, error: %v\n", obj, err)
				os.Exit(1)
			}
			jsonEntries = append(jsonEntries, parsed)
		}, funcr.Options{
			LogTimestamp: true,
		})

		jsonLogger.Info("structured json test", "cluster", "us-east-1", "nodes", 5)
		testErr := errors.New("network timeout")
		jsonLogger.Error(testErr, "service failure", "retryable", true)

		mu.Lock()
		defer mu.Unlock()
		if len(jsonEntries) != 2 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 2 JSON log entries, got %d\n", len(jsonEntries))
			os.Exit(1)
		}

		infoEntry := jsonEntries[0]
		if infoEntry["msg"] != "structured json test" {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected msg field in JSON: %v\n", infoEntry["msg"])
			os.Exit(1)
		}
		if infoEntry["cluster"] != "us-east-1" {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected cluster field in JSON: %v\n", infoEntry["cluster"])
			os.Exit(1)
		}
		if _, ok := infoEntry["ts"]; !ok {
			fmt.Fprintf(os.Stderr, "FAIL: expected ts field in JSON entry with LogTimestamp: true\n")
			os.Exit(1)
		}

		errEntry := jsonEntries[1]
		if errEntry["error"] != "network timeout" {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected error field in JSON: %v\n", errEntry["error"])
			os.Exit(1)
		}
		if errEntry["retryable"] != true {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected retryable field in JSON: %v\n", errEntry["retryable"])
			os.Exit(1)
		}
	}

	// Contract 5: logr.Discard provides a safe no-op logger that disables all verbosity levels and suppresses output
	{
		discardLogger := logr.Discard()
		if discardLogger.Enabled() {
			fmt.Fprintf(os.Stderr, "FAIL: Discard logger should not be enabled\n")
			os.Exit(1)
		}
		if discardLogger.V(0).Enabled() || discardLogger.V(1).Enabled() {
			fmt.Fprintf(os.Stderr, "FAIL: Discard logger V-levels should be disabled\n")
			os.Exit(1)
		}
		// Calling Info and Error on discardLogger should not panic or fail
		discardLogger.Info("noop info message", "key", "val")
		discardLogger.Error(errors.New("discarded error"), "noop error message")
		discardWithValues := discardLogger.WithValues("k", "v").WithName("discardName")
		discardWithValues.Info("noop nested")
	}

	fmt.Println("PASS: github.com/go-logr/logr@v1.3.0 contracts verified successfully")
}

Seeder de origen

anónimo