CodeSampleX

Exemple

go.etcd.io/bbolt v1.4.3: DB.Batch

Échantillon vérifié pour golang go.etcd.io/bbolt v1.4.3: DB.Batch. Le contrat s'est exécuté sur go 1.26 · linux alpine/x64 · docker et a réussi : DB.Batch…

sha256:b6853ae0d07c98ddf400192c404c319b86f63188442de9db260c6b1f125941f5

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-31

Cas

HOW
Objectif
verify go.etcd.io/bbolt.DB.Batch in pkg:golang/go.etcd.io/bbolt@v1.4.3
Paquets
Symboles
  • go.etcd.io/bbolt.DB.Batch
Créé
2026-08-31T02:16:53Z

Contrat

  1. DB.Batch executes batch functions and commits modifications
  2. DB.Batch supports concurrent operations across multiple goroutines
  3. DB.Batch returns error when batch function returns an error without committing that function's changes
  4. DB.Batch returns ErrDatabaseReadOnly when called on a read-only database
  5. DB.Batch returns ErrDatabaseNotOpen when called on a closed database

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code 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 go.etcd.io/bbolt.DB.Batch in pkg:golang/go.etcd.io/bbolt@v1.4.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.etcd.io/bbolt@v1.4.3
Demonstrate these symbols/APIs:
  - go.etcd.io/bbolt.DB.Batch
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:d434cb909a4a2717328ad0a40c011e9c01d34d52313bbe5e5dbdcbf0f37f8b19","contract":["DB.Batch executes batch functions and commits modifications","DB.Batch supports concurrent operations across multiple goroutines","DB.Batch returns error when batch function returns an error without committing that function's changes","DB.Batch returns ErrDatabaseReadOnly when called on a read-only database","DB.Batch returns ErrDatabaseNotOpen when called on a closed database"],"goal":"verify go.etcd.io/bbolt.DB.Batch in pkg:golang/go.etcd.io/bbolt@v1.4.3","kind":"HOW","packages":["pkg:golang/go.etcd.io/bbolt@v1.4.3"],"schemaVersion":1,"symbols":["go.etcd.io/bbolt.DB.Batch"]},"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/go.etcd.io/bbolt@v1.4.3"],"schemaVersion":1,"subject":"pkg:golang/go.etcd.io/bbolt@v1.4.3","symbols":["go.etcd.io/bbolt.DB.Batch"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.23

require go.etcd.io/bbolt v1.4.3

require golang.org/x/sys v0.29.0 // indirect
go.sum
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
sample.go
package sample

import (
	"fmt"

	bolt "go.etcd.io/bbolt"
)

// OpenDB opens or creates a Bolt database at the specified path.
func OpenDB(path string) (*bolt.DB, error) {
	db, err := bolt.Open(path, 0600, nil)
	if err != nil {
		return nil, fmt.Errorf("failed to open bolt db: %w", err)
	}
	return db, nil
}

// OpenDBWithOptions opens a Bolt database with custom options.
func OpenDBWithOptions(path string, options *bolt.Options) (*bolt.DB, error) {
	db, err := bolt.Open(path, 0600, options)
	if err != nil {
		return nil, fmt.Errorf("failed to open bolt db with options: %w", err)
	}
	return db, nil
}

// BatchPut executes a batch operation to store a key-value pair in a bucket.
func BatchPut(db *bolt.DB, bucketName, key, value []byte) error {
	return db.Batch(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists(bucketName)
		if err != nil {
			return err
		}
		return b.Put(key, value)
	})
}

// BatchGet executes a batch operation to retrieve a value for a key in a bucket.
func BatchGet(db *bolt.DB, bucketName, key []byte) ([]byte, error) {
	var val []byte
	err := db.Batch(func(tx *bolt.Tx) error {
		b := tx.Bucket(bucketName)
		if b == nil {
			return bolt.ErrBucketNotFound
		}
		v := b.Get(key)
		if v != nil {
			val = make([]byte, len(v))
			copy(val, v)
		}
		return nil
	})
	return val, err
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.etcd.io/bbolt.DB.Batch in pkg:golang/go.etcd.io/bbolt@v1.4.3",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.etcd.io/bbolt@v1.4.3"
  ],
  "symbols": [
    "go.etcd.io/bbolt.DB.Batch"
  ],
  "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 (
	"bytes"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"sync"

	bolt "go.etcd.io/bbolt"
	"sample"
)

func main() {
	tmpDir, err := os.MkdirTemp("", "bbolt-batch-test-*")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to create temp dir: %v\n", err)
		os.Exit(1)
	}
	defer os.RemoveAll(tmpDir)

	dbPath := filepath.Join(tmpDir, "test.db")
	db, err := sample.OpenDB(dbPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to open db: %v\n", err)
		os.Exit(1)
	}
	defer db.Close()

	bucketName := []byte("batch_test")
	key := []byte("k1")
	val := []byte("v1")

	// Assertion 1: DB.Batch executes batch functions and commits modifications
	err = sample.BatchPut(db, bucketName, key, val)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: BatchPut failed: %v\n", err)
		os.Exit(1)
	}

	gotVal, err := sample.BatchGet(db, bucketName, key)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: BatchGet failed: %v\n", err)
		os.Exit(1)
	}
	if !bytes.Equal(gotVal, val) {
		fmt.Fprintf(os.Stderr, "FAIL: expected %q, got %q\n", string(val), string(gotVal))
		os.Exit(1)
	}

	// Assertion 2: DB.Batch supports concurrent operations across multiple goroutines
	var wg sync.WaitGroup
	numWorkers := 10
	errChan := make(chan error, numWorkers)

	for i := 0; i < numWorkers; i++ {
		wg.Add(1)
		go func(workerID int) {
			defer wg.Done()
			wKey := []byte(fmt.Sprintf("worker:%d", workerID))
			wVal := []byte(fmt.Sprintf("data:%d", workerID))
			if err := sample.BatchPut(db, bucketName, wKey, wVal); err != nil {
				errChan <- fmt.Errorf("worker %d BatchPut failed: %w", workerID, err)
			}
		}(i)
	}
	wg.Wait()
	close(errChan)

	for err := range errChan {
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: concurrent batch error: %v\n", err)
			os.Exit(1)
		}
	}

	for i := 0; i < numWorkers; i++ {
		wKey := []byte(fmt.Sprintf("worker:%d", i))
		expectedVal := []byte(fmt.Sprintf("data:%d", i))
		got, err := sample.BatchGet(db, bucketName, wKey)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: BatchGet for worker %d failed: %v\n", i, err)
			os.Exit(1)
		}
		if !bytes.Equal(got, expectedVal) {
			fmt.Fprintf(os.Stderr, "FAIL: expected worker %d value %q, got %q\n", i, string(expectedVal), string(got))
			os.Exit(1)
		}
	}

	// Assertion 3: DB.Batch returns error when batch function returns an error without committing that function's changes
	customErr := errors.New("aborted batch operation")
	errKey := []byte("err_key")
	errVal := []byte("err_val")

	err = db.Batch(func(tx *bolt.Tx) error {
		b := tx.Bucket(bucketName)
		if b == nil {
			return errors.New("bucket not found")
		}
		if err := b.Put(errKey, errVal); err != nil {
			return err
		}
		return customErr
	})

	if !errors.Is(err, customErr) {
		fmt.Fprintf(os.Stderr, "FAIL: expected customErr from Batch, got: %v\n", err)
		os.Exit(1)
	}

	// Verify that errKey was NOT committed
	errGotVal, err := sample.BatchGet(db, bucketName, errKey)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: BatchGet for errKey failed: %v\n", err)
		os.Exit(1)
	}
	if errGotVal != nil {
		fmt.Fprintf(os.Stderr, "FAIL: uncommitted key should be nil, got: %q\n", string(errGotVal))
		os.Exit(1)
	}

	// Assertion 4: DB.Batch returns ErrDatabaseReadOnly when called on a read-only database
	roDBPath := filepath.Join(tmpDir, "readonly.db")
	// Prepare readonly db with initial data
	initDB, err := sample.OpenDB(roDBPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to open init readonly db: %v\n", err)
		os.Exit(1)
	}
	_ = sample.BatchPut(initDB, bucketName, []byte("ro_key"), []byte("ro_val"))
	initDB.Close()

	roDB, err := sample.OpenDBWithOptions(roDBPath, &bolt.Options{ReadOnly: true})
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to open db in readonly mode: %v\n", err)
		os.Exit(1)
	}
	defer roDB.Close()

	err = roDB.Batch(func(tx *bolt.Tx) error {
		b := tx.Bucket(bucketName)
		if b == nil {
			return errors.New("bucket not found")
		}
		return b.Put([]byte("ro_key2"), []byte("ro_val2"))
	})
	if !errors.Is(err, bolt.ErrDatabaseReadOnly) {
		fmt.Fprintf(os.Stderr, "FAIL: expected ErrDatabaseReadOnly on readonly DB, got: %v\n", err)
		os.Exit(1)
	}

	// Assertion 5: DB.Batch returns ErrDatabaseNotOpen when called on a closed database
	closedDBPath := filepath.Join(tmpDir, "closed.db")
	closedDB, err := sample.OpenDB(closedDBPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to open closed db test: %v\n", err)
		os.Exit(1)
	}
	if err := closedDB.Close(); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to close db: %v\n", err)
		os.Exit(1)
	}

	err = closedDB.Batch(func(tx *bolt.Tx) error {
		return nil
	})
	if !errors.Is(err, bolt.ErrDatabaseNotOpen) {
		fmt.Fprintf(os.Stderr, "FAIL: expected ErrDatabaseNotOpen on closed DB, got: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("PASS: go.etcd.io/bbolt.DB.Batch contract assertions passed")
}

Seeder d'origine

anonyme