storage

package
v0.1.0-alpha.14 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package storage implements the current Meldbase copy-on-write page format.

Index

Constants

View Source
const (
	// DefaultCommitRetentionMaxCommits sets the default retained commit count.
	DefaultCommitRetentionMaxCommits uint64 = 10_000
	// DefaultCommitRetentionMaxBytes sets the default retained commit byte limit.
	DefaultCommitRetentionMaxBytes uint64 = 256 << 20
	// DefaultMaxFileBytes sets the default physical database file size limit.
	DefaultMaxFileBytes uint64 = 8 << 30
)
View Source
const (
	// PageSize is the byte size of every stored page.
	PageSize = 16 * 1024
	// PageHeaderSize is the byte size of a data page header.
	PageHeaderSize = 64
	// MetaHeaderSize is the byte size of the metadata header.
	MetaHeaderSize = 256
	// FormatVersion identifies the current on-disk format revision.
	FormatVersion = 3
)
View Source
const (
	// RequiredFeatureShadowIndexBuilds marks stored background index build records.
	//
	// Required feature bits must be understood before any generation is opened.
	RequiredFeatureShadowIndexBuilds uint64 = 1 << 0
	// RequiredFeatureCompoundIndexes marks indexes with multiple ordered fields.
	RequiredFeatureCompoundIndexes uint64 = 1 << 1
	// RequiredFeatureIndexBuildAppliedRoot marks index builds that retain their last applied catalog root.
	RequiredFeatureIndexBuildAppliedRoot uint64 = 1 << 2
	// SupportedRequiredFeatures lists the required features this binary understands.
	SupportedRequiredFeatures uint64 = RequiredFeatureShadowIndexBuilds | RequiredFeatureCompoundIndexes | RequiredFeatureIndexBuildAppliedRoot
	// OptionalFeaturePersistentFreeSpace marks a stored index of reusable pages.
	//
	// Unknown optional bits are preserved and ignored. A writer may only alter
	// bits it owns; this permits older binaries to carry future acceleration
	// metadata through a normal commit without treating it as allocation truth.
	OptionalFeaturePersistentFreeSpace uint64 = 1 << 0
	// SupportedOptionalFeatures lists the optional features this binary understands.
	SupportedOptionalFeatures uint64 = OptionalFeaturePersistentFreeSpace
)
View Source
const (
	// MaxConcurrentIndexBuilds bounds the number of persistent build records stored at one time.
	MaxConcurrentIndexBuilds = 64
	// MaxIndexBuildBatchEntries bounds the entries in one source scan batch.
	MaxIndexBuildBatchEntries = 4096
	// MaxIndexBuildBatchBytes bounds the accounted entry bytes in one source scan batch.
	MaxIndexBuildBatchBytes = 16 << 20
	// MaxIndexBuildCatchUpCommits bounds the commit range in one catch-up batch.
	MaxIndexBuildCatchUpCommits = 1024
	// MaxIndexBuildCatchUpMutations bounds the document changes in one catch-up batch.
	MaxIndexBuildCatchUpMutations = 10_000
)
View Source
const (

	// MaxSecondaryScalarKeyBytes bounds index value bytes before the position and document ID suffix.
	MaxSecondaryScalarKeyBytes = 4096 - 24
)

Variables

View Source
var (
	// ErrNodeFull reports that an encoded tree node cannot fit in one page.
	ErrNodeFull = errors.New("meldbase storage: tree node is full")
	// ErrKeyTooBig reports an invalid or oversized tree key.
	ErrKeyTooBig = errors.New("meldbase storage: tree key is too large")
)
View Source
var (
	// ErrHistoryLost reports that requested commits are no longer retained.
	ErrHistoryLost = errors.New("meldbase storage: commit history is no longer retained")
	// ErrHistoryPinned reports that a live replay cursor prevents history removal.
	ErrHistoryPinned = errors.New("meldbase storage: commit history is pinned by a live replay cursor")
	// ErrNoDeliveredCommit reports that a live stream has not yet delivered a commit.
	ErrNoDeliveredCommit = errors.New("meldbase storage: live stream has not delivered a commit")
	// ErrCursorClosed reports that a commit cursor is closed.
	ErrCursorClosed = errors.New("meldbase storage: commit cursor is closed")
)
View Source
var (

	// ErrDurableConsumerExists reports that a named consumer checkpoint already exists.
	//
	// Callers must explicitly open the existing consumer instead.
	ErrDurableConsumerExists = errors.New("meldbase storage: durable consumer already exists")
	// ErrDurableConsumerNotFound reports a missing named checkpoint.
	ErrDurableConsumerNotFound = errors.New("meldbase storage: durable consumer not found")
)
View Source
var (
	// ErrLocked reports that another writer owns the database file.
	ErrLocked = errors.New("meldbase storage: database is locked")
	// ErrRecoveryRequired reports that opening requires recovery disallowed by the chosen options.
	ErrRecoveryRequired = errors.New("meldbase storage: recovery required")
	// ErrInvalidStorageLimit reports an invalid physical file size limit.
	ErrInvalidStorageLimit = errors.New("meldbase storage: invalid storage limit")
	// ErrStorageLimit reports that allocating pages would exceed the physical storage limit.
	ErrStorageLimit = errors.New("meldbase storage: storage limit exceeded")
	// ErrStaleSnapshot reports that the database is older than the required minimum version.
	ErrStaleSnapshot = errors.New("meldbase storage: commit sequence is below the required minimum")
	// ErrDatabaseIdentity reports a database identity different from the expected identity.
	ErrDatabaseIdentity = errors.New("meldbase storage: unexpected database identity")
	// ErrInsecureFileMode reports file permissions that allow access by other users.
	ErrInsecureFileMode = errors.New("meldbase storage: database file permissions are not owner-private")
)
View Source
var (
	// ErrCorrupt reports invalid stored data.
	ErrCorrupt = errors.New("meldbase storage: corrupt database")
	// ErrUnsupportedFormat reports a format revision this binary cannot read.
	ErrUnsupportedFormat = errors.New("meldbase storage: unsupported format version")
	// ErrUnsupportedFeature reports a required feature this binary does not understand.
	ErrUnsupportedFeature = errors.New("meldbase storage: unsupported required feature")
)
View Source
var (
	// ErrIndexBuildExists reports a conflicting index build already stored.
	ErrIndexBuildExists = errors.New("meldbase storage: index build exists")
	// ErrIndexBuildNotFound reports a missing persistent index build.
	ErrIndexBuildNotFound = errors.New("meldbase storage: index build not found")
	// ErrIndexBuildState reports a build phase or progress that does not permit the requested operation.
	ErrIndexBuildState = errors.New("meldbase storage: invalid index build state")
	// ErrIndexBuildHistoryLost reports source commit history that a build can no longer replay.
	ErrIndexBuildHistoryLost = errors.New("meldbase storage: index build commit history lost")
)
View Source
var (
	// ErrIndexExists reports an attempt to create an existing index name.
	ErrIndexExists = errors.New("meldbase storage: index name exists")
	// ErrIndexNotFound reports a missing index name.
	ErrIndexNotFound = errors.New("meldbase storage: index name not found")
	// ErrUniqueConflict reports duplicate values in a unique index.
	ErrUniqueConflict = errors.New("meldbase storage: unique index conflict")
	// ErrIndexKeyTooLarge reports an index value exceeding the stored key size limit.
	ErrIndexKeyTooLarge = errors.New("meldbase storage: index key is too large")
)
View Source
var ErrCollectionExists = errors.New("meldbase storage: collection exists")

ErrCollectionExists reports an attempt to create a collection that already exists.

View Source
var ErrDocumentConflict = errors.New("meldbase storage: document precondition conflicted")

ErrDocumentConflict reports that an optimistic point precondition no longer matches the current root.

It is a safe logical rejection, not corruption or a durability failure.

View Source
var ErrDocumentExists = errors.New("meldbase storage: document already exists")

ErrDocumentExists distinguishes an insert collision from an optimistic update/delete precondition conflict.

The public DB maps it to ErrDuplicateID so a grouped candidate can fall back to ordinary per-request semantics.

View Source
var ErrReclamationConflict = errors.New("meldbase storage: online reclamation conflicted with a commit")

ErrReclamationConflict reports that a concurrent commit invalidated a reclamation scan.

Functions

func DecodeDatabaseRoot

func DecodeDatabaseRoot(page []byte, expectedID uint64) (DatabaseRoot, Page, error)

DecodeDatabaseRoot validates and reads a database root page.

func EncodeDatabaseRoot

func EncodeDatabaseRoot(pageID, generation uint64, root DatabaseRoot) ([]byte, error)

EncodeDatabaseRoot encodes database root pointers as a data page.

func EncodeMeta

func EncodeMeta(meta Meta) ([]byte, error)

EncodeMeta validates and encodes database metadata with its checksum.

func EncodePage

func EncodePage(value Page) ([]byte, error)

EncodePage validates and encodes a data page with its checksum.

func Open

func Open(path string) (*File, Meta, error)

Open creates or opens a database file with default storage options.

func OpenForQualification

func OpenForQualification(path string, options OpenOptions, hook func(QualificationBoundary) error) (*File, Meta, OpenReport, error)

OpenForQualification opens a database file with a hook for destructive commit tests.

The hook runs synchronously and may block while an external controller cuts power, exhausts a disposable volume or terminates the process. This entry point lives in internal/storage so external applications cannot opt into qualification behavior accidentally.

func OpenWithOptions

func OpenWithOptions(path string, options OpenOptions) (*File, Meta, OpenReport, error)

OpenWithOptions opens and validates a database file using the requested safety and resource limits.

func OpenWithReport

func OpenWithReport(path string) (*File, Meta, OpenReport, error)

OpenWithReport opens a database file and reports the recovery decisions made during startup.

Types

type BeginIndexBuildTransaction

type BeginIndexBuildTransaction struct {
	BuildID         [16]byte
	Collection      string
	Name            string
	FieldPath       string
	Fields          []IndexField
	Unique          bool
	ReplaceExisting bool
	CreatedAt       time.Time
}

BeginIndexBuildTransaction describes an index to build from a protected collection snapshot.

type CollectionMeta

type CollectionMeta struct {
	ID               uint32
	PrimaryRoot      uint64
	OrderRoot        uint64
	IndexCatalogRoot uint64
	DocumentCount    uint64
	CreatedSequence  uint64
	UpdatedSequence  uint64
	// NextDocumentPosition is the greatest insertion position ever assigned in
	// this collection. Positions are never reused: update preserves one, while
	// delete followed by insert receives a newer position.
	NextDocumentPosition uint64
}

CollectionMeta records a collection's tree roots, document counts, and commit versions.

type CollectionPrecondition

type CollectionPrecondition struct {
	Collection              string
	ExpectedExists          bool
	ExpectedID              uint32
	ExpectedUpdatedSequence uint64
}

CollectionPrecondition records the collection version that a transaction requires at commit.

Any document or published-index change to the collection invalidates it. Checking the whole collection prevents new matching documents from appearing between a range read and commit without relying on an in-memory query plan.

ExpectedID and ExpectedUpdatedSequence are required only when ExpectedExists is true. A missing collection is a valid read state and conflicts if another transaction creates it before publication.

type CollectionRecord

type CollectionRecord struct {
	Name string
	Meta CollectionMeta
}

CollectionRecord pairs a collection name with its stored metadata.

type CommitBatch

type CommitBatch struct {
	Sequence      uint64
	TransactionID [16]byte
	CommittedAt   time.Time
	// CatalogRoot is the immutable post-commit catalog snapshot. Retaining it
	// in the Commit Log makes an exact historical Snapshot N reconstructible.
	CatalogRoot uint64
	Changes     []CommitChange
}

CommitBatch groups changes under one commit sequence and transaction identity.

type CommitChange

type CommitChange struct {
	CollectionID uint32
	// CollectionName is present only for named catalog changes. Ordinary
	// document events use the compact stable CollectionID exclusively.
	CollectionName string
	DocumentID     [16]byte
	Operation      CommitOperation
	ChangedPaths   []string
	Before         []byte
	After          []byte
	BeforeRef      *DocumentVersionRef
	AfterRef       *DocumentVersionRef
}

CommitChange records one change and its before and after document versions.

type CommitCursor

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

CommitCursor reads a finite, gap-checked commit range from a pinned history root.

Live streams tail later roots after this cursor reaches Through().

func (*CommitCursor) Close

func (cursor *CommitCursor) Close() error

Close releases the cursor's snapshot pin and is safe to call repeatedly.

func (*CommitCursor) Next

func (cursor *CommitCursor) Next() (CommitBatch, bool, error)

Next reads the next retained commit and reports whether one remains.

func (*CommitCursor) ResolveChange

func (cursor *CommitCursor) ResolveChange(change CommitChange) (ResolvedCommitChange, error)

ResolveChange loads document bytes for a change returned by this finite cursor.

The cursor's immutable root pin keeps referenced document versions valid until Close, even if logical retention advances concurrently.

func (*CommitCursor) Through

func (cursor *CommitCursor) Through() uint64

Through returns the last commit sequence captured when the cursor opened.

type CommitOperation

type CommitOperation uint8

CommitOperation identifies a document or catalog change in the commit log.

const (
	// CommitInsert marks a document insertion.
	CommitInsert CommitOperation = 1 + iota
	// CommitUpdate marks a document update.
	CommitUpdate
	// CommitDelete marks a document deletion.
	CommitDelete
	// CommitCatalog marks a catalog change.
	CommitCatalog
)
const (
	// DocumentInsert identifies a document insertion.
	DocumentInsert CommitOperation = CommitInsert
	// DocumentUpdate identifies a document replacement.
	DocumentUpdate CommitOperation = CommitUpdate
	// DocumentDelete identifies a document deletion.
	DocumentDelete CommitOperation = CommitDelete
)

type CreateCollectionTransaction

type CreateCollectionTransaction struct {
	TransactionID [16]byte
	CommittedAt   time.Time
	Collection    string
}

CreateCollectionTransaction describes the creation of an empty stored collection.

Creation receives its own commit identity and replay event without a document mutation.

type CreateIndexTransaction

type CreateIndexTransaction struct {
	TransactionID   [16]byte
	CommittedAt     time.Time
	Collection      string
	Name            string
	FieldPath       string
	Fields          []IndexField
	Unique          bool
	ReplaceExisting bool
	// Entries is consumed and may be reordered/populated by ApplyCreateIndex.
	// Callers must not reuse or mutate it once the call begins.
	Entries []IndexEntry
}

CreateIndexTransaction describes an index to create or replace with supplied entries.

type DatabaseRoot

type DatabaseRoot struct {
	CommitSequence         uint64
	CatalogRoot            uint64
	CommitLogRoot          uint64
	FreeSpaceRoot          uint64
	OldestRetainedSequence uint64
	CatalogGeneration      uint64
	DocumentCount          uint64
	CollectionCount        uint64
	IndexBuildCatalogRoot  uint64
}

DatabaseRoot locates the stored trees belonging to one committed database version.

type DocumentIterator

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

DocumentIterator reads collection documents from a fixed database snapshot.

It owns an independent reader pin, so the ReadSnapshot used to create it may be closed immediately. DocumentIterator is not safe for concurrent use.

func (*DocumentIterator) Close

func (iterator *DocumentIterator) Close() error

Close releases the document iterator and its reader pin.

func (*DocumentIterator) Err

func (iterator *DocumentIterator) Err() error

Err returns the document iterator failure.

func (*DocumentIterator) Next

func (iterator *DocumentIterator) Next() bool

Next advances to the next document and records any scan or decoding error.

func (*DocumentIterator) Record

func (iterator *DocumentIterator) Record() DocumentRecord

Record returns the current document record.

type DocumentMutation

type DocumentMutation struct {
	Collection   string
	DocumentID   [16]byte
	Operation    CommitOperation
	Document     []byte
	ChangedPaths []string
	// Indexes must contain exactly one entry for every index currently defined
	// on the collection. BeforeKey/AfterKey are encoded scalar keys; an empty key
	// means the indexed field is absent.
	Indexes []IndexMutation
}

DocumentMutation describes one document change and its index key changes.

type DocumentPrecondition

type DocumentPrecondition struct {
	Collection     string
	DocumentID     [16]byte
	ExpectedExists bool
	ExpectedHash   [32]byte
}

DocumentPrecondition binds an optimistic transaction to the canonical document bytes it actually read.

ExpectedHash is SHA-256 over the decoded storage document body when ExpectedExists is true and must otherwise be zero.

type DocumentRecord

type DocumentRecord struct {
	DocumentID        [16]byte
	InsertionPosition uint64
	Document          []byte
}

DocumentRecord holds stored document bytes with their identity and insertion position.

type DocumentSystemTransaction

type DocumentSystemTransaction struct {
	DocumentTransaction DocumentTransaction
	SystemRecords       []SystemRecordMutation
}

DocumentSystemTransaction atomically publishes document mutations and a bounded set of private system-record changes.

Every CAS must match or no document/system mutation is published.

type DocumentTransaction

type DocumentTransaction struct {
	TransactionID           [16]byte
	CommittedAt             time.Time
	Preconditions           []DocumentPrecondition
	CollectionPreconditions []CollectionPrecondition
	Mutations               []DocumentMutation
}

DocumentTransaction groups document changes with the read conditions required to commit them.

type DocumentVersionRef

type DocumentVersionRef struct {
	PrimaryRoot uint64
	DocumentID  [16]byte
}

DocumentVersionRef locates a document in a particular immutable primary tree.

type DurableCommitConsumer

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

DurableCommitConsumer reads commits from a named checkpoint that survives a restart.

Closing releases only its process-local replay pin; its named checkpoint remains durable and continues to cap retention until DeleteDurableCommitConsumer is called deliberately.

func (*DurableCommitConsumer) Ack

func (consumer *DurableCommitConsumer) Ack(sequence uint64) error

Ack saves a delivered commit sequence as this consumer's checkpoint.

Ack is monotonic and idempotent; a stale process may acknowledge an older sequence but can never move the durable checkpoint backward. The control-plane update has no logical commit sequence, so it cannot create an acknowledgement loop.

func (*DurableCommitConsumer) Checkpoint

func (consumer *DurableCommitConsumer) Checkpoint() uint64

Checkpoint returns this consumer's latest acknowledged commit sequence.

func (*DurableCommitConsumer) Close

func (consumer *DurableCommitConsumer) Close() error

Close releases the active stream while retaining the saved checkpoint.

func (*DurableCommitConsumer) Next

func (consumer *DurableCommitConsumer) Next(ctx context.Context) (CommitBatch, error)

Next reads the next committed batch without changing the saved checkpoint.

Callers must Ack only after their own side effect is complete.

func (*DurableCommitConsumer) ResolveChange

func (consumer *DurableCommitConsumer) ResolveChange(change CommitChange) (ResolvedCommitChange, error)

ResolveChange loads the document images for a change in the most recently read batch.

Callers must resolve all required images before reading the next batch.

type FailIndexBuildTransaction

type FailIndexBuildTransaction struct {
	BuildID   [16]byte
	Failure   IndexBuildFailure
	UpdatedAt time.Time
}

FailIndexBuildTransaction records why a persistent build stopped.

type File

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

File owns the database file, committed roots, reader pins, and page allocation state.

func (*File) AbortIndexBuild

func (f *File) AbortIndexBuild(buildID [16]byte) error

AbortIndexBuild removes only the protected build record.

Its private pages become reclaimable under the normal dual-Meta epoch rules.

func (*File) ApplyCreateCollection

func (f *File) ApplyCreateCollection(transaction CreateCollectionTransaction) (uint64, error)

ApplyCreateCollection commits an empty collection and its catalog change event together.

func (*File) ApplyCreateIndex

func (f *File) ApplyCreateIndex(transaction CreateIndexTransaction) (uint64, error)

ApplyCreateIndex atomically publishes an immutable secondary tree, its index catalog entry, the owning collection metadata, and one matching CommitBatch.

func (*File) ApplyDocumentSystemTransaction

func (f *File) ApplyDocumentSystemTransaction(transaction DocumentSystemTransaction) (SystemRecordResult, error)

ApplyDocumentSystemTransaction applies all document mutations only if every system-record precondition matches.

A mismatch returns Applied=false and the isolated current value of the first mismatch without publishing any change.

func (*File) ApplyDocumentTransaction

func (f *File) ApplyDocumentTransaction(transaction DocumentTransaction) (uint64, error)

ApplyDocumentTransaction atomically publishes document roots, catalog roots, and one matching durable CommitBatch.

Duplicate document mutations inside one transaction are rejected so each logical change has unambiguous before/after version roots.

func (*File) ApplyDocumentTransactionGroup

func (f *File) ApplyDocumentTransactionGroup(transactions []DocumentTransaction) ([]uint64, error)

ApplyDocumentTransactionGroup commits ordered document transactions in one physical generation.

Callers receive one sequence per logical member, while recovery observes either the whole group or none of it. System-record CAS is intentionally excluded until its separate idempotency and rollback-anchor matrix has group evidence.

func (*File) ApplyIndexBuildCatchUpBatch

func (f *File) ApplyIndexBuildCatchUpBatch(batch IndexBuildCatchUpBatch) (IndexBuildMeta, error)

ApplyIndexBuildCatchUpBatch updates an unfinished index from a contiguous range of committed changes.

The caller supplies the derived keys for every relevant change. The storage layer validates sequence continuity, operation/document identity and immutable Before/After document positions before mutating the private tree.

func (*File) ApplyIndexBuildScanBatch

func (f *File) ApplyIndexBuildScanBatch(batch IndexBuildScanBatch) (IndexBuildMeta, error)

ApplyIndexBuildScanBatch adds one Primary-key-ordered, bounded batch to the private Secondary tree and advances its durable scan cursor.

Source records are resolved through the build's protected CatalogRoot, never current state.

func (*File) ApplyReplicationNoop

func (f *File) ApplyReplicationNoop(transactionID [16]byte, committedAt time.Time) (uint64, error)

ApplyReplicationNoop advances a replica for a source commit with no public changes.

The marker is private to the target's own Commit Log: it carries no user document or System-record value, but preserves the contiguous token contract required before a later public batch can be applied.

Replication of private System-record contents is deliberately not implied by this method. A follower is read-only and must not serve source-side RPC or idempotency ownership; those records need a separately authenticated control plane if they are ever replicated.

func (*File) ApplySystemRecordTransaction

func (f *File) ApplySystemRecordTransaction(transaction SystemRecordTransaction) (SystemRecordResult, error)

ApplySystemRecordTransaction commits a private record change if its expected value matches.

func (*File) BeginIndexBuild

func (f *File) BeginIndexBuild(transaction BeginIndexBuildTransaction) (IndexBuildMeta, error)

BeginIndexBuild protects the current CatalogRoot and one empty shadow Secondary root in a physical maintenance generation.

It does not advance the logical commit sequence or publish an ordinary index definition.

func (*File) Close

func (f *File) Close() error

Close releases the writer lock, closes the file, and wakes commit stream waiters.

func (*File) CommitRoot

func (f *File) CommitRoot(root DatabaseRoot) error

CommitRoot publishes the supplied database root as the next committed generation.

Referenced tree roots must already be durable, and the supplied sequence must match the next transaction sequence.

func (*File) CopyPhysicalToContext

func (f *File) CopyPhysicalToContext(ctx context.Context, destination io.Writer) (PhysicalCopyResult, error)

CopyPhysicalToContext copies the page-aligned database file and computes its checksum.

A storage read lock blocks writers during the copy while readers remain available. The caller creates, syncs, verifies, and publishes the destination.

func (*File) CreateDurableCommitConsumer

func (f *File) CreateDurableCommitConsumer(name string, after uint64) (*DurableCommitConsumer, error)

CreateDurableCommitConsumer creates a named consumer starting after a commit sequence.

The selected position must already be recoverable from the current retained Commit Log. Creation changes only private control-plane state: it publishes a physical COW generation but does not advance the logical commit sequence or inject a synthetic change into the consumer's stream.

func (*File) DatabaseRoot

func (f *File) DatabaseRoot() (DatabaseRoot, error)

DatabaseRoot returns the current committed root while the file is open.

func (*File) DeleteDurableCommitConsumer

func (f *File) DeleteDurableCommitConsumer(name string) error

DeleteDurableCommitConsumer explicitly removes a checkpoint and its durable retention pin.

It does not close another process's active stream; that stream still owns its temporary pin until Close, but future acknowledgements fail.

func (*File) FailIndexBuild

func (f *File) FailIndexBuild(transaction FailIndexBuildTransaction) (IndexBuildMeta, error)

FailIndexBuild durably stops automatic progress without publishing or deleting the private tree.

Failed builds no longer pin Commit Log history; their source/shadow pages remain reachable until explicit abort.

func (*File) FinalizeIndexBuild

func (f *File) FinalizeIndexBuild(transaction FinalizeIndexBuildTransaction) (uint64, error)

FinalizeIndexBuild atomically moves an already-current shadow root into the ordinary IndexCatalog, removes its build record and appends one catalog Commit Log event.

The Secondary tree is neither copied nor rebuilt.

func (*File) GetDocument

func (f *File) GetDocument(collection string, documentID [16]byte) ([]byte, bool, error)

GetDocument reads a document from the current committed collection.

func (*File) GetSystemRecord

func (f *File) GetSystemRecord(key []byte) ([]byte, bool, error)

GetSystemRecord reads a private record from the current committed database.

func (*File) IndexBuild

func (f *File) IndexBuild(buildID [16]byte) (IndexBuildMeta, bool, error)

IndexBuild returns one current build record without pinning it after return.

func (*File) IndexBuilds

func (f *File) IndexBuilds() ([]IndexBuildMeta, error)

IndexBuilds lists the current persistent index build records.

func (*File) Meta

func (f *File) Meta() Meta

Meta returns a copy of the current committed metadata.

func (*File) OpenCommitCursor

func (f *File) OpenCommitCursor(after uint64) (*CommitCursor, error)

OpenCommitCursor pins the current history and opens a finite cursor after the given sequence.

func (*File) OpenDurableCommitConsumer

func (f *File) OpenDurableCommitConsumer(name string) (*DurableCommitConsumer, error)

OpenDurableCommitConsumer resumes a named consumer from its saved checkpoint.

It fails explicitly if the checkpoint predates retained history; a caller must resynchronize rather than silently starting from a newer position.

func (*File) OpenIndexBuildCatchUpSnapshot

func (f *File) OpenIndexBuildCatchUpSnapshot(buildID [16]byte) (IndexBuildMeta, *ReadSnapshot, error)

OpenIndexBuildCatchUpSnapshot atomically reads the current build record and pins the current DatabaseRoot.

Its Commit Log and every document-version root referenced by retained commits cannot be reclaimed until the snapshot closes.

func (*File) OpenIndexBuildScanIterator

func (f *File) OpenIndexBuildScanIterator(buildID [16]byte, limit int) (IndexBuildMeta, *DocumentIterator, error)

OpenIndexBuildScanIterator streams the next protected source-Primary batch.

Its reader pin protects the current DatabaseRoot, which in turn protects the build record, source CatalogRoot and shadow tree for the iterator lifetime.

func (*File) OpenLiveCommitStream

func (f *File) OpenLiveCommitStream(after uint64) (*LiveCommitStream, error)

OpenLiveCommitStream opens a durable commit stream after a retained commit sequence.

func (*File) OpenSnapshot

func (f *File) OpenSnapshot() (*ReadSnapshot, error)

OpenSnapshot opens a fixed view of the current database version.

It is the query/read path; callers that also need an N+1 stream use OpenSnapshotAndStream instead.

func (*File) OpenSnapshotAndStream

func (f *File) OpenSnapshotAndStream() (*ReadSnapshot, *LiveCommitStream, error)

OpenSnapshotAndStream opens a snapshot and a stream of all subsequent commits atomically.

The stream starts after the snapshot, eliminating the query/watch registration gap.

func (*File) OpenSnapshotAndStreamAt

func (f *File) OpenSnapshotAndStreamAt(sequence uint64) (*ReadSnapshot, *LiveCommitStream, error)

OpenSnapshotAndStreamAt opens a retained database version and its subsequent commit stream atomically.

The requested sequence must remain in the retained commit history. Sequence zero denotes the known empty state before commit 1.

func (*File) PageCacheStats

func (f *File) PageCacheStats() PageCacheStats

PageCacheStats samples page cache occupancy and access counters.

func (*File) PersistFreeSpace

func (f *File) PersistFreeSpace() error

PersistFreeSpace publishes the current audited pool as an optional physical maintenance generation without advancing the logical commit sequence.

func (*File) PersistFreeSpaceContext

func (f *File) PersistFreeSpaceContext(ctx context.Context) error

PersistFreeSpaceContext persists the audited reusable page pool with cancellation support.

func (*File) Reachability

func (f *File) Reachability() (ReachabilityStats, error)

Reachability checks all pages retained by recoverable database versions and active snapshots.

This explicit scan can be expensive and never runs on the commit path.

func (*File) ReachabilityContext

func (f *File) ReachabilityContext(ctx context.Context) (ReachabilityStats, error)

ReachabilityContext audits protected pages with cancellation support.

func (*File) ReadCommit

func (f *File) ReadCommit(rootPage, sequence uint64) (CommitBatch, error)

ReadCommit reads a batch at the requested sequence from a stored commit log root.

func (*File) ReadDocumentVersion

func (f *File) ReadDocumentVersion(reference DocumentVersionRef) ([]byte, error)

ReadDocumentVersion reads a document from the stored tree named by its version reference.

func (*File) ReclaimPages

func (f *File) ReclaimPages() (ReachabilityStats, error)

ReclaimPages makes unused pages available for future writes after checking all protected versions.

Pages retained by either valid metadata root or an active reader remain protected; this operation does not change the file on disk.

func (*File) ReclaimPagesContext

func (f *File) ReclaimPagesContext(ctx context.Context) (ReachabilityStats, error)

ReclaimPagesContext audits protected roots and marks unreachable pages reusable with cancellation support.

func (*File) ReclaimPagesOptimisticContext

func (f *File) ReclaimPagesOptimisticContext(ctx context.Context, maxAttempts int, persistFreeSpace bool) (ReachabilityStats, int, error)

ReclaimPagesOptimisticContext finds reusable pages without blocking writes during the scan.

Installation takes the writer mutex only long enough to prove that Meta generation, physical high-water mark and the previous free pool are unchanged. A concurrent commit causes a bounded retry rather than extending the commit pause across the full graph walk.

func (*File) RetainCommitsFrom

func (f *File) RetainCommitsFrom(keepFrom uint64, transactionID [16]byte, committedAt time.Time) (uint64, error)

RetainCommitsFrom removes older commits and records the retention change atomically.

Physical page reclamation remains a separate phase protected by reader pins.

func (*File) StorageStats

func (f *File) StorageStats() StorageStats

StorageStats returns a bounded snapshot intended for low-frequency admin sampling.

It does not traverse database trees or perform file IO.

func (*File) TreeGet

func (f *File) TreeGet(rootPage uint64, kind TreeKind, key []byte) ([]byte, bool, error)

TreeGet looks up a stored tree key and returns a copied value.

func (*File) TreeScan

func (f *File) TreeScan(rootPage uint64, kind TreeKind, start, end []byte, limit int) ([]KeyValue, error)

TreeScan collects copied entries from a stored tree within the requested range and limit.

func (*File) Update

func (f *File) Update(build func(*WriteTxn) (DatabaseRoot, error)) error

Update builds and publishes a new database version atomically.

The callback must not retain tx and must not perform network or user callbacks.

func (*File) ValidateCollectionPreconditions

func (f *File) ValidateCollectionPreconditions(preconditions []CollectionPrecondition) error

ValidateCollectionPreconditions checks recorded collection versions without committing changes.

ApplyDocumentTransaction performs the same validation inside its atomic write transaction, which is the required commit path for phantom-safe callers.

func (*File) ValidateDocumentPreconditions

func (f *File) ValidateDocumentPreconditions(preconditions []DocumentPrecondition) error

ValidateDocumentPreconditions checks recorded document reads against the current committed version.

type FinalizeIndexBuildTransaction

type FinalizeIndexBuildTransaction struct {
	BuildID                 [16]byte
	TransactionID           [16]byte
	ExpectedAppliedSequence uint64
	CommittedAt             time.Time
}

FinalizeIndexBuildTransaction publishes a build at its expected applied commit sequence.

type IndexAuditFunc

type IndexAuditFunc func(IndexMeta, [16]byte, []byte) (key []byte, indexed bool, err error)

IndexAuditFunc derives the expected index key from a stored document.

Only the offline verifier uses it; normal open, reachability, reclamation, and commit paths never invoke it.

type IndexBuildCatchUpBatch

type IndexBuildCatchUpBatch struct {
	BuildID                 [16]byte
	ExpectedAppliedSequence uint64
	ThroughSequence         uint64
	Mutations               []IndexBuildCatchUpMutation
	UpdatedAt               time.Time
}

IndexBuildCatchUpBatch advances a build through a contiguous range of source commits.

type IndexBuildCatchUpMutation

type IndexBuildCatchUpMutation struct {
	Sequence   uint64
	DocumentID [16]byte
	Operation  CommitOperation
	BeforeKey  []byte
	AfterKey   []byte
}

IndexBuildCatchUpMutation records index value changes for a document at one commit.

type IndexBuildFailure

type IndexBuildFailure uint8

IndexBuildFailure identifies why a persistent index build stopped.

const (
	// IndexBuildFailureNone marks a build with no recorded failure.
	IndexBuildFailureNone IndexBuildFailure = iota
	// IndexBuildFailureUniqueConflict marks duplicate values encountered in a unique index.
	IndexBuildFailureUniqueConflict
	// IndexBuildFailureResourceLimit marks a build stopped by a resource limit.
	IndexBuildFailureResourceLimit
	// IndexBuildFailureHistoryLost marks a build whose required replay history is unavailable.
	IndexBuildFailureHistoryLost
	// IndexBuildFailureCanceled marks a canceled build.
	IndexBuildFailureCanceled
	// IndexBuildFailureInvalidIndex marks a build rejected by index validation.
	IndexBuildFailureInvalidIndex
)

type IndexBuildMeta

type IndexBuildMeta struct {
	BuildID           [16]byte
	CollectionID      uint32
	Collection        string
	Name              string
	FieldPath         string
	Fields            []IndexField
	Unique            bool
	ReplaceExisting   bool
	Phase             IndexBuildPhase
	Failure           IndexBuildFailure
	SourceSequence    uint64
	SourceCatalogRoot uint64
	// AppliedCatalogRoot is the immutable catalog snapshot represented by the
	// shadow after catch-up advances beyond SourceSequence. Zero is the legacy
	// encoding and is equivalent to SourceCatalogRoot only while both sequences
	// are equal.
	AppliedCatalogRoot uint64
	ShadowRoot         uint64
	ScanAfter          [16]byte
	AppliedSequence    uint64
	EntryCount         uint64
	CanonicalBytes     uint64
	CreatedAt          time.Time
	UpdatedAt          time.Time
}

IndexBuildMeta records a persistent index build's definition, progress, and protected snapshots.

type IndexBuildPhase

type IndexBuildPhase uint8

IndexBuildPhase identifies the current stage of a persistent index build.

const (
	// IndexBuildScan marks a build scanning its source collection.
	IndexBuildScan IndexBuildPhase = 1 + iota
	// IndexBuildCatchUp marks a build applying commits after its source snapshot.
	IndexBuildCatchUp
	// IndexBuildReady marks a build ready for index publication.
	IndexBuildReady
	// IndexBuildFailed marks a build stopped by a recorded failure.
	IndexBuildFailed
)

type IndexBuildScanBatch

type IndexBuildScanBatch struct {
	BuildID           [16]byte
	ExpectedScanAfter [16]byte
	ScanAfter         [16]byte
	Entries           []IndexEntry
	Complete          bool
	UpdatedAt         time.Time
}

IndexBuildScanBatch adds source snapshot entries and advances an expected scan position.

type IndexEntry

type IndexEntry struct {
	Key               []byte
	InsertionPosition uint64
	DocumentID        [16]byte
}

IndexEntry links an encoded index value to a document and its insertion position.

type IndexField

type IndexField struct {
	Path      string
	Direction int8
}

IndexField describes a field path and its sort direction in an index key.

FieldPath on the surrounding metadata mirrors Fields[0].Path for compatibility.

type IndexIterator

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

IndexIterator reads index entries from a fixed database snapshot.

It owns an independent reader pin and is not safe for concurrent use.

func (*IndexIterator) Close

func (iterator *IndexIterator) Close() error

Close releases the index iterator and its snapshot pin.

func (*IndexIterator) Entry

func (iterator *IndexIterator) Entry() IndexEntry

Entry returns the current decoded index entry.

func (*IndexIterator) Err

func (iterator *IndexIterator) Err() error

Err returns the index iterator failure.

func (*IndexIterator) Next

func (iterator *IndexIterator) Next() bool

Next advances to the next index entry within the requested bounds.

type IndexMeta

type IndexMeta struct {
	Name            string
	FieldPath       string
	Fields          []IndexField
	Unique          bool
	Root            uint64
	EntryCount      uint64
	CreatedSequence uint64
	UpdatedSequence uint64
	KeyCodecVersion uint16
}

IndexMeta records an index definition, stored tree root, and commit versions.

func DecodeIndexMeta

func DecodeIndexMeta(name string, encoded []byte) (IndexMeta, error)

DecodeIndexMeta reads an index definition from a commit log catalog event.

This exposes the definition rather than a public contract for the physical catalog layout.

type IndexMutation

type IndexMutation struct {
	Name      string
	BeforeKey []byte
	AfterKey  []byte
}

IndexMutation describes the old and new index values for one document.

type KeyValue

type KeyValue struct {
	Key, Value []byte
}

KeyValue holds one tree entry's key and value bytes.

type LiveCommitStream

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

LiveCommitStream reads committed changes after a sequence as they become available.

It does not keep a per-subscriber event queue: waiters wake, read the current root, and replay their own next sequence from the durable Commit Log.

func (*LiveCommitStream) Close

func (stream *LiveCommitStream) Close() error

Close stops the commit stream and releases its reader pin.

func (*LiveCommitStream) Next

func (stream *LiveCommitStream) Next(ctx context.Context) (CommitBatch, error)

Next waits for and reads the next durable commit, or returns a cancellation or stream error.

func (*LiveCommitStream) ResolveChange

func (stream *LiveCommitStream) ResolveChange(change CommitChange) (ResolvedCommitChange, error)

ResolveChange loads document bytes for a change from the latest delivered live batch.

Calling Next again acknowledges that batch and may advance the replay retention lease, so callers must resolve all required images before Next.

type Meta

type Meta struct {
	DatabaseID             [16]byte
	Generation             uint64
	CommitSequence         uint64
	RootPage               uint64
	PhysicalPageCount      uint64
	OldestRetainedSequence uint64
	RequiredFeatures       uint64
	OptionalFeatures       uint64
}

Meta describes a published database version and its storage bounds.

func DecodeMeta

func DecodeMeta(page []byte) (Meta, error)

DecodeMeta validates and reads metadata in the supported format.

type MetaEnvelope

type MetaEnvelope struct {
	Revision          uint16
	HeaderSize        uint16
	PageSize          uint32
	DatabaseID        [16]byte
	Generation        uint64
	CommitSequence    uint64
	RootPage          uint64
	PhysicalPageCount uint64
	RequiredFeatures  uint64
	OptionalFeatures  uint64
}

MetaEnvelope holds the header fields used to identify a database file format.

These fields retain their byte positions across revisions and can be read from a checksum-valid future revision without interpreting its page graph.

func InspectMetaEnvelope

func InspectMetaEnvelope(page []byte) (MetaEnvelope, error)

InspectMetaEnvelope reads database header fields after checking the file signature and checksum.

It can read these fields even when the revision is newer than this binary. Callers must not treat it as validation of the referenced page graph.

type MutableTree

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

MutableTree edits a stored tree within one write transaction.

func (*MutableTree) Delete

func (tree *MutableTree) Delete(key []byte) (bool, error)

Delete removes a key using copy-on-write path mutation.

Empty children are eliminated and adjacent siblings are merged whenever the combined node fits; it never rebuilds the complete tree.

func (*MutableTree) Flush

func (tree *MutableTree) Flush() (uint64, error)

Flush writes changed tree nodes and returns the resulting root page.

func (*MutableTree) Get

func (tree *MutableTree) Get(key []byte) ([]byte, bool, error)

Get looks up a key and returns a copy of its value.

func (*MutableTree) Put

func (tree *MutableTree) Put(key, value []byte) error

Put inserts or replaces an entry, splitting nodes as needed.

func (*MutableTree) Scan

func (tree *MutableTree) Scan(start, end []byte, limit int) ([]KeyValue, error)

Scan returns keys in bytewise order in [start, end).

A nil bound is open and a non-positive limit is unbounded.

type OpenOptions

type OpenOptions struct {
	RequireClean bool
	// RequireGraphAudit verifies every page protected by either valid Meta root
	// before Open succeeds. It is deliberately opt-in: ordinary  startup is
	// metadata-only so large databases do not pay an unbounded open pause.
	// Unlike VerifyPathContext it is a structural audit only; callers needing
	// Secondary-to-document semantic proof must run the offline verifier.
	RequireGraphAudit bool
	// RequirePrivateFileMode rejects a database whose existing Unix permission
	// bits grant group or other access. It never chmods an operator-owned file:
	// callers choose this fail-closed boundary explicitly for deployments where
	// the database can contain secrets.
	RequirePrivateFileMode    bool
	ExpectedDatabaseID        [16]byte
	MinimumCommitSequence     uint64
	MinimumGeneration         uint64
	CommitRetentionMaxCommits uint64
	CommitRetentionMaxBytes   uint64
	MaxFileBytes              uint64
}

OpenOptions sets storage safety checks, retention limits, and file size bounds.

type OpenReport

type OpenReport struct {
	Created                bool
	SelectedMetaSlot       uint8
	ChecksumValidMetaSlots uint8
	RootValidMetaSlots     uint8
	MetaRedundancyDegraded bool
	FallbackToOlderRoot    bool
	TrailingBytesRemoved   uint64
	FreeSpaceLoadDegraded  bool
}

OpenReport describes only recovery decisions made while opening a file.

It contains no path or user data and is immutable after OpenWithReport returns.

type Page

type Page struct {
	Type         PageType
	Flags        uint8
	ID           uint64
	Generation   uint64
	BornSequence uint64
	ItemCount    uint32
	Link         uint64
	Payload      []byte
}

Page holds a data page header and its payload.

func DecodePage

func DecodePage(page []byte, expectedID uint64) (Page, error)

DecodePage validates a data page and copies its payload.

type PageCacheStats

type PageCacheStats struct {
	CapacityPages uint64
	ResidentPages uint64
	Hits          uint64
	Misses        uint64
	Evictions     uint64
}

PageCacheStats reports cache occupancy, hits, misses, and evictions.

type PageType

type PageType uint8

PageType identifies the kind of content stored in a page.

const (
	// PageDatabaseRoot marks the page containing database root pointers.
	PageDatabaseRoot PageType = 1 + iota
	// PageCatalogBranch marks an internal collection catalog node.
	PageCatalogBranch
	// PageCatalogLeaf marks a collection catalog leaf.
	PageCatalogLeaf
	// PagePrimaryBranch marks an internal document index node.
	PagePrimaryBranch
	// PagePrimaryLeaf marks a document index leaf.
	PagePrimaryLeaf
	// PageSecondaryBranch marks an internal secondary index node.
	PageSecondaryBranch
	// PageSecondaryLeaf marks a secondary index leaf.
	PageSecondaryLeaf
	// PageDocumentOverflow stores document bytes that do not fit in a leaf.
	PageDocumentOverflow
	// PageCommitLogBranch marks an internal commit log node.
	PageCommitLogBranch
	// PageCommitLogLeaf marks a commit log leaf.
	PageCommitLogLeaf
	// PageCommitOverflow stores commit bytes that do not fit in a leaf.
	PageCommitOverflow
	// PageFreeSpaceBranch marks an internal free space index node.
	PageFreeSpaceBranch
	// PageFreeSpaceLeaf marks a free space index leaf.
	PageFreeSpaceLeaf
	// PageIndexCatalogBranch marks an internal index definition catalog node.
	PageIndexCatalogBranch
	// PageIndexCatalogLeaf marks an index definition catalog leaf.
	PageIndexCatalogLeaf
	// PageOrderBranch marks an internal insertion order index node.
	PageOrderBranch
	// PageOrderLeaf marks an insertion order index leaf.
	PageOrderLeaf
	// PageSystemBranch marks an internal system record index node.
	PageSystemBranch
	// PageSystemLeaf marks a system record index leaf.
	PageSystemLeaf
	// PageSystemOverflow stores system record bytes that do not fit in a leaf.
	PageSystemOverflow
	// PageIndexBuildCatalogBranch marks an internal index build catalog node.
	PageIndexBuildCatalogBranch
	// PageIndexBuildCatalogLeaf marks an index build catalog leaf.
	PageIndexBuildCatalogLeaf
)

type PhysicalCopyResult

type PhysicalCopyResult struct {
	Meta   Meta
	Bytes  uint64
	SHA256 [32]byte
}

PhysicalCopyResult records the copied database version, byte count, and checksum.

type QualificationBoundary

type QualificationBoundary string

QualificationBoundary names a commit stage used by internal destructive tests.

This type is not a storage or application API contract.

const (
	// QualificationAfterPageWrite identifies the stage after staged pages are written.
	QualificationAfterPageWrite QualificationBoundary = "after-page-write"
	// QualificationBeforeDataSync identifies the stage before staged page data is synced.
	QualificationBeforeDataSync QualificationBoundary = "before-data-sync"
	// QualificationAfterDataSync identifies the stage after staged page data is synced.
	QualificationAfterDataSync QualificationBoundary = "after-data-sync"
	// QualificationAfterMetaWrite identifies the stage after publication metadata is written.
	QualificationAfterMetaWrite QualificationBoundary = "after-meta-write"
	// QualificationAfterMetaSync identifies the stage after publication metadata is synced.
	QualificationAfterMetaSync QualificationBoundary = "after-meta-sync"
)

type ReachabilityStats

type ReachabilityStats struct {
	PhysicalPages    uint64
	ReachablePages   uint64
	ReclaimablePages uint64
	PinnedSnapshots  uint64
}

ReachabilityStats counts stored, protected, and reusable pages and active snapshots.

type ReadSnapshot

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

ReadSnapshot keeps a fixed database version available for reading.

Reclamation must retain every page reachable through the snapshot until Close.

func (*ReadSnapshot) Close

func (snapshot *ReadSnapshot) Close() error

Close releases the snapshot's reader pin so its pages can eventually be reclaimed.

func (*ReadSnapshot) CollectionMeta

func (snapshot *ReadSnapshot) CollectionMeta(collection string) (CollectionMeta, bool, error)

CollectionMeta returns metadata from this snapshot's immutable CatalogRoot, including the stable numeric collection ID used by Commit Log changes.

func (*ReadSnapshot) Collections

func (snapshot *ReadSnapshot) Collections() ([]CollectionRecord, error)

Collections lists collection names and metadata from the pinned database version.

func (*ReadSnapshot) GetDocument

func (snapshot *ReadSnapshot) GetDocument(collection string, documentID [16]byte) ([]byte, bool, error)

GetDocument reads document bytes from the pinned database version.

func (*ReadSnapshot) GetDocumentRecord

func (snapshot *ReadSnapshot) GetDocumentRecord(collection string, documentID [16]byte) (DocumentRecord, bool, error)

GetDocumentRecord resolves one primary record including its stable insertion position, which query execution uses as the deterministic sort tie breaker.

func (*ReadSnapshot) IndexMeta

func (snapshot *ReadSnapshot) IndexMeta(collection, name string) (IndexMeta, bool, error)

IndexMeta reads one index definition from the pinned database version.

func (*ReadSnapshot) Indexes

func (snapshot *ReadSnapshot) Indexes(collection string) ([]IndexMeta, error)

Indexes lists the index definitions for a collection in the pinned database version.

func (*ReadSnapshot) OpenCollectionIterator

func (snapshot *ReadSnapshot) OpenCollectionIterator(collection string, start, end *[16]byte, limit int) (*DocumentIterator, error)

OpenCollectionIterator creates a bounded-memory scan over [start, end).

A nil bound is open and a non-positive limit is unbounded.

func (*ReadSnapshot) OpenIndexIterator

func (snapshot *ReadSnapshot) OpenIndexIterator(collection, name string, start, end []byte, limit int) (*IndexIterator, error)

OpenIndexIterator creates a bounded-memory Secondary scan over encoded scalar keys in [start, end).

The iterator owns a snapshot pin independently.

func (*ReadSnapshot) OpenInsertionOrderIterator

func (snapshot *ReadSnapshot) OpenInsertionOrderIterator(collection string, start, end *uint64, limit int) (*DocumentIterator, error)

OpenInsertionOrderIterator streams documents by their durable insertion position over [start, end).

It resolves every Order entry through the Primary tree from the same snapshot and owns an independent reader pin.

func (*ReadSnapshot) ReadCommit

func (snapshot *ReadSnapshot) ReadCommit(sequence uint64) (CommitBatch, error)

ReadCommit resolves one commit from this snapshot's pinned CommitLogRoot.

DocumentVersionRef values returned by it remain protected until Close.

func (*ReadSnapshot) ReadDocumentVersion

func (snapshot *ReadSnapshot) ReadDocumentVersion(reference DocumentVersionRef) ([]byte, error)

ReadDocumentVersion reads a version reference obtained from a commit in this same pinned snapshot.

The reader pin prevents reclamation/reuse of its Primary root while the version is decoded.

func (*ReadSnapshot) ScanCollection

func (snapshot *ReadSnapshot) ScanCollection(collection string, start, end *[16]byte, limit int) ([]DocumentRecord, error)

ScanCollection collects document records within the requested document ID range and limit.

func (*ReadSnapshot) ScanIndex

func (snapshot *ReadSnapshot) ScanIndex(collection, name string, start, end []byte, limit int) ([]IndexEntry, error)

ScanIndex returns entries whose encoded scalar key is in [start, end).

Nil bounds are open. DocumentID remains an implicit deterministic key suffix.

func (*ReadSnapshot) ScanSystemRecords

func (snapshot *ReadSnapshot) ScanSystemRecords(start, end []byte, limit int) ([]KeyValue, error)

ScanSystemRecords returns private records in bytewise [start,end) order.

A non-positive limit is unbounded. It exists for bounded first-party retention maintenance, not application queries.

func (*ReadSnapshot) Sequence

func (snapshot *ReadSnapshot) Sequence() uint64

Sequence returns the commit number fixed by the snapshot.

func (*ReadSnapshot) SystemRecords

func (snapshot *ReadSnapshot) SystemRecords() ([]KeyValue, error)

SystemRecords returns an isolated key/value snapshot for maintenance such as compact-to-new-file.

It is not exposed through the public collection API.

type ResolvedCommitChange

type ResolvedCommitChange struct {
	CollectionID uint32
	DocumentID   [16]byte
	Operation    CommitOperation
	ChangedPaths []string
	Before       []byte
	After        []byte
}

ResolvedCommitChange holds independent copies of a change and its before and after document bytes.

Empty images retain their operation-specific meaning (insert has no Before, delete has no After). ChangedPaths and image bytes never alias Commit Log or page-cache data.

type SortedTreeBuilder

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

SortedTreeBuilder builds an immutable tree from entries supplied in increasing key order.

Leaves are written as they fill, and Finish builds the remaining branch levels. This is the storage boundary used by index construction today and by a future external-merge source without changing catalog publication.

A builder belongs to one WriteTxn, is not concurrency-safe, and must not be retained after the transaction callback returns.

func (*SortedTreeBuilder) Add

func (builder *SortedTreeBuilder) Add(key, value []byte) error

Add copies one entry whose key must follow all previously added keys.

func (*SortedTreeBuilder) Finish

func (builder *SortedTreeBuilder) Finish() (uint64, error)

Finish completes the tree and returns its root page, failing if called again.

type StorageStats

type StorageStats struct {
	PageSize                   uint64
	Generation                 uint64
	PhysicalPages              uint64
	CommitSequence             uint64
	OldestRetainedSequence     uint64
	RetainedCommits            uint64
	CommitRetentionMax         uint64
	CommitRetentionOverage     uint64
	RetainedCommitBytes        uint64
	CommitRetentionMaxBytes    uint64
	CommitRetentionByteOverage uint64
	RetentionPrunedCommits     uint64
	RetentionPressureEvents    uint64
	RetentionPressure          bool
	StorageUsedBytes           uint64
	StorageMaxBytes            uint64
	StorageByteOverage         uint64
	StorageLimitRejections     uint64
	StorageQuotaExhausted      bool
	ActiveReaders              uint64
	ActiveReplayLeases         uint64
	DocumentCount              uint64
	CollectionCount            uint64
	ReusablePages              uint64
	TreeSplits                 uint64
	TreeMerges                 uint64
	PersistentFreeSpace        bool
	FreeSpaceLoads             uint64
	FreeSpaceLoadFailures      uint64
	FreeSpacePublishes         uint64
	FreeSpaceCandidateChecks   uint64
	PageCache                  PageCacheStats
}

StorageStats reports physical storage health without exposing application data.

type SystemRecordMutation

type SystemRecordMutation struct {
	Key            []byte
	ExpectedExists bool
	ExpectedHash   [32]byte
	NewValue       []byte
	Delete         bool
	Unconditional  bool
}

SystemRecordMutation is one compare-and-set change in the private system tree.

It is also reusable by composite storage transactions that publish business and control-plane state under one DatabaseRoot.

type SystemRecordResult

type SystemRecordResult struct {
	Sequence uint64
	Applied  bool
	Current  []byte
}

SystemRecordResult reports whether a record change committed and returns the current value on a mismatch.

type SystemRecordTransaction

type SystemRecordTransaction struct {
	TransactionID  [16]byte
	CommittedAt    time.Time
	Key            []byte
	ExpectedExists bool
	ExpectedHash   [32]byte
	NewValue       []byte
	Delete         bool
	Unconditional  bool
}

SystemRecordTransaction performs one compare-and-swap in the private system tree.

ExpectedHash is SHA-256 over the decoded current value when ExpectedExists is true. NewValue must be non-empty unless Delete is set.

type TreeIterator

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

TreeIterator reads an immutable tree in key order without collecting all results.

Key and Value point into validated immutable cached pages and remain valid until the iterator is closed or garbage collected. TreeIterator is not safe for concurrent use.

A raw TreeIterator does not pin a DatabaseRoot. Callers that can run page reclamation must hold a snapshot pin for its lifetime. DocumentIterator does this automatically.

func (*TreeIterator) Close

func (iterator *TreeIterator) Close() error

Close stops iteration and releases references to cached pages.

func (*TreeIterator) Err

func (iterator *TreeIterator) Err() error

Err returns the error that stopped iteration.

func (*TreeIterator) Key

func (iterator *TreeIterator) Key() []byte

Key returns the current key as a borrowed view of immutable page data.

func (*TreeIterator) Next

func (iterator *TreeIterator) Next() bool

Next advances to the next entry in bytewise key order within [start, end).

func (*TreeIterator) Value

func (iterator *TreeIterator) Value() []byte

Value returns the current value as a borrowed view of immutable page data.

type TreeKind

type TreeKind uint8

TreeKind identifies the purpose and page types of a stored tree.

const (
	// TreeCatalog identifies the collection catalog tree.
	TreeCatalog TreeKind = 1 + iota
	// TreePrimary identifies a document lookup tree.
	TreePrimary
	// TreeSecondary identifies a secondary index tree.
	TreeSecondary
	// TreeCommitLog identifies the commit history tree.
	TreeCommitLog
	// TreeIndexCatalog identifies an index definition catalog tree.
	TreeIndexCatalog
	// TreeOrder identifies a document insertion order tree.
	TreeOrder
	// TreeSystem identifies a private system record tree.
	TreeSystem
	// TreeFreeSpace identifies the reusable page index tree.
	TreeFreeSpace
	// TreeIndexBuildCatalog identifies the persistent index build catalog tree.
	TreeIndexBuildCatalog
)

type VerificationResult

type VerificationResult struct {
	Meta                        Meta
	FileBytes                   uint64
	TrailingBytes               uint64
	PhysicalPages               uint64
	ReachablePages              uint64
	ReclaimablePages            uint64
	ValidMetaSlots              int
	PersistentFreeSpace         bool
	FreeSpaceValid              bool
	SemanticIndexesVerified     bool
	SemanticIndexBuildsVerified bool
	SHA256                      [sha256.Size]byte
}

VerificationResult records the results of checking all protected database pages.

ReachablePages excludes the two Meta pages and optional FreeSpace acceleration pages, matching ReachabilityStats.

func VerifyPathContext

func VerifyPathContext(ctx context.Context, path string) (result VerificationResult, resultErr error)

VerifyPathContext audits an existing database file under a shared read-only lock.

It never creates, truncates, repairs, reclaims, or publishes a generation. A running writer's exclusive lock prevents verification from starting.

func VerifyPathContextWithIndexAudit

func VerifyPathContextWithIndexAudit(ctx context.Context, path string, indexAudit IndexAuditFunc) (result VerificationResult, resultErr error)

VerifyPathContextWithIndexAudit audits a database and optionally verifies index keys against stored documents.

The callback runs under the offline shared lock and must be deterministic, bounded, and free of side effects.

type WriteTxn

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

WriteTxn stages immutable pages in memory.

Nothing becomes visible until the DatabaseRoot and inactive MetaPage are durably published by File.Update.

func (*WriteTxn) AppendCommit

func (tx *WriteTxn) AppendCommit(rootPage uint64, batch CommitBatch) (uint64, error)

AppendCommit stores one complete batch of changes in the commit log.

It must be called inside the File.Update callback for the same sequence.

func (*WriteTxn) AppendCommitRetained

func (tx *WriteTxn) AppendCommitRetained(rootPage, oldest uint64, batch CommitBatch) (uint64, uint64, error)

AppendCommitRetained stores a commit and removes expired history in the same database update.

Active replay pins limit how much history can expire; the configured window never removes commits still needed by a reader.

func (*WriteTxn) BaseRoot

func (tx *WriteTxn) BaseRoot() DatabaseRoot

BaseRoot returns the committed database root from which the transaction started.

func (*WriteTxn) NewSortedTreeBuilder

func (tx *WriteTxn) NewSortedTreeBuilder(kind TreeKind) (*SortedTreeBuilder, error)

NewSortedTreeBuilder starts an empty immutable tree build.

func (*WriteTxn) OpenTree

func (tx *WriteTxn) OpenTree(rootPage uint64, kind TreeKind) (*MutableTree, error)

OpenTree opens a stored tree for editing or creates an empty tree for a zero root.

func (*WriteTxn) Sequence

func (tx *WriteTxn) Sequence() uint64

Sequence returns the logical commit number being built by the transaction.

Jump to

Keyboard shortcuts

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