CodeSampleX

Sample

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

Verified sample for golang github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de: NewCache. The contract ran on go 1.26 · linux alpine/x64 …

sha256:15dc00c170fa7e07477a9546ef66c108a3eb04ae4743e56c1adba8d276218acd

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 go

Verification-run environments

Environment Contract Stages Run
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

Case

HOW
Goal
verify github.com/dgraph-io/ristretto.NewCache in pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de
Packages
Symbols
  • github.com/dgraph-io/ristretto.NewCache
Created
2026-08-30T15:26:40Z

Contract

  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

Files

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

Download the source artifact (tar.gz)

Source

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.NewCache 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.NewCache

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:475d4069ce91104ed063c13fca10c5e051286fde514a5177d9bda120bdf0a8f6","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 github.com/dgraph-io/ristretto.NewCache 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.NewCache"]},"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.NewCache"],"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() {
	// Initialize cache with custom configuration
	cache, err := ristretto.NewCache(&ristretto.Config{
		NumCounters: 1e4,     // Number of 4-bit access counters
		MaxCost:     1 << 20, // Maximum cache cost (1 MB)
		BufferItems: 64,      // Number of keys per Get buffer
		Metrics:     true,    // Enable hit/miss metrics tracking
		Cost: func(value interface{}) int64 {
			if str, ok := value.(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(fmt.Sprintf("failed to create cache: %v", err))
	}
	defer cache.Close()

	// Store item with automatic cost evaluation
	cache.Set("app-title", "CodeSampleX Example", 0)
	time.Sleep(50 * time.Millisecond)

	// Retrieve item from cache
	val, found := cache.Get("app-title")
	if found {
		fmt.Printf("Retrieved app-title: %v\n", val)
	}

	// Store item with TTL
	cache.SetWithTTL("session-id", "sess-98765", 1, 10*time.Minute)
	time.Sleep(50 * time.Millisecond)

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

	// Display cache metrics
	fmt.Printf("Cache Hits: %d, Misses: %d, Hit Ratio: %.2f\n",
		cache.Metrics.Hits(), cache.Metrics.Misses(), cache.Metrics.Ratio())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/dgraph-io/ristretto.NewCache 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.NewCache"
  ]
}
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.NewCache 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
}

Origin Seeder

anonymous