샘플
github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de: NewCache
검증된 샘플 — golang github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de: NewCache. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.
sha256:15dc00c170fa7e07477a9546ef66c108a3eb04ae4743e56c1adba8d276218acd
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
linux 24 · ubuntu · glibc 2.39 x64 go
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| 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 |
케이스
HOW- 목표
- verify github.com/dgraph-io/ristretto.NewCache in pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de
- 심벌
-
- github.com/dgraph-io/ristretto.NewCache
- 생성일
- 2026-08-30T15:26:40Z
컨트랙트
- 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
파일
- PROMPT.md
- csx.json
- go.mod
- go.sum
- main.go
- spec.json
- test/contract.go
소스
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.
{"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"}
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
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=
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())
}
{
"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"
]
}
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
}
오리진 시더
익명