CodeSampleX

示例

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

已验证示例 — golang github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过.

sha256:ed1e8fb23f89bd0d2a1991a54208bec56bd6cb2dc2c588d284cb3efd6f25a07f

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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-27

案例

HOW
目标
verify pkg:golang/github.com/dgraph-io/ristretto@v0.0.3-0.20200630154024-f66de99634de
包
创建时间
2026-08-27T17:35:54Z

契约

  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

文件

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

下载源代码构件 (tar.gz)

源代码

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
}

原始种子者

匿名