CodeSampleX

Ejemplo

github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de: Config

Muestra verificada para golang github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de: Config. El contrato se ejecutó en go 1.26 · linux…

sha256:9331dbd53a813c315a7a3a93e8c29cb8daf496d3ff88d3433b0ccb88e2862560

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-30

Caso

HOW
Objetivo
verify github.com/dgraph-io/ristretto.Config in pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de
Paquetes
Símbolos
  • github.com/dgraph-io/ristretto.Config
Creado
2026-08-30T15:20:54Z

Contrato

  1. NewCache returns an error when NumCounters, MaxCost, or BufferItems is zero
  2. Config.Cost dynamically evaluates and assigns item cost when Set is called with cost 0
  3. Config.KeyToHash applies custom key hashing algorithm for storage and retrieval
  4. Config.Metrics enables statistics tracking when true and leaves Metrics nil when false
  5. Config.OnEvict callback is triggered when cache exceeds MaxCost capacity

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 github.com/dgraph-io/ristretto.Config in pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de
Demonstrate these symbols/APIs:
  - github.com/dgraph-io/ristretto.Config

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:d6cb302b11d04fbcaaa1202376c132e9cb89921d44a60d0d6800c318c1bedd08","contract":["NewCache returns an error when NumCounters, MaxCost, or BufferItems is zero","Config.Cost dynamically evaluates and assigns item cost when Set is called with cost 0","Config.KeyToHash applies custom key hashing algorithm for storage and retrieval","Config.Metrics enables statistics tracking when true and leaves Metrics nil when false","Config.OnEvict callback is triggered when cache exceeds MaxCost capacity"],"goal":"verify github.com/dgraph-io/ristretto.Config in pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de","kind":"HOW","packages":["pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de"],"schemaVersion":1,"symbols":["github.com/dgraph-io/ristretto.Config"]},"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/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de"],"schemaVersion":1,"subject":"pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de","symbols":["github.com/dgraph-io/ristretto.Config"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de

require github.com/cespare/xxhash v1.1.0 // indirect
go.sum
github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de h1:t0UHb5vdojIDUqktM6+xJAfScFBsVpXZmqC9dsgJmeA=
github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E=
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA=
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
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/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
main.go
package main

import (
	"fmt"
	"time"

	"github.com/dgraph-io/ristretto"
)

func main() {
	// Configure ristretto cache
	config := &ristretto.Config{
		NumCounters: 1e4,     // 10k counters for frequency tracking
		MaxCost:     1 << 20, // 1MB max cost capacity
		BufferItems: 64,      // 64 items per Get buffer
		Metrics:     true,    // track cache statistics
		Cost: func(value interface{}) int64 {
			if str, ok := value.(string); ok {
				return int64(len(str))
			}
			return 1
		},
		OnEvict: func(key, conflict uint64, value interface{}, cost int64) {
			fmt.Printf("Evicted keyHash=%d cost=%d\n", key, cost)
		},
	}

	cache, err := ristretto.NewCache(config)
	if err != nil {
		panic(err)
	}
	defer cache.Close()

	// Store item with dynamically calculated cost
	cache.Set("greeting", "hello world", 0)

	// Wait for item to process through buffer
	time.Sleep(20 * time.Millisecond)

	// Retrieve item
	val, found := cache.Get("greeting")
	if found {
		fmt.Printf("Found greeting: %v\n", val)
	}

	if cache.Metrics != nil {
		fmt.Printf("Metrics hits: %d, misses: %d\n", cache.Metrics.Hits(), cache.Metrics.Misses())
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/dgraph-io/ristretto.Config in pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de"
  ],
  "symbols": [
    "github.com/dgraph-io/ristretto.Config"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"sync/atomic"
	"time"

	"github.com/dgraph-io/ristretto"
)

func main() {
	if err := runContract(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract verification failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All ristretto.Config contract assertions passed successfully.")
}

func runContract() error {
	// Assertion 1: NewCache returns an error when NumCounters, MaxCost, or BufferItems is zero
	if _, err := ristretto.NewCache(&ristretto.Config{NumCounters: 0, MaxCost: 100, BufferItems: 64}); err == nil {
		return fmt.Errorf("expected error when NumCounters is 0")
	}
	if _, err := ristretto.NewCache(&ristretto.Config{NumCounters: 100, MaxCost: 0, BufferItems: 64}); err == nil {
		return fmt.Errorf("expected error when MaxCost is 0")
	}
	if _, err := ristretto.NewCache(&ristretto.Config{NumCounters: 100, MaxCost: 100, BufferItems: 0}); err == nil {
		return fmt.Errorf("expected error when BufferItems is 0")
	}

	// Assertion 2: Config.Cost dynamically evaluates and assigns item cost when Set is called with cost 0
	costCache, err := ristretto.NewCache(&ristretto.Config{
		NumCounters: 1000,
		MaxCost:     100,
		BufferItems: 64,
		Cost: func(value interface{}) int64 {
			if str, ok := value.(string); ok {
				return int64(len(str))
			}
			return 1
		},
	})
	if err != nil {
		return fmt.Errorf("failed to create cache with Cost function: %w", err)
	}
	defer costCache.Close()

	if ok := costCache.Set("k1", "custom-cost-value", 0); !ok {
		return fmt.Errorf("expected Set with cost 0 to succeed with Cost function configured")
	}
	time.Sleep(20 * time.Millisecond)
	val, found := costCache.Get("k1")
	if !found || val != "custom-cost-value" {
		return fmt.Errorf("expected Get to retrieve item stored with dynamic cost function")
	}

	// Assertion 3: Config.KeyToHash applies custom key hashing algorithm for storage and retrieval
	var customHashCalled int64
	hashCache, err := ristretto.NewCache(&ristretto.Config{
		NumCounters: 1000,
		MaxCost:     100,
		BufferItems: 64,
		KeyToHash: func(key interface{}) (uint64, uint64) {
			atomic.AddInt64(&customHashCalled, 1)
			s := fmt.Sprintf("%v", key)
			return uint64(len(s)), 0
		},
	})
	if err != nil {
		return fmt.Errorf("failed to create cache with KeyToHash: %w", err)
	}
	defer hashCache.Close()

	hashCache.Set("custom-key", "custom-val", 1)
	time.Sleep(20 * time.Millisecond)
	val, found = hashCache.Get("custom-key")
	if !found || val != "custom-val" {
		return fmt.Errorf("expected Get to retrieve item stored using custom KeyToHash")
	}
	if atomic.LoadInt64(&customHashCalled) == 0 {
		return fmt.Errorf("expected custom KeyToHash to be invoked during cache operations")
	}

	// Assertion 4: Config.Metrics enables statistics tracking when true and leaves Metrics nil when false
	disabledMetricsCache, err := ristretto.NewCache(&ristretto.Config{
		NumCounters: 1000,
		MaxCost:     100,
		BufferItems: 64,
		Metrics:     false,
	})
	if err != nil {
		return fmt.Errorf("failed to create cache with disabled metrics: %w", err)
	}
	defer disabledMetricsCache.Close()
	if disabledMetricsCache.Metrics != nil {
		return fmt.Errorf("expected cache.Metrics to be nil when Metrics is false")
	}

	enabledMetricsCache, err := ristretto.NewCache(&ristretto.Config{
		NumCounters: 1000,
		MaxCost:     100,
		BufferItems: 64,
		Metrics:     true,
	})
	if err != nil {
		return fmt.Errorf("failed to create cache with enabled metrics: %w", err)
	}
	defer enabledMetricsCache.Close()
	if enabledMetricsCache.Metrics == nil {
		return fmt.Errorf("expected cache.Metrics to be non-nil when Metrics is true")
	}
	enabledMetricsCache.Set("metrics-key", "metrics-val", 1)
	time.Sleep(20 * time.Millisecond)
	enabledMetricsCache.Get("metrics-key")
	if enabledMetricsCache.Metrics.Hits() != 1 {
		return fmt.Errorf("expected 1 hit tracked in Metrics, got %d", enabledMetricsCache.Metrics.Hits())
	}

	// Assertion 5: Config.OnEvict callback is triggered when cache exceeds MaxCost capacity
	var evictions int64
	evictCache, err := ristretto.NewCache(&ristretto.Config{
		NumCounters: 100,
		MaxCost:     10,
		BufferItems: 64,
		OnEvict: func(key, conflict uint64, value interface{}, cost int64) {
			atomic.AddInt64(&evictions, 1)
		},
	})
	if err != nil {
		return fmt.Errorf("failed to create cache with OnEvict: %w", err)
	}
	defer evictCache.Close()

	for i := 0; i < 50; i++ {
		evictCache.Set(fmt.Sprintf("evict-key-%d", i), "evict-value", 2)
	}
	time.Sleep(50 * time.Millisecond)
	if atomic.LoadInt64(&evictions) == 0 {
		return fmt.Errorf("expected OnEvict callback to be triggered upon capacity eviction")
	}

	return nil
}

Seeder de origen

anónimo