CodeSampleX

Exemplo

go.etcd.io/bbolt v1.5.0: DB

Amostra verificada para golang go.etcd.io/bbolt v1.5.0: DB. O contrato rodou em go 1.26 · linux alpine/x64 · docker e passou: bbolt.DB.Path returns the…

sha256:8961df378159e0dafaf2ed4a230bfe181f02e345a2031c9e9e19d298a580074b

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
verify go.etcd.io/bbolt.DB in pkg:golang/go.etcd.io/bbolt@v1.5.0
Pacotes
Símbolos
  • go.etcd.io/bbolt.DB
Criado
2026-08-30T14:50:06Z

Contrato

  1. bbolt.DB.Path returns the filesystem path of the opened database file
  2. bbolt.DB.IsReadOnly returns false for writable databases and true for databases opened with ReadOnly option
  3. bbolt.DB.Update executes a read-write transaction and automatically commits changes on nil return
  4. bbolt.DB.Update automatically rolls back changes when the callback returns an error
  5. bbolt.DB.View executes a read-only transaction and allows reading data
  6. bbolt.DB.Batch executes batched transactions and commits changes
  7. bbolt.DB.Stats returns transaction statistics including TxN count
  8. bbolt.DB.Close closes the database file and releases file locks

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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

Use EXACTLY these public packages and versions:
  - pkg:golang/go.etcd.io/bbolt@v1.5.0
Demonstrate these symbols/APIs:
  - go.etcd.io/bbolt.DB

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:913f1bc08830209a7163df517f066ae45b63165ee04fb112e1f5be4c90e28fcd","contract":["bbolt.DB.Path returns the filesystem path of the opened database file","bbolt.DB.IsReadOnly returns false for writable databases and true for databases opened with ReadOnly option","bbolt.DB.Update executes a read-write transaction and automatically commits changes on nil return","bbolt.DB.Update automatically rolls back changes when the callback returns an error","bbolt.DB.View executes a read-only transaction and allows reading data","bbolt.DB.Batch executes batched transactions and commits changes","bbolt.DB.Stats returns transaction statistics including TxN count","bbolt.DB.Close closes the database file and releases file locks"],"goal":"verify go.etcd.io/bbolt.DB in pkg:golang/go.etcd.io/bbolt@v1.5.0","kind":"HOW","packages":["pkg:golang/go.etcd.io/bbolt@v1.5.0"],"schemaVersion":1,"symbols":["go.etcd.io/bbolt.DB"]},"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.5.0"],"schemaVersion":1,"subject":"pkg:golang/go.etcd.io/bbolt@v1.5.0","symbols":["go.etcd.io/bbolt.DB"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.25.0

require go.etcd.io/bbolt v1.5.0

require golang.org/x/sys v0.45.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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU=
go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
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 (
	"errors"
	"fmt"
	"time"

	bolt "go.etcd.io/bbolt"
)

// OpenDatabase opens a Bolt database at the specified path with the provided options.
func OpenDatabase(path string, readOnly bool, timeout time.Duration) (*bolt.DB, error) {
	opts := &bolt.Options{
		ReadOnly: readOnly,
		Timeout:  timeout,
	}
	return bolt.Open(path, 0600, opts)
}

// SetKey stores a key-value pair in the specified bucket using db.Update.
func SetKey(db *bolt.DB, bucket, key, value string) error {
	return db.Update(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte(bucket))
		if err != nil {
			return fmt.Errorf("create bucket failed: %w", err)
		}
		return b.Put([]byte(key), []byte(value))
	})
}

// GetKey retrieves a value for a key in the specified bucket using db.View.
func GetKey(db *bolt.DB, bucket, key string) (string, error) {
	var result string
	err := db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(bucket))
		if b == nil {
			return errors.New("bucket not found")
		}
		val := b.Get([]byte(key))
		if val == nil {
			return errors.New("key not found")
		}
		result = string(val)
		return nil
	})
	return result, err
}

// BatchSetKey stores a key-value pair using db.Batch.
func BatchSetKey(db *bolt.DB, bucket, key, value string) error {
	return db.Batch(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte(bucket))
		if err != nil {
			return fmt.Errorf("create bucket failed: %w", err)
		}
		return b.Put([]byte(key), []byte(value))
	})
}

// GetStats returns the Stats struct for the database.
func GetStats(db *bolt.DB) bolt.Stats {
	return db.Stats()
}

// CloseDatabase closes the Bolt database.
func CloseDatabase(db *bolt.DB) error {
	if db == nil {
		return nil
	}
	return db.Close()
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.etcd.io/bbolt.DB in pkg:golang/go.etcd.io/bbolt@v1.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.etcd.io/bbolt@v1.5.0"
  ],
  "symbols": [
    "go.etcd.io/bbolt.DB"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"time"

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

func main() {
	tmpDir, err := os.MkdirTemp("", "bbolt-db-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")

	// Assertion 1: bbolt.DB.Path returns the filesystem path of the opened database file
	db, err := sample.OpenDatabase(dbPath, false, 1*time.Second)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to open db: %v\n", err)
		os.Exit(1)
	}
	defer sample.CloseDatabase(db)

	if db.Path() != dbPath {
		fmt.Fprintf(os.Stderr, "FAIL: expected db.Path() %q, got %q\n", dbPath, db.Path())
		os.Exit(1)
	}

	// Assertion 2: bbolt.DB.IsReadOnly returns false for writable databases and true for databases opened with ReadOnly option
	if db.IsReadOnly() {
		fmt.Fprintf(os.Stderr, "FAIL: expected db.IsReadOnly() to be false for writable db\n")
		os.Exit(1)
	}

	// Assertion 3: bbolt.DB.Update executes a read-write transaction and automatically commits changes on nil return
	bucketName := "config"
	key := "app_name"
	expectedVal := "CodeSampleX"

	if err := sample.SetKey(db, bucketName, key, expectedVal); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: SetKey failed: %v\n", err)
		os.Exit(1)
	}

	// Assertion 4: bbolt.DB.View executes a read-only transaction and allows reading data
	gotVal, err := sample.GetKey(db, bucketName, key)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: GetKey failed: %v\n", err)
		os.Exit(1)
	}
	if gotVal != expectedVal {
		fmt.Fprintf(os.Stderr, "FAIL: expected %q, got %q\n", expectedVal, gotVal)
		os.Exit(1)
	}

	// Assertion 5: bbolt.DB.Update automatically rolls back changes when the callback returns an error
	simulatedErr := errors.New("simulated transaction failure")
	err = db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(bucketName))
		if b == nil {
			return errors.New("bucket missing")
		}
		if err := b.Put([]byte("temp_key"), []byte("temp_value")); err != nil {
			return err
		}
		return simulatedErr
	})
	if !errors.Is(err, simulatedErr) {
		fmt.Fprintf(os.Stderr, "FAIL: expected simulated error on update rollback, got: %v\n", err)
		os.Exit(1)
	}

	_, err = sample.GetKey(db, bucketName, "temp_key")
	if err == nil {
		fmt.Fprintf(os.Stderr, "FAIL: temp_key should not exist after rolled back Update\n")
		os.Exit(1)
	}

	// Assertion 6: bbolt.DB.Batch executes batched transactions and commits changes
	batchKey := "batch_key"
	batchVal := "batch_val"
	if err := sample.BatchSetKey(db, bucketName, batchKey, batchVal); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: BatchSetKey failed: %v\n", err)
		os.Exit(1)
	}

	gotBatchVal, err := sample.GetKey(db, bucketName, batchKey)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: GetKey for batch key failed: %v\n", err)
		os.Exit(1)
	}
	if gotBatchVal != batchVal {
		fmt.Fprintf(os.Stderr, "FAIL: expected %q, got %q\n", batchVal, gotBatchVal)
		os.Exit(1)
	}

	// Assertion 7: bbolt.DB.Stats returns transaction statistics including TxN count
	stats := sample.GetStats(db)
	if stats.TxN < 1 {
		fmt.Fprintf(os.Stderr, "FAIL: expected stats.TxN >= 1, got %d\n", stats.TxN)
		os.Exit(1)
	}

	// Assertion 8: bbolt.DB.Close closes the database file and releases file locks
	if err := sample.CloseDatabase(db); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: CloseDatabase failed: %v\n", err)
		os.Exit(1)
	}

	// Verify ReadOnly mode on re-open
	roDB, err := sample.OpenDatabase(dbPath, true, 1*time.Second)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to open read-only db: %v\n", err)
		os.Exit(1)
	}
	defer sample.CloseDatabase(roDB)

	if !roDB.IsReadOnly() {
		fmt.Fprintf(os.Stderr, "FAIL: expected roDB.IsReadOnly() to be true\n")
		os.Exit(1)
	}

	roVal, err := sample.GetKey(roDB, bucketName, key)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: GetKey on read-only db failed: %v\n", err)
		os.Exit(1)
	}
	if roVal != expectedVal {
		fmt.Fprintf(os.Stderr, "FAIL: expected %q, got %q in read-only db\n", expectedVal, roVal)
		os.Exit(1)
	}

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

Seeder de origem

anônimo