Ejemplo
go.uber.org/zap v1.28.0: zapcore.Sampler
Muestra verificada para golang go.uber.org/zap v1.28.0: zapcore.Sampler. El contrato se ejecutó en go 1.26 · linux debian/x64 · docker y pasó.
sha256:0d35d980f59ab4cf8adfa6fa0a43485bbb4983de61b979e2474d35bf6d2bcdf1
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
go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| 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-01 |
Caso
HOW- Objetivo
- verify zapcore.Sampler in pkg:golang/go.uber.org/zap@v1.28.0
- Paquetes
- Símbolos
-
- zapcore.Sampler
- Entorno
- go 1.26
- Creado
- 2026-09-01T16:36:34Z
Contrato
- zapcore.NewSamplerWithOptions allows the first N entries with the same level and message within a tick interval
- zapcore.NewSamplerWithOptions drops all entries beyond the first N when thereafter is zero
- zapcore.NewSamplerWithOptions allows every Mth entry after the first N entries when thereafter is greater than zero
- zapcore.NewSamplerWithOptions maintains independent counters for distinct message strings and log levels
- zapcore.SamplerHook receives LogSampled and LogDropped decisions for processed log entries
- zapcore.NewSamplerWithOptions resets counters and permits new entries once the tick duration elapses
Archivos
- PROMPT.md
- contract_test.go
- csx.json
- go.mod
- go.sum
- sample.go
- spec.json
Código fuente
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 zapcore.Sampler in pkg:golang/go.uber.org/zap@v1.28.0
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:golang/go.uber.org/zap@v1.28.0
Demonstrate these symbols/APIs:
- zapcore.Sampler
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.
package sample
import (
"bytes"
"strings"
"testing"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func newBufferCore(buf *bytes.Buffer, enab zapcore.LevelEnabler) zapcore.Core {
encoderCfg := zapcore.EncoderConfig{
MessageKey: "msg",
LevelKey: "lvl",
EncodeLevel: zapcore.LowercaseLevelEncoder,
}
return zapcore.NewCore(
zapcore.NewJSONEncoder(encoderCfg),
zapcore.AddSync(buf),
enab,
)
}
func countLines(buf *bytes.Buffer) int {
str := strings.TrimSpace(buf.String())
if str == "" {
return 0
}
return len(strings.Split(str, "\n"))
}
func TestSamplerFirstEntriesAllowed(t *testing.T) {
var buf bytes.Buffer
base := newBufferCore(&buf, zapcore.DebugLevel)
core := NewSampledCore(base, time.Minute, 3, 0)
logger := zap.New(core)
for i := 0; i < 5; i++ {
logger.Info("repeated message")
}
if got := countLines(&buf); got != 3 {
t.Fatalf("expected 3 logs emitted for first=3 with thereafter=0, got %d", got)
}
}
func TestSamplerDropsAllAfterFirstWhenThereafterZero(t *testing.T) {
var buf bytes.Buffer
var stats SamplingStats
base := newBufferCore(&buf, zapcore.DebugLevel)
core := NewSampledCore(base, time.Minute, 2, 0, NewStatsHook(&stats))
logger := zap.New(core)
for i := 0; i < 10; i++ {
logger.Info("spike message")
}
if got := countLines(&buf); got != 2 {
t.Fatalf("expected 2 logs emitted, got %d", got)
}
if sampled := stats.Sampled.Load(); sampled != 2 {
t.Fatalf("expected 2 sampled decisions, got %d", sampled)
}
if dropped := stats.Dropped.Load(); dropped != 8 {
t.Fatalf("expected 8 dropped decisions, got %d", dropped)
}
}
func TestSamplerThereafterInterval(t *testing.T) {
var buf bytes.Buffer
base := newBufferCore(&buf, zapcore.DebugLevel)
core := NewSampledCore(base, time.Minute, 2, 3)
logger := zap.New(core)
for i := 0; i < 10; i++ {
logger.Info("periodic message")
}
// 10 entries total: 1st, 2nd (first=2), then 5th (2+3), 8th (2+6). Total = 4.
if got := countLines(&buf); got != 4 {
t.Fatalf("expected 4 logs emitted for 10 entries with first=2, thereafter=3; got %d", got)
}
}
func TestSamplerIndependentCountersPerMessageAndLevel(t *testing.T) {
var buf bytes.Buffer
base := newBufferCore(&buf, zapcore.DebugLevel)
core := NewSampledCore(base, time.Minute, 2, 0)
logger := zap.New(core)
for i := 0; i < 4; i++ {
logger.Info("message A")
}
for i := 0; i < 3; i++ {
logger.Info("message B")
}
for i := 0; i < 3; i++ {
logger.Warn("message A")
}
if got := countLines(&buf); got != 6 {
t.Fatalf("expected 6 total logs emitted (2 per unique msg/level bucket), got %d", got)
}
}
func TestSamplerHookDecisionTracking(t *testing.T) {
var buf bytes.Buffer
var stats SamplingStats
base := newBufferCore(&buf, zapcore.DebugLevel)
logger := CreateSampledLogger(base, time.Minute, 1, 2, &stats)
// Log 5 times: 1st allowed, 2nd dropped, 3rd allowed (1+2), 4th dropped, 5th allowed (1+4)
for i := 0; i < 5; i++ {
logger.Info("hook test")
}
if sampled := stats.Sampled.Load(); sampled != 3 {
t.Fatalf("expected 3 sampled decisions, got %d", sampled)
}
if dropped := stats.Dropped.Load(); dropped != 2 {
t.Fatalf("expected 2 dropped decisions, got %d", dropped)
}
}
func TestSamplerTickReset(t *testing.T) {
var buf bytes.Buffer
base := newBufferCore(&buf, zapcore.DebugLevel)
tick := 10 * time.Millisecond
core := NewSampledCore(base, tick, 1, 0)
baseTime := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
ent1 := zapcore.Entry{Level: zapcore.InfoLevel, Message: "reset test", Time: baseTime}
ent2 := zapcore.Entry{Level: zapcore.InfoLevel, Message: "reset test", Time: baseTime.Add(2 * time.Millisecond)}
ent3 := zapcore.Entry{Level: zapcore.InfoLevel, Message: "reset test", Time: baseTime.Add(20 * time.Millisecond)}
ce1 := core.Check(ent1, nil)
if ce1 == nil {
t.Fatal("expected first entry in tick to be checked/sampled")
}
ce1.Write()
ce2 := core.Check(ent2, nil)
if ce2 != nil {
t.Fatal("expected second entry within same tick to be dropped")
}
ce3 := core.Check(ent3, nil)
if ce3 == nil {
t.Fatal("expected entry after tick expiration to be checked/sampled")
}
ce3.Write()
if got := countLines(&buf); got != 2 {
t.Fatalf("expected 2 logs emitted across tick boundaries, got %d", got)
}
}
{"case":{"caseId":"case:sha256:d2fdfa9dd0e5b71eaf42c7c031ad37ae248d1782fe2f417c879eba10b9127d4a","contract":["zapcore.NewSamplerWithOptions allows the first N entries with the same level and message within a tick interval","zapcore.NewSamplerWithOptions drops all entries beyond the first N when thereafter is zero","zapcore.NewSamplerWithOptions allows every Mth entry after the first N entries when thereafter is greater than zero","zapcore.NewSamplerWithOptions maintains independent counters for distinct message strings and log levels","zapcore.SamplerHook receives LogSampled and LogDropped decisions for processed log entries","zapcore.NewSamplerWithOptions resets counters and permits new entries once the tick duration elapses"],"goal":"verify zapcore.Sampler in pkg:golang/go.uber.org/zap@v1.28.0","kind":"HOW","packages":["pkg:golang/go.uber.org/zap@v1.28.0"],"schemaVersion":1,"symbols":["zapcore.Sampler"]},"contractCommand":["go","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","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.uber.org/zap@v1.28.0"],"schemaVersion":1,"subject":"pkg:golang/go.uber.org/zap@v1.28.0","symbols":["zapcore.Sampler"],"verifierAdapter":"golang@1"}
module example.com/sample
go 1.24.0
require go.uber.org/zap v1.28.0
require go.uber.org/multierr v1.10.0 // indirect
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/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.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
package sample
import (
"sync/atomic"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// SamplingStats tracks the number of sampled and dropped log decisions.
type SamplingStats struct {
Sampled atomic.Int64
Dropped atomic.Int64
}
// NewSampledCore creates a sampled zapcore.Core with the specified tick, first, and thereafter thresholds.
func NewSampledCore(core zapcore.Core, tick time.Duration, first, thereafter int, opts ...zapcore.SamplerOption) zapcore.Core {
return zapcore.NewSamplerWithOptions(core, tick, first, thereafter, opts...)
}
// NewStatsHook creates a SamplerOption that tracks sampling decisions into SamplingStats.
func NewStatsHook(stats *SamplingStats) zapcore.SamplerOption {
return zapcore.SamplerHook(func(ent zapcore.Entry, dec zapcore.SamplingDecision) {
if dec&zapcore.LogSampled != 0 {
stats.Sampled.Add(1)
}
if dec&zapcore.LogDropped != 0 {
stats.Dropped.Add(1)
}
})
}
// CreateSampledLogger constructs a zap.Logger using a sampled core wrapping the provided base core.
func CreateSampledLogger(base zapcore.Core, tick time.Duration, first, thereafter int, stats *SamplingStats) *zap.Logger {
var opts []zapcore.SamplerOption
if stats != nil {
opts = append(opts, NewStatsHook(stats))
}
sampledCore := NewSampledCore(base, tick, first, thereafter, opts...)
return zap.New(sampledCore)
}
{
"schemaVersion": 1,
"goal": "verify zapcore.Sampler in pkg:golang/go.uber.org/zap@v1.28.0",
"kind": "HOW",
"packages": [
"pkg:golang/go.uber.org/zap@v1.28.0"
],
"symbols": [
"zapcore.Sampler"
]
}
Seeder de origen
anónimo