treedb

package
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 1, 2026 License: MIT Imports: 28 Imported by: 0

README

TreeDB

TreeDB is a high-performance, persistent key-value store optimized for the Cosmos SDK workload. It features a B+Tree index backed by a memory-mapped file plus a persistent value log for large values, with a separate journal/redo log for crash recovery.

Canonical Spec

The canonical TreeDB specification now lives under:

  • TreeDB/docs/spec/README.md

Use that folder for architecture, format, durability, recovery, lifecycle, and verification requirements. Practical typed-storage quickstarts and benchmark-adjacent guides live under TreeDB/docs/guides/. The root docs/TREEDB_*.md files remain supporting material.

Features

  • Crash-consistent commits: Atomic batch commits and recovery behavior according to the selected durability mode.
  • Snapshot Isolation: Lock-free concurrent readers using Multi-Version Concurrency Control (MVCC) and Reference Counting.
  • Hybrid Storage:
    • Index: Memory-mapped B+Tree for keys and small values.
    • Value log: Append-only log for large values (contract code, blobs) to reduce write amplification and memory pressure.
    • Journal/redo log: Commit metadata for crash recovery and checkpointing.
  • Crash Recovery: Automatic recovery from torn writes using strict write-ordering and checksum verification.
  • Lifecycle Management: Safe page reclamation using a Graveyard and Reader Registry to protect active snapshots.

Architecture

Storage Layout
  • Root dir: Options.Dir is a root directory with maindb/ (main data) plus optional side stores such as dictdb/ and templatedb/.
  • Pages: 4KB fixed-size blocks in maindb/index.db.
  • Nodes: Slotted pages supporting variable-length keys.
  • Value log: Persistent append-only segments under maindb/value_vlog/ storing large values with CRC checksums.
  • Leaf log: Optional persistent outer-leaf generations under maindb/leaf_vlog/ when IndexOuterLeavesInValueLog is enabled.
  • Journal/redo log: Commit metadata for crash recovery under maindb/wal/.
Write Path ("The Zipper")

Writes are batched and applied using a recursive "Zipper" merge algorithm. This creates a new version of the tree path (COW) without modifying existing on-disk pages, ensuring crash safety and snapshot isolation.

Read Path

Readers acquire a Snapshot which pins the version of the tree and the relevant value-log segments. This guarantees a consistent view of the database even while writers are committing new versions.

Usage

package main

import (
	"errors"
	"fmt"
	"log"

	treedb "github.com/snissn/gomap/TreeDB"
)

func main() {
	// Open the database (recommended: cached wrapper)
	opts := treedb.Options{Dir: "./my-db-data"}
	database, err := treedb.Open(opts)
	if err != nil {
		if errors.Is(err, treedb.ErrLocked) {
			log.Fatal("database is already open in another process")
		}
		log.Fatal(err)
	}
	defer database.Close()

	// Set a key-value pair
	if err := database.Set([]byte("key1"), []byte("value1")); err != nil {
		log.Fatal(err)
	}

	// Get a value
	val, err := database.Get([]byte("key1"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Got: %s\n", val)

	// Iterate
	it, _ := database.Iterator(nil, nil)
	defer it.Close()
	for ; it.Valid(); it.Next() {
		fmt.Printf("%s = %s\n", it.Key(), it.Value())
	}
	
	// Atomic Batch
	batch := database.NewBatch()
	batch.Set([]byte("k2"), []byte("v2"))
	batch.Delete([]byte("key1"))
	batch.Write() // Atomic commit
}

Profiles (Command WAL / Bench)

If you want a simple, documented “bundle” of options, start with a profile and then override a few workload-specific knobs:

opts := treedb.OptionsFor(treedb.ProfileCommandWALDurable, "./my-db-data")
opts.FlushThreshold = 128 << 20 // optional tuning
db, err := treedb.Open(opts)

The public profile surface is intentionally narrow:

  • ProfileCommandWALDurable: command-WAL collections and raw writes with durable sync/checksum settings. Use this as the default server profile.
  • ProfileCommandWALRelaxed: command-WAL collections and raw writes with relaxed sync/read-integrity settings for high-throughput ingest and benchmark comparisons.
  • ProfileBench: benchmark-only no-WAL ceiling for measuring raw in-process storage overhead. Do not use it as a production profile.

Legacy/raw bundles such as ProfileDurable, ProfileFast, and ProfileWALOnFast remain temporarily available for compatibility and focused low-level tests, but they are not the current public guidance.

Note: WAL-off is selected by ProfileBench or by explicitly setting opts.Durability = treedb.DurabilityWALOffRelaxed in low-level experiments. The value log remains enabled in cached mode, so large values can still go through value_vlog/ even when the redo journal is off.

Details: docs/TREEDB_WRITE_PATHS.md.

If you are integrating TreeDB behind a Cosmos/Comet-style wrapper, use TreeDB/integration/kvstoreadapter to standardize profile/env/default handling instead of re-copying the open-path glue in each downstream repo.

Leaf Pages in the Value Log

Options.IndexOuterLeavesInValueLog stores the B+Tree leaf pages (the 4096B pages that contain keys and values/pointers) in the persistent value log instead of in index.db. Internal pages remain in index.db and still provide exact lookup routing to a single leaf page (no leaf scanning).

Leaf pages may still contain inline values or ValuePtr entries using the existing placement rules.

Collections can store caller-generated float32 embeddings in JSON document fields and search them without making ANN storage the source of truth. Canonical documents and embeddings remain in TreeDB primary storage; vector indexes keep stable collection document IDs and exact-rerank candidates from canonical rows.

Current entry points:

Goal Entry point Boundary
High-QPS no-document collection serving Collection.SearchVectorIndexWithBuffer Caller-owned VectorIndexSearchBuffer; exact IncludeDocuments=false; warm the hnsw_search_pack_v1 prepared route before serving.
Convenience no-document calls Collection.SearchVectorIndex with IncludeDocuments=false Response-owned results/IDs; healthy exact calls use the cached no-document route but intentionally allocate result storage.
Reusable low-level workers Collection.OpenVectorIndexSearcher + VectorIndexSearcher.SearchWithBuffer One opened searcher and one reusable buffer per worker; caller owns searcher/snapshot lifetime.
Search plus materialization Collection.SearchVectorIndex with IncludeDocuments=true Explicit with-document path; report document-fetch/materialization counters separately from no-document rows.
Quantized score planes Explicit quantized_only / quantized_rerank modes Separate codec-generic follow-up path; not the exact high-QPS demo route or no-document hnsw_search_pack_v1 claim.

Exact-only runnable demo from the repository root:

GOWORK=off go run ./cmd/treedb_vector_highqps_demo \
  -docs 1000 \
  -dims 64 \
  -queries 1000 \
  -warmup-queries 16 \
  -top-k 10 \
  -m 16 \
  -ef-construction 128 \
  -ef-search 128

Use TreeDB/docs/guides/vector-search-high-qps-collection-api.md for the API chooser and buffer lifetime caveats, TreeDB/docs/guides/vector-search-benchmark-workflow.md for the canonical Tier S/Tier F workflow and guardrail counters, and cmd/treedb_vector_highqps_demo/README.md for demo output interpretation. The exact demo intentionally excludes document materialization and quantized modes. Healthy exact no-document rows prove search_route_hnsw_search_pack/search=1, hnsw_search_pack_active/search=1, docs_fetched/search=0, zero fallback and scratch counters, and no per-query collection open/setup in timed loops.

Additional collection vector APIs and diagnostics live in TreeDB/collections:

  • Collection.SearchVectorsExact scans live rows and returns exact top-k results for cosine, squared L2, or inner-product distance.
  • Collection.BuildVectorIndex builds an in-memory HNSW-style secondary index that returns candidates and exact-reranks final results.
  • BenchmarkCollectionVectorIndexGraphOnlySearch is a benchmark-only engine comparison path that times TreeDB graph search without collection row fetches, JSON vector extraction, metadata filtering, or exact rerank.
  • BenchmarkCollectionVectorIndexBuild and BenchmarkCollectionVectorUSearchBuild isolate index build cost from query latency for TreeDB and the optional USearch comparator.
  • Declared quantized score planes use explicit quantized_only or quantized_rerank query modes with codec-generic quantized_* route, validation, and fail-closed counters. Scalar scalar_u8 evidence is a behavior/storage baseline, not a current speedup claim; keep it separate from the exact no-document high-QPS path and demo. See TreeDB/docs/spec/quantized-vector-index.md.
  • VectorIndex.SaveSnapshot and Collection.LoadVectorIndexSnapshot persist immutable index epochs under vector_indexes/<collection>/<index>/ with a manifest plus checksum-verified node, edge, tombstone, and docmap files.
  • VectorIndexRangeFilter restricts exact or ANN searches with an existing scalar secondary-index range. Selective filters use an exact_filtered strategy; broader filters use ann_postfilter and can fall back to exact filtered search if ANN underfills.
  • VectorIndex.Stats, VectorIndex.Search traces, and VectorIndex.CheckRecall expose live/deleted counts, memory and disk bytes, persisted epoch state, snapshot dirtiness, candidate counts, selected strategy, exact fallback reason, rebuild duration, and recall-at-k.

Native column_graph benchmark tiers are documented in docs/guides/vector-search-typed-column.md#vector-search-benchmark-tiers. Use that matrix to distinguish core graph search, existing public response-owned Search, collection-level caller-buffered SearchVectorIndexWithBuffer, reusable-buffer no-document SearchWithBuffer, parallel callers, and explicit document-fetch paths. Report ops/sec (1e9 / ns/op) with ns/op, B/op, allocs/op, and vector/adjacency direct-vs-scratch counters.

Smoke benchmark:

TREEDB_VECTOR_BENCH_DOCS=1000 TREEDB_VECTOR_BENCH_DIMS=32 \
  go test ./TreeDB/collections -run '^$' \
  -bench 'BenchmarkCollectionVector(SearchExact|Index(Search|SearchInt8|FilteredSearch))$' \
  -benchtime=1x -count=1

Optional NumKong dot-product kernel: build with -tags numkong on hosts where cgo and NumKong are available. Default builds, including cgo-enabled builds, use the pure-Go kernel.

External comparison benchmark with local USearch bootstrap:

scripts/bench_vector_search_compare.sh

The script downloads and extracts a USearch Linux or macOS release package into /tmp when USEARCH_ROOT is not set, configures cgo include/library paths, and writes results under /tmp/gomap_vector_search_compare_*. The canonical current production rows include BenchmarkCollectionVectorUSearchProductionCompare/TreeDB_CollectionSearchVectorIndexNoDocsOneShot as the response-owned collection convenience API on the cached no-document hnsw_search_pack_v1 route, .../TreeDB_CollectionSearchVectorIndexWithBuffer as the collection-level caller-owned result-buffer seam on the same warmed collection-owned prepared cache (open_searcher_calls/op=0, open_setup_in_timed_loop=0 in the timed loop), plus .../TreeDB_SearchWithBuffer* versus .../USearch_Search*: TreeDB's high-QPS comparison uses persisted column_graph through Collection.OpenVectorIndexSearcher plus VectorIndexSearcher.SearchWithBuffer with one searcher and one reusable buffer per worker, while USearch is a pure in-memory cosine/f32 HNSW baseline. Use CPU_LIST=1,8 for c=1/c=8 evidence. Older BenchmarkCollectionVectorIndex* rows are historical controls, not the current high-QPS production fast path; with-documents Collection.SearchVectorIndex rows still include setup/open and materialization cost and should not be presented as the no-document fast path. See TreeDB/docs/guides/vector-search-high-qps-collection-api.md for the final collection API boundary, and TreeDB/docs/guides/vector-search-benchmark-workflow.md for the dated Tier S snapshot from #2366/#2379, required fast-path counters, canonical Tier S/Tier F commands, USearch platform path setup, artifact/profile capture notes, and the zero-allocation vs response-owned vs materialization row boundary. Override USEARCH_VERSION, USEARCH_ROOT, TREEDB_VECTOR_BENCH_DOCS, TREEDB_VECTOR_BENCH_DIMS, TREEDB_VECTOR_BENCH_M, TREEDB_VECTOR_BENCH_EF_CONSTRUCTION, TREEDB_VECTOR_BENCH_EF_SEARCH, TREEDB_VECTOR_BENCH_TOPK, TREEDB_VECTOR_BENCH_QUERIES, BENCHTIME, COUNT, and CPU_LIST to change the comparison shape. The USearch filtered Go binding currently trips Go's cgo pointer checks on this toolchain; set RUN_UNSAFE_USEARCH_FILTERED=true only when you explicitly want that benchmark with GODEBUG=cgocheck=0.

Recent 10k x 1536 external snapshot, using TreeDB DB-demo no-document search, USearch f32 HNSW, and PostgreSQL+pgvector HNSW with M=16, efConstruction=128, efSearch=128, and topK=10:

system recall@10 c=1 avg / QPS c=8 avg / QPS
TreeDB exact FP32 0.9859 418 µs / 2,391 852 µs / 9,386
TreeDB scalar_u8 rerank32 0.9828 165 µs / 6,072 511 µs / 15,571
USearch f32 HNSW 0.8938 725 µs / 1,380 160 µs / 6,259
PostgreSQL+pgvector HNSW 0.9859 2.67 ms / 374 4.29 ms / 1,864

Full context, commands, guardrails, and caveats are in ../docs/benchmarks/treedb_vector_external_compare_2026-06-08.md. The USearch row is an in-memory library comparator, not a persistent DB/server row, and its averages are from batch searches with threads=1/8.

TreeDB's VectorDBBench integration uses the document service and the shared treedb-client Python package. It exposes separate exact FP32, scalar_u8-rerank32, and experimental RaBitQ rows while keeping Haystack's /search/vector route as exact dense document scoring. Those rows include Python/client/HTTP/service overhead and are not native Go allocation evidence; see ../docs/benchmarks/treedb_vectordbbench_runbook_2026-06-11.md.

The tiny BERT embedding demo in ../examples/vector_search/tiny_bert/ is a caller-side fixture/demo; TreeDB core does not generate embeddings. Export it with --output-jsonl and set TREEDB_VECTOR_BENCH_JSONL to run BenchmarkCollectionVectorTinyBERTFixture.

Optional external engine baseline: build with -tags usearch_bench after installing the USearch C library and headers for the host. The current comparison benchmark runs the same deterministic synthetic vector/query generator through TreeDB's persisted column_graph reusable-buffer path and through USearch's Go bindings with cosine/f32 HNSW and matching M, efConstruction, efSearch, topK, docs, dims, and -cpu/concurrency knobs:

The Go binding is intentionally kept as an indirect module dependency because it is only imported by the optional usearch_bench build tag.

for cpu in 1 8; do
  TREEDB_VECTOR_BENCH_DOCS=10000 TREEDB_VECTOR_BENCH_DIMS=64 \
    TREEDB_VECTOR_BENCH_EF_SEARCH=128 \
    go test -tags usearch_bench ./TreeDB/collections -run '^$' \
    -bench '^BenchmarkCollectionVectorUSearchProductionCompare$' \
    -benchmem -benchtime=1x -count=1 -cpu="$cpu"
done

Durability & Safety Notes

  • Safe defaults keep WAL, fsync, and read checksums enabled; relax safety knobs via Options.Durability and Options.ValueLog.ReadIntegrity.
  • In relaxed durability modes (DurabilityWALOnRelaxed / DurabilityWALOffRelaxed), SetSync/WriteSync are crash-consistent only (no fsync) and may not survive power loss.
  • Page checksums are verified once and cached until the page is rewritten; use VerifyOnRead for paranoid always-verify behavior. Options.ValueLog.ReadIntegrity = IntegritySkipChecksums disables value-log CRC checks entirely.
  • CRC checksums detect accidental corruption, not malicious tampering; use filesystem encryption/HMAC if your threat model includes adversarial disk access.
  • GetUnsafe on a Snapshot and iterator Key()/Value() return short-lived views; use Get, KeyCopy, or ValueCopy for stable bytes.
  • TreeDB does not provide encryption-at-rest or secure deletion; deleted data may remain on disk until compacted. Use OS/disk encryption for confidentiality.
  • For production final disk footprint, use db.CompactStorage(ctx, treedb.CompactStorageOptions{Mode: treedb.CompactStorageFull}) or treemap compact <db-dir> -rw. This is the best-practice policy path across index.db, value_vlog, leaf_vlog, and empty segment cleanup; platforms without online index vacuum report that phase as skipped while still compacting the value-log domains. For byte-minimized benchmark/VACUUM-equivalent claims, use CompactStorageExhaustive or treemap compact <db-dir> -rw -mode exhaustive, which also seals the current leaf generation and bypasses production leaf-pack yield thresholds.
  • Low-level APIs such as ValueLogGC, ValueLogRewriteOffline, LeafGenerationPack*, and VacuumIndex* are maintenance building blocks. Do not manually chain them for benchmark storage numbers unless you are working on TreeDB internals.
  • Optional guardrail: Options.ValueLog.MaxRetainedBytes emits a warning when retained value-log bytes exceed the threshold.
  • Optional hard cap: Options.ValueLog.MaxRetainedBytesHard disables value-log pointers for new large values once retained bytes exceed the threshold.
  • TreeDB is pre-alpha; public APIs and on-disk format may change without backward-compatibility guarantees.
Durability Overview (Cached Mode)

The canonical durability-mode matrix is TreeDB/docs/spec/write-path-and-durability.md#1-durability-modes.

In short: durable mode gives fsync durability at sync/checkpoint boundaries; WAL-on relaxed mode is process-crash-oriented and is not a power-loss fsync guarantee; WAL-off relaxed mode has no per-write journal replay and relies on flush/checkpoint/close boundaries. Collection writes currently remain governed by TreeDB/docs/spec/collections-write-domain.md; the target durable-at-ack collection overlay is gated by TreeDB/docs/spec/collection-wal-durability-plan.md; it is target behavior after the collection WAL gate, not current behavior.

Tuning (Cached Mode)

treedb.Open defaults to cached mode (memtable + journal + value log + background flush). The most important knobs:

  • Options.FlushThreshold + Options.MaxQueuedMemtables (throughput vs. backlog/memory)
  • Adaptive backpressure: SlowdownBacklogSeconds, StopBacklogSeconds, MaxBacklogBytes
  • Cached-mode auto checkpointing: BackgroundCheckpointInterval, BackgroundCheckpointIdleDuration
  • Command-WAL bounded growth: CommandWALSegmentTargetBytes rotates active command-WAL segments independently from WALMaxSegmentBytes, which remains a per-frame safety cap; MaxWALBytes triggers command-WAL-aware auto checkpoints in command-WAL cached mode.
  • Background pruning: PruneInterval, PruneMaxPages, PruneMaxDuration
  • Optional flush build parallelism: FlushBuildConcurrency
  • Auto-admitted span-native flush apply workers: FlushApplyConcurrency defaults to detected physical cores capped by GOMAXPROCS and 8 under FlushAdmissionPolicyAuto (falling back to min(GOMAXPROCS, 8) when physical cores are unknown); default journal/value-log lanes stay coalescing-safe, and FlushAdmissionPolicyOff, FlushAdmissionPolicyExplicit, explicit FlushApplyConcurrency, and explicit JournalLanes remain available for c4/c8/c16/lane experiments
  • Optional piggyback compaction toggle: DisablePiggybackCompaction
  • Value-log retention guardrails: ValueLog.MaxRetainedBytes, ValueLog.MaxRetainedBytesHard
  • Value-log compression mode: ValueLog.Compression (off|block|dict|auto) and ValueLog.BlockCodec (snappy|lz4|zstd)
  • Full storage compaction: db.CompactStorage(ctx, treedb.CompactStorageOptions{Mode: treedb.CompactStorageFull}) or treemap compact <db-dir> -rw; benchmark byte-minimized compaction: CompactStorageExhaustive or treemap compact <db-dir> -rw -mode exhaustive
  • Index-only rebuild: treedb.CompactIndex() or treedb.VacuumIndexOffline(opts) when you explicitly want only index.db maintenance

ValueLog.Compression defaults to auto when unset.

Details: docs/TREEDB_TUNING.md.

Exclusive Open (Process Lock)

TreeDB acquires an exclusive lock on Options.Dir. If another process has the database open, treedb.Open returns treedb.ErrLocked.

Testing

TreeDB includes a comprehensive test suite covering unit functionality, integration, fuzzing, and crash recovery.

Unit & Integration Tests
go test -v ./...
Fuzz Testing

Model-based fuzzing verifies consistency against a simple in-memory map map model.

go test -v ./db/fuzz_test.go
Crash Simulation

The verify_crash.sh script compiles a stress tool, runs it, kills it (kill -9), and verifies database integrity upon restart.

./verify_crash.sh

License

MIT

Documentation

Index

Examples

Constants

View Source
const (
	CompactStorageDefault    = treedbdb.CompactStorageDefault
	CompactStorageFull       = treedbdb.CompactStorageFull
	CompactStorageQuick      = treedbdb.CompactStorageQuick
	CompactStorageExhaustive = treedbdb.CompactStorageExhaustive
)
View Source
const (
	CompactStorageOwnerStatusSupportedTarget      = treedbdb.CompactStorageOwnerStatusSupportedTarget
	CompactStorageOwnerStatusLiveWriterFailClosed = treedbdb.CompactStorageOwnerStatusLiveWriterFailClosed
	CompactStorageOwnerStatusExternalUnsupported  = treedbdb.CompactStorageOwnerStatusExternalUnsupported
	CompactStorageOwnerStatusBlockingBug          = treedbdb.CompactStorageOwnerStatusBlockingBug
)
View Source
const (
	CompactStorageLeafPageLogOwnerNone                     = treedbdb.CompactStorageLeafPageLogOwnerNone
	CompactStorageLeafPageLogOwnerCommandWALReplayInline   = treedbdb.CompactStorageLeafPageLogOwnerCommandWALReplayInline
	CompactStorageLeafPageLogOwnerInternalHiddenByWrapper  = treedbdb.CompactStorageLeafPageLogOwnerInternalHiddenByWrapper
	CompactStorageLeafPageLogOwnerCachedWrapper            = treedbdb.CompactStorageLeafPageLogOwnerCachedWrapper
	CompactStorageLeafPageLogOwnerStandaloneCallerExternal = treedbdb.CompactStorageLeafPageLogOwnerStandaloneCallerExternal
)
View Source
const (
	CompactStorageLifecycleExclusiveMaintenance = treedbdb.CompactStorageLifecycleExclusiveMaintenance
	CompactStorageLifecycleQuiescedMaintenance  = treedbdb.CompactStorageLifecycleQuiescedMaintenance
	CompactStorageLifecycleActiveWriter         = treedbdb.CompactStorageLifecycleActiveWriter
)
View Source
const (
	DurabilityDurable       = db.DurabilityDurable
	DurabilityWALOnRelaxed  = db.DurabilityWALOnRelaxed
	DurabilityWALOffRelaxed = db.DurabilityWALOffRelaxed
)
View Source
const (
	IntegrityVerify        = db.IntegrityVerify
	IntegritySkipChecksums = db.IntegritySkipChecksums
)
View Source
const (
	ValueLogCompressionOff   = db.ValueLogCompressionOff
	ValueLogCompressionBlock = db.ValueLogCompressionBlock
	ValueLogCompressionDict  = db.ValueLogCompressionDict
	ValueLogCompressionAuto  = db.ValueLogCompressionAuto
)
View Source
const (
	ValueLogBlockSnappy = db.ValueLogBlockSnappy
	ValueLogBlockLZ4    = db.ValueLogBlockLZ4
	ValueLogBlockZSTD   = db.ValueLogBlockZSTD
)
View Source
const (
	ValueLogAutoThroughput = db.ValueLogAutoThroughput
	ValueLogAutoBalanced   = db.ValueLogAutoBalanced
	ValueLogAutoSize       = db.ValueLogAutoSize
)
View Source
const (
	ValueLogDictClassSingle         = db.ValueLogDictClassSingle
	ValueLogDictClassSplitOuterLeaf = db.ValueLogDictClassSplitOuterLeaf
)
View Source
const (
	ValueLogGenerationDefault     = db.ValueLogGenerationDefault
	ValueLogGenerationOff         = db.ValueLogGenerationOff
	ValueLogGenerationHotWarmCold = db.ValueLogGenerationHotWarmCold
)
View Source
const (
	AutotuneUnset      = valuelog.AutotuneUnset
	AutotuneOff        = valuelog.AutotuneOff
	AutotuneMedium     = valuelog.AutotuneMedium
	AutotuneAggressive = valuelog.AutotuneAggressive
)
View Source
const (
	ZSTDLevelFastest = zstd.SpeedFastest
	ZSTDLevelDefault = zstd.SpeedDefault
	ZSTDLevelBetter  = zstd.SpeedBetterCompression
	ZSTDLevelBest    = zstd.SpeedBestCompression
)
View Source
const (
	MaintenancePhaseSteady  = caching.MaintenancePhaseSteady
	MaintenancePhaseRestore = caching.MaintenancePhaseRestore
	MaintenancePhaseCatchUp = caching.MaintenancePhaseCatchUp

	LeafPageReadCacheWriteAdmissionImmediate = db.LeafPageReadCacheWriteAdmissionImmediate
	LeafPageReadCacheWriteAdmissionAdaptive  = db.LeafPageReadCacheWriteAdmissionAdaptive

	FlushAdmissionPolicyExplicit = db.FlushAdmissionPolicyExplicit
	FlushAdmissionPolicyOff      = db.FlushAdmissionPolicyOff
	FlushAdmissionPolicyAuto     = db.FlushAdmissionPolicyAuto
)
View Source
const (
	// UpdateNoop leaves the key unchanged.
	UpdateNoop = db.UpdateNoop
	// UpdateSet replaces the key with Value.
	UpdateSet = db.UpdateSet
	// UpdateDelete removes the key.
	UpdateDelete = db.UpdateDelete
)
View Source
const (
	ValueLogRewriteLocalityDefault = treedbdb.ValueLogRewriteLocalityDefault
	ValueLogRewriteLocalityGrouped = treedbdb.ValueLogRewriteLocalityGrouped
)
View Source
const LegacyEntryRevision = page.LegacyEntryRevision
View Source
const ProfileFlagHelp = "command_wal_durable, command_wal_relaxed, or bench (benchmark-only no-WAL)"

ProfileFlagHelp is the recommended public profile vocabulary for CLI flag help. Legacy profile constants are intentionally omitted here; they are transitional/internal compatibility surfaces, not normal public choices.

Variables

View Source
var (
	// ErrLocked indicates the database directory is already opened by another process.
	ErrLocked = db.ErrLocked
	// ErrMemtableFull indicates the cached memtable has reached its hard cap.
	ErrMemtableFull = caching.ErrMemtableFull
	// ErrBatchDeleteRangeTooLarge indicates the cached batch DeleteRange fallback
	// exceeded its bounded materialization cap before publishing any mutation.
	ErrBatchDeleteRangeTooLarge = caching.ErrBatchDeleteRangeTooLarge

	// ErrClosed indicates the DB handle has been closed.
	ErrClosed = db.ErrClosed
	// ErrRecoveryRequired indicates the DB must be opened read-write for recovery
	// before the requested read-only or offline-maintenance operation can run.
	ErrRecoveryRequired = db.ErrRecoveryRequired
	// ErrCommandWALUnsupported indicates a directory advertises command_wal_v1
	// before this binary has enabled command WAL execution/recovery.
	ErrCommandWALUnsupported = db.ErrCommandWALUnsupported
	// ErrCommandWALRejected indicates a command is intentionally rejected while
	// command_wal_v1 is active.
	ErrCommandWALRejected = db.ErrCommandWALRejected
	// ErrCommandWALSegmentSeqExhausted indicates no new command-WAL segment
	// sequence is available during open.
	ErrCommandWALSegmentSeqExhausted = db.ErrCommandWALSegmentSeqExhausted
	// ErrUnsupportedRequiredFeature indicates format.json requires a storage
	// feature this binary does not understand.
	ErrUnsupportedRequiredFeature = db.ErrUnsupportedRequiredFeature

	// ErrKeyNotFound indicates the key does not exist.
	ErrKeyNotFound = tree.ErrKeyNotFound
)
View Source
var ErrCompactStorageLeafPageLogHandoffCleanup = treedbdb.ErrCompactStorageLeafPageLogHandoffCleanup
View Source
var ErrCompactStorageLeafPageLogOwnerUnsupported = treedbdb.ErrCompactStorageLeafPageLogOwnerUnsupported

Functions

func ApplyProfile

func ApplyProfile(opts *Options, profile Profile)

ApplyProfile applies a profile to opts without overwriting explicit caller overrides.

For numeric/duration fields, "explicit override" means the field is already set to a non-zero value. For background intervals, note TreeDB conventions:

  • `0` means "use default"
  • `<0` means "disable"

For booleans, Go does not provide a way to distinguish “unset” from “explicit false”, so profiles set boolean policy knobs to match the profile. If you want the opposite policy, apply the profile and then override the boolean explicitly.

ApplyProfile panics for unknown profiles so misspelled programmatic profile tokens cannot silently select bare default options.

func DisableValueLogDictCompression added in v0.3.0

func DisableValueLogDictCompression(opts *Options)

DisableValueLogDictCompression disables background dictionary training for value-log frame compression (cached mode).

It does not remove dictdb state on disk; it only prevents training/publishing new dictionaries for future writes.

func EnableValueLogDictCompression added in v0.3.0

func EnableValueLogDictCompression(opts *Options)

EnableValueLogDictCompression enables background dictionary training for value-log frame compression (cached mode).

This is a convenience helper intended to avoid requiring callers to set many low-level knobs. It sets TrainBytes to a safe default if unset and ensures side stores are enabled so dictionaries can be persisted in dictdb/.

Advanced tuning remains available via opts.ValueLog.DictTrain and opts.ValueLog.CompressionAutotune.

func OpenBackend

func OpenBackend(opts Options) (*db.DB, func() error, error)

OpenBackend opens the TreeDB backend directly (no caching layer) while wiring side-store lookups (dictdb/templatedb) when present.

This is intended for maintenance tooling (e.g. treemap vlog-gc) that must avoid cached-layer side effects but still needs value-log decode plumbing.

func OpenBackendWithCachedLeafLog added in v0.6.0

func OpenBackendWithCachedLeafLog(opts Options) (*db.DB, func() error, error)

OpenBackendWithCachedLeafLog opens TreeDB through the cached layer and returns the underlying backend. This is for native-root callers that need backend root APIs while also requiring cached-layer wiring such as the leaf-page value log used by IndexOuterLeavesInValueLog.

func VacuumIndexOffline

func VacuumIndexOffline(opts Options) error

VacuumIndexOffline rewrites `index.db` into a fresh file and swaps it in. This is intended to reclaim space and restore locality after long churn.

It is an offline operation: it acquires the exclusive open lock for opts.Dir.

Types

type AutotuneMode added in v0.3.0

type AutotuneMode = valuelog.AutotuneMode

type AutotuneOptions added in v0.3.0

type AutotuneOptions = valuelog.AutotuneOptions

type Batch

type Batch interface {
	Set(key, value []byte) error
	Delete(key []byte) error
	DeleteRange(start, end []byte) error
	Write() error
	WriteSync() error
	Close() error
	Replay(func(batch.Entry) error) error
	GetByteSize() (int, error)
}

Batch is the public batch contract returned by TreeDB. Both cached and backend implementations satisfy it.

Example
package main

import (
	"fmt"
	"os"

	treedb "github.com/snissn/gomap/TreeDB"
)

func main() {
	dir, err := os.MkdirTemp("", "treedb-batch-example-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	db, err := treedb.Open(treedb.Options{Dir: dir})
	if err != nil {
		panic(err)
	}
	defer db.Close()

	batch := db.NewBatch()
	if batch == nil {
		panic("batch creation failed")
	}

	batch.Set([]byte("key1"), []byte("value1"))
	batch.Set([]byte("key2"), []byte("value2"))
	batch.Delete([]byte("key1"))

	// WriteSync ensures durability.
	if err := batch.WriteSync(); err != nil {
		panic(err)
	}

	val, _ := db.Get([]byte("key2"))
	fmt.Println("key2:", string(val))
	val, _ = db.Get([]byte("key1"))
	fmt.Println("key1:", val)

}
Output:
key2: value2
key1: []

type CompactStorageDebt added in v0.6.0

type CompactStorageDebt = treedbdb.CompactStorageDebt

CompactStorageDebt summarizes remaining work after planning or compaction.

type CompactStorageLeafPageLogHandoffError added in v0.6.0

type CompactStorageLeafPageLogHandoffError = treedbdb.CompactStorageLeafPageLogHandoffError

type CompactStorageLeafPageLogOwnerClass added in v0.6.0

type CompactStorageLeafPageLogOwnerClass = treedbdb.CompactStorageLeafPageLogOwnerClass

type CompactStorageLeafPageLogOwnerClassification added in v0.6.0

type CompactStorageLeafPageLogOwnerClassification = treedbdb.CompactStorageLeafPageLogOwnerClassification

type CompactStorageLeafPageLogOwnerError added in v0.6.0

type CompactStorageLeafPageLogOwnerError = treedbdb.CompactStorageLeafPageLogOwnerError

type CompactStorageLifecycleState added in v0.6.0

type CompactStorageLifecycleState = treedbdb.CompactStorageLifecycleState

type CompactStorageMode added in v0.6.0

type CompactStorageMode = treedbdb.CompactStorageMode

CompactStorageMode selects how aggressively CompactStorage should reclaim storage. Empty/default currently maps to full storage compaction.

type CompactStorageOptions added in v0.6.0

type CompactStorageOptions = treedbdb.CompactStorageOptions

CompactStorageOptions controls full storage compaction across TreeDB storage domains. Prefer this high-level API over manually sequencing value-log rewrite, value-log GC, leaf-generation pack/GC, and index vacuum.

type CompactStorageOwnerStatus added in v0.6.0

type CompactStorageOwnerStatus = treedbdb.CompactStorageOwnerStatus

type CompactStoragePhaseStats added in v0.6.0

type CompactStoragePhaseStats = treedbdb.CompactStoragePhaseStats

CompactStoragePhaseStats records one phase in a full compaction run.

type CompactStorageStats added in v0.6.0

type CompactStorageStats = treedbdb.CompactStorageStats

CompactStorageStats is the single high-level report for TreeDB storage compaction and planning.

type CompactStorageUsage added in v0.6.0

type CompactStorageUsage = treedbdb.CompactStorageUsage

CompactStorageUsage summarizes file usage for a storage domain.

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is the public TreeDB handle (cached mode by default; read-only opens skip caching).

func Open

func Open(opts Options) (*DB, error)

Open opens TreeDB. By default it enables caching (write-back layer).

Example
package main

import (
	"fmt"
	"os"

	treedb "github.com/snissn/gomap/TreeDB"
)

func main() {
	dir, err := os.MkdirTemp("", "treedb-example-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	db, err := treedb.Open(treedb.Options{Dir: dir, ChunkSize: 64 * 1024})
	if err != nil {
		panic(err)
	}
	defer db.Close()

	if err := db.SetSync([]byte("k"), []byte("v")); err != nil {
		panic(err)
	}

	val, err := db.Get([]byte("k"))
	if err != nil {
		panic(err)
	}
	fmt.Println(string(val))

}
Output:
v

func (*DB) AcquireSnapshot

func (db *DB) AcquireSnapshot() Snapshot

AcquireSnapshot returns a new snapshot.

In cached mode, snapshots include writes that are buffered in memtables. In read-only mode (no caching), snapshots are backend-only.

Callers may use GetUnsafe to obtain zero-copy views tied to the snapshot lifetime.

func (*DB) Checkpoint

func (db *DB) Checkpoint() error

Checkpoint forces a durable backend boundary and trims cached-mode WAL segments, so long-running cached-mode workloads do not accumulate unbounded `wal/` growth.

In cached mode this flushes queued memtables with backend sync and resets the WAL to a fresh segment. In backend mode it forces a sync boundary.

Current collection-local pending writes may have their own flush-boundary behavior; see docs/spec/contracts.md for the current collection contract and the PR1 collection WAL target contract. After collection WAL lands, Checkpoint returning nil must also cover pre-cut collection WAL transactions or return/report explicit collection WAL debt.

func (*DB) Close

func (db *DB) Close() error

Close closes the DB.

func (*DB) CompactIndex

func (db *DB) CompactIndex() error

CompactIndex performs an in-place index vacuum (bulk rebuild) on the backend. In cached mode it first drains the caching layer so the backend reflects all buffered writes before rebuilding.

func (*DB) CompactStorage added in v0.6.0

func (db *DB) CompactStorage(ctx context.Context, opts CompactStorageOptions) (CompactStorageStats, error)

CompactStorage runs the recommended full storage compaction sequence: value-log rewrite, value-log GC, leaf-generation pack, leaf-generation GC, index vacuum, final GC settle passes, empty value-log file cleanup, and a final audit.

func (*DB) CompactStorageLeafPageLogOwnerClassification added in v0.6.0

func (db *DB) CompactStorageLeafPageLogOwnerClassification(lifecycle CompactStorageLifecycleState) CompactStorageLeafPageLogOwnerClassification

CompactStorageLeafPageLogOwnerClassification reports the backend leaf-log owner classification currently visible to CompactStorage. The lifecycle argument is a modeled contract category, not runtime proof of quiescence.

func (*DB) CompactStoragePlan added in v0.6.0

func (db *DB) CompactStoragePlan(ctx context.Context, opts CompactStorageOptions) (CompactStorageStats, error)

CompactStoragePlan reports full storage compaction debt without mutating the database. It is safe for read-only opens.

func (*DB) Delete

func (db *DB) Delete(key []byte) error

Delete removes a key without forcing an fsync boundary.

func (*DB) DeleteRange

func (db *DB) DeleteRange(start, end []byte) error

DeleteRange removes all keys in the range [start, end).

This is primarily used by benchmark suites and maintenance tooling. In cached mode, it may use fast paths that avoid per-key tombstones when safe.

func (*DB) DeleteSync

func (db *DB) DeleteSync(key []byte) error

DeleteSync removes a key and forces a durability boundary.

func (*DB) DurabilityMode

func (db *DB) DurabilityMode() string

DurabilityMode reports the effective durability/integrity policy string.

func (*DB) FragmentationReport

func (db *DB) FragmentationReport() (map[string]string, error)

FragmentationReport returns best-effort structural stats about the on-disk user index that help diagnose scan regressions after churn.

Note: In cached mode this reflects the backend state only; queued memtables are not included unless the caller has explicitly drained the cache (e.g. via close+reopen or a maintenance operation that drains).

func (*DB) Get

func (db *DB) Get(key []byte) ([]byte, error)

Get returns the value for a key.

Semantics: Returns a safe copy of the value.

func (*DB) GetAppend

func (db *DB) GetAppend(key, dst []byte) ([]byte, error)

GetAppend appends the value for the key to dst and returns the new slice. It avoids internal allocations by using the provided buffer. If the key is not found, it returns dst and ErrKeyNotFound.

func (*DB) GetMany added in v0.4.0

func (db *DB) GetMany(keys [][]byte) ([][]byte, error)

GetMany returns values for keys.

Semantics: Returns safe copies of values. Missing keys are returned as nil entries with no error.

func (*DB) GetManyParallelPlan added in v0.4.0

func (db *DB) GetManyParallelPlan(keyCount int) (workers int, parallel bool)

GetManyParallelPlan reports how TreeDB would schedule GetMany for the given key count. It can be used by adapters to enforce external worker budgets without duplicating TreeDB scheduler constants.

func (*DB) GetManyView added in v0.6.0

func (db *DB) GetManyView(keys [][]byte, fn GetManyViewFunc) error

GetManyView calls fn once for each key with a read-only value view. The callback may be invoked in any order and may be invoked concurrently for large batches; the index argument identifies the input key. Values are valid only until fn returns and must be copied before retaining. Missing keys are reported with found=false and value=nil. Existing safe-copy GetMany semantics are unchanged.

func (*DB) GetUnsafe

func (db *DB) GetUnsafe(key []byte) ([]byte, error)

GetUnsafe returns the value for a key.

Semantics: Returns a safe copy of the value. For zero-copy views tied to a snapshot lifetime, use AcquireSnapshot().GetUnsafe.

func (*DB) GetVersioned added in v0.6.1

func (db *DB) GetVersioned(key []byte) ([]byte, EntryRevision, error)

GetVersioned returns the value for a key plus TreeDB's native per-entry revision. Missing keys return a nil value and nil error, matching Get.

func (*DB) GetVersionedAppend added in v0.6.1

func (db *DB) GetVersionedAppend(key, dst []byte) ([]byte, EntryRevision, error)

GetVersionedAppend appends the value for key to dst and returns TreeDB's native per-entry revision. Missing/tombstoned keys return dst and ErrKeyNotFound; tombstones preserve their stored revision.

func (*DB) Has

func (db *DB) Has(key []byte) (bool, error)

Has reports whether a key exists in the database.

func (*DB) HasMany added in v0.6.0

func (db *DB) HasMany(keys [][]byte) ([]bool, error)

HasMany reports whether each key exists.

func (*DB) HasPrefixes added in v0.6.0

func (db *DB) HasPrefixes(prefixes [][]byte) ([]bool, error)

HasPrefixes reports whether each prefix has at least one visible key.

func (*DB) Iterator

func (db *DB) Iterator(start, end []byte) (Iterator, error)

Iterator returns a forward iterator over the range [start, end).

func (*DB) LeafGenerationGC added in v0.5.0

func (db *DB) LeafGenerationGC(ctx context.Context, opts LeafGenerationGCOptions) (LeafGenerationGCStats, error)

LeafGenerationGC deletes fully unreachable, unpinned sealed leaf generations.

In cached mode, this first checkpoints so the backend root used for reachability matches the current public DB state.

func (*DB) LeafGenerationPack added in v0.5.0

func (db *DB) LeafGenerationPack(ctx context.Context, opts LeafGenerationPackOptions) (LeafGenerationPackStats, error)

LeafGenerationPack copies live pages from sealed source generations into a fresh leaf-log output so whole-generation GC can later reclaim the old files.

In cached mode, this first checkpoints so the backend roots match the current public DB state.

func (*DB) LeafGenerationPackFromPlan added in v0.5.0

func (db *DB) LeafGenerationPackFromPlan(ctx context.Context, opts LeafGenerationPackFromPlanOptions) (LeafGenerationPackStats, error)

LeafGenerationPackFromPlan computes the current plan, selects a bounded candidate prefix, then packs those sealed generations.

In cached mode, this first checkpoints so the backend roots match the current public DB state.

func (*DB) LeafGenerationPackRunOnce added in v0.5.0

func (db *DB) LeafGenerationPackRunOnce(ctx context.Context, opts LeafGenerationPackFromPlanOptions) (LeafGenerationPackRunOnceStats, error)

LeafGenerationPackRunOnce computes the current plan, applies bounded selection, and either runs one pack pass or reports why it skipped.

In cached mode, this first checkpoints so the backend roots match the current public DB state.

func (*DB) LeafGenerationPlan added in v0.5.0

func (db *DB) LeafGenerationPlan(ctx context.Context, opts LeafGenerationPlanOptions) (LeafGenerationPlan, error)

LeafGenerationPlan scans the current live tree and reports per-generation live/dead bytes for explicit leaf-pack planning.

In cached mode, this first checkpoints so the backend roots match the current public DB state.

func (*DB) MaintenancePhase added in v0.4.0

func (db *DB) MaintenancePhase() MaintenancePhase

func (*DB) NewBatch

func (db *DB) NewBatch() Batch

NewBatch creates a new batch for buffered writes.

func (*DB) NewBatchWithSize

func (db *DB) NewBatchWithSize(size int) Batch

NewBatchWithSize creates a new batch with a best-effort capacity hint.

The size parameter is a best-effort hint, not a strict limit. Small hints are treated like approximate entry reserves. Larger hints may be interpreted as a byte budget and normalized into an internal entry estimate instead. Extremely large hints may also be capped internally.

Callers must not rely on an exact 1:1 mapping between size and the number of entries or bytes that can be written to the batch.

func (*DB) Print

func (db *DB) Print() error

Print dumps best-effort debug output for the underlying backend.

func (*DB) ReverseIterator

func (db *DB) ReverseIterator(start, end []byte) (Iterator, error)

ReverseIterator returns a reverse iterator over the range [start, end).

func (*DB) Set

func (db *DB) Set(key, value []byte) error

Set writes a key/value pair without forcing an fsync boundary.

func (*DB) SetMaintenancePhase added in v0.4.0

func (db *DB) SetMaintenancePhase(phase MaintenancePhase)

func (*DB) SetSync

func (db *DB) SetSync(key, value []byte) error

SetSync writes a key/value pair and forces a durability boundary. With DurabilityWALOnRelaxed or DurabilityWALOffRelaxed enabled, Sync operations are crash-consistent only (no fsync) and may not survive power loss.

func (*DB) Stats

func (db *DB) Stats() map[string]string

Stats returns diagnostic stats for the active backend and cached layer.

func (*DB) Update added in v0.6.0

func (db *DB) Update(key []byte, fn UpdateFunc) error

Update applies fn to the current value for key and writes the returned mutation without forcing an fsync boundary.

Concurrent Update calls for the same key on the same DB handle do not lose each other's changes: if the key changes while fn is running, Update retries with the newer value. Point Set/Delete calls on the same handle participate in the same single-key commit serialization but remain unconditional writes. Because fn may be retried, it should avoid externally visible side effects.

func (*DB) UpdateSync added in v0.6.0

func (db *DB) UpdateSync(key []byte, fn UpdateFunc) error

UpdateSync applies fn to the current value for key and writes the returned mutation with a sync durability boundary. With DurabilityWALOnRelaxed or DurabilityWALOffRelaxed enabled, Sync operations are crash-consistent only (no fsync) and may not survive power loss.

Concurrent UpdateSync/Update calls for the same key on the same DB handle do not lose each other's changes. Because fn may be retried, it should avoid externally visible side effects.

func (*DB) VacuumIndexOnline

func (db *DB) VacuumIndexOnline(ctx context.Context) error

VacuumIndexOnline rebuilds the user index into a new file and swaps it in with a short writer pause. Disk space from the old index is reclaimed once any old snapshots/iterators drain.

func (*DB) ValueLogGC added in v0.3.0

func (db *DB) ValueLogGC(ctx context.Context, opts ValueLogGCOptions) (ValueLogGCStats, error)

ValueLogGC deletes fully-unreferenced value-log segments.

In cached mode, strict mode checkpoints first. Online mode avoids a global checkpoint and protects retained value-log segments; if no protection data is available, it fails closed to dry-run.

func (*DB) ValueLogRewriteOnline added in v0.4.0

func (db *DB) ValueLogRewriteOnline(ctx context.Context, opts ValueLogRewriteOnlineOptions) (ValueLogRewriteStats, error)

ValueLogRewriteOnline rewrites pointer-backed values in bounded commit batches and atomically swaps keys to rewritten pointers.

In cached mode this method checkpoints first to establish a stable backend baseline before running online rewrite against the backend DB.

type DictLookup added in v0.3.0

type DictLookup = valuelog.DictLookup

type DurabilityMode added in v0.3.0

type DurabilityMode = db.DurabilityMode

type EntryRevision added in v0.6.1

type EntryRevision = page.EntryRevision

EntryRevision is TreeDB's native per-entry revision metadata. Revision zero is reserved for legacy entries that do not carry revision metadata.

type FlushAdmissionDecision added in v0.6.0

type FlushAdmissionDecision = db.FlushAdmissionDecision

type FlushAdmissionPolicy added in v0.6.0

type FlushAdmissionPolicy = db.FlushAdmissionPolicy

type GetManyViewFunc added in v0.6.0

type GetManyViewFunc = db.GetManyViewFunc

GetManyViewFunc receives one GetManyView result. DB-level callbacks may be invoked in any order and may be invoked concurrently for large batches; callers that mutate shared state must synchronize it. The value slice is a read-only view that is valid only until the callback returns (or until a snapshot/view boundary documented by the caller closes, whichever comes first). Copy value before retaining it. Missing/tombstoned keys are reported with found=false and value=nil.

type IntegrityMode added in v0.3.0

type IntegrityMode = db.IntegrityMode

type Iterator

type Iterator interface {
	Valid() bool
	Next()
	Key() []byte
	Value() []byte
	KeyCopy(dst []byte) []byte
	ValueCopy(dst []byte) []byte
	Close() error
	Error() error
}

Iterator is the public iterator contract returned by TreeDB.

Semantics (performance-first; callers must treat returned slices as read-only):

  • Key() and Value() return views valid only until the next Next()/Close() on the same iterator.
  • Do not retain or mutate Key()/Value() views across iterator movement.
  • KeyCopy/ValueCopy return caller-owned stable bytes, reusing dst capacity when possible.
Example
package main

import (
	"fmt"
	"os"

	treedb "github.com/snissn/gomap/TreeDB"
)

func main() {
	dir, err := os.MkdirTemp("", "treedb-iter-example-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	db, err := treedb.Open(treedb.Options{Dir: dir})
	if err != nil {
		panic(err)
	}
	defer db.Close()

	// Insert keys in random order
	db.SetSync([]byte("b"), []byte("2"))
	db.SetSync([]byte("a"), []byte("1"))
	db.SetSync([]byte("c"), []byte("3"))

	// Iterate over all keys
	it, err := db.Iterator(nil, nil)
	if err != nil {
		panic(err)
	}
	defer it.Close()

	for ; it.Valid(); it.Next() {
		fmt.Printf("%s: %s\n", it.Key(), it.Value())
	}

}
Output:
a: 1
b: 2
c: 3

type LeafGenerationGCOptions added in v0.5.0

type LeafGenerationGCOptions struct {
	DryRun                 bool
	ProtectedRootIDs       []uint64
	ProtectedSystemRootIDs []uint64
}

LeafGenerationGCOptions controls whole-generation leaf-log garbage collection.

type LeafGenerationGCStats added in v0.5.0

type LeafGenerationGCStats struct {
	GenerationsTotal    int
	GenerationsWritable int
	GenerationsLive     int
	GenerationsRetiring int
	GenerationsEligible int
	GenerationsDeleted  int
	FilesDeleted        int
}

LeafGenerationGCStats summarizes whole-generation leaf-log GC work.

type LeafGenerationPackFromPlanOptions added in v0.5.0

type LeafGenerationPackFromPlanOptions = treedbdb.LeafGenerationPackFromPlanOptions

LeafGenerationPackFromPlanOptions combines planner thresholds, bounded selection limits, and pack execution settings for the manual from-plan path.

type LeafGenerationPackOptions added in v0.5.0

type LeafGenerationPackOptions = treedbdb.LeafGenerationPackOptions

LeafGenerationPackOptions selects sealed source generations for explicit leaf-page compaction.

type LeafGenerationPackRunOnceStats added in v0.5.0

type LeafGenerationPackRunOnceStats = treedbdb.LeafGenerationPackRunOnceStats

LeafGenerationPackRunOnceStats describes one bounded admission/evaluation pass for leaf-generation packing.

type LeafGenerationPackSelectOptions added in v0.5.0

type LeafGenerationPackSelectOptions = treedbdb.LeafGenerationPackSelectOptions

LeafGenerationPackSelectOptions bounds a selected prefix of plan candidates.

type LeafGenerationPackSelection added in v0.5.0

type LeafGenerationPackSelection = treedbdb.LeafGenerationPackSelection

LeafGenerationPackSelection summarizes a bounded prefix of pack candidates.

func SelectLeafGenerationPackCandidates added in v0.5.0

func SelectLeafGenerationPackCandidates(plan LeafGenerationPlan, opts LeafGenerationPackSelectOptions) (LeafGenerationPackSelection, error)

SelectLeafGenerationPackCandidates selects a bounded prefix from an eligible leaf-generation plan. This is a pure helper for operator tooling and future bounded online maintenance runners.

type LeafGenerationPackStats added in v0.5.0

type LeafGenerationPackStats = treedbdb.LeafGenerationPackStats

LeafGenerationPackStats summarizes explicit leaf-generation pack work.

type LeafGenerationPlan added in v0.5.0

type LeafGenerationPlan = treedbdb.LeafGenerationPlan

LeafGenerationPlan summarizes explicit leaf-pack candidate generations.

type LeafGenerationPlanGeneration added in v0.5.0

type LeafGenerationPlanGeneration = treedbdb.LeafGenerationPlanGeneration

LeafGenerationPlanGeneration describes one manifest generation's current live and reclaim geometry.

type LeafGenerationPlanOptions added in v0.5.0

type LeafGenerationPlanOptions = treedbdb.LeafGenerationPlanOptions

LeafGenerationPlanOptions controls leaf-generation sparse-pack planning.

type LeafPageReadCacheWriteAdmissionPolicy added in v0.6.0

type LeafPageReadCacheWriteAdmissionPolicy = db.LeafPageReadCacheWriteAdmissionPolicy

type MaintenancePhase added in v0.4.0

type MaintenancePhase = caching.MaintenancePhase

type Options

type Options = db.Options

Options configures TreeDB. It is re-exported from TreeDB/db for convenience.

func OptionsFor

func OptionsFor(profile Profile, dir string) Options

OptionsFor returns a copy of Options pre-filled for the given Profile.

The returned Options still follow TreeDB's normal defaulting rules for fields left as zero values unless the selected profile intentionally owns that knob (e.g. fast profiles set ChunkSize; KeepRecent, allocator policy, and backpressure thresholds still use normal defaults).

OptionsFor panics for unknown profiles. Parse public CLI/env strings with ParsePublicProfile before calling OptionsFor.

type Profile

type Profile string

Profile is a documented, high-level preset for TreeDB Options.

Why profiles exist ------------------ TreeDB exposes many low-level knobs because different workloads want different trade-offs (durability vs throughput, steady-state vs benchmark determinism, background maintenance vs predictable latency).

In practice, most public callers should choose one of these explicit bundles:

  • "Command WAL durable": command WAL plus durable sync/integrity.
  • "Command WAL relaxed": command WAL plus relaxed sync/integrity.
  • "Bench": no-WAL benchmark ceiling only.

Additional legacy/no-WAL constants remain temporarily available for compatibility and low-level tests while the public profile surface is being narrowed. New server, collection, and Mongo gateway entry points should not advertise those names as normal choices.

Profiles are intentionally conservative:

  • They set the *meaningful policy knobs* (durability/integrity/background), while leaving the many throughput/capacity tuning knobs at their usual defaults.
  • They do not require TreeDB internals to infer "intent" from combinations of flags. You pick the intent explicitly.

How to use ----------

  1. New DB (recommended): opts := treedb.OptionsFor(treedb.ProfileCommandWALDurable, "/path/to/db") opts.FlushThreshold = 128 << 20 // optional tuning db, err := treedb.Open(opts)

  2. Existing Options (merge without clobbering explicit overrides): opts := treedb.Options{Dir: "/path/to/db"} treedb.ApplyProfile(&opts, treedb.ProfileBench) opts.FlushThreshold = 64 << 20 // explicit overrides always win db, err := treedb.Open(opts)

Note: Profiles are a convenience API. TreeDB still honors the established "0 uses a default; <0 disables" convention for background knobs, and callers can always override any field directly after applying a profile.

const (
	// ProfileCommandWALDurable is the explicit command-WAL production profile for
	// callers that want command-WAL recovery, durable fsync boundaries, corruption
	// detection, and the fast collection/index layout bundle.
	ProfileCommandWALDurable Profile = "command_wal_durable"

	// ProfileCommandWALRelaxed is the explicit command-WAL relaxed profile for
	// write-heavy benchmark and ingest workloads. It enables command WAL but uses
	// relaxed sync and read-integrity semantics.
	ProfileCommandWALRelaxed Profile = "command_wal_relaxed"

	// ProfileLegacyWALDurable is the explicit name for the pre-command-WAL durable
	// profile. It keeps WAL and checksums enabled, but does not enable CommandWAL.
	ProfileLegacyWALDurable Profile = "legacy_wal_durable"

	// ProfileLegacyWALRelaxedFast is the explicit name for the pre-command-WAL
	// relaxed fast profile. It is equivalent to ProfileWALOnFast.
	ProfileLegacyWALRelaxedFast Profile = "legacy_wal_relaxed_fast"

	// ProfileNoWALFast is the explicit name for the no-WAL fast profile. It is
	// equivalent to ProfileFast.
	ProfileNoWALFast Profile = "no_wal_fast"

	// ProfileDurable is the legacy-compatible short name for
	// ProfileLegacyWALDurable.
	//
	// Prefer ProfileCommandWALDurable for new command-WAL durability decisions, or
	// ProfileLegacyWALDurable when the old/raw WAL path is intentional.
	//
	// This profile keeps WAL and checksums enabled and leaves background
	// maintenance at its default settings, but it does not enable CommandWAL.
	//
	// Deprecated: use ProfileCommandWALDurable or ProfileLegacyWALDurable to make
	// the WAL path explicit.
	ProfileDurable Profile = "durable"

	// ProfileFast prioritizes throughput by relaxing durability/integrity knobs.
	//
	// This profile is appropriate when:
	//   - you are running on top of an external durability boundary (e.g. you
	//     snapshot at higher layers), or
	//   - you are exploring performance limits, and crashes/corruption detection
	//     are acceptable trade-offs.
	//
	// Collection writes under this profile use DurabilityWALOffRelaxed. A
	// successful collection write is not a durable-at-ack promise; use Flush,
	// FlushAll, Checkpoint, or Close for a persistence boundary.
	//
	// It also pins the current run_celestia-style value-log compression policy:
	// auto compression, balanced auto policy, snappy block fallback, and medium
	// autotune.
	//
	// Background maintenance is left enabled by default; it is generally helpful
	// for keeping the index compact and read-friendly.
	//
	// Deprecated: use ProfileNoWALFast when the no-WAL path is intentional.
	ProfileFast Profile = "fast"

	// ProfileWALOnFast is a legacy-compatible short name for
	// ProfileLegacyWALRelaxedFast. It is a "WAL on + relaxed durability" profile
	// intended for write-heavy benchmarks and ingest workloads.
	//
	// It keeps the legacy/raw WAL path enabled but disables fsync and value-log
	// read checksums.
	//
	// It also pins the same value-log compression policy as ProfileNoWALFast.
	//
	// Deprecated: use ProfileLegacyWALRelaxedFast when the legacy/raw WAL path is
	// intentional, or ProfileCommandWALRelaxed for the command-WAL relaxed path.
	ProfileWALOnFast Profile = "wal_on_fast"

	// ProfileBench is a "fast + deterministic" profile intended specifically for
	// benchmarking.
	//
	// It disables background workers that can inject heavy work mid-run (e.g.
	// background index vacuum). This makes comparisons more stable across runs.
	//
	// IMPORTANT: This is not a recommended production profile.
	ProfileBench Profile = "bench"
)

func NormalizeProfile added in v0.6.0

func NormalizeProfile(profile Profile) (Profile, bool)

NormalizeProfile normalizes supported profile names and aliases to their public Profile constants.

func NormalizePublicProfile added in v0.6.0

func NormalizePublicProfile(profile Profile) (Profile, bool)

NormalizePublicProfile normalizes supported public profile names and aliases.

func ParseProfile added in v0.6.0

func ParseProfile(raw string, fallback Profile) (Profile, bool)

ParseProfile parses a profile name using TreeDB's standard profile vocabulary. Empty input returns fallback. The bool reports whether a known name or empty fallback was accepted.

func ParsePublicProfile added in v0.6.0

func ParsePublicProfile(raw string, fallback Profile) (Profile, bool)

ParsePublicProfile parses the public server/profile vocabulary. Empty input returns fallback only when fallback is also a public profile. Deprecated compatibility names such as fast, wal_on_fast, durable, legacy_wal_* and no_wal_fast are intentionally rejected here.

type Snapshot

type Snapshot interface {
	Pager() *pager.Pager
	State() *backenddb.DBState

	Get(key []byte) ([]byte, error)
	GetAppend(key, dst []byte) ([]byte, error)
	GetVersioned(key []byte) ([]byte, EntryRevision, error)
	GetVersionedAppend(key, dst []byte) ([]byte, EntryRevision, error)
	GetManyView(keys [][]byte, fn GetManyViewFunc) error
	GetUnsafe(key []byte) ([]byte, error)
	Has(key []byte) (bool, error)
	HasMany(keys [][]byte) ([]bool, error)
	HasPrefixes(prefixes [][]byte) ([]bool, error)

	GetEntry(key []byte) (node.LeafEntry, error)
	GetEntryExact(key []byte) (node.LeafEntry, error)

	Close() error
}

Snapshot is a consistent point-in-time view of the database.

In cached mode, snapshots include writes that are buffered in memtables.

TreeDB is pre-alpha; this interface may change without notice.

type TrainConfig added in v0.3.0

type TrainConfig = compression.TrainConfig

Dictionary training/lookup helpers for value-log compression.

type UpdateFunc added in v0.6.0

type UpdateFunc = db.UpdateFunc

UpdateFunc transforms the current value for a key into a mutation. The old value is nil when the key is absent and is a safe copy when present. The callback may be retried if the key changes before the mutation commits.

type UpdateOp added in v0.6.0

type UpdateOp = db.UpdateOp

UpdateOp describes the write produced by an Update callback.

type UpdateResult added in v0.6.0

type UpdateResult = db.UpdateResult

UpdateResult is returned by an Update callback.

func DeleteUpdate added in v0.6.0

func DeleteUpdate() UpdateResult

DeleteUpdate returns an Update result that removes the key.

func NoopUpdate added in v0.6.0

func NoopUpdate() UpdateResult

NoopUpdate returns an Update result that leaves the key unchanged.

func SetUpdate added in v0.6.0

func SetUpdate(value []byte) UpdateResult

SetUpdate returns an Update result that replaces the key with value.

type ValueLogAutoPolicy added in v0.3.0

type ValueLogAutoPolicy = db.ValueLogAutoPolicy

type ValueLogBlockCodec added in v0.3.0

type ValueLogBlockCodec = db.ValueLogBlockCodec

type ValueLogCompressionMode added in v0.3.0

type ValueLogCompressionMode = db.ValueLogCompressionMode

type ValueLogDictClassMode added in v0.4.0

type ValueLogDictClassMode = db.ValueLogDictClassMode

type ValueLogDomainThreshold added in v0.4.0

type ValueLogDomainThreshold = db.ValueLogDomainThreshold

type ValueLogGCMode added in v0.4.0

type ValueLogGCMode string

ValueLogGCMode controls cached-mode coordination for value-log GC.

Pre-alpha note: "online" currently uses retained-path protection and may fail closed to dry-run when protection data is unavailable.

const (
	ValueLogGCModeStrict ValueLogGCMode = "strict"
	ValueLogGCModeOnline ValueLogGCMode = "online"
)

type ValueLogGCOptions added in v0.3.0

type ValueLogGCOptions struct {
	DryRun bool
	// Mode controls cached-mode behavior. Empty defaults to "strict".
	Mode ValueLogGCMode
}

ValueLogGCOptions controls value-log garbage collection.

type ValueLogGCStats added in v0.3.0

type ValueLogGCStats struct {
	SegmentsTotal      int
	SegmentsReferenced int
	SegmentsActive     int
	SegmentsProtected  int
	SegmentsEligible   int
	SegmentsDeleted    int
	BytesTotal         int64
	BytesReferenced    int64
	BytesActive        int64
	BytesProtected     int64
	BytesEligible      int64
	BytesDeleted       int64
	// FailClosedToDryRun reports that online mode intentionally converted the
	// operation to a dry-run for safety.
	FailClosedToDryRun bool
}

ValueLogGCStats summarizes value-log GC work.

type ValueLogGenerationConfig added in v0.4.0

type ValueLogGenerationConfig = db.ValueLogGenerationConfig

type ValueLogGenerationPolicy added in v0.4.0

type ValueLogGenerationPolicy = db.ValueLogGenerationPolicy

type ValueLogOptions added in v0.3.0

type ValueLogOptions = db.ValueLogOptions

type ValueLogRewriteLocalityPolicy added in v0.4.0

type ValueLogRewriteLocalityPolicy = treedbdb.ValueLogRewriteLocalityPolicy

ValueLogRewriteLocalityPolicy controls pointer rewrite ordering.

type ValueLogRewriteOnlineOptions added in v0.4.0

type ValueLogRewriteOnlineOptions = treedbdb.ValueLogRewriteOnlineOptions

ValueLogRewriteOnlineOptions controls online rewrite batching behavior.

type ValueLogRewriteStats added in v0.3.0

type ValueLogRewriteStats = treedbdb.ValueLogRewriteStats

ValueLogRewriteStats summarizes value-log rewrite compaction results.

func ValueLogRewriteOffline added in v0.3.0

func ValueLogRewriteOffline(opts Options) (ValueLogRewriteStats, error)

ValueLogRewriteOffline rewrites value-log pointers into new segments and swaps index.db to reference the new log. This is an offline operation that requires an exclusive lock and a clean commitlog.

type ZSTDEncoderLevel added in v0.3.0

type ZSTDEncoderLevel = zstd.EncoderLevel

Zstd encoder levels (for dict-compressed value-log frames).

Directories

Path Synopsis
cmd
db_histogram command
debug_open command
stress command
template_lab command
treemap command
unified_bench command
verify command
wal_classify command
Package documentservice exposes TreeDB's pre-alpha Haystack-style document service contract.
Package documentservice exposes TreeDB's pre-alpha Haystack-style document service contract.
integration
gethethdb module
internal
brq
Package brq implements the TreeDB brq_1bit v1 oracle.
Package brq implements the TreeDB brq_1bit v1 oracle.
commandwalapply
Package commandwalapply exposes the narrow internal boundary between future R3a deterministic-entry lowering and TreeDB's local command WAL.
Package commandwalapply exposes the narrow internal boundary between future R3a deterministic-entry lowering and TreeDB's local command WAL.
crc
Package crc is TreeDB's audited CRC-32 facade.
Package crc is TreeDB's audited CRC-32 facade.
mappedresource
Package mappedresource defines TreeDB's shared vocabulary for immutable file-backed resource views.
Package mappedresource defines TreeDB's shared vocabulary for immutable file-backed resource views.
quantizedasset
Package quantizedasset validates quantized vector-index asset schemas and prepares allocation-conscious ordinal readers over typed-column part images.
Package quantizedasset validates quantized vector-index asset schemas and prepares allocation-conscious ordinal readers over typed-column part images.
rabitq
Package rabitq defines TreeDB's clean-room rabitq_1bit v1 reference codec.
Package rabitq defines TreeDB's clean-room rabitq_1bit v1 reference codec.
raftapply
Package raftapply applies committed R3a deterministic entry bytes to a local TreeDB replica.
Package raftapply applies committed R3a deterministic entry bytes to a local TreeDB replica.
raftcluster
Package raftcluster defines the single-group Raft cluster boundary for TreeDB.
Package raftcluster defines the single-group Raft cluster boundary for TreeDB.
raftentry
Package raftentry defines the R3a v1 deterministic command-entry contract.
Package raftentry defines the R3a v1 deterministic command-entry contract.
raftfsm
Package raftfsm wires the single-group R3a committed-entry apply loop.
Package raftfsm wires the single-group R3a committed-entry apply loop.
raftharness
Package raftharness provides a deterministic in-process harness for the TreeDB single-group Raft apply substrate.
Package raftharness provides a deterministic in-process harness for the TreeDB single-group Raft apply substrate.
raftplacement
Package raftplacement validates the first TreeDB multi-group placement catalog shapes and resolves explicit route requests to Raft group decisions or token partitions through explicit helper APIs.
Package raftplacement validates the first TreeDB multi-group placement catalog shapes and resolves explicit route requests to Raft group decisions or token partitions through explicit helper APIs.
typedcolumn
Package typedcolumn contains the transplanted experiments/colgranule typed-column data plane for TreeDB.
Package typedcolumn contains the transplanted experiments/colgranule typed-column data plane for TreeDB.
typeddecode
Package typeddecode contains shared typed-column fast-decode planning and validated direct-view helpers.
Package typeddecode contains shared typed-column fast-decode planning and validated direct-view helpers.
typedkernel
Package typedkernel contains internal typed-column aggregate and predicate kernel substrate.
Package typedkernel contains internal typed-column aggregate and predicate kernel substrate.
vectorops
Package vectorops contains allocation-free vector kernels shared by TreeDB packages.
Package vectorops contains allocation-free vector kernels shared by TreeDB packages.
fastclient
Package fastclient provides a narrow, low-overhead client for bulk inserts into the TreeDB Mongo gateway.
Package fastclient provides a narrow, low-overhead client for bulk inserts into the TreeDB Mongo gateway.
Package nativewire implements TreeDB's native client/server wire transport.
Package nativewire implements TreeDB's native client/server wire transport.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL