CodeSampleX

Ejemplo

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

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

sha256:ed1e8fb23f89bd0d2a1991a54208bec56bd6cb2dc2c588d284cb3efd6f25a07f

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

Caso

HOW
Objetivo
verify pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de
Paquetes
Creado
2026-08-27T17:35:54Z

Contrato

  1. NewCache initializes cache with custom Cost and KeyToHash functions and metrics enabled
  2. Set with zero cost computes item cost using the configured Cost callback function
  3. KeyToHash custom hashing function is invoked to hash keys for storage and retrieval
  4. SetWithTTL sets an item with positive TTL duration and item is retrievable before expiration
  5. Metrics records hits and misses accurately to calculate hit ratio

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/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
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:3e2916dfe7052c3d7e52980dad4f9f71fab00abb01d378df251bbd62c3adeea0","contract":["NewCache initializes cache with custom Cost and KeyToHash functions and metrics enabled","Set with zero cost computes item cost using the configured Cost callback function","KeyToHash custom hashing function is invoked to hash keys for storage and retrieval","SetWithTTL sets an item with positive TTL duration and item is retrievable before expiration","Metrics records hits and misses accurately to calculate hit ratio"],"goal":"verify 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},"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","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/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/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/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
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/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/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
main.go
package main

import (
	"fmt"
	"time"

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

func main() {
	cache, err := ristretto.NewCache(&ristretto.Config{
		NumCounters: 1000,
		MaxCost:     100,
		BufferItems: 64,
		Metrics:     true,
		Cost: func(val interface{}) int64 {
			if str, ok := val.(string); ok {
				return int64(len(str))
			}
			return 1
		},
		KeyToHash: func(key interface{}) (uint64, uint64) {
			if str, ok := key.(string); ok {
				return uint64(len(str)), 1
			}
			return 0, 1
		},
	})
	if err != nil {
		panic(err)
	}
	defer cache.Close()

	// Store item with automatic cost calculation
	cache.Set("greeting", "hello world", 0)
	time.Sleep(50 * time.Millisecond)

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

	// Store item with TTL
	cache.SetWithTTL("session-token", "token-xyz", 1, 5*time.Minute)
	time.Sleep(50 * time.Millisecond)

	val, found = cache.Get("session-token")
	if found {
		fmt.Printf("found session-token: %v\n", val)
	}

	// Check metrics
	fmt.Printf("Hits: %d, Misses: %d, Ratio: %.2f\n", cache.Metrics.Hits(), cache.Metrics.Misses(), cache.Metrics.Ratio())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify 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"
  ],
  "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 (
	"fmt"
	"os"
	"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 v0.0.3 contract assertions passed successfully.")
}

func runContract() error {
	costCalculated := false
	customHashUsed := false

	// Assertion 1: NewCache initializes cache with custom Cost and KeyToHash functions and metrics enabled
	cache, err := ristretto.NewCache(&ristretto.Config{
		NumCounters: 1000,
		MaxCost:     100,
		BufferItems: 64,
		Metrics:     true,
		Cost: func(val interface{}) int64 {
			costCalculated = true
			if s, ok := val.(string); ok {
				return int64(len(s))
			}
			return 1
		},
		KeyToHash: func(key interface{}) (uint64, uint64) {
			customHashUsed = true
			if s, ok := key.(string); ok {
				return uint64(len(s)), 1
			}
			return 0, 1
		},
	})
	if err != nil {
		return fmt.Errorf("failed to create cache with custom config: %w", err)
	}
	defer cache.Close()

	if cache.Metrics == nil {
		return fmt.Errorf("expected Metrics to be initialized when Metrics: true")
	}

	// Assertion 2: Set with zero cost computes item cost using the configured Cost callback function
	if ok := cache.Set("custom-key", "sample-payload", 0); !ok {
		return fmt.Errorf("expected Set to return true for zero cost item")
	}
	time.Sleep(50 * time.Millisecond)

	if !costCalculated {
		return fmt.Errorf("expected custom Cost callback function to be invoked")
	}

	// Assertion 3: KeyToHash custom hashing function is invoked to hash keys for storage and retrieval
	if !customHashUsed {
		return fmt.Errorf("expected KeyToHash custom hashing function to be invoked")
	}

	val, found := cache.Get("custom-key")
	if !found {
		return fmt.Errorf("expected Get to find 'custom-key'")
	}
	if strVal, ok := val.(string); !ok || strVal != "sample-payload" {
		return fmt.Errorf("expected value 'sample-payload', got %v", val)
	}

	// Assertion 4: SetWithTTL sets an item with positive TTL duration and item is retrievable before expiration
	ttlDuration := 2 * time.Second
	if ok := cache.SetWithTTL("expiring-key", "active-session", 1, ttlDuration); !ok {
		return fmt.Errorf("expected SetWithTTL to return true")
	}
	time.Sleep(50 * time.Millisecond)

	valTTL, foundTTL := cache.Get("expiring-key")
	if !foundTTL {
		return fmt.Errorf("expected Get to find 'expiring-key' before TTL expiration")
	}
	if strVal, ok := valTTL.(string); !ok || strVal != "active-session" {
		return fmt.Errorf("expected value 'active-session', got %v", valTTL)
	}

	// Assertion 5: Metrics records hits and misses accurately to calculate hit ratio
	cache.Get("custom-key")        // Hit
	cache.Get("nonexistent-key")   // Miss

	hits := cache.Metrics.Hits()
	misses := cache.Metrics.Misses()
	if hits < 1 {
		return fmt.Errorf("expected at least 1 hit in metrics, got %d", hits)
	}
	if misses < 1 {
		return fmt.Errorf("expected at least 1 miss in metrics, got %d", misses)
	}
	if ratio := cache.Metrics.Ratio(); ratio <= 0.0 || ratio >= 1.0 {
		return fmt.Errorf("expected hit ratio between 0.0 and 1.0, got %f", ratio)
	}

	return nil
}

Seeder de origen

anónimo