CodeSampleX

示例

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

已验证示例 — golang go.etcd.io/bbolt v1.3.9: DB. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: bbolt.DB instance provides path and status metadata when…

sha256:4d1867fe3f69ef39841133030d95970e6dccb0404e0c7c43d024b9884e7d1299

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-30

案例

HOW
目标
verify go.etcd.io/bbolt.DB in pkg:golang/go.etcd.io/bbolt@v1.3.9
包
符号
  • go.etcd.io/bbolt.DB
创建时间
2026-08-30T17:04:43Z

契约

  1. bbolt.DB instance provides path and status metadata when opened
  2. bbolt.DB.Update executes a read-write transaction and commits modifications to the database
  3. bbolt.DB.View executes a read-only transaction and retrieves existing key-value data
  4. bbolt.DB.Update rolls back modifications when the transaction callback returns an error
  5. bbolt.DB.Batch coordinates concurrent batch write transactions to disk
  6. bbolt.DB.Stats provides transaction and page allocation metrics
  7. bbolt.DB.Close terminates database access and subsequent transactions return ErrDatabaseNotOpen

文件

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.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 go.etcd.io/bbolt.DB in pkg:golang/go.etcd.io/bbolt@v1.3.9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.etcd.io/bbolt@v1.3.9
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:a9b0d79dc7e0050f104a4023cabeb4e1bff2fd527713fa8b614d22bdab99c60f","contract":["bbolt.DB instance provides path and status metadata when opened","bbolt.DB.Update executes a read-write transaction and commits modifications to the database","bbolt.DB.View executes a read-only transaction and retrieves existing key-value data","bbolt.DB.Update rolls back modifications when the transaction callback returns an error","bbolt.DB.Batch coordinates concurrent batch write transactions to disk","bbolt.DB.Stats provides transaction and page allocation metrics","bbolt.DB.Close terminates database access and subsequent transactions return ErrDatabaseNotOpen"],"goal":"verify go.etcd.io/bbolt.DB in pkg:golang/go.etcd.io/bbolt@v1.3.9","kind":"HOW","packages":["pkg:golang/go.etcd.io/bbolt@v1.3.9"],"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.3.9"],"schemaVersion":1,"subject":"pkg:golang/go.etcd.io/bbolt@v1.3.9","symbols":["go.etcd.io/bbolt.DB"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require go.etcd.io/bbolt v1.3.9

require golang.org/x/sys v0.4.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.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
go.etcd.io/bbolt v1.3.9 h1:8x7aARPEXiXbHmtUwAIv7eV2fQFHrLLavdiJ3uzJXoI=
go.etcd.io/bbolt v1.3.9/go.mod h1:zaO32+Ti0PK1ivdPtgMESzuzL2VPoIG1PCQNvOdo/dE=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
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 DB file with custom options.
func OpenDatabase(path string, timeout time.Duration) (*bolt.DB, error) {
	opts := &bolt.Options{
		Timeout: timeout,
	}
	return bolt.Open(path, 0600, opts)
}

// UpdateKey performs a read-write transaction to insert or update a key in a bucket.
func UpdateKey(db *bolt.DB, bucketName, key, value string) error {
	return db.Update(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte(bucketName))
		if err != nil {
			return fmt.Errorf("create bucket: %w", err)
		}
		return b.Put([]byte(key), []byte(value))
	})
}

// UpdateWithRollback attempts an update but aborts if rollback is requested.
func UpdateWithRollback(db *bolt.DB, bucketName, key, value string, shouldRollback bool) error {
	return db.Update(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte(bucketName))
		if err != nil {
			return fmt.Errorf("create bucket: %w", err)
		}
		if err := b.Put([]byte(key), []byte(value)); err != nil {
			return err
		}
		if shouldRollback {
			return errors.New("simulated error to trigger transaction rollback")
		}
		return nil
	})
}

// ViewKey performs a read-only transaction to retrieve a value by key.
func ViewKey(db *bolt.DB, bucketName, key string) (string, error) {
	var val string
	err := db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(bucketName))
		if b == nil {
			return errors.New("bucket not found")
		}
		data := b.Get([]byte(key))
		if data == nil {
			return errors.New("key not found")
		}
		val = string(data)
		return nil
	})
	return val, err
}

// BatchInsert executes a series of writes inside a db.Batch call.
func BatchInsert(db *bolt.DB, bucketName string, entries map[string]string) error {
	return db.Batch(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte(bucketName))
		if err != nil {
			return fmt.Errorf("create bucket: %w", err)
		}
		for k, v := range entries {
			if err := b.Put([]byte(k), []byte(v)); err != nil {
				return err
			}
		}
		return nil
	})
}

// GetDBStats returns cumulative database statistics.
func GetDBStats(db *bolt.DB) bolt.Stats {
	return db.Stats()
}

// CloseDatabase closes the Bolt database handle.
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.3.9",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.etcd.io/bbolt@v1.3.9"
  ],
  "symbols": [
    "go.etcd.io/bbolt.DB"
  ]
}
test/contract.go
package main

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

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

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

	dbPath := filepath.Join(tmpDir, "database.db")

	// Assertion 1: bbolt.DB instance provides path and string representation when opened
	db, err := sample.OpenDatabase(dbPath, 1*time.Second)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to open database: %v\n", err)
		os.Exit(1)
	}
	if db == nil {
		fmt.Fprintf(os.Stderr, "expected *bolt.DB, got nil\n")
		os.Exit(1)
	}

	if db.Path() != dbPath {
		fmt.Fprintf(os.Stderr, "expected db.Path() == %q, got %q\n", dbPath, db.Path())
		os.Exit(1)
	}
	if db.String() == "" {
		fmt.Fprintf(os.Stderr, "expected non-empty db.String()\n")
		os.Exit(1)
	}
	if db.IsReadOnly() {
		fmt.Fprintf(os.Stderr, "expected db.IsReadOnly() == false\n")
		os.Exit(1)
	}

	// Assertion 2: bbolt.DB.Update executes a read-write transaction and commits modifications to the database
	bucket := "config"
	key1 := "app_name"
	val1 := "bbolt_test"
	if err := sample.UpdateKey(db, bucket, key1, val1); err != nil {
		fmt.Fprintf(os.Stderr, "UpdateKey failed: %v\n", err)
		os.Exit(1)
	}

	// Assertion 3: bbolt.DB.View executes a read-only transaction and retrieves existing key-value data
	readVal, err := sample.ViewKey(db, bucket, key1)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ViewKey failed: %v\n", err)
		os.Exit(1)
	}
	if readVal != val1 {
		fmt.Fprintf(os.Stderr, "expected value %q, got %q\n", val1, readVal)
		os.Exit(1)
	}

	// Assertion 4: bbolt.DB.Update rolls back modifications when the transaction callback returns an error
	rollbackKey := "temp_key"
	rollbackVal := "temp_value"
	err = sample.UpdateWithRollback(db, bucket, rollbackKey, rollbackVal, true)
	if err == nil {
		fmt.Fprintf(os.Stderr, "expected rollback error, got nil\n")
		os.Exit(1)
	}

	_, err = sample.ViewKey(db, bucket, rollbackKey)
	if err == nil {
		fmt.Fprintf(os.Stderr, "expected key %q to not exist after rollback\n", rollbackKey)
		os.Exit(1)
	}

	// Assertion 5: bbolt.DB.Batch coordinates concurrent batch write transactions to disk
	var wg sync.WaitGroup
	batchErrors := make(chan error, 10)
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func(idx int) {
			defer wg.Done()
			entries := map[string]string{
				fmt.Sprintf("batch_key_%d", idx): fmt.Sprintf("batch_val_%d", idx),
			}
			if bErr := sample.BatchInsert(db, "batch_bucket", entries); bErr != nil {
				batchErrors <- bErr
			}
		}(i)
	}
	wg.Wait()
	close(batchErrors)

	for bErr := range batchErrors {
		fmt.Fprintf(os.Stderr, "BatchInsert error: %v\n", bErr)
		os.Exit(1)
	}

	for i := 0; i < 5; i++ {
		k := fmt.Sprintf("batch_key_%d", i)
		expectedV := fmt.Sprintf("batch_val_%d", i)
		v, err := sample.ViewKey(db, "batch_bucket", k)
		if err != nil {
			fmt.Fprintf(os.Stderr, "ViewKey for batch entry %q failed: %v\n", k, err)
			os.Exit(1)
		}
		if v != expectedV {
			fmt.Fprintf(os.Stderr, "expected batch value %q, got %q\n", expectedV, v)
			os.Exit(1)
		}
	}

	// Assertion 6: bbolt.DB.Stats provides transaction and page allocation metrics
	stats := sample.GetDBStats(db)
	if stats.TxStats.Write <= 0 {
		fmt.Fprintf(os.Stderr, "expected positive write transactions in stats, got %d\n", stats.TxStats.Write)
		os.Exit(1)
	}

	// Assertion 7: bbolt.DB.Close terminates database access and subsequent transactions return ErrDatabaseNotOpen
	if err := sample.CloseDatabase(db); err != nil {
		fmt.Fprintf(os.Stderr, "CloseDatabase failed: %v\n", err)
		os.Exit(1)
	}

	err = sample.UpdateKey(db, bucket, "after_close", "val")
	if !errors.Is(err, bolt.ErrDatabaseNotOpen) {
		fmt.Fprintf(os.Stderr, "expected ErrDatabaseNotOpen after close, got %v\n", err)
		os.Exit(1)
	}

	fmt.Println("All bbolt.DB contract assertions passed.")
}

原始种子者

匿名