database

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: 33 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 database implements the Meldbase database API behind the module-root public package.

Index

Constants

View Source
const (
	// IndexBuildPhaseScan marks a build scanning its initial document snapshot.
	IndexBuildPhaseScan IndexBuildPhase = "scan"
	// IndexBuildPhaseCatchUp marks a build applying changes after its initial snapshot.
	IndexBuildPhaseCatchUp IndexBuildPhase = "catch_up"
	// IndexBuildPhaseReady marks a build ready for publication.
	IndexBuildPhaseReady IndexBuildPhase = "ready"
	// IndexBuildPhaseFailed marks a build that stopped with a terminal failure.
	IndexBuildPhaseFailed IndexBuildPhase = "failed"

	// IndexBuildFailureNone marks the absence of an index-build failure.
	IndexBuildFailureNone IndexBuildFailure = ""
	// IndexBuildFailureUniqueConflict marks a duplicate key found while building a unique index.
	IndexBuildFailureUniqueConflict IndexBuildFailure = "unique_conflict"
	// IndexBuildFailureResourceLimit marks an index build that exceeded a resource limit.
	IndexBuildFailureResourceLimit IndexBuildFailure = "resource_limit"
	// IndexBuildFailureHistoryLost marks a build whose required change history was lost.
	IndexBuildFailureHistoryLost IndexBuildFailure = "history_lost"
	// IndexBuildFailureCanceled marks a canceled index build.
	IndexBuildFailureCanceled IndexBuildFailure = "canceled"
	// IndexBuildFailureInvalidIndex marks a build with invalid index data.
	IndexBuildFailureInvalidIndex IndexBuildFailure = "invalid_index"
)
View Source
const (
	// DefaultCommitCoordinatorMaxBatch sets the default maximum number of writes in a commit group.
	DefaultCommitCoordinatorMaxBatch = 32
	// DefaultCommitCoordinatorMaxPending sets the default maximum number of queued writes.
	DefaultCommitCoordinatorMaxPending = 1024
)
View Source
const (
	// PageSize sets the byte size of each storage page.
	PageSize uint64 = 16 << 10
	// DefaultMaxFileBytes sets the default physical database file size limit.
	DefaultMaxFileBytes uint64 = 8 << 30
)
View Source
const (
	// DefaultCommitRetentionMaxCommits sets the default retained commit count limit.
	DefaultCommitRetentionMaxCommits uint64 = 10_000
	// DefaultCommitRetentionMaxBytes sets the default retained commit payload limit.
	DefaultCommitRetentionMaxBytes uint64 = 256 << 20
	// DefaultReplayDeliveryTimeout limits how long replay waits to deliver into a full buffer.
	//
	// A delivery timeout releases the retained-history lease.
	DefaultReplayDeliveryTimeout = 5 * time.Second
)
View Source
const (
	// ReplicationHelloFrame identifies a replication handshake frame.
	ReplicationHelloFrame = "hello"
	// ReplicationBatchFrame identifies a replication change-batch frame.
	ReplicationBatchFrame = "batch"
	// ReplicationAckFrame identifies a durable replication acknowledgment.
	ReplicationAckFrame = "ack"
	// ReplicationResyncFrame identifies a request to rebuild a replica from a snapshot.
	ReplicationResyncFrame = "resync_required"
)
View Source
const (
	// DefaultMaxDocumentBytes sets the default canonical document byte limit.
	DefaultMaxDocumentBytes uint64 = 16 << 20
	// DefaultMaxTransactionBytes sets the default canonical transaction byte limit.
	DefaultMaxTransactionBytes uint64 = 64 << 20
	// DefaultMaxTransactionChanges sets the default transaction change count limit.
	DefaultMaxTransactionChanges uint64 = 10_000
	// DefaultMaxIndexBuildEntries sets the default index-build entry count limit.
	DefaultMaxIndexBuildEntries uint64 = 1_000_000
	// DefaultMaxIndexBuildBytes sets the default index-build byte limit.
	DefaultMaxIndexBuildBytes uint64 = 256 << 20
	// DefaultMaxReactiveViewDocuments sets the default number of document versions retained by a live query.
	//
	// Views retain matching versions for incremental ordering and updates,
	// not merely the page currently emitted to a subscriber.
	DefaultMaxReactiveViewDocuments uint64 = 10_000
	// DefaultMaxReactiveViewBytes sets the default retained live query byte limit.
	DefaultMaxReactiveViewBytes uint64 = 64 << 20
	// DefaultMaxQueryDocumentsExamined sets the default examined document limit per query.
	DefaultMaxQueryDocumentsExamined uint64 = 100_000
	// DefaultMaxQueryKeysExamined sets the default examined index key limit per query.
	DefaultMaxQueryKeysExamined uint64 = 100_000
	// DefaultMaxQueryCandidates sets the default retained query candidate limit.
	DefaultMaxQueryCandidates uint64 = 100_000
	// DefaultMaxQuerySortBytes sets the default retained sort data byte limit.
	DefaultMaxQuerySortBytes uint64 = 64 << 20
	// DefaultMaxQuerySkip sets the default query offset limit.
	DefaultMaxQuerySkip uint64 = 100_000
	// DefaultMaxQueryPredicateSteps sets the default number of filter evaluation steps per query.
	//
	// Steps include expression visits and data-dependent comparisons such as
	// scalar membership within stored arrays, bounding work beyond scan counts.
	DefaultMaxQueryPredicateSteps uint64 = 10_000_000
)
View Source
const DefaultCommitCoordinatorMaxDelay = time.Millisecond

DefaultCommitCoordinatorMaxDelay sets the default wait for grouping queued writes.

View Source
const (
	// DefaultReplicationMaxFrameBytes sets the default replication frame byte limit.
	DefaultReplicationMaxFrameBytes = 96 << 20
)
View Source
const DefaultRollbackAnchorOperationTimeout = 10 * time.Second

DefaultRollbackAnchorOperationTimeout limits how long a rollback anchor operation may delay a commit response.

View Source
const ReplicationProtocolVersion = 1

ReplicationProtocolVersion identifies the protocol for replicating commits between trusted servers.

This version is separate from the browser realtime subscription protocol.

Variables

View Source
var (
	// ErrClosed reports that the database is closed.
	ErrClosed = errors.New("meldbase: database is closed")
	// ErrInvalidDocument reports an invalid document.
	ErrInvalidDocument = errors.New("meldbase: invalid document")
	// ErrInvalidFilter reports an invalid filter.
	ErrInvalidFilter = errors.New("meldbase: invalid filter")
	// ErrInvalidUpdate reports an invalid update.
	ErrInvalidUpdate = errors.New("meldbase: invalid update")
	// ErrMutationLimit reports that a mutation exceeded its affected-row limit.
	ErrMutationLimit = errors.New("meldbase: mutation affected-row limit exceeded")
	// ErrWriteConflict reports that the write transaction snapshot conflicted.
	ErrWriteConflict = errors.New("meldbase: write transaction snapshot conflicted")
	// ErrWriteTransactionUnsupported reports that write transactions require a durable database.
	ErrWriteTransactionUnsupported = errors.New("meldbase: write transactions require a durable database")
	// ErrNotFound reports that the document was not found.
	ErrNotFound = errors.New("meldbase: document not found")
	// ErrDuplicateID reports a duplicate document ID.
	ErrDuplicateID = errors.New("meldbase: duplicate document id")
	// ErrInvalidCollection reports an invalid collection name.
	ErrInvalidCollection = errors.New("meldbase: invalid collection")
	// ErrImmutableID reports that _id is immutable.
	ErrImmutableID = errors.New("meldbase: _id is immutable")
	// ErrSlowConsumer reports that the change consumer is too slow.
	ErrSlowConsumer = errors.New("meldbase: change consumer is too slow")
	// ErrCorrupt reports database corruption.
	ErrCorrupt = errors.New("meldbase: corrupt database")
	// ErrUnsupportedFormat reports an unsupported storage format or required feature.
	ErrUnsupportedFormat = errors.New("meldbase: unsupported storage format or required feature")
	// ErrDuplicateKey reports a duplicate index key.
	ErrDuplicateKey = errors.New("meldbase: duplicate index key")
	// ErrInvalidIndex reports an invalid index definition.
	ErrInvalidIndex = errors.New("meldbase: invalid index")
	// ErrCompoundIndexUnsupported reports that compound or descending indexes are unsupported.
	ErrCompoundIndexUnsupported = errors.New("meldbase: compound or descending indexes are unsupported")
	// ErrDurability reports a durability failure that disables writes.
	ErrDurability = errors.New("meldbase: durability failure; writes are disabled")
	// ErrInvalidDelta reports an invalid query delta.
	ErrInvalidDelta = errors.New("meldbase: invalid query delta")
	// ErrHistoryLost reports that the requested history is no longer retained.
	ErrHistoryLost = errors.New("meldbase: requested history is no longer retained")
	// ErrDestinationExists reports that the destination already exists.
	ErrDestinationExists = errors.New("meldbase: destination already exists")
	// ErrCompactionUnsupported reports that compaction requires an open durable database.
	ErrCompactionUnsupported = errors.New("meldbase: compaction requires an open durable database")
	// ErrCompactionDestinationExists reports that the compaction destination already exists.
	ErrCompactionDestinationExists = errors.New("meldbase: compaction destination already exists")
	// ErrReclamationUnsupported reports that page reclamation requires an open durable database.
	ErrReclamationUnsupported = errors.New("meldbase: page reclamation requires an open durable database")
	// ErrInvalidReclamationOptions reports invalid reclamation options.
	ErrInvalidReclamationOptions = errors.New("meldbase: invalid reclamation options")
	// ErrReclamationConflict reports that the online reclamation conflicted with concurrent writes.
	ErrReclamationConflict = errors.New("meldbase: online reclamation conflicted with concurrent writes")
	// ErrBackupUnsupported reports that physical backup requires an open durable database.
	ErrBackupUnsupported = errors.New("meldbase: physical backup requires an open durable database")
	// ErrBackupDestinationExists reports that the backup destination already exists or is the source.
	ErrBackupDestinationExists = errors.New("meldbase: backup destination already exists or is the source")
	// ErrLogicalArchiveUnsupported reports that logical archive requires an open durable database.
	ErrLogicalArchiveUnsupported = errors.New("meldbase: logical archive requires an open durable database")
	// ErrLogicalArchiveDestinationExists reports that the logical archive destination already exists or is the source.
	ErrLogicalArchiveDestinationExists = errors.New("meldbase: logical archive destination already exists or is the source")
	// ErrVerificationUnsupported reports that verification requires an existing database.
	ErrVerificationUnsupported = errors.New("meldbase: verification requires an existing database")
	// ErrDatabaseLocked reports that the database is locked by another process.
	ErrDatabaseLocked = errors.New("meldbase: database is locked by another process")
	// ErrRollbackDetected reports that the database was rolled back.
	ErrRollbackDetected = errors.New("meldbase: database rollback detected")
	// ErrDatabaseIdentity reports an unexpected database identity.
	ErrDatabaseIdentity = errors.New("meldbase: unexpected database identity")
	// ErrInsecureFileMode reports that the database file permissions are not owner-private.
	ErrInsecureFileMode = errors.New("meldbase: database file permissions are not owner-private")
	// ErrRollbackAnchorRequired reports that the rollback anchor is missing; explicit initialization is required.
	ErrRollbackAnchorRequired = errors.New("meldbase: rollback anchor is missing; explicit initialization is required")
	// ErrRollbackAnchor reports a failure to persist the rollback anchor.
	ErrRollbackAnchor = errors.New("meldbase: rollback anchor durability failure")
	// ErrInvalidRollbackProtection reports invalid rollback protection options.
	ErrInvalidRollbackProtection = errors.New("meldbase: invalid rollback protection options")
	// ErrRecoveryRequired reports that the selected policy requires startup recovery.
	ErrRecoveryRequired = errors.New("meldbase: startup recovery required by the selected policy")
	// ErrInvalidResourceLimits reports invalid resource limits.
	ErrInvalidResourceLimits = errors.New("meldbase: invalid resource limits")
	// ErrResourceLimit reports that an operation exceeded a resource limit.
	ErrResourceLimit = errors.New("meldbase: resource limit exceeded")
	// ErrQueryBudget reports that the query exceeded its execution budget.
	ErrQueryBudget = errors.New("meldbase: query execution budget exceeded")
	// ErrIndexBuildUnsupported reports that resumable index builds require a durable database.
	ErrIndexBuildUnsupported = errors.New("meldbase: resumable index builds require a durable database")
	// ErrIndexBuildNotFound reports that the index build was not found.
	ErrIndexBuildNotFound = errors.New("meldbase: index build not found")
	// ErrIndexBuildExists reports that the index build already exists.
	ErrIndexBuildExists = errors.New("meldbase: index build already exists")
	// ErrIndexBuildFailed reports that the index build is in a terminal failed state.
	ErrIndexBuildFailed = errors.New("meldbase: index build is in a terminal failed state")
	// ErrInvalidIndexBuildSchedulerOptions reports invalid index build scheduler options.
	ErrInvalidIndexBuildSchedulerOptions = errors.New("meldbase: invalid index build scheduler options")
	// ErrIndexBuildSchedulerRunning reports that the index build scheduler is already running.
	ErrIndexBuildSchedulerRunning = errors.New("meldbase: index build scheduler already running")
	// ErrInvalidCommitCoordinatorOptions reports invalid commit coordinator options.
	ErrInvalidCommitCoordinatorOptions = errors.New("meldbase: invalid commit coordinator options")
	// ErrInvalidReplayDeliveryTimeout reports invalid replay delivery timeout.
	ErrInvalidReplayDeliveryTimeout = errors.New("meldbase: invalid replay delivery timeout")
	// ErrDurableConsumerUnsupported reports that durable change consumers require a durable database.
	ErrDurableConsumerUnsupported = errors.New("meldbase: durable change consumers require a durable database")
	// ErrDurableConsumerExists reports that the durable change consumer already exists.
	ErrDurableConsumerExists = errors.New("meldbase: durable change consumer already exists")
	// ErrDurableConsumerNotFound reports that the durable change consumer was not found.
	ErrDurableConsumerNotFound = errors.New("meldbase: durable change consumer not found")
	// ErrReplicaReadOnly reports that the follower is read-only.
	ErrReplicaReadOnly = errors.New("meldbase: follower is read-only")
	// ErrReplicaSequence reports that the follower change token is not the next sequence.
	ErrReplicaSequence = errors.New("meldbase: follower change token is not the next sequence")
	// ErrReplicaProtocol reports an invalid replication protocol frame.
	ErrReplicaProtocol = errors.New("meldbase: invalid replication protocol frame")
	// ErrReplicaSourceActive reports that the replication source consumer already has an active session.
	ErrReplicaSourceActive = errors.New("meldbase: replication source consumer already has an active session")
	// ErrReplicaPromotionAuthority reports that the follower promotion requires an external fencing authority.
	ErrReplicaPromotionAuthority = errors.New("meldbase: follower promotion requires an external fencing authority")
	// ErrReplicaPromotionFence reports that the follower promotion fence does not match local state.
	ErrReplicaPromotionFence = errors.New("meldbase: follower promotion fence does not match local state")
	// ErrReplicaPromotionWriteFence reports that the follower promotion requires a configured primary write fence.
	ErrReplicaPromotionWriteFence = errors.New("meldbase: follower promotion requires a configured primary write fence")
	// ErrReplicaPromoted reports that the follower has been promoted and no longer accepts replication.
	ErrReplicaPromoted = errors.New("meldbase: follower has been promoted and no longer accepts replication")
	// ErrPrimaryWriteFence reports that the primary write fence rejected the commit.
	ErrPrimaryWriteFence = errors.New("meldbase: primary write fence rejected the commit")
	// ErrCommitOutcomeUnknown reports that an admitted write has no confirmed result.
	//
	// Callers must reconcile by the returned document IDs instead of retrying blindly.
	ErrCommitOutcomeUnknown = errors.New("meldbase: commit outcome is unknown; do not retry blindly")
)
View Source
var DefaultQueryLimits = QueryLimits{
	MaxWireBytes: 1 << 20, MaxDepth: 16, MaxNodes: 128,
	MaxArrayItems: 256, MaxValueBytes: 16_384, MaxSortFields: 4,
	MaxLimit: 10_000,
}

DefaultQueryLimits provides the default query input limits.

View Source
var (
	// ErrDiagnosticsActive reports that a diagnostics session is already active.
	ErrDiagnosticsActive = errors.New("meldbase: diagnostics are already active")
)

Functions

func MarshalQuerySpecJSON

func MarshalQuerySpecJSON(query QuerySpec) ([]byte, error)

MarshalQuerySpecJSON validates a query and encodes its canonical JSON representation.

The encoded query is used for transport fingerprints and cross-language conformance.

func MarshalReplicationFrame

func MarshalReplicationFrame(frame ReplicationFrame, limits ReplicationFrameLimits) ([]byte, error)

MarshalReplicationFrame validates and encodes a replication message as bounded JSON.

Document images use base64 of the storage-independent typed document codec. It is suitable for WebSocket binary/text messages, QUIC streams or framed RPC, but it does not provide authentication or encryption itself.

func MarshalWireDocument

func MarshalWireDocument(document Document) ([]byte, error)

MarshalWireDocument encodes a document as typed wire JSON.

func MarshalWireValue

func MarshalWireValue(value Value) ([]byte, error)

MarshalWireValue encodes a typed value as wire JSON.

func ValidateStrictJSON

func ValidateStrictJSON(data []byte, maxBytes int) error

ValidateStrictJSON rejects oversized, trailing, deeply nested, and duplicate-key JSON before a transport decodes it into structs or maps.

Types

type ArchiveBootstrap

type ArchiveBootstrap struct {
	Backup          BackupResult
	CheckpointToken uint64
	SnapshotToken   uint64
}

ArchiveBootstrap binds an exact verified physical snapshot to the durable database change feed that was pinned before that snapshot began.

A receiver must persist and verify Backup, then drain and Ack every batch up through SnapshotToken without applying it (the snapshot already contains those effects). It can then apply and Ack later batches in order. This avoids the bootstrap/tail gap without inventing a second, weaker history contract.

type BackupResult

type BackupResult struct {
	Bytes          uint64 `json:"bytes"`
	Pages          uint64 `json:"pages"`
	CommitSequence uint64 `json:"commitSequence"`
	MetaGeneration uint64 `json:"metaGeneration"`
	DatabaseIDHex  string `json:"databaseIdHex"`
	SHA256         string `json:"sha256"`
}

BackupResult records the identity, size, and checksum of a physical backup.

func ImportPhysicalBackup

func ImportPhysicalBackup(ctx context.Context, source io.Reader, destination string, expected BackupResult, options PhysicalBackupImportOptions) (BackupResult, error)

ImportPhysicalBackup verifies a physical backup stream and publishes it at a new path.

It writes a private temporary file, checks the claimed byte count and SHA-256 while streaming, verifies the stored page structure and index contents, then publishes without overwriting an existing file and syncs the directory.

source is intentionally transport-neutral. A WebSocket, HTTP response, QUIC stream, or removable-media reader may supply it, but transport cancellation must close or honor ctx itself: a generic io.Reader cannot be interrupted while blocked in Read. The destination is never opened as a writable DB by this function; callers normally open the successfully imported file through OpenFollower before applying a replication tail.

type BackupStats

type BackupStats struct {
	Active       uint64        `json:"active"`
	Attempts     uint64        `json:"attempts"`
	Completed    uint64        `json:"completed"`
	Failed       uint64        `json:"failed"`
	LastBytes    uint64        `json:"lastBytes"`
	LastDuration time.Duration `json:"lastDurationNanos"`
}

BackupStats reports backup activity, sizes, and outcomes.

type Change

type Change struct {
	Collection string
	Operation  Operation
	DocumentID DocumentID
	Before     *Document
	After      *Document
	Index      *IndexDefinition

	// ChangedPaths is the sorted, deduplicated set of document paths changed by
	// an Update operation when the writer can prove it. A nil value means the
	// changed field set is unknown and consumers must conservatively treat the
	// whole document as affected. Insert, delete and catalog changes intentionally
	// use that conservative form: their membership and visible payload may change
	// through any query path.
	//
	// The slice is immutable once a Change enters the dispatcher. Public watcher
	// deliveries receive an independent copy via cloneChange.
	ChangedPaths []string
	// contains filtered or unexported fields
}

Change records a document or catalog edit at a commit.

type ChangeBatch

type ChangeBatch struct {
	Token   uint64
	Changes []Change
}

ChangeBatch groups changes under one ordered commit token.

type Collection

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

Collection provides document operations for one named collection.

func (*Collection) CreateIndex

func (c *Collection) CreateIndex(ctx context.Context, name string, fields []IndexField, options IndexOptions) error

CreateIndex builds and commits a named index over the collection.

func (*Collection) CreateIndexOnline

func (c *Collection) CreateIndexOnline(ctx context.Context, name string, fields []IndexField, options IndexOptions) (IndexBuildID, error)

CreateIndexOnline creates and runs a resumable index build until publication or interruption.

Context cancellation leaves the returned build discoverable through IndexBuilds; use StartIndexBuild when the ID must be known before execution.

func (*Collection) DeleteMany

func (c *Collection) DeleteMany(ctx context.Context, filter Filter) (DeleteResult, error)

DeleteMany atomically removes all documents matching the filter.

func (*Collection) DeleteManyQuery

func (c *Collection) DeleteManyQuery(ctx context.Context, query QuerySpec) (DeleteResult, error)

DeleteManyQuery atomically removes all documents matching a compiled query.

func (*Collection) DeleteManyQueryLimited

func (c *Collection) DeleteManyQueryLimited(ctx context.Context, query QuerySpec, maxAffected int) (DeleteResult, error)

DeleteManyQueryLimited deletes matches only when their count stays within maxAffected.

func (*Collection) DeleteOne

func (c *Collection) DeleteOne(ctx context.Context, filter Filter) (DeleteResult, error)

DeleteOne removes the first document matching the filter.

func (*Collection) DeleteOneQuery

func (c *Collection) DeleteOneQuery(ctx context.Context, query QuerySpec) (DeleteResult, error)

DeleteOneQuery removes the first document matching a compiled query.

func (*Collection) Explain

func (c *Collection) Explain(ctx context.Context, filter Filter) (ExplainResult, error)

Explain executes a filter query and reports its access plan and observed work.

func (*Collection) ExplainQuery

func (c *Collection) ExplainQuery(ctx context.Context, query QuerySpec) (ExplainResult, error)

ExplainQuery executes a compiled query and reports its plan and measured work.

It validates the same query used by FindQuery, including sort, skip, limit, and seek options.

func (*Collection) ExplainWithOptions

func (c *Collection) ExplainWithOptions(ctx context.Context, filter Filter, options QueryOptions) (ExplainResult, error)

ExplainWithOptions executes a filter with query options and reports its plan and measured work.

func (*Collection) Find

func (c *Collection) Find(ctx context.Context, filter Filter, options ...QueryOptions) (*Cursor, error)

Find compiles a filter and optional pagination settings into a result cursor.

func (*Collection) FindOne

func (c *Collection) FindOne(ctx context.Context, filter Filter) (Document, error)

FindOne returns the first matching document or ErrNotFound.

func (*Collection) FindQuery

func (c *Collection) FindQuery(ctx context.Context, query QuerySpec) (*Cursor, error)

FindQuery opens a result cursor for a validated compiled query.

func (*Collection) InsertMany

func (c *Collection) InsertMany(ctx context.Context, documents []Document) ([]DocumentID, error)

InsertMany validates and atomically inserts a batch of copied documents.

func (*Collection) InsertOne

func (c *Collection) InsertOne(ctx context.Context, document Document) (DocumentID, error)

InsertOne inserts one document and returns its assigned ID.

func (*Collection) RebuildIndexOnline

func (c *Collection) RebuildIndexOnline(ctx context.Context, name string, fields []IndexField, options IndexOptions) (IndexBuildID, error)

RebuildIndexOnline builds and atomically publishes a replacement for an existing durable index.

A cancellation leaves the old index published and the private replacement discoverable through IndexBuilds.

func (*Collection) SnapshotQuery

func (c *Collection) SnapshotQuery(ctx context.Context, query QuerySpec) (QuerySnapshot, error)

SnapshotQuery reads query results and their token from the same committed state.

func (*Collection) StartIndexBuild

func (c *Collection) StartIndexBuild(ctx context.Context, name string, fields []IndexField, options IndexOptions) (IndexBuildID, error)

StartIndexBuild creates a stored, resumable build for a new index.

It requires a durable database and does not yet scan documents or expose the index to queries.

func (*Collection) StartIndexRebuild

func (c *Collection) StartIndexRebuild(ctx context.Context, name string, fields []IndexField, options IndexOptions) (IndexBuildID, error)

StartIndexRebuild creates a resumable build to replace a published index with the same name.

The old index remains available to queries until atomic publication of its replacement; the build can be resumed or aborted.

func (*Collection) SubscribeQuery

func (c *Collection) SubscribeQuery(ctx context.Context, query QuerySpec, buffer int) (*QuerySubscription, error)

SubscribeQuery starts a bounded stream of full snapshots for a compiled query.

func (*Collection) SubscribeQueryDeltas

func (c *Collection) SubscribeQueryDeltas(ctx context.Context, query QuerySpec, buffer int) (*QueryDeltaSubscription, error)

SubscribeQueryDeltas returns an initial snapshot and a bounded stream of ordered changes.

func (*Collection) UpdateMany

func (c *Collection) UpdateMany(ctx context.Context, filter Filter, update Update) (UpdateResult, error)

UpdateMany atomically applies an update to all documents matching the filter.

func (*Collection) UpdateManyQuery

func (c *Collection) UpdateManyQuery(ctx context.Context, query QuerySpec, mutation MutationSpec) (UpdateResult, error)

UpdateManyQuery atomically applies a compiled mutation to all matching documents.

func (*Collection) UpdateManyQueryLimited

func (c *Collection) UpdateManyQueryLimited(ctx context.Context, query QuerySpec, mutation MutationSpec, maxAffected int) (UpdateResult, error)

UpdateManyQueryLimited updates matching documents only if their count stays within maxAffected.

A non-positive limit is invalid, and exceeding it rejects the whole mutation.

func (*Collection) UpdateOne

func (c *Collection) UpdateOne(ctx context.Context, filter Filter, update Update) (UpdateResult, error)

UpdateOne applies an update to the first document matching the filter.

func (*Collection) UpdateOneQuery

func (c *Collection) UpdateOneQuery(ctx context.Context, query QuerySpec, mutation MutationSpec) (UpdateResult, error)

UpdateOneQuery applies a compiled mutation to the first document matching the query.

type CommitCoordinatorOptions

type CommitCoordinatorOptions struct {
	Enabled    bool
	MaxBatch   int
	MaxPending int
	MaxDelay   time.Duration
}

CommitCoordinatorOptions sets the queue and batch limits for optional grouped writes.

Grouping is disabled by default.

A coordinator group publishes one stored database version but retains one logical commit token for every admitted write request, including prepared public write transactions. Index builds and other maintenance operations remain exclusive commits. When rollback protection is configured, the coordinator advances the external anchor after the group's stored version is durable and before acknowledging any member.

type CommitCoordinatorStats

type CommitCoordinatorStats struct {
	Enabled             bool   `json:"enabled"`
	Pending             uint64 `json:"pending"`
	PendingCapacity     uint64 `json:"pendingCapacity"`
	Admitted            uint64 `json:"admitted"`
	AdmissionRejected   uint64 `json:"admissionRejected"`
	Batches             uint64 `json:"batches"`
	GroupedTransactions uint64 `json:"groupedTransactions"`
	OutcomeUnknown      uint64 `json:"outcomeUnknown"`
}

CommitCoordinatorStats reports queued writes, admission decisions, and commit groups.

DBStats and the versioned admin schema expose these bounded counters so applications can alert on queue pressure without inspecting the queue.

type CommitRetentionPolicy

type CommitRetentionPolicy struct {
	MaxCommits uint64
	MaxBytes   uint64
}

CommitRetentionPolicy limits retained history by commit count and encoded byte size.

Zero fields select production defaults. Active replay leases may temporarily exceed either budget rather than losing history under a reader.

type CommitStats

type CommitStats struct {
	Total   uint64 `json:"total"`
	Changes uint64 `json:"changes"`
}

CommitStats counts committed batches and their changes.

type CompactionOptions

type CompactionOptions struct {
	StorageLimits  StorageLimits
	ResourceLimits ResourceLimits
}

CompactionOptions sets storage and resource limits for a rewritten database.

ResourceLimits govern transient index construction as well as the reopened destination handle; zero fields select production defaults.

type CompactionStats

type CompactionStats struct {
	Active       uint64        `json:"active"`
	Attempts     uint64        `json:"attempts"`
	Completed    uint64        `json:"completed"`
	Failed       uint64        `json:"failed"`
	InputBytes   uint64        `json:"inputBytes"`
	OutputBytes  uint64        `json:"outputBytes"`
	LastDuration time.Duration `json:"lastDurationNanos"`
}

CompactionStats reports compaction activity, byte counts, and outcomes.

type Cursor

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

Cursor reads query results and releases their resources when closed.

func (*Cursor) All

func (c *Cursor) All(ctx context.Context) ([]Document, error)

All collects and consumes the remaining cursor results.

func (*Cursor) Close

func (c *Cursor) Close() error

Close releases cursor resources and is safe to call repeatedly.

Exhaustion, limit completion, errors, and context cancellation close lazy cursors automatically; callers that stop early must close explicitly.

func (*Cursor) Next

func (c *Cursor) Next(ctx context.Context) (Document, bool, error)

Next returns the next query result and reports whether a document was returned.

type DB

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

DB owns an in-memory or durable document database.

func New

func New() *DB

New creates an in-memory database with default limits.

func NewWithOptions

func NewWithOptions(options DatabaseOptions) (*DB, error)

NewWithOptions creates an in-memory database with explicit resource limits.

func Open

func Open(path string) (*DB, error)

Open creates or opens a Meldbase durable database in the current format.

func OpenWithOptions

func OpenWithOptions(path string, options OpenOptions) (*DB, error)

OpenWithOptions creates or opens a durable database with explicit storage and resource options.

func (*DB) AbortIndexBuild

func (db *DB) AbortIndexBuild(ctx context.Context, id IndexBuildID) error

AbortIndexBuild removes an unfinished private index build and releases its name reservation.

func (*DB) AcquireReplicationSourceLease

func (db *DB) AcquireReplicationSourceLease(name string) (*ReplicationSourceLease, error)

AcquireReplicationSourceLease reserves a consumer name until the lease is released.

Callers must authenticate and derive the name outside untrusted replication frames; primary election remains an external responsibility.

func (*DB) Backup

func (db *DB) Backup(ctx context.Context, destination string) (result BackupResult, resultErr error)

Backup writes a verified physical database copy to a new path.

It preserves database identity and commit history, so the result is a restore artifact rather than an independent writable fork. The source writer is blocked for the copy duration; readers remain available.

func (*DB) BeginArchive

func (db *DB) BeginArchive(ctx context.Context, name, destination string, buffer int) (ArchiveBootstrap, *DurableDatabaseChangeSubscription, error)

BeginArchive creates a verified backup with a durable change stream for subsequent commits.

The checkpoint is established first, so Commit Log retention preserves every token needed to bridge from CheckpointToken to the returned SnapshotToken, even while writes continue before the snapshot's short read barrier begins.

This is deliberately a transport-neutral bootstrap primitive. It does not copy files to another machine, open a writable follower, or acknowledge a token on the caller's behalf. Those actions have different ownership and failure domains and must be explicit in the eventual wire protocol.

func (*DB) CanResumeFrom

func (db *DB) CanResumeFrom(token uint64) bool

CanResumeFrom reports whether retained in-memory history covers the requested token.

func (*DB) Close

func (db *DB) Close() error

Close stops background work and closes the database's storage and subscriptions.

func (*DB) Collection

func (db *DB) Collection(name string) *Collection

Collection returns an operation handle for the named collection.

func (*DB) CommitCoordinatorStats

func (db *DB) CommitCoordinatorStats() CommitCoordinatorStats

CommitCoordinatorStats returns a bounded snapshot of the optional admission scheduler.

It performs no I/O. DBStats includes the same snapshot in the versioned admin schema; this method is convenient for direct callers.

func (*DB) Compact

func (db *DB) Compact(ctx context.Context, destination string) (resultErr error)

Compact rewrites a database snapshot into a new compacted file.

Publication is atomic and never overwrites the destination or changes the source. Writes which commit after the source snapshot is pinned may continue and are intentionally absent from the destination. The compacted database receives a new identity and commit-log history, so callers must treat every old resume token as invalid.

func (*DB) CompactWithOptions

func (db *DB) CompactWithOptions(ctx context.Context, destination string, options CompactionOptions) (resultErr error)

CompactWithOptions rewrites a database snapshot with explicit storage and resource limits.

func (*DB) CreateCollection

func (db *DB) CreateCollection(ctx context.Context, name string) error

CreateCollection creates an empty collection in a durable database.

CRUD also creates collections implicitly; this method lets tools such as logical import preserve collections that contain no documents.

func (*DB) CreateDurableCollectionChanges

func (db *DB) CreateDurableCollectionChanges(ctx context.Context, name, collection string, afterToken uint64, buffer int) (*DurableChangeSubscription, error)

CreateDurableCollectionChanges creates a named collection change feed starting after a commit token.

The requested position must still be retained. A logical name may be reused for a different collection without collision; the storage checkpoint identity is derived from both values.

func (*DB) CreateDurableDatabaseChanges

func (db *DB) CreateDurableDatabaseChanges(ctx context.Context, name string, afterToken uint64, buffer int) (*DurableDatabaseChangeSubscription, error)

CreateDurableDatabaseChanges creates a named database change feed starting after a commit token.

The requested position must still be retained. Names share no namespace with collection-scoped consumers, so one application can use the same logical name for both an outbox and a database archive without a checkpoint clash.

func (*DB) DatabaseID

func (db *DB) DatabaseID() [16]byte

DatabaseID returns the stable, non-secret database namespace used to bind resume and replication protocols.

It is not an authentication token.

func (*DB) DatabaseIdentity

func (db *DB) DatabaseIdentity() [16]byte

DatabaseIdentity returns the database namespace identifier.

func (*DB) DeleteDurableCollectionChanges

func (db *DB) DeleteDurableCollectionChanges(ctx context.Context, name, collection string) error

DeleteDurableCollectionChanges explicitly removes one retained checkpoint.

Callers should stop every owner of that logical consumer first; an already open stream retains only its temporary process-local pin until it closes.

func (*DB) DeleteDurableDatabaseChanges

func (db *DB) DeleteDurableDatabaseChanges(ctx context.Context, name string) error

DeleteDurableDatabaseChanges removes a named database change checkpoint.

Stop all active owners first; deletion makes future resume fail.

func (*DB) DiagnosticSnapshotAfter

func (db *DB) DiagnosticSnapshotAfter(after uint64, limit int) DiagnosticSnapshot

DiagnosticSnapshotAfter copies newer events from the currently active diagnostic session.

Long-lived admin handlers can follow a replaced session through this method.

func (*DB) EnableDiagnostics

func (db *DB) EnableDiagnostics(options DiagnosticsOptions) (*Diagnostics, error)

EnableDiagnostics starts the database's single bounded diagnostic recording session.

func (*DB) ExportLogicalArchive

func (db *DB) ExportLogicalArchive(ctx context.Context, destination string) (result LogicalArchiveResult, resultErr error)

ExportLogicalArchive saves collections, documents, and indexes from one database snapshot as JSON Lines.

The archive excludes storage pages, database identity, and commit history. Writes committed after the snapshot are absent.

func (*DB) IndexBuild

func (db *DB) IndexBuild(id IndexBuildID) (IndexBuildStatus, error)

IndexBuild returns the persisted status of one unfinished index build.

func (*DB) IndexBuilds

func (db *DB) IndexBuilds() ([]IndexBuildStatus, error)

IndexBuilds returns the stored status of all unfinished index builds.

Build records survive a clean close, process crash, and reopen.

func (*DB) IndexCatalog

func (db *DB) IndexCatalog(ctx context.Context) ([]IndexCatalogEntry, error)

IndexCatalog returns copied index definitions sorted by collection and index name.

func (*DB) MeldbaseSystemRecordBackend

func (db *DB) MeldbaseSystemRecordBackend() systemrecord.Backend

MeldbaseSystemRecordBackend returns the private durable-record bridge for built-in services.

Its internal return type is not an application-facing key/value API.

func (*DB) MeldbaseSystemWrite

func (db *DB) MeldbaseSystemWrite(ctx context.Context, systemMutation systemrecord.Mutation, build func(*WriteTransaction) ([]byte, error)) (systemrecord.Result, bool, error)

MeldbaseSystemWrite commits a callback's document changes together with a private system record.

The callback runs against an immutable snapshot without the writer lock; publication requires its recorded reads to remain valid. The bool reports whether a composite commit was attempted; false means build produced no business change or lost optimistic validation.

Only repository packages can use this method because its systemrecord parameter is internal; external applications cannot access the private system records.

func (*DB) OpenDurableCollectionChanges

func (db *DB) OpenDurableCollectionChanges(ctx context.Context, name, collection string, buffer int) (*DurableChangeSubscription, error)

OpenDurableCollectionChanges resumes a named collection change feed from its saved checkpoint.

If retention cannot satisfy that position it returns ErrHistoryLost; it never silently starts from a newer token.

func (*DB) OpenDurableDatabaseChanges

func (db *DB) OpenDurableDatabaseChanges(ctx context.Context, name string, buffer int) (*DurableDatabaseChangeSubscription, error)

OpenDurableDatabaseChanges resumes a named database change feed from its saved checkpoint.

It returns ErrHistoryLost when the required commit history is no longer retained, rather than silently starting at a later token.

func (*DB) OpenQueryReplay

func (db *DB) OpenQueryReplay(ctx context.Context, collection string, query QuerySpec, afterToken uint64, buffer int) (*QueryReplaySubscription, error)

OpenQueryReplay opens a query change stream after the supplied commit token.

func (*DB) OperationalState

func (db *DB) OperationalState() OperationalState

OperationalState reports whether the database currently accepts reads and writes.

func (*DB) ReclaimPages

func (db *DB) ReclaimPages(ctx context.Context) (result ReclaimResult, resultErr error)

ReclaimPages audits protected roots and makes unreachable pages available for reuse.

func (*DB) ReclaimPagesWithOptions

func (db *DB) ReclaimPagesWithOptions(ctx context.Context, options ReclaimOptions) (result ReclaimResult, resultErr error)

ReclaimPagesWithOptions reclaims unused pages with the selected scan and persistence settings.

Online mode may return ErrReclamationConflict when every bounded attempt overlaps a commit.

func (*DB) RecoveryReport

func (db *DB) RecoveryReport() RecoveryReport

RecoveryReport returns the receipt captured by the successful constructor.

It performs no I/O and never changes after the DB is opened.

func (*DB) ResourceLimits

func (db *DB) ResourceLimits() ResourceLimits

ResourceLimits returns the immutable normalized limits selected at open.

func (*DB) ResumeIndexBuild

func (db *DB) ResumeIndexBuild(ctx context.Context, id IndexBuildID) error

ResumeIndexBuild continues a stored index build until publication or interruption.

It scans bounded batches, applies retained changes, and publishes atomically. Only one caller should resume a given build; stale concurrent callers receive ErrWriteConflict from durable CAS checks.

func (*DB) RunWriteTransaction

func (db *DB) RunWriteTransaction(ctx context.Context, build func(*WriteTransaction) error) error

RunWriteTransaction runs a callback and commits its staged writes if the snapshot remains valid.

The callback runs without the database writer lock. A conflicting point write returns ErrWriteConflict; callbacks are never retried because they may contain application side effects.

A successful callback with no effective changes is a successful no-op and does not advance the commit sequence. The transaction is invalid as soon as the callback returns. Normal DB and Collection methods must not be called from inside build.

func (*DB) StartIndexBuildScheduler

func (db *DB) StartIndexBuildScheduler(parent context.Context, options IndexBuildSchedulerOptions) (*IndexBuildScheduler, error)

StartIndexBuildScheduler starts the database's single background index-build scheduler.

func (*DB) StartMaintenance

func (db *DB) StartMaintenance(parent context.Context, options MaintenanceOptions) (*Maintenance, error)

StartMaintenance starts a bounded background page-reclamation loop for a durable database.

func (*DB) Stats

func (db *DB) Stats() DBStats

Stats captures database state and activity counters without scanning stored documents.

func (*DB) Sync

func (db *DB) Sync() error

Sync confirms that the database's current state is durable.

Successful writes are already synced, so this is normally a cheap health check.

func (*DB) WatchChanges

func (db *DB) WatchChanges(ctx context.Context, collection string, buffer int) (<-chan ChangeBatch, <-chan error, error)

WatchChanges subscribes to future collection changes through a bounded delivery queue.

type DBStats

type DBStats struct {
	CapturedAt           time.Time     `json:"capturedAt"`
	StartedAt            time.Time     `json:"startedAt"`
	Uptime               time.Duration `json:"uptimeNanos"`
	Closed               bool          `json:"closed"`
	WritesDisabled       bool          `json:"writesDisabled"`
	Durable              bool          `json:"durable"`
	CommitSequence       uint64        `json:"commitSequence"`
	Collections          uint64        `json:"collections"`
	Documents            uint64        `json:"documents"`
	Indexes              uint64        `json:"indexes"`
	ActiveChangeWatchers uint64        `json:"activeChangeWatchers"`

	Commits           CommitStats            `json:"commits"`
	Transactions      WriteTransactionStats  `json:"writeTransactions"`
	Queries           QueryStats             `json:"queries"`
	Realtime          RealtimeStats          `json:"realtime"`
	CommitCoordinator CommitCoordinatorStats `json:"commitCoordinator"`
	PrimaryWriteFence PrimaryWriteFenceStats `json:"primaryWriteFence"`
	Durability        DurabilityStats        `json:"durability"`
	Storage           StorageStats           `json:"storage"`
	Compaction        CompactionStats        `json:"compaction"`
	Reclamation       ReclamationStats       `json:"reclamation"`
	Backup            BackupStats            `json:"backup"`
	Diagnostics       DiagnosticStats        `json:"diagnostics"`
	Recovery          RecoveryReport         `json:"recovery"`
	Resources         ResourceStats          `json:"resources"`
	IndexBuilds       IndexBuildStats        `json:"indexBuilds"`
}

DBStats is a point-in-time, allocation-bounded view of database health.

Counters are process-lifetime values and reset when the database is reopened. Persistent state such as CommitSequence is read from the database itself.

Stats deliberately exposes no user values, document IDs, query parameters, or callbacks. It is safe for an admin sampler to call periodically, but it is not intended to be called on every database operation.

type DatabaseOptions

type DatabaseOptions struct{ ResourceLimits ResourceLimits }

DatabaseOptions configures an in-memory database.

type DeleteResult

type DeleteResult struct{ DeletedCount int64 }

DeleteResult reports how many documents were deleted.

type DiagnosticEvent

type DiagnosticEvent struct {
	Sequence              uint64            `json:"sequence"`
	CapturedAt            time.Time         `json:"capturedAt"`
	Kind                  DiagnosticKind    `json:"kind"`
	Outcome               DiagnosticOutcome `json:"outcome"`
	ErrorClass            string            `json:"errorClass,omitempty"`
	Stage                 string            `json:"stage,omitempty"`
	PlanReason            string            `json:"planReason,omitempty"`
	FallbackReason        string            `json:"fallbackReason,omitempty"`
	EarlyStopReason       string            `json:"earlyStopReason,omitempty"`
	EarlyStopScope        string            `json:"earlyStopScope,omitempty"`
	BudgetPressure        string            `json:"budgetPressure,omitempty"`
	BudgetExceeded        string            `json:"budgetExceeded,omitempty"`
	Duration              time.Duration     `json:"durationNanos"`
	DocumentsExamined     uint64            `json:"documentsExamined,omitempty"`
	DocumentsReturned     uint64            `json:"documentsReturned,omitempty"`
	KeysExamined          uint64            `json:"keysExamined,omitempty"`
	PredicateSteps        uint64            `json:"predicateSteps,omitempty"`
	CandidateIDs          uint64            `json:"candidateIds,omitempty"`
	UniqueCandidateIDs    uint64            `json:"uniqueCandidateIds,omitempty"`
	DuplicateCandidateIDs uint64            `json:"duplicateCandidateIds,omitempty"`
	CandidatesRetained    uint64            `json:"candidatesRetained,omitempty"`
	SortBytes             uint64            `json:"sortBytes,omitempty"`
	EarlyStopped          bool              `json:"earlyStopped,omitempty"`
	Changes               uint64            `json:"changes,omitempty"`
	Slow                  bool              `json:"slow"`
	Sampled               bool              `json:"sampled"`
}

DiagnosticEvent records one operation's timing, outcome, and work counters.

type DiagnosticKind

type DiagnosticKind string

DiagnosticKind identifies the operation recorded by a diagnostic event.

const (
	// DiagnosticQuery marks a query diagnostic.
	DiagnosticQuery DiagnosticKind = "query"
	// DiagnosticCommit marks a commit diagnostic.
	DiagnosticCommit DiagnosticKind = "commit"
)

type DiagnosticOutcome

type DiagnosticOutcome string

DiagnosticOutcome identifies how a recorded operation ended.

const (
	// DiagnosticSuccess marks a successful operation.
	DiagnosticSuccess DiagnosticOutcome = "success"
	// DiagnosticFailure marks a failed operation.
	DiagnosticFailure DiagnosticOutcome = "failure"
	// DiagnosticCanceled marks a canceled operation.
	DiagnosticCanceled DiagnosticOutcome = "canceled"
)

type DiagnosticSnapshot

type DiagnosticSnapshot struct {
	Session    uint64            `json:"session"`
	StartedAt  time.Time         `json:"startedAt"`
	CapturedAt time.Time         `json:"capturedAt"`
	Stats      DiagnosticStats   `json:"stats"`
	Events     []DiagnosticEvent `json:"events"`
	Truncated  bool              `json:"truncated"`
	HasMore    bool              `json:"hasMore"`
}

DiagnosticSnapshot captures a diagnostics session's counters and retained events.

type DiagnosticStats

type DiagnosticStats struct {
	Enabled         bool   `json:"enabled"`
	Capacity        uint64 `json:"capacity"`
	Retained        uint64 `json:"retained"`
	Recorded        uint64 `json:"recorded"`
	Overwritten     uint64 `json:"overwritten"`
	QueriesObserved uint64 `json:"queriesObserved"`
	CommitsObserved uint64 `json:"commitsObserved"`
}

DiagnosticStats reports diagnostics activity and retained event counts.

type Diagnostics

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

Diagnostics owns a bounded ring of recorded operation events.

Close disables timing and recording but keeps retained events readable.

func (*Diagnostics) Close

func (d *Diagnostics) Close() error

Close disables recording while leaving retained diagnostic events readable.

func (*Diagnostics) DiagnosticSnapshotAfter

func (d *Diagnostics) DiagnosticSnapshotAfter(after uint64, limit int) DiagnosticSnapshot

DiagnosticSnapshotAfter copies newer events through the admin diagnostic-source contract.

func (*Diagnostics) Snapshot

func (d *Diagnostics) Snapshot() DiagnosticSnapshot

Snapshot copies all events currently retained by the diagnostic session.

func (*Diagnostics) SnapshotAfter

func (d *Diagnostics) SnapshotAfter(after uint64, limit int) DiagnosticSnapshot

SnapshotAfter copies retained events newer than after in chronological order.

A non-positive limit means the ring capacity; Truncated reports that after predates the oldest retained sequence; HasMore asks the caller to continue from the last returned sequence.

func (*Diagnostics) Stats

func (d *Diagnostics) Stats() DiagnosticStats

Stats samples diagnostic activity and event retention counters.

type DiagnosticsOptions

type DiagnosticsOptions struct {
	Capacity            int
	SlowQueryThreshold  time.Duration
	SlowCommitThreshold time.Duration
	SampleEvery         uint64
	RecordAll           bool
	ExcludeFailures     bool
}

DiagnosticsOptions configures bounded diagnostic recording and event selection.

Defaults retain 256 events and record failures, queries taking at least 50ms, and commits taking at least 100ms. RecordAll is intended only for short development sessions. SampleEvery adds a deterministic one-in-N sample of otherwise fast successful operations.

type Document

type Document map[string]Value

Document maps field names to typed database values.

func NewDocument

func NewDocument(fields map[string]any) (Document, error)

NewDocument converts Go fields into a document and rejects invalid names or values.

func UnmarshalWireDocument

func UnmarshalWireDocument(data []byte, limits QueryLimits) (Document, error)

UnmarshalWireDocument decodes a typed wire document with a required document ID.

func UnmarshalWireInputDocument

func UnmarshalWireInputDocument(data []byte, limits QueryLimits) (Document, error)

UnmarshalWireInputDocument decodes a typed wire document whose ID may be omitted.

func (Document) Clone

func (d Document) Clone() Document

Clone copies the document and all nested values.

func (Document) Equal

func (d Document) Equal(other Document) bool

Equal reports whether both documents contain the same fields and values.

func (Document) ID

func (d Document) ID() (DocumentID, bool)

ID returns the document ID if the _id field holds one.

func (Document) Validate

func (d Document) Validate() error

Validate checks every nested field and value before a document crosses a storage or transport boundary.

type DocumentCacheStats

type DocumentCacheStats struct {
	CapacityEntries uint64 `json:"capacityEntries"`
	CapacityBytes   uint64 `json:"capacityBytes"`
	Entries         uint64 `json:"entries"`
	Bytes           uint64 `json:"bytes"`
	Hits            uint64 `json:"hits"`
	Misses          uint64 `json:"misses"`
	Evictions       uint64 `json:"evictions"`
}

DocumentCacheStats reports document-cache occupancy, hits, misses, and evictions.

type DocumentID

type DocumentID [16]byte

DocumentID is a 16-byte document identifier.

func NewDocumentID

func NewDocumentID() (DocumentID, error)

NewDocumentID creates an identifier from cryptographically random bytes.

func ParseDocumentID

func ParseDocumentID(s string) (DocumentID, error)

ParseDocumentID reads a 16-byte identifier from a hexadecimal string.

func (DocumentID) IsZero

func (id DocumentID) IsZero() bool

IsZero reports whether every byte of the identifier is zero.

func (DocumentID) String

func (id DocumentID) String() string

String returns the identifier as lowercase hexadecimal text.

type DurabilityStats

type DurabilityStats struct {
	WALAppends           uint64        `json:"walAppends"`
	WALPayloadBytes      uint64        `json:"walPayloadBytes"`
	WALCurrentBytes      uint64        `json:"walCurrentBytes"`
	WALCurrentCommits    uint64        `json:"walCurrentCommits"`
	WALAppendFailures    uint64        `json:"walAppendFailures"`
	WALAppendNanos       uint64        `json:"walAppendNanos"`
	WALAppendMaxLatency  time.Duration `json:"walAppendMaxLatencyNanos"`
	CheckpointAttempts   uint64        `json:"checkpointAttempts"`
	CheckpointsCompleted uint64        `json:"checkpointsCompleted"`
	CheckpointFailures   uint64        `json:"checkpointFailures"`
	AutomaticCheckpoints uint64        `json:"automaticCheckpoints"`
	CheckpointNanos      uint64        `json:"checkpointNanos"`
	CheckpointMaxLatency time.Duration `json:"checkpointMaxLatencyNanos"`
}

DurabilityStats preserves legacy durability counters in the admin response format.

Current-format databases do not use a WAL or checkpoints, so every field is zero.

type DurableChangeBatch

type DurableChangeBatch struct {
	Token   uint64
	Changes []Change
}

DurableChangeBatch contains one collection's document changes at a commit token.

Changes is empty when another collection or private catalog change advanced the durable position; callers must still Ack that Token after processing it so the checkpoint can advance without pinning history forever.

This is deliberately a document-change feed, not a full replication protocol: it does not expose private System records, index definitions, collection lifecycle or raw storage bytes.

type DurableChangeSubscription

type DurableChangeSubscription struct {
	Batches <-chan DurableChangeBatch
	Errors  <-chan error
	// contains filtered or unexported fields
}

DurableChangeSubscription delivers ordered collection changes with a saved acknowledgement.

Ack must be called only after the consumer's external side effect for that token is durable.

func (*DurableChangeSubscription) Ack

func (subscription *DurableChangeSubscription) Ack(token uint64) error

Ack saves the last processed commit token in the durable checkpoint.

func (*DurableChangeSubscription) Close

func (subscription *DurableChangeSubscription) Close()

Close cancels delivery and waits for the collection subscription to stop.

type DurableDatabaseChangeBatch

type DurableDatabaseChangeBatch struct {
	Token         uint64
	TransactionID [16]byte
	CommittedAt   time.Time
	Changes       []Change
}

DurableDatabaseChangeBatch contains public document and catalog changes from one commit.

Archives and single-writer followers must acknowledge Token only after the externally applied effect is durable.

Private System records, raw pages, index-build progress and retention control records are deliberately excluded. A batch can therefore be empty when a private record advanced a retained position; it must still be Acked.

type DurableDatabaseChangeSubscription

type DurableDatabaseChangeSubscription struct {
	Batches <-chan DurableDatabaseChangeBatch
	Errors  <-chan error
	// contains filtered or unexported fields
}

DurableDatabaseChangeSubscription delivers public database changes with a saved acknowledgement.

It exposes collection creation, index publication and document changes in exact Commit Log order. It does not itself copy a bootstrap snapshot or apply changes to a follower; those transport and ownership contracts are intentionally separate.

func (*DurableDatabaseChangeSubscription) Ack

func (subscription *DurableDatabaseChangeSubscription) Ack(token uint64) error

Ack saves the last processed database commit token in the durable checkpoint.

func (*DurableDatabaseChangeSubscription) Checkpoint

func (subscription *DurableDatabaseChangeSubscription) Checkpoint() (uint64, error)

Checkpoint returns the last commit token whose acknowledgement was saved.

Delivered batches do not move it; callers may use it to bind a replication hello to the exact retained position, rather than to a process-local queue position.

func (*DurableDatabaseChangeSubscription) Close

func (subscription *DurableDatabaseChangeSubscription) Close()

Close cancels delivery and waits for the database subscription to stop.

type ExplainAccessSource

type ExplainAccessSource struct {
	IndexName                                 string
	Primary                                   bool
	Bounds                                    []ExplainBound
	Spans, ExactSpans                         int
	KeysExamined, CandidateIDs                int64
	UniqueCandidateIDs, DuplicateCandidateIDs int64
	DocumentsExamined                         int64
}

ExplainAccessSource records the query work performed through one index or primary key path.

CandidateIDs counts document IDs processed by the deduplicator. Read-ahead needed for an ordered union remains visible in KeysExamined even when execution stops before those IDs are consumed.

type ExplainAdvice

type ExplainAdvice struct {
	Code  string
	Paths []string
	Sort  []SortField
}

ExplainAdvice records a possible query improvement to check against the workload.

It is not an instruction to create an index. Paths and Sort contain schema facts but never query values. Callers should validate selectivity against workload measurements.

type ExplainBound

type ExplainBound struct {
	Path                           string
	Values                         []Value
	Lower, Upper                   *Value
	LowerInclusive, UpperInclusive bool
}

ExplainBound describes the values that restrict one indexed field.

Values is used for equality and membership unions; range bounds use Lower and Upper. A nil range endpoint is unbounded.

type ExplainBudget

type ExplainBudget struct {
	DocumentsUsed, DocumentsLimit           uint64
	KeysUsed, KeysLimit                     uint64
	CandidatesUsed, CandidatesLimit         uint64
	SortBytesUsed, SortBytesLimit           uint64
	SkipUsed, SkipLimit                     uint64
	PredicateStepsUsed, PredicateStepsLimit uint64
	Pressure, Exceeded                      string
}

ExplainBudget is the final resource-budget snapshot for one execution.

Pressure and Exceeded are fixed reason codes naming one of "documents", "keys", "candidates", "sort_bytes", "skip", or "predicate_steps".

type ExplainResult

type ExplainResult struct {
	Stage, IndexName string
	// IndexNames contains every access path used by an index union. IndexName
	// remains populated for the common single-index and primary-key plans.
	IndexNames                        []string
	Bounds                            []ExplainBound
	ResidualPredicate, SortRequired   bool
	SortIndexCompatible               bool
	EstimatedDocuments, EstimatedKeys int64
	DocumentsExamined, KeysExamined   int64
	CandidatesRetained, SortBytes     uint64
	PlanReason, FallbackReason        string
	UnindexedPaths                    []string
	// IndexableConjunctPaths lists distinct AND predicate paths that each have
	// an independently usable access path. It is populated only by explicit
	// Explain calls and does not imply that an index intersection was selected.
	IndexableConjunctPaths []string
	// CompoundIndexOpportunity is a structural signal: multiple independently
	// indexable AND paths exist, while the selected non-unique source constrains
	// only a subset. Advice still requires observed amplification.
	CompoundIndexOpportunity         bool
	Sources                          []ExplainAccessSource
	CandidateIDs, UniqueCandidateIDs int64
	DuplicateCandidateIDs            int64
	EarlyStopEligible, EarlyStopped  bool
	EarlyStopScope, EarlyStopReason  string
	Budget                           ExplainBudget
	Advice                           []ExplainAdvice
}

ExplainResult describes the query plan and the work measured during execution.

Estimated fields are conservative candidate estimates when the selected backend can provide them; DocumentsExamined and KeysExamined are the actual completed scan counts. ResidualPredicate means the complete compiled predicate is rechecked after index admission, including when the index appears to cover every condition.

type Filter

type Filter map[string]any

Filter maps document fields and query operators to their conditions.

type FilterCapability

type FilterCapability struct {
	Path     string
	Operator string
}

FilterCapability identifies a field and predicate operation for authorization.

Policies can grant equality lookup independently of range scans and sorting.

type Follower

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

Follower owns a read-only local database advanced by validated source change batches.

Transport authentication and snapshot transfer are managed outside this type; promotion requires the external authority and write guard described below.

func OpenFollower

func OpenFollower(path string, options OpenOptions) (*Follower, error)

OpenFollower opens a database copy as a read-only replica.

Normal public mutations on DB return ErrReplicaReadOnly; use Apply to advance the next source token. The returned DB remains fully queryable and reactive.

func (*Follower) Apply

func (follower *Follower) Apply(ctx context.Context, source DurableDatabaseChangeBatch) error

Apply saves exactly the next source change batch as one atomic commit.

A gap, duplicate or locally diverged token returns ErrReplicaSequence; it never guesses, retries business logic or advances past missing history.

func (*Follower) ApplyFrame

func (follower *Follower) ApplyFrame(ctx context.Context, frame ReplicationFrame) error

ApplyFrame checks a replication frame's database identity before applying its batch.

A transport handles hello/ack/resync; only a validated batch frame belongs at the follower mutation boundary.

func (*Follower) Close

func (follower *Follower) Close() error

Close closes the follower's database while serializing follower operations.

func (*Follower) DB

func (follower *Follower) DB() *DB

DB returns the follower's database handle for queries and subscriptions.

func (*Follower) Promote

func (follower *Follower) Promote(ctx context.Context, authority FollowerPromotionAuthority) (FollowerPromotionFence, error)

Promote enables writes after an external authority revokes the former primary's write access.

The authority must certify this exact database identity and commit token. There is no default or best-effort implementation: promoting without a durable external fence would turn a network partition into split-brain data loss.

type FollowerPromotionAuthority

type FollowerPromotionAuthority interface {
	AuthorizeFollowerPromotion(context.Context, FollowerPromotionRequest) (FollowerPromotionFence, error)
}

FollowerPromotionAuthority grants promotion after durably revoking the former primary's write authority.

Implementations normally revoke a primary lease through a quorum controller or external consensus store.

type FollowerPromotionFence

type FollowerPromotionFence struct {
	DatabaseID     [16]byte
	CommitSequence uint64
	Epoch          string
}

FollowerPromotionFence proves that the former primary lost write authority for this database version.

Epoch is non-empty and deliberately opaque to Meldbase: a controller may use it as an epoch ID or a compact signed lease certificate (as integrations/primarylease does). Meldbase does not invent a local substitute for that distributed safety decision.

type FollowerPromotionFenceBinder

type FollowerPromotionFenceBinder interface {
	BindFollowerPromotion(context.Context, FollowerPromotionFence) error
}

FollowerPromotionFenceBinder connects a promotion certificate to the local write protection guard.

The binder may update caller-owned local lease/epoch state, but must not enable writes until it has accepted the exact fence. It runs on the promotion control path, outside the DB writer lock; unlike ValidatePrimaryWrite it may coordinate with the controller if the implementation needs to.

A promoted follower requires this interface in addition to PrimaryWriteFence. Otherwise an unrelated always-allow guard could make a one-time promotion certificate appear to grant permanent write authority.

type FollowerPromotionRequest

type FollowerPromotionRequest struct {
	DatabaseID     [16]byte
	CommitSequence uint64
}

FollowerPromotionRequest identifies the database version requesting permission to become writable.

type IndexBuildFailure

type IndexBuildFailure string

IndexBuildFailure identifies why an index build stopped permanently.

type IndexBuildID

type IndexBuildID [16]byte

IndexBuildID identifies one durable, resumable index build.

func ParseIndexBuildID

func ParseIndexBuildID(value string) (IndexBuildID, error)

ParseIndexBuildID parses a hexadecimal index-build identifier.

func (IndexBuildID) IsZero

func (id IndexBuildID) IsZero() bool

IsZero reports whether the build ID is empty.

func (IndexBuildID) MarshalText

func (id IndexBuildID) MarshalText() ([]byte, error)

MarshalText encodes the build ID as hexadecimal text.

func (IndexBuildID) String

func (id IndexBuildID) String() string

String returns the build ID as lowercase hexadecimal text.

func (*IndexBuildID) UnmarshalText

func (id *IndexBuildID) UnmarshalText(value []byte) error

UnmarshalText parses a nonzero hexadecimal build ID into the receiver.

type IndexBuildPhase

type IndexBuildPhase string

IndexBuildPhase identifies the current stage of a resumable index build.

type IndexBuildScheduler

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

IndexBuildScheduler runs resumable index builds in bounded background tasks.

func (*IndexBuildScheduler) Done

func (scheduler *IndexBuildScheduler) Done() <-chan struct{}

Done returns a channel that closes after the scheduler and its tasks finish.

func (*IndexBuildScheduler) Stats

func (scheduler *IndexBuildScheduler) Stats() IndexBuildSchedulerStats

Stats samples scheduling counters and the most recent outcome.

func (*IndexBuildScheduler) Stop

func (scheduler *IndexBuildScheduler) Stop()

Stop cancels scheduling and waits for active tasks to finish.

type IndexBuildSchedulerOptions

type IndexBuildSchedulerOptions struct {
	PollInterval   time.Duration
	RunTimeout     time.Duration
	MaxConcurrency int
	RunImmediately bool
}

IndexBuildSchedulerOptions configures polling, time slices, and build concurrency.

The scheduler must be started explicitly; each task yields durable progress between bounded time slices so document writes and other builds can proceed.

type IndexBuildSchedulerStats

type IndexBuildSchedulerStats struct {
	Polls        uint64        `json:"polls"`
	Runs         uint64        `json:"runs"`
	Completed    uint64        `json:"completed"`
	Yielded      uint64        `json:"yielded"`
	MarkedFailed uint64        `json:"markedFailed"`
	Conflicts    uint64        `json:"conflicts"`
	Failed       uint64        `json:"failed"`
	Active       uint64        `json:"active"`
	LastDuration time.Duration `json:"lastDurationNanos"`
	LastError    string        `json:"lastError,omitempty"`
}

IndexBuildSchedulerStats reports background index-build activity and outcomes.

type IndexBuildStats

type IndexBuildStats struct {
	Active               uint64        `json:"active"`
	Persistent           uint64        `json:"persistent"`
	Scanning             uint64        `json:"scanning"`
	CatchingUp           uint64        `json:"catchingUp"`
	Ready                uint64        `json:"ready"`
	PersistentFailed     uint64        `json:"persistentFailed"`
	RetentionLeaseActive bool          `json:"retentionLeaseActive"`
	RetentionPressure    bool          `json:"retentionPressure"`
	PersistentEntries    uint64        `json:"persistentEntries"`
	PersistentBytes      uint64        `json:"persistentBytes"`
	SchedulerRuns        uint64        `json:"schedulerRuns"`
	SchedulerYields      uint64        `json:"schedulerYields"`
	SchedulerFailures    uint64        `json:"schedulerFailures"`
	Attempts             uint64        `json:"attempts"`
	Completed            uint64        `json:"completed"`
	Failed               uint64        `json:"failed"`
	Retries              uint64        `json:"retries"`
	Conflicts            uint64        `json:"conflicts"`
	LastEntries          uint64        `json:"lastEntries"`
	LastBytes            uint64        `json:"lastBytes"`
	LastDuration         time.Duration `json:"lastDurationNanos"`
	MaxDuration          time.Duration `json:"maxDurationNanos"`
	// contains filtered or unexported fields
}

IndexBuildStats reports index-build progress, resource use, and outcomes.

type IndexBuildStatus

type IndexBuildStatus struct {
	ID              IndexBuildID      `json:"id"`
	Collection      string            `json:"collection"`
	Name            string            `json:"name"`
	Field           string            `json:"field"`
	Fields          []IndexField      `json:"fields"`
	Unique          bool              `json:"unique"`
	ReplaceExisting bool              `json:"replaceExisting,omitempty"`
	Phase           IndexBuildPhase   `json:"phase"`
	Failure         IndexBuildFailure `json:"failure,omitempty"`
	SourceSequence  uint64            `json:"sourceSequence"`
	AppliedSequence uint64            `json:"appliedSequence"`
	EntryCount      uint64            `json:"entryCount"`
	CanonicalBytes  uint64            `json:"canonicalBytes"`
	CreatedAt       time.Time         `json:"createdAt"`
	UpdatedAt       time.Time         `json:"updatedAt"`
}

IndexBuildStatus reports the stored progress and outcome of a resumable index build.

EntryCount and CanonicalBytes describe the pending index tree, not transient Go heap usage.

type IndexCatalogEntry

type IndexCatalogEntry struct {
	Collection string
	Definition IndexDefinition
}

IndexCatalogEntry describes a published index without exposing document data.

Index management remains a deployment concern; this catalog supports CLIs and protected operator views.

type IndexDefinition

type IndexDefinition struct {
	Name, Field string
	Order       int
	Unique      bool
	// Fields is the ordered definition for compound/descending indexes. Field
	// and Order remain the compatibility mirror of Fields[0] for existing
	// callers; new code must use indexDefinitionFields.
	Fields []IndexField
}

IndexDefinition describes the ordered fields and uniqueness of an index.

type IndexField

type IndexField struct {
	Field string
	Order int
}

IndexField selects a field and its sort direction within an index.

Order must be 1 (ascending) or -1 (descending); fields are evaluated left to right.

type IndexOptions

type IndexOptions struct{ Unique bool }

IndexOptions controls complete-tuple uniqueness.

type Kind

type Kind uint8

Kind identifies the type stored in a Value.

const (
	// NullKind identifies a null value.
	NullKind Kind = iota
	// BoolKind identifies a boolean value.
	BoolKind
	// Int64Kind identifies a signed 64-bit integer.
	Int64Kind
	// Float64Kind identifies a 64-bit float.
	Float64Kind
	// StringKind identifies a string.
	StringKind
	// BinaryKind identifies binary data.
	BinaryKind
	// TimeKind identifies a timestamp.
	TimeKind
	// ArrayKind identifies an array of values.
	ArrayKind
	// ObjectKind identifies a document object.
	ObjectKind
	// IDKind identifies a document identifier.
	IDKind
)

type LogicalArchiveImportOptions

type LogicalArchiveImportOptions struct{ MaxBytes uint64 }

LogicalArchiveImportOptions limits the size of an archive accepted for import.

Zero MaxBytes selects the normal storage-file limit; the receiver owns this cap.

type LogicalArchiveResult

type LogicalArchiveResult struct {
	Format      string `json:"format"`
	Version     int    `json:"version"`
	Bytes       uint64 `json:"bytes"`
	Collections uint64 `json:"collections"`
	Documents   uint64 `json:"documents"`
	Indexes     uint64 `json:"indexes"`
	SHA256      string `json:"sha256"`
}

LogicalArchiveResult records archive counts, byte size, and checksum.

SHA256 covers every JSONL record before the final end record; the end record stores the same digest so an importer can reject truncation or alteration.

func ImportLogicalArchive

func ImportLogicalArchive(ctx context.Context, source io.Reader, destination string, options LogicalArchiveImportOptions) (result LogicalArchiveResult, resultErr error)

ImportLogicalArchive creates a new database from a validated logical archive.

Import and offline verification run in a private temporary database before atomic publication, so a malformed archive leaves no destination database.

type Maintenance

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

Maintenance runs background tasks that make unused database pages reusable.

Stop waits for an active scan to observe cancellation; closing the database also cancels the loop.

func (*Maintenance) Done

func (maintenance *Maintenance) Done() <-chan struct{}

Done returns a channel that closes when the maintenance loop finishes.

func (*Maintenance) Stats

func (maintenance *Maintenance) Stats() MaintenanceStats

Stats samples maintenance counters and the most recent outcome.

func (*Maintenance) Stop

func (maintenance *Maintenance) Stop()

Stop cancels maintenance and waits for its loop to finish.

type MaintenanceOptions

type MaintenanceOptions struct {
	Interval       time.Duration
	Timeout        time.Duration
	MaxAttempts    int
	RunImmediately bool
	// PersistFreeSpace opts into a physical maintenance generation after each
	// successful scan. The default memory-only mode minimizes writer pauses.
	PersistFreeSpace bool
}

MaintenanceOptions sets the schedule and limits for background page reclamation.

Each loop uses online optimistic reclamation and never overlaps its own runs.

type MaintenanceStats

type MaintenanceStats struct {
	Runs         uint64
	Completed    uint64
	Conflicts    uint64
	Failed       uint64
	Active       bool
	LastDuration time.Duration
	LastError    string
}

MaintenanceStats counts background page reclamation runs and records their outcomes.

type MutationSpec

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

MutationSpec holds a compiled document update.

func CompileUpdate

func CompileUpdate(update Update) (MutationSpec, error)

CompileUpdate validates update operators and produces a reusable mutation.

func DecodeMutationSpecJSON

func DecodeMutationSpecJSON(data []byte, limits QueryLimits) (MutationSpec, error)

DecodeMutationSpecJSON validates and decodes a data-only mutation within the supplied limits.

func (MutationSpec) Apply

func (m MutationSpec) Apply(document Document) (Document, error)

Apply runs the compiled edits on a copy of the document and validates the result.

func (MutationSpec) Paths

func (m MutationSpec) Paths() []string

Paths returns the edited field paths in sorted order.

type OpenOptions

type OpenOptions struct {
	Recovery              RecoveryMode
	CommitRetention       CommitRetentionPolicy
	ReplayDeliveryTimeout time.Duration
	CommitCoordinator     CommitCoordinatorOptions
	ResourceLimits        ResourceLimits
	StorageLimits         StorageLimits
	RollbackProtection    RollbackProtection
	// RequireGraphAudit rejects a database at startup when any page
	// protected by the current or fallback Meta root is structurally invalid.
	// It is intentionally opt-in because audit cost grows with database size.
	// This does not replace the offline semantic index verifier.
	RequireGraphAudit bool
	// RequirePrivateFileMode rejects a database file with group/world permission
	// bits instead of silently changing operator-owned permissions.
	RequirePrivateFileMode bool
	// PrimaryWriteFence optionally proves that this local database still holds
	// external primary authority before every business commit. It is not
	// consulted by a read-only follower applying an already validated source
	// batch. The guard must be local, non-blocking and safe for concurrent use;
	// controller I/O/lease renewal belongs outside Meldbase's writer lock.
	PrimaryWriteFence PrimaryWriteFence
	// Follower marks this local open as a replica. Normal application writes
	// fail with ErrReplicaReadOnly; only Follower.Apply may advance it.
	Follower bool
}

OpenOptions configures the current durable storage format.

type Operation

type Operation string

Operation identifies a document or catalog change.

const (
	// InsertOperation marks a document insertion.
	InsertOperation Operation = "insert"
	// UpdateOperation marks a document update.
	UpdateOperation Operation = "update"
	// DeleteOperation marks a document deletion.
	DeleteOperation Operation = "delete"
	// CreateCollectionOperation marks collection creation in the durable database change feed.
	//
	// Ordinary collection creation remains implicit for CRUD callers.
	CreateCollectionOperation Operation = "create_collection"
	// CreateIndexOperation marks publication of a new index.
	CreateIndexOperation Operation = "create_index"
	// ReplaceIndexOperation marks replacement of an existing index.
	ReplaceIndexOperation Operation = "replace_index"
)

type OperationalState

type OperationalState struct {
	Readable bool `json:"readable"`
	Writable bool `json:"writable"`
}

OperationalState records whether the database accepts reads and writes.

A durability failure disables writes but preserves reads of committed data; closing the database disables both reads and writes.

type PageCacheStats

type PageCacheStats struct {
	CapacityPages uint64 `json:"capacityPages"`
	ResidentPages uint64 `json:"residentPages"`
	Hits          uint64 `json:"hits"`
	Misses        uint64 `json:"misses"`
	Evictions     uint64 `json:"evictions"`
}

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

type PhysicalBackupImportOptions

type PhysicalBackupImportOptions struct {
	MaxBytes uint64
}

PhysicalBackupImportOptions limits the bytes accepted from a physical backup stream.

Zero selects the normal file limit. Deployments with a deliberately larger database must set MaxBytes explicitly on the receiving side; a sender never chooses that authority.

type PrimaryWriteFence

type PrimaryWriteFence interface {
	ValidatePrimaryWrite(PrimaryWriteFenceRequest) error
}

PrimaryWriteFence checks whether an external authority still permits a local write.

Its implementation normally checks an atomically refreshed lease epoch and expiry, not the network. Returning an error rejects the whole logical commit before storage mutation; it never poisons the database or advances a token.

Implementations must not call back into DB and must return promptly: the check runs while the writer has admitted a commit. Election, renewal, certificate rotation and old-primary revocation remain external concerns.

type PrimaryWriteFenceRequest

type PrimaryWriteFenceRequest struct {
	DatabaseID         [16]byte
	NextCommitSequence uint64
}

PrimaryWriteFenceRequest identifies the database and next commit requiring write authority.

A lease implementation must reject when its external authority/epoch/expiry no longer permits that write.

type PrimaryWriteFenceStats

type PrimaryWriteFenceStats struct {
	Configured bool   `json:"configured"`
	Enforced   bool   `json:"enforced"`
	Checks     uint64 `json:"checks"`
	Rejected   uint64 `json:"rejected"`
}

PrimaryWriteFenceStats reports whether write protection is active and counts its checks and rejections.

Configured means a guard was supplied at open; Enforced is false while a read-only follower applies validated source history. Checks and Rejected count only actual primary write admissions. No lease, epoch, endpoint, database ID, or controller detail is exposed.

type QueryDelta

type QueryDelta struct {
	FromToken  uint64
	Token      uint64
	Operations []QueryDeltaOperation
}

QueryDelta transforms a query result from FromToken to Token through ordered edits.

Apply operations in slice order: removals come first, followed by reverse-order add or move anchors and document changes.

type QueryDeltaOperation

type QueryDeltaOperation struct {
	Kind       QueryDeltaOperationKind
	DocumentID DocumentID
	BeforeID   DocumentID
	Document   Document
}

QueryDeltaOperation describes one edit to an ordered query result.

A zero BeforeID means the end of the result; document IDs are never zero.

type QueryDeltaOperationKind

type QueryDeltaOperationKind string

QueryDeltaOperationKind identifies a change to an ordered query result.

const (
	// QueryDeltaRemove removes a document from the result.
	QueryDeltaRemove QueryDeltaOperationKind = "remove"
	// QueryDeltaAdd inserts a document before an anchor.
	QueryDeltaAdd QueryDeltaOperationKind = "add_before"
	// QueryDeltaMove moves a document before an anchor.
	QueryDeltaMove QueryDeltaOperationKind = "move_before"
	// QueryDeltaChange replaces a document without changing its position.
	QueryDeltaChange QueryDeltaOperationKind = "change"
)

type QueryDeltaSubscription

type QueryDeltaSubscription struct {
	Initial QuerySnapshot
	Deltas  <-chan QueryDelta
	Errors  <-chan error
	// contains filtered or unexported fields
}

QueryDeltaSubscription provides an initial snapshot followed by ordered result changes.

Transports and reactive clients should prefer it to the full-snapshot adapter.

func (*QueryDeltaSubscription) Close

func (s *QueryDeltaSubscription) Close()

Close cancels delta delivery and is safe to call repeatedly.

type QueryLimits

type QueryLimits struct {
	MaxWireBytes  int
	MaxDepth      int
	MaxNodes      int
	MaxArrayItems int
	MaxValueBytes int
	MaxSortFields int
	MaxLimit      int
}

QueryLimits bounds the size and complexity of accepted queries.

type QueryOptions

type QueryOptions struct {
	Sort  []SortField
	Skip  int
	Limit *int
}

QueryOptions configures query sorting and pagination.

type QueryReplaySource

type QueryReplaySource interface {
	OpenQueryReplay(ctx context.Context, collection string, query QuerySpec, afterToken uint64, buffer int) (*QueryReplaySubscription, error)
}

QueryReplaySource opens a historical query snapshot with an ordered stream of later changes.

Initial.Token must equal afterToken; unavailable history returns ErrHistoryLost.

type QueryReplaySubscription

type QueryReplaySubscription struct {
	Initial QuerySnapshot
	Deltas  <-chan QueryDelta
	Errors  <-chan error
	// contains filtered or unexported fields
}

QueryReplaySubscription provides a historical query snapshot and its later changes.

func (*QueryReplaySubscription) Close

func (subscription *QueryReplaySubscription) Close()

Close cancels replay and waits for delivery to stop.

type QuerySnapshot

type QuerySnapshot struct {
	Token     uint64
	Documents []Document
}

QuerySnapshot pairs an ordered query result with its commit token.

func ApplyQueryDelta

func ApplyQueryDelta(snapshot QuerySnapshot, delta QueryDelta) (QuerySnapshot, error)

ApplyQueryDelta validates and applies ordered changes to a copy of the snapshot.

type QuerySpec

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

QuerySpec holds a compiled filter with sorting and pagination.

func CompileQuery

func CompileQuery(filter Filter, options QueryOptions) (QuerySpec, error)

CompileQuery validates a filter and options to produce a reusable query.

func DecodeQuerySpecJSON

func DecodeQuerySpecJSON(data []byte, limits QueryLimits) (QuerySpec, error)

DecodeQuerySpecJSON validates and decodes a data-only query within the supplied limits.

func (QuerySpec) Capped

func (q QuerySpec) Capped(max int) QuerySpec

Capped applies a nonnegative result cap to a copy of the query.

func (QuerySpec) Constrain

func (q QuerySpec) Constrain(policy QuerySpec) QuerySpec

Constrain adds a required row predicate while preserving sorting and pagination.

func (QuerySpec) Execute

func (q QuerySpec) Execute(documents []Document) []Document

Execute filters, sorts, and paginates supplied documents into copied results.

func (QuerySpec) FilterCapabilities

func (q QuerySpec) FilterCapabilities() []FilterCapability

FilterCapabilities returns distinct field and predicate-operation pairs in sorted order.

func (QuerySpec) HasModifiers

func (q QuerySpec) HasModifiers() bool

HasModifiers reports whether sorting, an offset, or a limit is set.

func (QuerySpec) Limit

func (q QuerySpec) Limit() (int, bool)

Limit returns the requested result count and whether a limit is set.

func (QuerySpec) Match

func (q QuerySpec) Match(document Document) bool

Match reports whether a document satisfies the query's filter.

func (QuerySpec) Paths

func (q QuerySpec) Paths() []string

Paths returns distinct filter and sort paths in sorted order.

func (QuerySpec) Skip

func (q QuerySpec) Skip() int

Skip returns the requested result offset.

func (QuerySpec) Sort

func (q QuerySpec) Sort() []SortField

Sort returns a copy of the query's ordered sort fields.

func (QuerySpec) SortPaths

func (q QuerySpec) SortPaths() []string

SortPaths returns field paths in the query's sort order.

func (QuerySpec) UsesSeekPagination

func (q QuerySpec) UsesSeekPagination() bool

UsesSeekPagination reports whether the query was compiled with seek pagination.

func (QuerySpec) Validate

func (q QuerySpec) Validate() error

Validate checks that the compiled query is safe to execute under default input limits.

A zero QuerySpec is invalid because it has no filter expression.

type QueryStats

type QueryStats struct {
	ActiveCursors         uint64 `json:"activeCursors"`
	Total                 uint64 `json:"total"`
	Failed                uint64 `json:"failed"`
	CollectionScans       uint64 `json:"collectionScans"`
	IndexScans            uint64 `json:"indexScans"`
	IDLookups             uint64 `json:"idLookups"`
	DocumentsExamined     uint64 `json:"documentsExamined"`
	DocumentsReturned     uint64 `json:"documentsReturned"`
	KeysExamined          uint64 `json:"keysExamined"`
	PredicateSteps        uint64 `json:"predicateSteps"`
	CandidateIDs          uint64 `json:"candidateIds"`
	UniqueCandidateIDs    uint64 `json:"uniqueCandidateIds"`
	DuplicateCandidateIDs uint64 `json:"duplicateCandidateIds"`
	CandidatesRetained    uint64 `json:"candidatesRetained"`
	SortBytes             uint64 `json:"sortBytes"`
	EarlyStops            uint64 `json:"earlyStops"`
	BudgetPressureEvents  uint64 `json:"budgetPressureEvents"`
	BudgetRejections      uint64 `json:"budgetRejections"`
}

QueryStats counts query activity and execution work during the current process session.

Physical key and candidate counters include work completed before a failed query; the older document/return counters retain their successful-query contract.

type QuerySubscription

type QuerySubscription struct {
	Snapshots <-chan QuerySnapshot
	Errors    <-chan error
	// contains filtered or unexported fields
}

QuerySubscription provides full query snapshots as the result changes.

func (*QuerySubscription) Close

func (s *QuerySubscription) Close()

Close cancels full-snapshot delivery and is safe to call repeatedly.

type RealtimeStats

type RealtimeStats struct {
	SharedViews            uint64 `json:"sharedViews"`
	QuerySubscribers       uint64 `json:"querySubscribers"`
	SharedViewReuses       uint64 `json:"sharedViewReuses"`
	IncrementalBatches     uint64 `json:"incrementalBatches"`
	IncrementalViewUpdates uint64 `json:"incrementalViewUpdates"`
	FullViewRecomputes     uint64 `json:"fullViewRecomputes"`
	QueueOverflows         uint64 `json:"queueOverflows"`
	PendingBatches         uint64 `json:"pendingBatches"`
	PendingChanges         uint64 `json:"pendingChanges"`
	PendingBytes           uint64 `json:"pendingBytes"`
	PendingBatchCapacity   uint64 `json:"pendingBatchCapacity"`
	PendingChangeCapacity  uint64 `json:"pendingChangeCapacity"`
	PendingByteCapacity    uint64 `json:"pendingByteCapacity"`
	WatcherPendingBytes    uint64 `json:"watcherPendingBytes"`
	WatcherByteCapacity    uint64 `json:"watcherByteCapacity"`
	DispatchPendingBatches uint64 `json:"dispatchPendingBatches"`
	DispatchPendingChanges uint64 `json:"dispatchPendingChanges"`
	DispatchPendingBytes   uint64 `json:"dispatchPendingBytes"`
	DispatchBatchCapacity  uint64 `json:"dispatchBatchCapacity"`
	DispatchChangeCapacity uint64 `json:"dispatchChangeCapacity"`
	DispatchByteCapacity   uint64 `json:"dispatchByteCapacity"`
	SharedDeltas           uint64 `json:"sharedDeltas"`
	DeltaDeliveries        uint64 `json:"deltaDeliveries"`
	DeltaOperations        uint64 `json:"deltaOperations"`
	PublishedBatches       uint64 `json:"publishedBatches"`
	PublishedChanges       uint64 `json:"publishedChanges"`
	WatcherDeliveries      uint64 `json:"watcherDeliveries"`
	InitialSnapshots       uint64 `json:"initialSnapshots"`
	QueryRecomputes        uint64 `json:"queryRecomputes"`
	SnapshotsEmitted       uint64 `json:"snapshotsEmitted"`
	DocumentsEmitted       uint64 `json:"documentsEmitted"`
	SlowConsumers          uint64 `json:"slowConsumers"`
}

RealtimeStats reports live query activity, queued work, and overloads.

type ReclaimOptions

type ReclaimOptions struct {
	Online      bool
	MaxAttempts int
	// MemoryOnly skips the physical FreeSpace maintenance generation. It keeps
	// the final installation pause O(1), but another audit is needed after reopen.
	MemoryOnly bool
}

ReclaimOptions configures page-reclamation mode, retries, and persistence.

Online scans a duplicate read handle without the storage writer lock and installs its result only if the Meta generation is unchanged. MaxAttempts bounds complete graph rescans after concurrent commits; zero selects three attempts.

type ReclaimResult

type ReclaimResult struct {
	PhysicalPages   uint64
	ReachablePages  uint64
	ReusablePages   uint64
	PinnedSnapshots uint64
	Attempts        int
	Online          bool
	Persisted       bool
}

ReclaimResult reports reachable and reusable pages after reclamation.

type ReclamationStats

type ReclamationStats struct {
	Active          uint64        `json:"active"`
	Attempts        uint64        `json:"attempts"`
	Scans           uint64        `json:"scans"`
	Conflicts       uint64        `json:"conflicts"`
	Completed       uint64        `json:"completed"`
	Failed          uint64        `json:"failed"`
	LastAttempts    uint64        `json:"lastAttempts"`
	LastOnline      bool          `json:"lastOnline"`
	LastReachable   uint64        `json:"lastReachable"`
	LastReclaimable uint64        `json:"lastReclaimable"`
	LastDuration    time.Duration `json:"lastDurationNanos"`
}

ReclamationStats reports page-reclamation activity and outcomes.

type RecoveryMode

type RecoveryMode uint8

RecoveryMode selects whether startup may perform bounded recovery actions.

Zero selects automatic recovery; RecoveryReport describes completed actions.

const (
	// RecoveryAutomatic allows bounded automatic recovery when opening a database.
	RecoveryAutomatic RecoveryMode = iota
	// RecoveryRequireClean rejects opening a database that needs recovery.
	RecoveryRequireClean
)

type RecoveryReport

type RecoveryReport struct {
	SchemaVersion          int    `json:"schemaVersion"`
	Engine                 string `json:"engine"`
	Created                bool   `json:"created"`
	Recovered              bool   `json:"recovered"`
	CommitSequenceBefore   uint64 `json:"commitSequenceBefore"`
	CommitSequenceAfter    uint64 `json:"commitSequenceAfter"`
	SelectedMetaSlot       uint8  `json:"selectedMetaSlot"`
	ChecksumValidMetaSlots uint8  `json:"checksumValidMetaSlots"`
	RootValidMetaSlots     uint8  `json:"rootValidMetaSlots"`
	MetaRedundancyDegraded bool   `json:"metaRedundancyDegraded"`
	FallbackToOlderRoot    bool   `json:"fallbackToOlderRoot"`
	MainTailBytesRemoved   uint64 `json:"mainTailBytesRemoved"`
	WALRecordsReplayed     uint64 `json:"walRecordsReplayed"`
	WALTailBytesRemoved    uint64 `json:"walTailBytesRemoved"`
	AccelerationDegraded   bool   `json:"accelerationDegraded"`
}

RecoveryReport records completed startup recovery actions without exposing sensitive data.

It reports only actions that were completed before Open returned successfully; corruption and unsupported formats still fail Open instead of being described as recovered.

type ReplicationFrame

type ReplicationFrame struct {
	Type       string
	DatabaseID [16]byte
	AfterToken uint64 // hello: receiver's durable position
	MaxBytes   int    // hello: receiver frame cap
	Batch      *DurableDatabaseChangeBatch
	AckToken   uint64
	Reason     string
}

ReplicationFrame carries a handshake, change batch, acknowledgement, or resync request.

A transport must authenticate both peers (for example with mTLS) before it accepts frames; DatabaseID binds every frame to one durable source identity.

func UnmarshalReplicationFrame

func UnmarshalReplicationFrame(data []byte, limits ReplicationFrameLimits) (ReplicationFrame, error)

UnmarshalReplicationFrame validates and decodes a bounded JSON replication message.

It rejects unknown fields, duplicate keys, malformed base64, invalid typed documents, and non-canonical identities before the follower receives a batch.

type ReplicationFrameLimits

type ReplicationFrameLimits struct{ MaxFrameBytes int }

ReplicationFrameLimits caps the size of a decompressed replication message.

The default accommodates the configured 64 MiB canonical transaction limit plus JSON/base64 overhead, while still rejecting unbounded peer allocation.

type ReplicationSourceLease

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

ReplicationSourceLease reserves a replica consumer for one session in this process.

It prevents sessions from racing the same checkpoint and does not replace external primary election or follower-promotion fencing.

func (*ReplicationSourceLease) Release

func (lease *ReplicationSourceLease) Release()

Release frees the reserved consumer name and is safe to call repeatedly.

It leaves the durable checkpoint unchanged; only session acknowledgments advance that recovery position.

type ReplicationSourceSession

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

ReplicationSourceSession sends committed database changes to one authenticated receiver.

Only one batch may await acknowledgement at a time, limiting queued work and preventing acknowledgement of an unseen source token.

func NewReplicationSourceSession

func NewReplicationSourceSession(db *DB, subscription *DurableDatabaseChangeSubscription, limits ReplicationFrameLimits) (*ReplicationSourceSession, error)

NewReplicationSourceSession creates a replication session from a named database change feed.

The caller authenticates the receiver and must close the session when that authenticated connection ends.

func (*ReplicationSourceSession) AcceptAck

func (session *ReplicationSourceSession) AcceptAck(frame ReplicationFrame) error

AcceptAck saves the receiver's acknowledgement of the batch awaiting confirmation.

The token must exactly match the one batch in flight; stale, future or duplicate ACKs cannot release retained history.

func (*ReplicationSourceSession) AcceptHello

func (session *ReplicationSourceSession) AcceptHello(frame ReplicationFrame) (*ReplicationFrame, error)

AcceptHello checks the receiver's database identity and saved commit position.

A different identity or checkpoint is a safe resync response, never an implicit rewind or jump of the source durable consumer.

func (*ReplicationSourceSession) Checkpoint

func (session *ReplicationSourceSession) Checkpoint() (uint64, error)

Checkpoint returns the last source commit durably acknowledged by the receiver.

func (*ReplicationSourceSession) Close

func (session *ReplicationSourceSession) Close()

Close stops the source session's durable change subscription.

func (*ReplicationSourceSession) NextFrame

func (session *ReplicationSourceSession) NextFrame(ctx context.Context) (*ReplicationFrame, error)

NextFrame waits for the next source batch and prepares it for transmission.

The caller must not send another frame until AcceptAck succeeds for this token. If the peer's declared frame cap cannot carry one atomic Commit Log batch, the session terminates with snapshot_required rather than splitting or partially sending a commit.

type ResourceLimits

type ResourceLimits struct {
	MaxDocumentBytes          uint64 `json:"maxDocumentBytes"`
	MaxTransactionBytes       uint64 `json:"maxTransactionBytes"`
	MaxTransactionChanges     uint64 `json:"maxTransactionChanges"`
	MaxIndexBuildEntries      uint64 `json:"maxIndexBuildEntries"`
	MaxIndexBuildBytes        uint64 `json:"maxIndexBuildBytes"`
	MaxReactiveViewDocuments  uint64 `json:"maxReactiveViewDocuments"`
	MaxReactiveViewBytes      uint64 `json:"maxReactiveViewBytes"`
	MaxQueryDocumentsExamined uint64 `json:"maxQueryDocumentsExamined"`
	MaxQueryKeysExamined      uint64 `json:"maxQueryKeysExamined"`
	MaxQueryCandidates        uint64 `json:"maxQueryCandidates"`
	MaxQuerySortBytes         uint64 `json:"maxQuerySortBytes"`
	MaxQuerySkip              uint64 `json:"maxQuerySkip"`
	MaxQueryPredicateSteps    uint64 `json:"maxQueryPredicateSteps"`
}

ResourceLimits bounds work admitted by writes, index maintenance, and query execution.

Zero values select production defaults; limits cannot be disabled accidentally. Byte limits use the canonical typed binary representation, independent of Go heap layout, JSON spelling, storage generation, or transport compression.

type ResourceStats

type ResourceStats struct {
	Limits     ResourceLimits `json:"limits"`
	Rejections uint64         `json:"rejections"`
}

ResourceStats reports configured resource limits and rejection counts.

type RollbackAnchor

type RollbackAnchor struct {
	DatabaseID            [16]byte
	MinimumCommitSequence uint64
	MinimumGeneration     uint64
}

RollbackAnchor records trusted minimum commit and generation values outside the database.

A server must never accept the same identity below either an acknowledged logical commit sequence or physical maintenance generation after restart. The coordinates are independently monotonic: one group may advance several logical sequences while publishing a single physical generation.

type RollbackAnchorStatusProvider

type RollbackAnchorStatusProvider interface {
	RollbackAnchorStatus() RollbackAnchorStoreStatus
}

RollbackAnchorStatusProvider exposes anchor store counters without acquiring locks.

type RollbackAnchorStore

type RollbackAnchorStore interface {
	Load(context.Context) (RollbackAnchor, bool, error)
	Advance(context.Context, RollbackAnchor) error
}

RollbackAnchorStore loads and durably advances a database's trusted rollback boundary.

Advance must not return until the anchor is persistent and must reject identity changes or regression of either monotonic coordinate. Implementations must be safe for concurrent callers and honor cancellation. An Advance error does not prove that state was unchanged: persistence may have completed before a response, deadline or cancellation was observed.

func NewFileRollbackAnchorStore

func NewFileRollbackAnchorStore(path string) (RollbackAnchorStore, error)

NewFileRollbackAnchorStore creates a file-backed store for trusted database version limits.

Updates replace the anchor atomically and reject invalid saved state. The parent directory must exist on storage trusted independently from the database.

type RollbackAnchorStoreStatus

type RollbackAnchorStoreStatus struct {
	Replicas               uint64 `json:"replicas"`
	Quorum                 uint64 `json:"quorum"`
	Loads                  uint64 `json:"loads"`
	Advances               uint64 `json:"advances"`
	EndpointFailures       uint64 `json:"endpointFailures"`
	QuorumFailures         uint64 `json:"quorumFailures"`
	Conflicts              uint64 `json:"conflicts"`
	AuthenticationFailures uint64 `json:"authenticationFailures"`
	ProtocolFailures       uint64 `json:"protocolFailures"`
	ConfigurationFailures  uint64 `json:"configurationFailures"`
}

RollbackAnchorStoreStatus reports anchor backend counters without exposing database identities.

These diagnostic counters never participate in recovery.

type RollbackProtection

type RollbackProtection struct {
	ExpectedDatabaseID    [16]byte
	MinimumCommitSequence uint64
	MinimumGeneration     uint64
	AnchorStore           RollbackAnchorStore
	InitializeAnchor      bool
	// OperationTimeout bounds each Load/Advance/read-back interaction. Zero
	// selects DefaultRollbackAnchorOperationTimeout.
	OperationTimeout time.Duration
}

RollbackProtection configures identity and progress checks that reject database rollback.

AnchorStore should live on an independently trusted device or remote quorum; placing it beside the database cannot detect whole-device rollback. InitializeAnchor explicitly trusts the database currently at Path when the store is empty and should only be used during provisioning or audited restore.

type SortField

type SortField struct {
	Path      string `json:"path"`
	Direction int    `json:"direction"`
}

SortField specifies a document path and its ascending or descending sort direction.

type StorageFormat

type StorageFormat string

StorageFormat identifies the supported file format or an absent database.

Unknown denotes a missing or zero-length path, not an unrecognized non-empty file.

const (
	// StorageFormatUnknown identifies a missing or empty database file.
	StorageFormatUnknown StorageFormat = ""
	// StorageFormatCurrent identifies the supported database file format.
	StorageFormatCurrent StorageFormat = "current"
)

func DetectStorageFormat

func DetectStorageFormat(path string) (StorageFormat, error)

DetectStorageFormat distinguishes an absent database from a recognized database format.

Old database files deliberately fail closed: this build contains no legacy reader or automatic migration path.

type StorageFormatInfo

type StorageFormatInfo struct {
	Format            StorageFormat `json:"format"`
	Revision          uint16        `json:"revision"`
	Generation        uint64        `json:"generation"`
	CommitSequence    uint64        `json:"commitSequence"`
	PhysicalPageCount uint64        `json:"physicalPageCount,omitempty"`
	RequiredFeatures  uint64        `json:"requiredFeatures"`
	OptionalFeatures  uint64        `json:"optionalFeatures"`
	DatabaseIDHex     string        `json:"databaseIdHex,omitempty"`
	ValidMetaSlots    int           `json:"validMetaSlots"`
	ReaderCompatible  bool          `json:"readerCompatible"`
}

StorageFormatInfo reports file format metadata and compatibility with this reader.

ReaderCompatible says this binary understands the reported revision and all required feature bits; callers must still Open the database before use.

func InspectStorageFormat

func InspectStorageFormat(path string) (StorageFormatInfo, error)

InspectStorageFormat validates current Meta checksums and reports its newest readable envelope without opening the database for mutation.

type StorageLimits

type StorageLimits struct{ MaxFileBytes uint64 }

StorageLimits caps the physical database file size.

Zero selects DefaultMaxFileBytes; the limit must be a multiple of the 16 KiB page size.

type StorageStats

type StorageStats struct {
	Engine                     string                    `json:"engine"`
	RollbackProtected          bool                      `json:"rollbackProtected"`
	RollbackAnchorSequence     uint64                    `json:"rollbackAnchorSequence"`
	RollbackAnchorGeneration   uint64                    `json:"rollbackAnchorGeneration"`
	RollbackAnchorFailures     uint64                    `json:"rollbackAnchorFailures"`
	RollbackAnchorTimeout      time.Duration             `json:"rollbackAnchorTimeoutNanos"`
	RollbackAnchorNanos        uint64                    `json:"rollbackAnchorNanos"`
	RollbackAnchorMaxLatency   time.Duration             `json:"rollbackAnchorMaxLatencyNanos"`
	RollbackAnchorStore        RollbackAnchorStoreStatus `json:"rollbackAnchorStore"`
	PageSize                   uint64                    `json:"pageSize"`
	Generation                 uint64                    `json:"generation"`
	PhysicalPages              uint64                    `json:"physicalPages"`
	CommitSequence             uint64                    `json:"commitSequence"`
	OldestRetainedSequence     uint64                    `json:"oldestRetainedSequence"`
	RetainedCommits            uint64                    `json:"retainedCommits"`
	CommitRetentionMax         uint64                    `json:"commitRetentionMax"`
	CommitRetentionOverage     uint64                    `json:"commitRetentionOverage"`
	RetainedCommitBytes        uint64                    `json:"retainedCommitBytes"`
	CommitRetentionMaxBytes    uint64                    `json:"commitRetentionMaxBytes"`
	CommitRetentionByteOverage uint64                    `json:"commitRetentionByteOverage"`
	RetentionPrunedCommits     uint64                    `json:"retentionPrunedCommits"`
	RetentionPressureEvents    uint64                    `json:"retentionPressureEvents"`
	RetentionPressure          bool                      `json:"retentionPressure"`
	StorageUsedBytes           uint64                    `json:"storageUsedBytes"`
	StorageMaxBytes            uint64                    `json:"storageMaxBytes"`
	StorageByteOverage         uint64                    `json:"storageByteOverage"`
	StorageLimitRejections     uint64                    `json:"storageLimitRejections"`
	StorageQuotaExhausted      bool                      `json:"storageQuotaExhausted"`
	ActiveReaders              uint64                    `json:"activeReaders"`
	ActiveReplayLeases         uint64                    `json:"activeReplayLeases"`
	Documents                  uint64                    `json:"documents"`
	Collections                uint64                    `json:"collections"`
	ReusablePages              uint64                    `json:"reusablePages"`
	TreeSplits                 uint64                    `json:"treeSplits"`
	TreeMerges                 uint64                    `json:"treeMerges"`
	PersistentFreeSpace        bool                      `json:"persistentFreeSpace"`
	FreeSpaceLoads             uint64                    `json:"freeSpaceLoads"`
	FreeSpaceLoadFailures      uint64                    `json:"freeSpaceLoadFailures"`
	FreeSpacePublishes         uint64                    `json:"freeSpacePublishes"`
	FreeSpaceCandidateChecks   uint64                    `json:"freeSpaceCandidateChecks"`
	PageCache                  PageCacheStats            `json:"pageCache"`
	DocumentCache              DocumentCacheStats        `json:"documentCache"`
	CommitAttempts             uint64                    `json:"commitAttempts"`
	CommittedTransactions      uint64                    `json:"committedTransactions"`
	RejectedTransactions       uint64                    `json:"rejectedTransactions"`
	CommitNanos                uint64                    `json:"commitNanos"`
	CommitMaxLatency           time.Duration             `json:"commitMaxLatencyNanos"`
}

StorageStats describes the selected physical backend.

Session counters reset on reopen; physical state and cache counters come from the backend itself.

type Update

type Update map[string]any

Update maps update operators to their requested field changes.

type UpdateResult

type UpdateResult struct{ MatchedCount, ModifiedCount int64 }

UpdateResult reports how many documents matched and changed.

type Value

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

Value stores typed database data behind a private representation.

func Array

func Array(v ...Value) Value

Array creates an array value from copies of its elements.

func Binary

func Binary(v []byte) Value

Binary creates a binary value from a copy of the bytes.

func Bool

func Bool(v bool) Value

Bool creates a boolean value.

func Float

func Float(v float64) Value

Float creates a 64-bit floating-point value.

func ID

func ID(v DocumentID) Value

ID creates a document identifier value.

func Int

func Int(v int64) Value

Int creates a signed 64-bit integer value.

func Null

func Null() Value

Null creates a null value.

func Object

func Object(v Document) Value

Object creates an object value from a copy of the document.

func String

func String(v string) Value

String creates a string value.

func Time

func Time(v time.Time) Value

Time creates a UTC timestamp value rounded down to millisecond precision.

func UnmarshalWireValue

func UnmarshalWireValue(data []byte, limits QueryLimits) (Value, error)

UnmarshalWireValue decodes a typed JSON value within the supplied query limits.

It applies the same nesting, item count, and size limits as query operands. Protocol arguments such as RPC inputs contain data only; decoding never runs code.

func ValueOf

func ValueOf(x any) (Value, error)

ValueOf converts a supported Go value into a database value with copied nested data.

func (Value) ArrayValue

func (v Value) ArrayValue() ([]Value, bool)

ArrayValue returns copies of the stored elements and whether the value is an array.

func (Value) BinaryValue

func (v Value) BinaryValue() ([]byte, bool)

BinaryValue returns a copy of the stored bytes and whether the value is binary.

func (Value) Bool

func (v Value) Bool() (bool, bool)

Bool returns the stored boolean and whether the value is a boolean.

func (Value) Clone

func (v Value) Clone() Value

Clone copies the value and all nested data.

func (Value) Equal

func (v Value) Equal(other Value) bool

Equal compares values recursively and allows exact equality between integers and floats.

func (Value) Float64

func (v Value) Float64() (float64, bool)

Float64 returns the stored float and whether the value is a float.

func (Value) IDValue

func (v Value) IDValue() (DocumentID, bool)

IDValue returns the stored identifier and whether the value is an identifier.

func (Value) Int64

func (v Value) Int64() (int64, bool)

Int64 returns the stored integer and whether the value is an integer.

func (Value) Kind

func (v Value) Kind() Kind

Kind returns the type of the value.

func (Value) ObjectValue

func (v Value) ObjectValue() (Document, bool)

ObjectValue returns a copy of the stored document and whether the value is an object.

func (Value) StringValue

func (v Value) StringValue() (string, bool)

StringValue returns the stored string and whether the value is a string.

func (Value) TimeValue

func (v Value) TimeValue() (time.Time, bool)

TimeValue returns the stored time and whether the value is a time.

type VerificationReport

type VerificationReport struct {
	SchemaVersion              int           `json:"schemaVersion"`
	Verified                   bool          `json:"verified"`
	Format                     StorageFormat `json:"format"`
	Revision                   uint16        `json:"revision"`
	DatabaseIDHex              string        `json:"databaseIdHex"`
	MetaGeneration             uint64        `json:"metaGeneration"`
	CommitSequence             uint64        `json:"commitSequence"`
	OldestRetainedSequence     uint64        `json:"oldestRetainedSequence"`
	RequiredFeatures           uint64        `json:"requiredFeatures"`
	OptionalFeatures           uint64        `json:"optionalFeatures"`
	ValidMetaSlots             int           `json:"validMetaSlots"`
	FileBytes                  uint64        `json:"fileBytes"`
	TrailingBytes              uint64        `json:"trailingBytes"`
	PhysicalPages              uint64        `json:"physicalPages"`
	CommittedPhysicalPages     uint64        `json:"committedPhysicalPages"`
	ReachablePages             uint64        `json:"reachablePages"`
	ReclaimablePages           uint64        `json:"reclaimablePages"`
	PersistentFreeSpace        bool          `json:"persistentFreeSpace"`
	FreeSpaceValid             bool          `json:"freeSpaceValid"`
	IndexContentsVerified      bool          `json:"indexContentsVerified"`
	IndexBuildContentsVerified bool          `json:"indexBuildContentsVerified"`
	SHA256                     string        `json:"sha256"`
}

VerificationReport records the results of a read-only page and index audit.

ReclaimablePages is informational; verification never installs a free pool or publishes maintenance metadata.

func VerifyFile

func VerifyFile(ctx context.Context, path string) (VerificationReport, error)

VerifyFile checks an existing database's protected pages and index contents without changing it.

It takes a non-blocking shared advisory lock, so an active writer fails with ErrDatabaseLocked. It never creates, truncates, repairs, reclaims, or advances the database. Meta inspection alone is cheaper; this method walks every page protected by both valid Meta roots, recomputes published and provable shadow Secondary keys from canonical Primary documents in both directions, and hashes the file. Legacy caught-up builds lacking an applied CatalogRoot remain readable but report IndexBuildContentsVerified=false.

type WriteTransaction

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

WriteTransaction stages reads and writes against a snapshot for an atomic commit.

Commit validation detects conflicting changes, and returned values are independent copies.

A transaction is active only during its handler callback. Handlers must not retain it or call normal DB/Collection methods from inside the callback.

func (*WriteTransaction) DeleteOne

func (tx *WriteTransaction) DeleteOne(collection string, id DocumentID) error

DeleteOne stages the deletion of a document by ID.

Deleting a document inserted earlier in the same callback cancels that insert without producing a storage mutation.

func (*WriteTransaction) Find

func (tx *WriteTransaction) Find(collection string, query QuerySpec) (QuerySnapshot, error)

Find queries the transaction snapshot including its staged document changes.

It installs a collection snapshot fence, so any concurrent document or published-index change in that collection causes the eventual commit to return ErrWriteConflict rather than admitting a phantom.

The first range-read primitive intentionally uses a collection-wide fence. It is serializable and independent of a process-local index plan; a future narrower predicate-fence implementation can refine conflicts without weakening this API's correctness contract.

func (*WriteTransaction) GetOne

func (tx *WriteTransaction) GetOne(collection string, id DocumentID) (Document, error)

GetOne returns a document by ID, including changes staged earlier in the transaction.

func (*WriteTransaction) InsertOne

func (tx *WriteTransaction) InsertOne(collection string, document Document) (DocumentID, error)

InsertOne stages one insert and returns its generated or supplied ID.

func (*WriteTransaction) MeldbaseStageSystemMutation

func (tx *WriteTransaction) MeldbaseStageSystemMutation(mutation systemrecord.Mutation, onCommit func(uint64)) error

MeldbaseStageSystemMutation stages a private system record change alongside document writes.

Its internal parameter type prevents external applications from accessing the private System tree. onCommit runs synchronously after the durable root is published and before the matching business ChangeBatch becomes visible; it must be bounded, non-blocking and must not call back into the database.

func (*WriteTransaction) ReplaceOne

func (tx *WriteTransaction) ReplaceOne(collection string, id DocumentID, document Document) error

ReplaceOne stages a full replacement for an existing document.

The supplied document may omit _id; if present it must equal id.

func (*WriteTransaction) UpdateOne

func (tx *WriteTransaction) UpdateOne(collection string, id DocumentID, mutation MutationSpec) error

UpdateOne stages a mutation of the transaction's current document.

Earlier writes in the same transaction are visible, and _id cannot change.

type WriteTransactionStats

type WriteTransactionStats struct {
	Active    uint64 `json:"active"`
	Started   uint64 `json:"started"`
	Committed uint64 `json:"committed"`
	Noops     uint64 `json:"noops"`
	Conflicts uint64 `json:"conflicts"`
	Aborted   uint64 `json:"aborted"`
}

WriteTransactionStats counts active transactions and their outcomes.

Every started callback reaches exactly one terminal counter. These aggregates do not contain collection, document, actor, or callback identifiers.

Jump to

Keyboard shortcuts

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