CodeSampleX

Пример

github.com/hashicorp/golang-lru/v2 v2.0.7: New

Проверенный пример — golang github.com/hashicorp/golang-lru/v2 v2.0.7: New. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:9fb5545ee737b09180bce361a3ccce48f9f82a3f1df75c359783884482bac314

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Среды запусков проверки

Окружение Контракт Этапы Запуск
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-16

Кейс

HOW
Цель
verify github.com/hashicorp/golang-lru/v2.New in pkg:golang/github.com/hashicorp/golang-lru/v2@v2.0.7
Пакеты
Символы
  • github.com/hashicorp/golang-lru/v2.New
Окружение
go 1.26.6
Создан
2026-09-16T11:18:58Z

Контракт

  1. lru.New returns a non-nil cache and nil error when initialized with a positive capacity
  2. lru.New returns an error when initialized with zero or negative capacity
  3. Add inserts new key-value pairs, updates existing keys without increasing length, and reports whether an eviction occurred
  4. Get retrieves stored values for present keys and updates recent-ness so that least recently used entries are evicted first upon exceeding capacity
  5. Contains and Peek inspect presence and values without altering LRU order, and Purge removes all entries from the cache

Файлы

  • 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 github.com/hashicorp/golang-lru/v2.New in pkg:golang/github.com/hashicorp/golang-lru/v2@v2.0.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/hashicorp/golang-lru/v2@v2.0.7
Demonstrate these symbols/APIs:
  - github.com/hashicorp/golang-lru/v2.New

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:675eaff6fb3f00f7e288c202ff69c20727d268c532ef942b7035fe23d062c74e","contract":["lru.New returns a non-nil cache and nil error when initialized with a positive capacity","lru.New returns an error when initialized with zero or negative capacity","Add inserts new key-value pairs, updates existing keys without increasing length, and reports whether an eviction occurred","Get retrieves stored values for present keys and updates recent-ness so that least recently used entries are evicted first upon exceeding capacity","Contains and Peek inspect presence and values without altering LRU order, and Purge removes all entries from the cache"],"goal":"verify github.com/hashicorp/golang-lru/v2.New in pkg:golang/github.com/hashicorp/golang-lru/v2@v2.0.7","kind":"HOW","packages":["pkg:golang/github.com/hashicorp/golang-lru/v2@v2.0.7"],"schemaVersion":1,"symbols":["github.com/hashicorp/golang-lru/v2.New"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/hashicorp/golang-lru/v2@v2.0.7"],"schemaVersion":1,"subject":"pkg:golang/github.com/hashicorp/golang-lru/v2@v2.0.7","symbols":["github.com/hashicorp/golang-lru/v2.New"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require github.com/hashicorp/golang-lru/v2 v2.0.7
go.sum
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
main.go
package main

import (
	"fmt"

	lru "github.com/hashicorp/golang-lru/v2"
)

func main() {
	// Initialize an LRU cache with capacity 2
	cache, err := lru.New[string, int](2)
	if err != nil {
		panic(err)
	}

	// Add entries
	cache.Add("alpha", 1)
	cache.Add("beta", 2)
	fmt.Printf("Cache size: %d\n", cache.Len())

	// Access "alpha" to mark it as most recently used
	if val, ok := cache.Get("alpha"); ok {
		fmt.Printf("alpha: %d\n", val)
	}

	// Add third entry, which will evict "beta" (the least recently used)
	cache.Add("gamma", 3)

	// Verify "beta" was evicted and "alpha" remains
	_, hasBeta := cache.Get("beta")
	_, hasAlpha := cache.Get("alpha")
	fmt.Printf("contains beta: %v, contains alpha: %v\n", hasBeta, hasAlpha)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/hashicorp/golang-lru/v2.New in pkg:golang/github.com/hashicorp/golang-lru/v2@v2.0.7",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/hashicorp/golang-lru/v2@v2.0.7"
  ],
  "symbols": [
    "github.com/hashicorp/golang-lru/v2.New"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"

	lru "github.com/hashicorp/golang-lru/v2"
)

func main() {
	// Assertion 1: lru.New returns a non-nil cache and nil error when initialized with a positive capacity
	{
		c, err := lru.New[string, int](3)
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: expected nil error, got %v\n", err)
			os.Exit(1)
		}
		if c == nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: expected non-nil cache\n")
			os.Exit(1)
		}
		if c.Len() != 0 {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: initial length should be 0, got %d\n", c.Len())
			os.Exit(1)
		}
	}

	// Assertion 2: lru.New returns an error when initialized with zero or negative capacity
	{
		_, errZero := lru.New[string, int](0)
		if errZero == nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected error for size 0\n")
			os.Exit(1)
		}

		_, errNeg := lru.New[string, int](-5)
		if errNeg == nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected error for negative size\n")
			os.Exit(1)
		}
	}

	// Assertion 3: Add inserts new key-value pairs, updates existing keys without increasing length, and reports whether an eviction occurred
	{
		c, err := lru.New[string, int](2)
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: setup error: %v\n", err)
			os.Exit(1)
		}

		evicted := c.Add("k1", 100)
		if evicted || c.Len() != 1 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: adding first item should not evict, len should be 1\n")
			os.Exit(1)
		}

		evicted = c.Add("k2", 200)
		if evicted || c.Len() != 2 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: adding second item should not evict, len should be 2\n")
			os.Exit(1)
		}

		evicted = c.Add("k1", 150)
		if evicted || c.Len() != 2 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: updating existing key should not evict or change len\n")
			os.Exit(1)
		}

		val, ok := c.Get("k1")
		if !ok || val != 150 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected updated value 150, got %d (ok=%v)\n", val, ok)
			os.Exit(1)
		}
	}

	// Assertion 4: Get retrieves stored values for present keys and updates recent-ness so that least recently used entries are evicted first upon exceeding capacity
	{
		c, err := lru.New[string, string](2)
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: setup error: %v\n", err)
			os.Exit(1)
		}

		c.Add("x", "valX")
		c.Add("y", "valY")

		// Access "x" so "y" becomes least recently used
		valX, okX := c.Get("x")
		if !okX || valX != "valX" {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: Get(x) failed\n")
			os.Exit(1)
		}

		// Adding "z" must evict "y"
		evicted := c.Add("z", "valZ")
		if !evicted {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: expected eviction when exceeding capacity\n")
			os.Exit(1)
		}

		if _, ok := c.Get("y"); ok {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: y should have been evicted\n")
			os.Exit(1)
		}

		if _, ok := c.Get("x"); !ok {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: x should still be in cache\n")
			os.Exit(1)
		}

		if _, ok := c.Get("z"); !ok {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: z should still be in cache\n")
			os.Exit(1)
		}
	}

	// Assertion 5: Contains and Peek inspect presence and values without altering LRU order, and Purge removes all entries from the cache
	{
		c, err := lru.New[string, int](2)
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: setup error: %v\n", err)
			os.Exit(1)
		}

		c.Add("first", 1)
		c.Add("second", 2)

		// Peek and Contains should not alter LRU order ("first" remains oldest)
		val, ok := c.Peek("first")
		if !ok || val != 1 {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: Peek(first) failed\n")
			os.Exit(1)
		}

		if !c.Contains("first") || !c.Contains("second") {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: Contains check failed\n")
			os.Exit(1)
		}

		// Adding "third" must evict "first" because Peek/Contains did not update its recency
		evicted := c.Add("third", 3)
		if !evicted {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: expected eviction\n")
			os.Exit(1)
		}

		if c.Contains("first") {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: first should have been evicted\n")
			os.Exit(1)
		}

		// Purge completely empties the cache
		c.Purge()
		if c.Len() != 0 || c.Contains("second") || c.Contains("third") {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: cache should be empty after Purge\n")
			os.Exit(1)
		}
	}

	fmt.Println("All contract assertions passed successfully.")
}

Исходный сидер

аноним