caching

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: 48 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBatchClosed = fmt.Errorf("batch has been written or closed")
View Source
var ErrBatchDeleteRangeTooLarge = errors.New("cachingdb: batch DeleteRange materialization limit exceeded")
View Source
var ErrKeyEmpty = fmt.Errorf("key cannot be empty")
View Source
var ErrMemtableFull = fmt.Errorf("memtable full")
View Source
var ErrSnapshotValueLogReaderUnavailable = errors.New("caching snapshot: value-log reader unavailable")

ErrSnapshotValueLogReaderUnavailable reports that a snapshot value-log pointer read could not proceed because the snapshot has no value-log reader.

View Source
var ErrUnsafeOptions = fmt.Errorf("unsafe options require AllowUnsafe")
View Source
var ErrValueNil = fmt.Errorf("value cannot be nil")

Functions

func SetIteratorDebug

func SetIteratorDebug(enabled bool)

SetIteratorDebug toggles attaching debug metadata to iterators returned by CachingDB.Iterator. It is intended for benchmarking/diagnostics.

Types

type BackendDB

type BackendDB interface {
	Get(key []byte) ([]byte, error)
	GetUnsafe(key []byte) ([]byte, error)
	GetAppend(key, dst []byte) ([]byte, error)
	Has(key []byte) (bool, error)
	Iterator(start, end []byte) (iterator.UnsafeIterator, error)
	ReverseIterator(start, end []byte) (iterator.UnsafeIterator, error)
	NewBatch() batch.Interface
	Close() error
	Print() error
	Stats() map[string]string
}

BackendDB defines the subset of treedb.DB needed by CachingDB.

type Batch

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

func (*Batch) Close

func (b *Batch) Close() error

func (*Batch) Delete

func (b *Batch) Delete(key []byte) error

func (*Batch) DeleteRange added in v0.6.0

func (b *Batch) DeleteRange(start, end []byte) error

func (*Batch) DeleteView

func (b *Batch) DeleteView(key []byte) error

DeleteView records a Delete without copying key bytes. Callers must treat key as immutable until the batch is written or closed.

func (*Batch) DeleteViewValidated added in v0.6.0

func (b *Batch) DeleteViewValidated(key []byte) error

DeleteViewValidated is DeleteView for callers that already performed public input validation. The caller must keep key immutable until Write/Close.

func (*Batch) DeleteViewValidatedWithRevision added in v0.6.1

func (b *Batch) DeleteViewValidatedWithRevision(key []byte, revision page.EntryRevision) error

func (*Batch) DeleteViewWithRevision added in v0.6.1

func (b *Batch) DeleteViewWithRevision(key []byte, revision page.EntryRevision) error

func (*Batch) DeleteWithRevision added in v0.6.1

func (b *Batch) DeleteWithRevision(key []byte, revision page.EntryRevision) error

func (*Batch) DisableStreamingBypass added in v0.6.0

func (b *Batch) DisableStreamingBypass()

DisableStreamingBypass keeps subsequent writes on the cached memtable path. Command-WAL public batches use this so the command frame can be appended after cached preflight and before the batch becomes visible.

func (*Batch) GetByteSize

func (b *Batch) GetByteSize() (int, error)

func (*Batch) OrderedEntries added in v0.6.1

func (b *Batch) OrderedEntries() []batch.Entry

OrderedEntries returns the submission-order operation stream. The returned slice aliases batch-owned storage and must be treated as read-only.

func (*Batch) PointRevisionStats added in v0.6.1

func (b *Batch) PointRevisionStats() (page.EntryRevision, bool)

PointRevisionStats returns the highest point-entry revision and whether any point entry is still legacy-versioned.

func (*Batch) Replay

func (b *Batch) Replay(fn func(batch.Entry) error) error

func (*Batch) Reset

func (b *Batch) Reset()

Reset clears the batch for reuse without closing it.

This intentionally keeps internal buffers to avoid per-batch allocations in callers that frequently reset (e.g. geth benchmarks).

func (*Batch) Set

func (b *Batch) Set(key, value []byte) error

func (*Batch) SetOps

func (b *Batch) SetOps(ops []batch.Entry) error

func (*Batch) SetView

func (b *Batch) SetView(key, value []byte) error

SetView records a Put without copying key/value bytes. Callers must treat key/value as immutable until the batch is written or closed.

func (*Batch) SetViewValidated added in v0.6.0

func (b *Batch) SetViewValidated(key, value []byte) error

SetViewValidated is SetView for callers that already performed public input validation. The caller must still keep key/value immutable until Write/Close.

func (*Batch) SetViewValidatedWithRevision added in v0.6.1

func (b *Batch) SetViewValidatedWithRevision(key, value []byte, revision page.EntryRevision) error

func (*Batch) SetViewWithRevision added in v0.6.1

func (b *Batch) SetViewWithRevision(key, value []byte, revision page.EntryRevision) error

func (*Batch) SetWithRevision added in v0.6.1

func (b *Batch) SetWithRevision(key, value []byte, revision page.EntryRevision) error

func (*Batch) Write

func (b *Batch) Write() error

func (*Batch) WriteAfterCommandWALAppend added in v0.6.0

func (b *Batch) WriteAfterCommandWALAppend(sync bool, appendCommand func() error) error

WriteAfterCommandWALAppend writes a cached batch by running appendCommand after cached write preflight succeeds and before the mutation becomes visible in the mutable table. This is intentionally limited to command-WAL public mode, where the cached redo log is disabled.

func (*Batch) WriteSync

func (b *Batch) WriteSync() error

type DB

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

func Open

func Open(dir string, backend BackendDB, opts Options) (*DB, error)

func (*DB) AcquireBackendSnapshotFastPath added in v0.6.0

func (db *DB) AcquireBackendSnapshotFastPath() *backenddb.Snapshot

AcquireBackendSnapshotFastPath returns a backend snapshot when the cached layer has no mutable, queued, root-domain, or pending value-log state that the cached Snapshot wrapper must preserve. The returned snapshot has the normal backend snapshot lifetime and must be closed by the caller.

func (*DB) AcquireSnapshot added in v0.4.0

func (db *DB) AcquireSnapshot() *Snapshot

AcquireSnapshot returns a cached snapshot that includes queued memtable writes.

func (*DB) BeginValueLogMaintenanceFence added in v0.6.0

func (db *DB) BeginValueLogMaintenanceFence(ctx context.Context) (func(), error)

BeginValueLogMaintenanceFence blocks cached writers and rotates current value-log writers so backend maintenance can reclaim formerly active unreachable segments without racing mutable cached state.

func (*DB) Checkpoint

func (db *DB) Checkpoint() error

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

It blocks writers while it:

  • rotates the current mutable memtable (if non-empty),
  • rotates to a fresh WAL segment,
  • flushes all queued memtables with backend sync,
  • forces a backend sync boundary (even if the queue is empty),
  • removes all older WAL segments (keeping only the currently-open one).

func (*DB) Close

func (db *DB) Close() error

func (*DB) CommandWALPayloadShouldBypassForValue added in v0.6.1

func (db *DB) CommandWALPayloadShouldBypassForValue(key, value []byte) bool

CommandWALPayloadShouldBypassForValue reports whether the public command-WAL wrapper should let cached write preflight promote this value to a value-log pointer before command-frame encoding.

func (*DB) CompactionAssist

func (db *DB) CompactionAssist()

CompactionAssist performs bounded flush work when backpressure triggers. It is intended to be called by background maintenance (e.g. index compaction) so that flush debt does not grow unbounded in the absence of foreground writes.

func (*DB) Delete

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

func (*DB) DeleteAfterCommandWALAppend added in v0.6.0

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

DeleteAfterCommandWALAppend applies a point Delete after appendCommand succeeds under the same per-key serialization lock as Delete.

func (*DB) DeleteAfterCommandWALAppendWithRevision added in v0.6.1

func (db *DB) DeleteAfterCommandWALAppendWithRevision(key []byte, appendCommand func(page.EntryRevision) error) error

DeleteAfterCommandWALAppendWithRevision applies a point Delete after appendCommand succeeds and passes the assigned tombstone revision to the command-WAL callback before the mutation becomes visible.

func (*DB) DeleteRange

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

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

When WAL is disabled and the backend is empty, a full-range delete can be satisfied by clearing the in-memory layers without enumerating keys.

func (*DB) DeleteRangeAfterCommandWALAppend added in v0.6.0

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

DeleteRangeAfterCommandWALAppend applies a range delete after appendCommand succeeds. appendCommand runs after ordinary cached-mode preflight and before the range delete becomes visible in memory or durable backend roots. This is for public command-WAL mode, where command WAL durability replaces the cached redo log.

appendCommand runs while delete serialization is active. It must not re-enter the same caching DB or call methods that need the cache writer lock. It should return quickly and handle any synchronization with other components itself; long-blocking callbacks stall cached writers.

func (*DB) DeleteSync

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

func (*DB) Drain

func (db *DB) Drain() error

Drain flushes all currently buffered writes (mutable + queued memtables) to the backend. It is intended for maintenance operations that require a fully materialized backend state (e.g. index vacuum).

Drain does not provide mutual exclusion against concurrent writers; callers should ensure no writes occur concurrently if they require a fully drained state.

func (*DB) Get

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

Get 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. 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 safe copies of values for keys.

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 a safe upper-bound scheduling plan for GetMany.

When cache hit-rates are high, backend calls may involve fewer keys than the provided key count. This method intentionally reports based on the input upper-bound to stay conservative for concurrency budgeting at callers.

func (*DB) GetManyView added in v0.6.0

func (db *DB) GetManyView(keys [][]byte, fn tree.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 when backend fallback reads are parallelized. The value is valid only until fn returns; callers must copy values they retain. Missing keys are reported with found=false and value=nil.

func (*DB) GetUnsafe

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

GetUnsafe returns a safe copy of the value.

func (*DB) GetVersioned added in v0.6.1

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

func (*DB) GetVersionedAppend added in v0.6.1

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

func (*DB) Has

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

func (*DB) HasMany added in v0.6.0

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

func (*DB) HasPrefixes added in v0.6.0

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

func (*DB) Iterator

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

Iterator implements DB.Iterator

func (*DB) MaintenancePhase added in v0.4.0

func (db *DB) MaintenancePhase() MaintenancePhase

func (*DB) NewBatch

func (db *DB) NewBatch() *Batch

func (*DB) NewBatchWithSize

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

func (*DB) Print

func (db *DB) Print() error

func (*DB) ProtectedLeafGenerationRootIDPair added in v0.6.0

func (db *DB) ProtectedLeafGenerationRootIDPair() ([]uint64, []uint64)

func (*DB) ProtectedLeafGenerationRootIDs added in v0.6.0

func (db *DB) ProtectedLeafGenerationRootIDs() []uint64

func (*DB) ProtectedLeafGenerationSystemRootIDs added in v0.6.0

func (db *DB) ProtectedLeafGenerationSystemRootIDs() []uint64

func (*DB) PruneRetainedValueLogsForMaintenance added in v0.6.0

func (db *DB) PruneRetainedValueLogsForMaintenance()

PruneRetainedValueLogsForMaintenance runs a synchronous retained value-log prune before full backend maintenance computes reclaim candidates.

func (*DB) QueueBacklogBytes

func (db *DB) QueueBacklogBytes() int64

QueueBacklogBytes returns the current queued memtable backlog in bytes.

func (*DB) ReadValueLogRecord added in v0.4.0

func (db *DB) ReadValueLogRecord(ptr page.ValuePtr) ([]byte, error)

ReadValueLogRecord reads a raw value-log record for diagnostics and tooling.

func (*DB) ReclaimObservedValueLogSources added in v0.6.0

func (db *DB) ReclaimObservedValueLogSources(ctx context.Context, ids []uint32) (backenddb.ValueLogGCStats, error)

ReclaimObservedValueLogSources rotates cached writers past rewrite-selected source segments and reclaims storage classes that backend rewrite already proved obsolete.

func (*DB) ReconcileAfterBackendMaintenance added in v0.6.0

func (db *DB) ReconcileAfterBackendMaintenance() error

ReconcileAfterBackendMaintenance refreshes cached-mode value-log readers and advances split value-log writers past segments created directly by backend maintenance.

func (*DB) ReserveValueLogRIDs added in v0.4.0

func (db *DB) ReserveValueLogRIDs(count int) (uint64, error)

ReserveValueLogRIDs reserves a contiguous RID range from the cached-mode shared allocator and returns the starting RID.

func (*DB) ReverseIterator

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

func (*DB) Set

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

func (*DB) SetAfterCommandWALAppend added in v0.6.0

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

SetAfterCommandWALAppend applies a point Set after appendCommand succeeds. appendCommand runs while holding the same per-key serialization lock as Set, after cached-mode preflight has ruled out ordinary rejection paths and before the mutation becomes visible in the mutable table. This is for public command-WAL mode, where command WAL durability replaces the cached redo log.

func (*DB) SetAfterCommandWALAppendWithRevision added in v0.6.1

func (db *DB) SetAfterCommandWALAppendWithRevision(key, value []byte, appendCommand func(page.EntryRevision) error) error

SetAfterCommandWALAppendWithRevision applies a point Set after appendCommand succeeds. The assigned revision is passed to appendCommand before the command WAL frame is appended so replay can encode the same entry metadata that will become visible in the mutable table.

func (*DB) SetAutoCheckpointWALBytesHook added in v0.6.0

func (db *DB) SetAutoCheckpointWALBytesHook(fn func() int64)

SetAutoCheckpointWALBytesHook supplies external WAL pressure bytes for modes that use cached checkpointing while disabling the cached redo journal. The value should include reclaimable non-active bytes, not only active-writer bytes, so size-triggered checkpoints can bound total WAL growth.

func (*DB) SetCommandWALCheckpointCleanupHook added in v0.6.0

func (db *DB) SetCommandWALCheckpointCleanupHook(h func(sync bool) error)

SetCommandWALCheckpointCleanupHook installs an optional hook called after a cached checkpoint has published command-WAL coverage.

func (*DB) SetCommandWALCheckpointCutoverHook added in v0.6.0

func (db *DB) SetCommandWALCheckpointCutoverHook(h func())

SetCommandWALCheckpointCutoverHook installs an optional hook called while Checkpoint still holds the write cutover lock. Command-WAL publishers use it to cap AppliedCommandLSN publication to writes included in this checkpoint.

func (*DB) SetCommandWALCheckpointPublishHook added in v0.6.0

func (db *DB) SetCommandWALCheckpointPublishHook(h func(sync bool) (uint64, []backenddb.CommandWALLSNRange, error))

SetCommandWALCheckpointPublishHook installs an optional hook that lets a caller publish already-covered command-WAL LSNs in the same backend commit that Checkpoint uses for its root/sync boundary. Checkpoint may call the hook more than once when a piggyback attempt is prepared but not consumed; hook implementations must therefore be idempotent and safe to reinvoke within one checkpoint.

func (*DB) SetDictStore added in v0.2.0

func (db *DB) SetDictStore(store DictStore)

SetDictStore installs the dictionary store for current-ID freezing.

func (*DB) SetMaintenancePhase added in v0.4.0

func (db *DB) SetMaintenancePhase(phase MaintenancePhase)

func (*DB) SetStatsHook added in v0.6.0

func (db *DB) SetStatsHook(h func(map[string]string))

SetStatsHook installs an optional stats decorator for outer wrappers that own counters not stored on the cached layer itself. The hook must not call DB.Stats.

func (*DB) SetSync

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

func (*DB) SetTemplateStore added in v0.3.0

func (db *DB) SetTemplateStore(store template.Store)

SetTemplateStore installs the template store used for template compression.

func (*DB) StartAutoCheckpoint

func (db *DB) StartAutoCheckpoint(interval time.Duration, maxWALBytes int64, idleInterval time.Duration)

StartAutoCheckpoint enables a background loop that periodically forces a durable boundary and trims cached-mode WAL segments. When idleInterval > 0, it also triggers an opportunistic checkpoint after a period of write-idleness.

interval > 0 enables periodic checkpoints. maxWALBytes is a safety cap: if > 0, the loop will attempt to checkpoint when the effective WAL bytes exceed this cap. maxWALBytes <= 0 disables the size trigger.

This does not make each individual write durable; it bounds the window of unsynced writes for long-running workloads.

func (*DB) Stats

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

func (*DB) TriggerAutoCheckpoint

func (db *DB) TriggerAutoCheckpoint()

TriggerAutoCheckpoint schedules a best-effort immediate auto-checkpoint pass.

func (*DB) TriggerFlush

func (db *DB) TriggerFlush()

TriggerFlush schedules a background flush pass (best-effort).

func (*DB) Update added in v0.6.0

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

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

func (*DB) UpdateSync added in v0.6.0

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

UpdateSync applies fn to the current value for key and writes the returned mutation with a sync durability boundary.

func (*DB) ValueLogInUsePaths added in v0.6.0

func (db *DB) ValueLogInUsePaths() []string

ValueLogInUsePaths returns value-log segment paths currently backing cached mutable/queued writer state. It excludes retained lifecycle paths so callers that already hold a writer fence can still reclaim independently proven unreachable retained sources.

func (*DB) ValueLogProtectedPaths added in v0.6.0

func (db *DB) ValueLogProtectedPaths() []string

ValueLogProtectedPaths returns value-log segment paths that online backend maintenance must protect while this cached DB is live. The set includes retained pointer-lifecycle paths plus current/queued in-use writer paths.

func (*DB) ValueLogRetainedPaths added in v0.4.0

func (db *DB) ValueLogRetainedPaths() []string

ValueLogRetainedPaths returns a best-effort snapshot of retained value-log segment paths currently pinned by cached-mode pointer lifecycle tracking.

type DictStore added in v0.2.0

type DictStore interface {
	GetCurrent(ctx context.Context) (uint64, error)
	GetDictBytes(ctx context.Context, dictID uint64) ([]byte, error)
}

DictStore provides access to the current dictionary ID for write freezing.

type MaintenancePhase added in v0.4.0

type MaintenancePhase uint8
const (
	MaintenancePhaseSteady MaintenancePhase = iota
	MaintenancePhaseRestore
	MaintenancePhaseCatchUp
)

type Options

type Options struct {
	FlushThreshold int64

	// MemtableMode selects the in-memory write buffer implementation.
	// Supported: "skiplist", "hash_sorted", "btree", "append_only", "adaptive".
	// Use "adaptive" or "adaptive:<mode>" to switch per-rotation based on workload.
	MemtableMode string

	// MemtableShards controls the number of mutable memtable shards. Values <= 0
	// use a default derived from GOMAXPROCS. The count is rounded down to a power
	// of two.
	MemtableShards int
	// DomainIngressWorkers enables experimental domain-local write ingress queues.
	// Values <= 0 keep the legacy direct caller write path.
	DomainIngressWorkers int
	// DomainIngressQueueSize configures the per-worker ingress queue length.
	// Values <= 0 use a default.
	DomainIngressQueueSize int

	// Legacy backpressure knob: queue length limit.
	// 0 uses the default (4). <0 disables writer backpressure entirely.
	MaxQueuedMemtables int

	// Adaptive backpressure knobs (seconds/bytes). If any of these are non-zero,
	// the caching layer uses backlog-bytes thresholds instead of queue length.
	SlowdownBacklogSeconds float64
	StopBacklogSeconds     float64
	MaxBacklogBytes        int64

	// Writer flush assist limits when backpressure triggers.
	WriterFlushMaxMemtables int
	WriterFlushMaxDuration  time.Duration

	// FlushBuildConcurrency controls how many goroutines may be used to build a
	// combined flush batch from multiple immutable memtables. Values <= 1 disable
	// parallelism.
	FlushBuildConcurrency int
	// FlushBuildMinEntries gates the parallel build path by total entries.
	// Values <= 0 use a default of 16k.
	FlushBuildMinEntries int
	// FlushBuildMinUnits gates the parallel build path by number of queued units.
	// Values <= 0 use a default of 2.
	FlushBuildMinUnits int
	// FlushBuildChunkCap controls the maximum entries per build chunk.
	// Values < 0 use the fixed default of 8192, 0 enables adaptive chunk sizing,
	// and values > 0 set a fixed cap.
	FlushBuildChunkCap int
	// FlushBuildChunkTargetBytes controls adaptive chunk sizing (bytes per chunk).
	// Values <= 0 use a default of 2MiB.
	FlushBuildChunkTargetBytes int
	// FlushBuildChunkMinBytes clamps adaptive chunk sizes (minimum bytes).
	// Values <= 0 use a default of 1MiB.
	FlushBuildChunkMinBytes int
	// FlushBuildChunkMaxBytes clamps adaptive chunk sizes (maximum bytes).
	// Values <= 0 use a default of 4MiB.
	FlushBuildChunkMaxBytes int
	// FlushBuildPrefetchUnits controls how many memtables to start building ahead
	// of the consumer. Values <= 0 use FlushBuildConcurrency.
	FlushBuildPrefetchUnits int

	// FlushApplyConcurrency enables backend M2 opt-in COW apply workers. The
	// backend owns execution; cached mode carries this knob for config/reporting
	// symmetry with FlushBuildConcurrency. Values <=1 keep the M2 path off.
	FlushApplyConcurrency int
	// FlushApplyMinEntries gates backend opt-in parallel apply by planned ops.
	FlushApplyMinEntries int
	// FlushApplyMinSpans gates backend opt-in parallel apply by planned leaf spans.
	FlushApplyMinSpans int
	// FlushApplyMinBytes gates backend opt-in parallel apply by planned bytes.
	FlushApplyMinBytes int
	// FlushApplySpanNative enables backend M10 opt-in span-native apply. The
	// backend owns execution; cached mode carries this knob for config/reporting
	// symmetry and keeps the path default-off.
	FlushApplySpanNative bool

	// FlushBackendMaxEntries caps how many operations are buffered into a single
	// backend batch before committing it and continuing with a fresh batch.
	//
	// This increases backend commit cadence during very large flushes, which can
	// reduce index.db high-watermark growth under small KeepRecent windows by
	// making retired pages eligible for reuse sooner.
	//
	// 0 uses the internal default. Negative disables chunking (single backend
	// commit per flush).
	FlushBackendMaxEntries int
	// FlushBackendMaxBatches caps how many intermediate backend commits a single
	// flush may emit. This bounds zipper/apply overhead when FlushBackendMaxEntries
	// is very small relative to the flush size.
	//
	// 0 uses the internal default. Negative disables the cap.
	FlushBackendMaxBatches int

	// FlushSpanRunTargetPlanning enables diagnostic read-only target-leaf planning
	// for canonical flush runs. It is default-off because the extra root traversal
	// is not part of the M9 default write path; M10+ can use the same backend
	// planner when span-native execution consumes target spans.
	FlushSpanRunTargetPlanning bool

	// FlushBacklogCoalescing enables the M11 bounded adaptive cached-flush
	// coalescing controller. It is default-off; when enabled the coordinator may
	// include additional already-sealed eligible memtables before canonical run
	// planning under observed cumulative single-op-span pressure and explicit
	// budgets.
	FlushBacklogCoalescing bool
	// FlushBacklogCoalescingMaxMemtables bounds memtables per coalesced point run
	// after preserving the pre-existing base collector minimum (0=default, capped
	// internally).
	FlushBacklogCoalescingMaxMemtables int
	// FlushBacklogCoalescingMaxBytes is a soft queued-byte budget per coalesced
	// point run. It is checked before adding the next memtable after at least one
	// unit, so a selected run can exceed this value by one whole memtable and the
	// budget never tightens the pre-existing base collector (0=default).
	FlushBacklogCoalescingMaxBytes int64
	// FlushBacklogCoalescingMaxOps is a soft queued point-op budget per coalesced
	// point run. It is checked before adding the next memtable after at least one
	// unit, so a selected run can exceed this value by one whole memtable and the
	// budget never tightens the pre-existing base collector (0=default).
	FlushBacklogCoalescingMaxOps int
	// FlushBacklogCoalescingMinAge requires the oldest queued memtable to be at
	// least this old before adaptive coalescing admits extra work (0=no age floor).
	FlushBacklogCoalescingMinAge time.Duration
	// FlushBacklogCoalescingSingleOpSpanRatio is the observed single-op span ratio
	// that triggers coalescing (0=default). Pressure gates use cumulative apply/span
	// counters; after workload-shape changes, eligibility may decay only as
	// cumulative ratios change, while each admitted run remains bounded by the
	// explicit budgets above.
	FlushBacklogCoalescingSingleOpSpanRatio float64
	// FlushBacklogCoalescingMaxOpsPerSpan is the observed ops/span ceiling that
	// still counts as single-op pressure (0=default).
	FlushBacklogCoalescingMaxOpsPerSpan float64
	// FlushBacklogCoalescingMinOldLeafBytesPerOp optionally requires observed
	// old-leaf decode bytes/op before coalescing (0=disabled).
	FlushBacklogCoalescingMinOldLeafBytesPerOp float64

	// DisableWAL disables the redo/journal log while keeping the value log enabled.
	DisableWAL bool
	// JournalLanes controls the number of active commit/value log lanes
	// (0=GOMAXPROCS-aware default).
	// Max supported lanes is 255; value-log segment sequence per lane is capped at 8,388,607.
	JournalLanes int
	// WALMaxSegmentBytes caps the size of a single WAL segment payload.
	// 0 uses the default limit.
	WALMaxSegmentBytes int64
	// JournalCompression enables best-effort zstd compression for journal/commitlog
	// segments (metadata only). The writer only keeps compressed bytes when they
	// are smaller than the raw payload, so compression never causes size
	// amplification.
	JournalCompression bool
	// RelaxedSync disables fsync on Sync operations.
	RelaxedSync bool
	// ValueLogPointerThreshold controls when WAL/vlog pointers are used.
	// Values <= 0 use a default threshold. In relaxed durability modes, the
	// default is smaller to avoid catastrophic update-heavy cliffs at large key
	// counts by pushing moderate values into the value log.
	ValueLogPointerThreshold int
	// IndexOuterLeavesInValueLog stores B+Tree leaf pages (the pages containing
	// key/value entries) in the persistent value log instead of index.db.
	IndexOuterLeavesInValueLog bool
	// ValueLogDomainInlineThresholds configures optional per-domain overrides
	// for inline-vs-pointer placement. Longest-prefix match wins.
	ValueLogDomainInlineThresholds []backenddb.ValueLogDomainThreshold
	// ValueLogRawWritevMinAvgBytes controls raw grouped-frame writev usage for
	// the value log.
	//
	// 0 uses adaptive mode (no average-bytes floor); values >0 require average
	// payload bytes/record to meet this floor before raw writev is considered.
	ValueLogRawWritevMinAvgBytes int
	// ValueLogRawWritevMinBatchRecords controls the minimum grouped records before
	// raw writev is considered for value-log appends.
	//
	// Values <=0 use a default of 8.
	ValueLogRawWritevMinBatchRecords int
	// ValueLogCompression selects value-log compression behavior:
	// 0=default(unset; normalized to auto by TreeDB Open), 1=off, 2=block,
	// 3=dict, 4=auto.
	ValueLogCompression uint8
	// ValueLogBlockCodec selects block codec when block compression is enabled:
	// 0=snappy, 1=lz4.
	ValueLogBlockCodec uint8
	// ValueLogBlockTargetCompressedBytes controls block-mode grouped frame K
	// adaptation target (0=default).
	ValueLogBlockTargetCompressedBytes int
	// ValueLogIncompressibleHoldBytes configures auto-mode incompressible hold
	// window bytes (0=default).
	ValueLogIncompressibleHoldBytes int
	// ValueLogIncompressibleProbeBytes configures auto-mode hold probe interval
	// bytes (0=default).
	ValueLogIncompressibleProbeBytes int
	// ValueLogAutoPolicy controls auto-mode dict-vs-block bias:
	// 0=balanced, 1=throughput, 2=size.
	ValueLogAutoPolicy uint8
	// ValueLogMaxSegmentBytes caps the size of a single value-log segment file.
	// 0 disables the cap.
	//
	// This is an internal safety knob used by experimental index encodings
	// (e.g. packed on-disk ValuePtr) that require value-log offsets stay within a
	// smaller representable range.
	ValueLogMaxSegmentBytes int64
	// ValueLogGenerationPolicy selects generational mode:
	// 0=default(unset; normalized to hot_warm_cold by Open),
	// 1=off, 2=hot_warm_cold.
	ValueLogGenerationPolicy uint8
	// ValueLogGenerationLeafSegmentTargetBytes configures leaf_vlog segment target size.
	ValueLogGenerationLeafSegmentTargetBytes int64
	// ValueLogGenerationHotSegmentTargetBytes configures hot segment target size.
	ValueLogGenerationHotSegmentTargetBytes int64
	// ValueLogGenerationWarmSegmentTargetBytes configures warm segment target size.
	ValueLogGenerationWarmSegmentTargetBytes int64
	// ValueLogGenerationColdSegmentTargetBytes configures cold segment target size.
	ValueLogGenerationColdSegmentTargetBytes int64
	// ValueLogRewriteBudgetBytesPerSec configures incremental rewrite byte budget.
	ValueLogRewriteBudgetBytesPerSec int64
	// ValueLogRewriteBudgetRecordsPerSec configures incremental rewrite record budget.
	ValueLogRewriteBudgetRecordsPerSec int
	// ValueLogRewriteTriggerStaleRatioPPM triggers rewrite by stale/live ratio.
	ValueLogRewriteTriggerStaleRatioPPM uint32
	// ValueLogRewriteTriggerTotalBytes triggers rewrite by retained bytes.
	ValueLogRewriteTriggerTotalBytes int64
	// ValueLogRewriteTriggerChurnPerSec triggers rewrite by churn rate.
	ValueLogRewriteTriggerChurnPerSec int64
	// ValueLogRewriteMinSegmentAge gates online rewrite to source segments that
	// are at least this old.
	//
	// 0 uses the implementation default.
	ValueLogRewriteMinSegmentAge time.Duration
	// ForceValueLogPointers stores all values out-of-line in the value log.
	ForceValueLogPointers bool
	// DisableReadChecksum skips CRC verification on value-log reads.
	DisableReadChecksum bool
	// ValueLogCurrentWritableMmap enables mmap-backed reads for current writable
	// value-log segments.
	ValueLogCurrentWritableMmap bool
	// AllowUnsafe acknowledges unsafe durability options.
	// When false, Open will reject DisableWAL or RelaxedSync.
	AllowUnsafe bool
	// MaxValueLogRetainedBytes emits a warning once retained value-log bytes
	// reach or exceed this threshold and also acts as the soft retained-byte
	// trigger for background prune scheduling (0 disables both).
	MaxValueLogRetainedBytes int64
	// MaxValueLogRetainedBytesHard disables value-log pointers for new large
	// values once retained bytes exceed this threshold (0 disables the cap).
	MaxValueLogRetainedBytesHard int64

	// ValueLogDictTrain configures background dictionary training for value-log frame compression.
	// TrainBytes <= 0 disables training.
	ValueLogDictTrain compression.TrainConfig
	// ValueLogDictMaxK clamps the maximum group size (K) used for dict-compressed
	// value-log frames. Values <= 0 use the default (32).
	ValueLogDictMaxK int
	// ValueLogDictClassMode controls dictionary-state partitioning:
	// 0=single shared dict stream, 1=split outer-leaf vs single-value streams.
	ValueLogDictClassMode uint8
	// ValueLogDictFrameEncodeLevel controls the zstd encoder level used for
	// dict-compressed value-log frames. Values <= 0 use SpeedFastest.
	ValueLogDictFrameEncodeLevel zstd.EncoderLevel
	// ValueLogDictFrameEnableEntropy enables entropy coding for dict-compressed
	// frames (higher ratio, lower throughput).
	ValueLogDictFrameEnableEntropy bool
	// ValueLogDictAdaptiveRatio enables adaptive pause of dict compression when payload ratios degrade.
	// 0 disables.
	ValueLogDictAdaptiveRatio float64
	// ValueLogDictMetricsWindowBytes controls the metrics window size (0=default).
	ValueLogDictMetricsWindowBytes int
	// ValueLogDictMetricsMinRecords is a minimum record count before pausing (0=default).
	ValueLogDictMetricsMinRecords int
	// ValueLogDictMetricsPauseBytes controls pause duration in bytes (0=default).
	ValueLogDictMetricsPauseBytes int
	// ValueLogDictIncompressibleHoldBytes enables classifier-driven hold mode for
	// high-entropy streams. While hold mode is active, dict compression attempts
	// and trainer collection are bypassed until hold bytes are consumed.
	//
	// 0 uses profile/default hold configuration; <0 explicitly disables hold
	// mode and opts out of profile defaults.
	ValueLogDictIncompressibleHoldBytes int
	// ValueLogDictProbeIntervalBytes controls periodic probe attempts while
	// incompressible hold mode is active.
	//
	// Values <=0 use a default derived from hold bytes.
	ValueLogDictProbeIntervalBytes int
	// ValueLogDictMinPayloadSavingsRatio rejects newly trained dictionaries whose
	// payload ratio does not improve by at least this fraction (0 uses a
	// throughput-oriented default: 0.02 normally, 0.05 with force pointers or
	// WAL disabled).
	ValueLogDictMinPayloadSavingsRatio float64

	// ValueLogCompressionAutotune configures the wall-time value-log compression autotuner.
	// Cached mode only (value log enabled by default).
	ValueLogCompressionAutotune valuelog.AutotuneOptions

	// ValueLogTemplateMode controls template-based compression for value-log values.
	ValueLogTemplateMode template.Mode
	// ValueLogTemplateConfig controls template creation and encoding behavior.
	ValueLogTemplateConfig template.Config
	// ValueLogTemplateReadStrict controls strict template decode behavior.
	ValueLogTemplateReadStrict bool

	// NotifyError is an optional hook for background maintenance failures.
	NotifyError func(error)
}

type Snapshot added in v0.4.0

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

Snapshot is a consistent point-in-time view of the cached+backend TreeDB state.

Snapshot isolation in cached mode is implemented by rotating any pending writes out of the mutable memtables into the immutable queue, then reading from:

  • the frozen queue (stored oldest-to-newest, scanned newest-to-oldest)
  • the backend snapshot

Mutable memtables are intentionally ignored so that writes after AcquireSnapshot are not visible through the snapshot.

Snapshot pointers are single-use: after Close returns, callers must discard the pointer and treat further use as invalid.

func (*Snapshot) Close added in v0.4.0

func (s *Snapshot) Close() error

func (*Snapshot) Get added in v0.4.0

func (s *Snapshot) Get(key []byte) ([]byte, error)

func (*Snapshot) GetAppend added in v0.4.0

func (s *Snapshot) GetAppend(key, dst []byte) ([]byte, error)

func (*Snapshot) GetEntry added in v0.4.0

func (s *Snapshot) GetEntry(key []byte) (node.LeafEntry, error)

func (*Snapshot) GetEntryExact added in v0.4.0

func (s *Snapshot) GetEntryExact(key []byte) (node.LeafEntry, error)

func (*Snapshot) GetManyView added in v0.6.0

func (s *Snapshot) GetManyView(keys [][]byte, fn tree.GetManyViewFunc) error

GetManyView calls fn once for each key with a read-only value view. Values are valid only until fn returns and must be copied before retaining.

func (*Snapshot) GetUnsafe added in v0.4.0

func (s *Snapshot) GetUnsafe(key []byte) ([]byte, error)

func (*Snapshot) GetVersioned added in v0.6.1

func (s *Snapshot) GetVersioned(key []byte) ([]byte, page.EntryRevision, error)

func (*Snapshot) GetVersionedAppend added in v0.6.1

func (s *Snapshot) GetVersionedAppend(key, dst []byte) ([]byte, page.EntryRevision, error)

func (*Snapshot) Has added in v0.4.0

func (s *Snapshot) Has(key []byte) (bool, error)

func (*Snapshot) HasMany added in v0.6.0

func (s *Snapshot) HasMany(keys [][]byte) ([]bool, error)

func (*Snapshot) HasPrefixes added in v0.6.0

func (s *Snapshot) HasPrefixes(prefixes [][]byte) ([]bool, error)

func (*Snapshot) Iterator added in v0.6.0

func (s *Snapshot) Iterator(start, end []byte) (merging.Iterator, error)

Iterator returns a stable iterator over the snapshot's queued memtables plus its backend snapshot.

func (*Snapshot) Pager added in v0.4.0

func (s *Snapshot) Pager() *pager.Pager

func (*Snapshot) ReverseIterator added in v0.6.0

func (s *Snapshot) ReverseIterator(start, end []byte) (merging.Iterator, error)

ReverseIterator returns a stable reverse iterator over the snapshot's queued memtables plus its backend snapshot.

func (*Snapshot) State added in v0.4.0

func (s *Snapshot) State() *backenddb.DBState

type VlogAutotuneBenchMode added in v0.2.0

type VlogAutotuneBenchMode string

VlogAutotuneBenchMode controls the deterministic bench mode.

const (
	VlogAutotuneBenchOff         VlogAutotuneBenchMode = "off"
	VlogAutotuneBenchNoDictFixed VlogAutotuneBenchMode = "no_dict_fixed"
	VlogAutotuneBenchDictFixed   VlogAutotuneBenchMode = "dict_fixed"
	VlogAutotuneBenchAutotune    VlogAutotuneBenchMode = "autotune"
	VlogAutotuneBenchTemplate    VlogAutotuneBenchMode = "template_fixed"
)

type VlogAutotuneBenchRequest added in v0.2.0

type VlogAutotuneBenchRequest struct {
	Mode     VlogAutotuneBenchMode
	FixedK   int
	Segments []VlogAutotuneBenchSegment
}

type VlogAutotuneBenchResult added in v0.2.0

type VlogAutotuneBenchResult struct {
	Mode         VlogAutotuneBenchMode
	Segments     []VlogAutotuneBenchSegmentResult
	RawBytes     uint64
	StoredBytes  uint64
	WallTimeNs   int64
	ThroughputMB float64
	TrainerStats compression.TrainerStats
}

func RunVlogAutotuneBench added in v0.2.0

func RunVlogAutotuneBench(req VlogAutotuneBenchRequest) (*VlogAutotuneBenchResult, error)

type VlogAutotuneBenchSegment added in v0.2.0

type VlogAutotuneBenchSegment struct {
	Name               string
	Workload           valuelog.AutotuneWorkload
	ValueSize          int
	Records            int
	EncodeNsPerRawByte float64
	IoNsPerStoredByte  float64
}

type VlogAutotuneBenchSegmentResult added in v0.2.0

type VlogAutotuneBenchSegmentResult struct {
	Name               string
	RawBytes           uint64
	StoredBytes        uint64
	WallTimeNs         int64
	ThroughputRawMBps  float64
	AttemptedFrac      float64
	KeptFrac           float64
	ObservedRatio      float64
	FramesTotal        uint64
	FramesAttempted    uint64
	FramesKept         uint64
	EncodeNsTotal      int64
	IoNsTotal          int64
	State              string
	DictID             uint64
	DictHash           uint64
	HistoryBytes       int
	K                  int
	PublishOrderingOK  bool
	TrainerProfileOK   bool
	TrainerProfileK    int
	TrainerProfileHash uint64
}

Jump to

Keyboard shortcuts

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