storage

package
v1.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 77 Imported by: 1 module, 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

Author: NOR-288 implementation lane (Codex), 2026-10-26.

Package storage provides storage engine implementations for NornicDB.

BadgerEngine provides persistent disk-based storage using BadgerDB. It implements the Engine interface with full ACID transaction support.

Package storage provides storage engine implementations for NornicDB.

Package storage provides storage engine implementations for NornicDB.

Package storage provides storage engine implementations for NornicDB.

Package storage provides storage engine implementations for NornicDB.

Package storage provides storage engine implementations for NornicDB.

Package storage provides storage engine implementations for NornicDB.

Package storage provides storage engine implementations for NornicDB.

Plan 04-04-06: BadgerEngine metric attachment + per-op observation helpers.

AttachMetrics binds the StorageMetrics + MVCCMetrics bags into the engine and pre-binds the four op-duration observers (MET-25). Subsequent hot-path Get/Put/Delete/Scan calls use observeStorageOp(start, observer) which is zero-overhead when metrics are not attached (the BoundLatency Observer's zero value short-circuits via the typed wrapper's Observe path).

D-16 boundary: storage layer never imports observability for ErrConflict counters — that wiring lives in pkg/cypher (Plan 04-03). This file is the LIMITED storage→observability dependency: storage emits its OWN subsystem families only (op_duration_seconds, bytes, compactions, index_rebuild). Cross-layer counters (transaction_conflicts) stay at the Cypher transaction wrapper.

Package storage provides storage engine implementations for NornicDB.

Package storage provides storage engine implementations for NornicDB.

Package storage - Serialization helpers for BadgerDB.

All new writes use msgpack with a small header. Legacy gob bodies (no header) are still decodable for one purpose only: the offline in-place migration tool that rewrites them as msgpack. The encoder NEVER emits gob.

Package storage provides storage engine implementations for NornicDB.

Package storage - BadgerDB transaction wrapper with ACID guarantees.

This file implements atomic transactions for BadgerDB with full constraint validation and rollback support.

Plan 04-04-04: D-07 30s sweep lifecycle.Component populating nornicdb_storage_bytes{kind} gauges by calling badger.DB.EstimateSize(prefix) for each kind bucket.

Lifecycle semantics (RESEARCH §Architecture Pattern 2):

  • Start spawns a goroutine that ticks every interval (default 30s).
  • Each tick wraps `defer recover()` so a transient Badger panic during compaction does not crash the supervisor errgroup (RISK-8).
  • Shutdown closes the ticker and waits for the goroutine to exit within the supervisor's drain budget (5s typical).

Five `kind` buckets (closed enum AllowedStorageBytesKinds):

  • nodes — prefixNode
  • edges — prefixEdge
  • index — prefixLabelIndex + prefixEdgeBetweenIndex + prefixTemporalIndex (sum across the three index prefixes; user-created indexes are not separately accounted by D-13c)
  • wal — heuristic (vlog size - lsm size from db.Size()); RISK-6
  • search — sum of IndexSizeBytes() across all per-database search services (Plan 04-05 owns the IndexSizeBytes accessor; this sweeper consumes via the SearchSizeFn callback so the storage layer never imports pkg/search)

The sweeper is registered in cmd/nornicdb between pprof and workers components per RESEARCH §Q4 — i.e. it Drains AFTER the workers and BEFORE the telemetry listener, so the final scrape during drain still reflects the last known sizes.

CompositeEngine capability dispatchers.

CompositeEngine spans multiple constituent databases and must expose the same optional capabilities as the wrappers it aggregates so callers never silently fall back based on which engine they hold (DIVERGENCE_REPORT.md §2). ID-scoped reads route to every readable constituent until one resolves; merge reads aggregate across all readable constituents; maintenance and lifecycle operations broadcast.

Package storage provides composite engine for composite database support.

CompositeEngine implements the Engine interface by routing operations to multiple constituent databases and merging results transparently.

Package storage provides routing logic for composite engines.

This file implements query analysis and routing for composite databases, determining which constituents should be queried based on query patterns.

Package storage - Constraint validation when constraints are created.

Package storage provides edge provenance logging for NornicDB.

Edge provenance tracks the audit trail for edges - why they were created, when, what evidence supports them, and their lifecycle state.

Feature flag: NORNICDB_EDGE_PROVENANCE_ENABLED (enabled by default)

Usage:

store := NewEdgeMetaStore()
meta := EdgeMeta{
    Src:        "node-A",
    Dst:        "node-B",
    Label:      "relates_to",
    Score:      0.85,
    SignalType: "similarity",
}
store.Append(ctx, meta)

// Query history
history, _ := store.GetHistory(ctx, "node-A", "node-B", "relates_to")

Author: #1683 lane (Claude), 2026-10-30 (NOR-148); ported to release/v1.4.4.

Plan 04-04-05: D-13c index-name → enum mapping.

classifyIndexName is the pure function that maps an internal index identifier (e.g. "label_Person", "edge_between_KNOWS", "temporal_user_activity", "embedding_chunk", or any user-named string) to one of the closed-enum buckets accepted by observability.AllowedStorageIndexes:

{"label", "edge_between", "temporal", "embedding", "user_created"}

Anything not matching a known prefix buckets to "user_created" — the keystone of T-04-02 mitigation. Drives 1k arbitrary user index names → cardinality stays at 5.

Pure function, no allocations, safe in hot paths.

Package storage provides storage implementations and data import/export functionality.

This file specifically handles Neo4j JSON import/export functionality, enabling NornicDB to interoperate with Neo4j databases through standard JSON export formats.

Supported Formats:

  • Neo4j APOC JSON exports (nodes.json + relationships.json)
  • Combined Neo4j export format (single JSON file)
  • NornicDB native format with full fidelity

Key Features:

  • Bidirectional Neo4j compatibility
  • Bulk loading for performance
  • Property type preservation
  • Label and relationship type mapping
  • Error handling and validation

Example Usage:

// Load from Neo4j APOC export
engine := storage.NewMemoryEngine()
err := storage.LoadFromNeo4jJSON(engine, "./neo4j-export/")
if err != nil {
	log.Fatal(err)
}

// Load from combined export file
err = storage.LoadFromNeo4jExport(engine, "./data.json")
if err != nil {
	log.Fatal(err)
}

// Export to Neo4j format
err = storage.SaveToNeo4jExport(engine, "./nornicdb-export.json")
if err != nil {
	log.Fatal(err)
}

Neo4j APOC Export Format:

The APOC export format consists of two files:

  • nodes.json: One JSON object per line, each representing a node
  • relationships.json: One JSON object per line, each representing a relationship

Example nodes.json:

{"id":"0","labels":["Person"],"properties":{"name":"Alice","age":30}}
{"id":"1","labels":["Person"],"properties":{"name":"Bob","age":25}}

Example relationships.json:

{"id":"0","type":"KNOWS","startNode":"0","endNode":"1","properties":{"since":2020}}

Combined Export Format:

The combined format includes both nodes and relationships in a single JSON file:

{
  "nodes": [...],
  "relationships": [...]
}

Data Type Mapping:

Neo4j types are mapped to Go types as follows:

  • String -> string
  • Integer -> int64
  • Float -> float64
  • Boolean -> bool
  • Array -> []interface{}
  • Object -> map[string]interface{}

Performance:

  • Bulk operations are used for efficient loading
  • Streaming JSON parsing for large files
  • Memory-efficient processing
  • Progress reporting for large imports

ELI12 (Explain Like I'm 12):

Think of this like moving between different types of photo albums:

  1. **Neo4j format**: Like a specific brand of photo album with a special way of organizing photos (nodes) and the connections between them (relationships).

  2. **Loading**: Like taking photos from a Neo4j album and putting them into a NornicDB album, making sure each photo goes in the right place and keeps all its information.

  3. **Exporting**: Like taking photos from a NornicDB album and organizing them in the Neo4j format so they can be used in Neo4j tools.

  4. **Bulk operations**: Instead of moving photos one by one, we move whole pages at a time to make it much faster.

This lets you easily move your data between NornicDB and Neo4j!

Package storage provides storage engine implementations for NornicDB.

The storage package defines the Engine interface and provides multiple implementations:

  • MemoryEngine: In-memory storage using BadgerDB's in-memory mode (for testing)
  • BadgerEngine: Persistent disk-based storage

All storage engines are thread-safe and support concurrent operations.

Example Usage:

// Create in-memory storage (for testing)
engine := storage.NewMemoryEngine()
defer engine.Close()

// Create a node
node := &storage.Node{
	ID:     "user-001",
	Labels: []string{"User"},
	Properties: map[string]any{
		"name": "Alice",
	},
}
engine.CreateNode(ctx, node)

Package storage provides namespaced storage engine wrapper for multi-database support.

NamespacedEngine wraps any storage.Engine with automatic key prefixing for database isolation. This enables multiple logical databases (tenants) to share a single physical storage backend while maintaining complete data isolation.

Key Design:

  • All node and edge IDs are prefixed with the namespace: "tenant_a:123" instead of "123"
  • Queries only see data in the current namespace
  • DROP DATABASE = delete all keys with namespace prefix

Thread Safety:

Delegates to underlying engine's thread safety guarantees.

Example:

inner := storage.NewBadgerEngine("./data")
tenantA := storage.NewNamespacedEngine(inner, "tenant_a")

// Creates node with ID "tenant_a:123" in BadgerDB
tenantA.CreateNode(&Node{ID: "123", Labels: []string{"Person"}})

// Only sees nodes with "tenant_a:" prefix
nodes, _ := tenantA.AllNodes()

NamespacedEngine maintenance and capability forwards.

Before this file, the namespaced view silently lacked maintenance, counting, schema, iteration, embedding-update and event capabilities that the inner engine exposes (DIVERGENCE_REPORT.md §2). Callers holding a NamespacedEngine either failed a type assertion and fell back to a different path or could not reach the operation at all. Every forward here preserves the namespace boundary: IDs are prefixed on the way in and stripped on the way out.

Package storage provides per-node configuration for NornicDB inference.

Per-node config allows fine-grained control over edge materialization: - Pin list: edges to these targets never decay - Deny list: never create edges to these targets - Edge caps: maximum edges per node (in/out/total) - Per-label caps: limits on specific edge types - Trust level: affects confidence thresholds

Feature flags:

  • NORNICDB_PER_NODE_CONFIG_ENABLED=true (enabled by default)
  • NORNICDB_PER_NODE_CONFIG_AUTO_INTEGRATION_ENABLED=true (enabled by default)

Real-World Example 1: User preferences (social network)

// User wants max 50 friends, never connect to blocked users
store := storage.NewNodeConfigStore()
userConfig := storage.NewNodeConfig("user-alice")
userConfig.MaxOutEdges = 50  // Max 50 outgoing friendships
userConfig.DenyList = []string{"user-spammer", "user-troll"}  // Blocked users
userConfig.PinList = []string{"user-bestfriend"}  // Never decay this friendship
store.Set(userConfig)

// Later, inference engine checks before creating edge
if allowed, _ := store.IsEdgeAllowedWithReason("user-alice", "user-bob", "friend"); allowed {
    db.CreateEdge("user-alice", "user-bob", "friend")
    store.RecordEdgeCreation("user-alice", "user-bob")  // Update count (now at 23/50)
}

Real-World Example 2: Document categorization limits (knowledge base)

// Document should have max 5 categories, but unlimited references
docConfig := storage.NewNodeConfig("doc-123")
docConfig.LabelConfigs = map[string]storage.LabelConfig{
    "category": {MaxEdges: 5},        // Max 5 category tags
    "references": {MaxEdges: 0},      // Unlimited references (0 = no limit)
    "deprecated": {Disabled: true},   // Never create deprecated edges
}
store.Set(docConfig)

// Try to add 6th category - denied!
allowed, reason := store.IsEdgeAllowedWithReason("doc-123", "category-ai", "category")
// → (false, "label 'category' at max capacity (5/5)")

Real-World Example 3: Low-trust nodes (spam prevention)

// New users start with low trust - require higher confidence
newUserConfig := storage.NewNodeConfig("user-newbie")
newUserConfig.TrustLevel = storage.TrustLevelLow  // Requires +20% confidence
newUserConfig.MaxOutEdges = 10  // Limited connections until trust increases
store.Set(newUserConfig)

// After user proves trustworthy, upgrade trust
if userIsActive && userNotSpamming {
    newUserConfig.TrustLevel = storage.TrustLevelDefault
    newUserConfig.MaxOutEdges = 100
    store.Set(newUserConfig)  // Update config
}

ELI12 (Explain Like I'm 12):

Per-node config is like house rules for each person:

**Pin List**: "These are my best friends - never unfriend them!"

  • In NornicDB: Edges in pin list never decay, always kept

**Deny List**: "I never want to talk to these people"

  • In NornicDB: Never create edges to denied nodes (like blocking someone)

**Edge Caps**: "I can only have 50 friends max"

  • In NornicDB: Limits prevent one node from connecting to everything

**Trust Level**: "I just moved here, so teachers are extra careful with me"

  • Low trust: Requires stronger evidence before creating edges
  • High trust: Can create edges more easily
  • Pinned: Always trust (like family members)

Think of it like a bouncer at a party:

  • Deny list = banned from party
  • Pin list = VIP, always allowed
  • Max edges = party capacity (50 people max)
  • Trust level = how strict the bouncer is checking IDs

Bounded storage-delivery correction: Codex, NOR-160, 1 November 2026. Restores the caller-copy protocol of the approved original head (refs/codex/reference/pr-1688-20261104) as this release's structural owner.

Author: #1683 implementation lane (Codex), 2026-11-01; ported to release/v1.4.4.

Package storage provides receipt generation for mutation auditing.

Package storage schema management for constraints and indexes.

This file implements Neo4j-compatible schema management including:

  • Unique constraints
  • Property indexes (single and composite)
  • Range indexes (for efficient range queries)
  • Full-text indexes
  • Vector indexes

Schema definitions are stored in memory and enforced during node operations.

Package storage - Transaction types shared between storage implementations.

This file defines shared transaction types used by BadgerTransaction. All transactions in NornicDB use Badger's native transaction system which provides real ACID guarantees through the Write-Ahead Log (WAL).

ACID Guarantees

Transactions provide:

  • Atomicity: All operations commit together or none do
  • Consistency: Constraints validated before commit
  • Isolation: Changes invisible until commit
  • Durability: WAL ensures persistence even on crash

Usage

All engines (including MemoryEngine) use BadgerTransaction:

engine := storage.NewMemoryEngine() // or NewBadgerEngine()
tx, err := engine.BeginTransaction()
if err != nil {
    return err
}
defer tx.Rollback() // Rollback if not committed

tx.CreateNode(&Node{ID: "n1", Labels: []string{"Person"}})
tx.CreateNode(&Node{ID: "n2", Labels: []string{"Person"}})

return tx.Commit() // Atomic - both succeed or both fail

Package storage provides the storage engine interface and implementations for NornicDB.

The storage layer is designed for Neo4j compatibility while adding NornicDB-specific extensions for memory decay, vector embeddings, and automatic relationship inference.

Design Principles:

  • Neo4j JSON export/import compatibility
  • Testability through dependency injection
  • Thread-safe implementations
  • Property graph model (labeled property graph)

Example Usage:

// Create storage engine
engine := storage.NewMemoryEngine()
defer engine.Close()

// Create nodes
node := &storage.Node{
	ID:     storage.NodeID("user-123"),
	Labels: []string{"User", "Person"},
	Properties: map[string]any{
		"name":  "Alice",
		"email": "alice@example.com",
	},
	CreatedAt: time.Now(),
}
engine.CreateNode(node)

// Create relationships
edge := &storage.Edge{
	ID:        storage.EdgeID("follows-1"),
	StartNode: storage.NodeID("user-123"),
	EndNode:   storage.NodeID("user-456"),
	Type:      "FOLLOWS",
	CreatedAt: time.Now(),
}
engine.CreateEdge(edge)

// Export to Neo4j format
nodes, _ := engine.AllNodes()
edges, _ := engine.AllEdges()
export := storage.ToNeo4jExport(nodes, edges)

// Save as JSON
data, _ := valueconvert.PropertyJSON.MarshalIndent(export, "", "  ")
os.WriteFile("graph-export.json", data, 0644)

Package storage provides write-ahead logging for NornicDB durability.

WAL (Write-Ahead Logging) ensures crash recovery by logging all mutations before they are applied to the storage engine. Combined with periodic snapshots, this provides:

  • Durability: No data loss on crash
  • Recovery: Restore state from snapshot + WAL replay
  • Audit trail: Complete history of all mutations

Feature flag: NORNICDB_WAL_ENABLED (enabled by default)

Usage:

// Create WAL-backed storage
engine := NewMemoryEngine()
wal, err := NewWAL("/path/to/wal", nil)
walEngine := NewWALEngine(engine, wal)

// Operations are logged before execution
walEngine.CreateNode(&Node{ID: "n1", ...})

// Create periodic snapshots
snapshot, err := wal.CreateSnapshot(engine)
wal.SaveSnapshot(snapshot, "/path/to/snapshot.json")

// Recovery after crash
engine, err = RecoverFromWAL(ctx, "/path/to/wal", "/path/to/snapshot.json")

Package storage provides write-ahead logging for NornicDB durability.

Package storage provides write-ahead logging for NornicDB durability.

Storage capability contracts for the production wrapper stack.

The storage chain (BadgerEngine → WALEngine → AsyncEngine → NamespacedEngine, with MemoryEngine embedding BadgerEngine) must expose the same optional capabilities at every layer so callers that type-assert for a capability never silently fall back to a slower or incorrect path depending on which wrapper they hold (DIVERGENCE_REPORT.md §2: the pattern behind #420, #424, #473).

The var-block below turns every missing forward into a compile error. NamespaceLister, NamespaceSchemaProvider, PrefixStatsEngine, NamespaceLabelStatsProvider, PropertyKeyRegistry, StartupMaintenanceStateEngine, MVCCMaintenanceEngine, TemporalMaintenanceEngine and StorageEventNotifier are declared in types.go; the four interfaces below complete the set of capabilities the report found forwarded unevenly.

Index

Constants

View Source
const (
	ConstraintContractKindPrimitiveNode         = "primitive-node"
	ConstraintContractKindPrimitiveRelationship = "primitive-relationship"
	ConstraintContractKindBooleanNode           = "boolean-node"
	ConstraintContractKindBooleanRelationship   = "boolean-relationship"
)
View Source
const (
	DefaultNodeLookupIndexName         = "index_343aff4e"
	DefaultRelationshipLookupIndexName = "index_f7700477"
)

Neo4j's names for a new database's lookup indexes (the same in every database, derived from the index descriptor).

View Source
const CoordinatorOwnedTransactionMetadataKey = "nornicdb.fabric.coordinator_owned"

CoordinatorOwnedTransactionMetadataKey identifies a participant whose terminal outcome belongs to a Fabric coordinator. Independent commits by a batch-owning procedure cannot be rolled back by that coordinator.

View Source
const DefaultBytesMetricsInterval = 30 * time.Second

DefaultBytesMetricsInterval is the D-07 default sweep cadence.

View Source
const DefaultRetentionPolicyMaxVersionsPerKey = 0

DefaultRetentionPolicyMaxVersionsPerKey — closed historical versions preserved per key by default. Zero means "no history, head-only" which collapses every write to a single primary-key write (no MVCC version archival). Operators who need audit/rollback raise NORNICDB_MVCC_RETENTION_MAX_VERSIONS via config.

View Source
const EmbeddingCallerPendingKey = "embedding_caller_retry"

EmbeddingCallerPendingKey marks an authorized worker requeue while its original caller's live authority is needed for dispatch.

View Source
const EntityTransactionVersion uint16 = 3

EntityTransactionVersion identifies the portable semantic transaction format. Version 3 stores MessagePack timestamps, preserving unset and Unix epoch as distinct values without the range limit of version 2's Unix nanoseconds. Author: NOR-303 lane (Codex), 2026-10-29; codec change allocated by the user.

View Source
const PropertyTypeUnionSeparator = " | "

PropertyTypeUnionSeparator separates the member types of a union property type ("STRING | INTEGER", Neo4j's normalized spelling): a value satisfies the union when it satisfies any member.

View Source
const RemoteRequestTimeout = 30 * time.Second

RemoteRequestTimeout bounds each remote Engine call that has no earlier caller deadline. The HTTP transport also uses it as its client timeout.

View Source
const (
	// SnapshotEncryptionKeySize is the size of the AES-256 key SnapshotOptions
	// accepts. A non-empty key of any other size is refused before a snapshot
	// is written or read.
	SnapshotEncryptionKeySize = 32
)
View Source
const StreamChunkSize = 1000

StreamChunkSize is the batch size of a streaming read.

View Source
const (
	// WALEncryptionKeySize is the size of the XChaCha20-Poly1305 key
	// WALConfig.EncryptionKey accepts. A non-empty key of any other size is
	// refused before a journal is opened or converted.
	WALEncryptionKeySize = 32
)

Variables

View Source
var (
	// ErrSnapshotEncryptionKeyInvalid reports a key that is not exactly
	// SnapshotEncryptionKeySize bytes.
	ErrSnapshotEncryptionKeyInvalid = errors.New("snapshot encryption key must be 32 bytes")
	// ErrSnapshotEncryptionRequired reports an encrypted snapshot read without
	// a key.
	ErrSnapshotEncryptionRequired = errors.New("encrypted snapshot requires a snapshot encryption key")
	// ErrSnapshotEncryptionNotEncrypted reports a plaintext snapshot presented
	// to a key-aware reader (or an envelope without its magic).
	ErrSnapshotEncryptionNotEncrypted = errors.New("snapshot is not an encrypted NDS2 stream")
	// ErrSnapshotEncryptionFormat reports an envelope that cannot be framed:
	// a short or invalid header, an invalid chunk length, a missing completion
	// frame or trailing data.
	ErrSnapshotEncryptionFormat = errors.New("invalid encrypted snapshot envelope")
	// ErrSnapshotEncryptionAuthentication reports a chunk that does not
	// authenticate under the supplied key and its header, counter and kind.
	ErrSnapshotEncryptionAuthentication = errors.New("encrypted snapshot authentication failed")
)
View Source
var (
	ErrNoTransaction       = errors.New("no active transaction")
	ErrTransactionActive   = errors.New("transaction already active")
	ErrTransactionClosed   = errors.New("transaction already closed")
	ErrTransactionRollback = errors.New("transaction rolled back")
)

Transaction errors

View Source
var (
	ErrNotFound       = errors.New("not found")
	ErrAlreadyExists  = errors.New("already exists")
	ErrConflict       = errors.New("conflict")
	ErrDeadlock       = errors.New("transaction deadlock") // a lock wait closing a cycle of waiting transactions (DeadlockDetected)
	ErrExhausted      = errors.New("exhausted")
	ErrInvalidID      = errors.New("invalid id")
	ErrInvalidData    = errors.New("invalid data")
	ErrNotImplemented = errors.New("not implemented")
	ErrInvalidEdge    = errors.New("invalid edge: start or end node not found")
	ErrStorageClosed  = errors.New("storage closed")
	// ErrStorageRestoring is returned by a read or write that starts while
	// Restore replaces the store. It is transient (DatabaseUnavailable):
	// retrying once the restore completes succeeds.
	ErrStorageRestoring = errors.New("storage restoring")
	ErrIterationStopped = errors.New("iteration stopped") // Sentinel to stop streaming early
	// ErrEmbeddingSourceChanged is returned by an embedding writeback whose
	// node changed (properties or labels) after the worker read it: the
	// embedding describes content the node no longer has, so nothing is
	// written and the node stays pending for re-embedding (#889).
	ErrEmbeddingSourceChanged = errors.New("node changed since it was read for embedding")
	// ErrCrossNamespaceTransaction is returned when a single transaction
	// attempts to mix writes from multiple namespaces. The transaction layer
	// pins each transaction to one namespace at the first prefixed write, and
	// every subsequent write must share that prefix. Per-database MVCC
	// counters depend on this invariant.
	ErrCrossNamespaceTransaction = errors.New("transaction spans multiple namespaces")
	// ErrNotVisibleAtSnapshot signals that the entity exists (a head
	// record is present) but is not visible to the snapshot version
	// the caller passed. Distinct from ErrNotFound, which means the
	// entity has no head at all. Callers that maintain transaction
	// snapshot isolation MUST treat this as a hard miss rather than
	// falling back to a fresh-view read of the primary key, which
	// would expose peer commits that landed between the reader's
	// begin and the read.
	ErrNotVisibleAtSnapshot = errors.New("entity not visible at snapshot")
	// ErrHistoryNotRetained reports a historical read at a time before the
	// retained history of the entity: a persisted prune floor says the store
	// discarded the versions that answer it. Distinct from ErrNotFound, which
	// reports an entity that did not exist at the requested time.
	ErrHistoryNotRetained = errors.New("history not retained at requested time")
	// ErrHistoryUnavailable reports a historical read whose retained records
	// hold no state of the entity at or after its creation floor: the record
	// the read needs is missing, so the answer cannot be given.
	ErrHistoryUnavailable = errors.New("history unavailable at requested time")
	// ErrHistoricalReadOnly reports a mutation attempted through a historical
	// read engine, which answers reads only.
	ErrHistoricalReadOnly = errors.New("historical read is read-only")
)

Common errors

View Source
var (
	ErrMVCCSnapshotGracefulCancel = errors.New("mvcc: snapshot cancelled due to resource pressure")
	ErrMVCCSnapshotHardExpired    = errors.New("mvcc: snapshot forcibly expired due to critical resource pressure")
)

Snapshot expiration errors surface when an already-admitted reader is forced to stop.

View Source
var (
	ErrWALClosed         = errors.New("wal: closed")
	ErrWALCorrupted      = errors.New("wal: corrupted entry")
	ErrWALPartialWrite   = errors.New("wal: partial write detected")
	ErrWALChecksumFailed = errors.New("wal: checksum verification failed")
	ErrWALMissingTrailer = errors.New("wal: missing or invalid trailer (incomplete write)")
	ErrSnapshotFailed    = errors.New("wal: snapshot creation failed")
	ErrRecoveryFailed    = errors.New("wal: recovery failed")
)

Common WAL errors

View Source
var (
	// ErrWALEncryptionKeyInvalid reports a WAL key that is not exactly
	// WALEncryptionKeySize bytes.
	ErrWALEncryptionKeyInvalid = errors.New("wal: expected 32-byte encryption key")
	// ErrWALPlaintextFrames reports a plaintext frame in a journal opened,
	// read or converted with a key. Such a journal must be converted first
	// (EncryptWALDirectory); it is never rewritten by the attempt.
	ErrWALPlaintextFrames = errors.New("wal: plaintext frames in an encrypted WAL")
)
View Source
var ErrEventSubscriptionUnsupported = errors.New("storage: engine does not deliver storage events")

ErrEventSubscriptionUnsupported reports an engine that cannot deliver the storage events: neither it nor the engines it wraps publish them.

View Source
var ErrLockWaitTimeout = errors.New("lock wait timed out")

ErrLockWaitTimeout is the cause of a MERGE that waited its engine's LockWaitOptions.Timeout for a key another transaction holds.

View Source
var ErrMVCCResourcePressure = errors.New("mvcc: resource pressure exceeded snapshot lifetime")

ErrMVCCResourcePressure is returned when MVCC resource pressure exceeds snapshot lifetime.

View Source
var ErrManagedVectorAnchorSource = errors.New("wal: managed vector anchor source is not the committed node")

ErrManagedVectorAnchorSource reports an anchor whose recorded source is not the node the store has committed: the node is gone, or its body changed after the vectors were acknowledged. Replay changes nothing for it - it neither creates the node nor restores vectors onto a body they were not computed from.

View Source
var ErrNoUndoData = errors.New("wal: entry has no undo data")

ErrNoUndoData means a WAL entry lacks the before image needed for undo.

View Source
var ErrOfflineDatabaseRestore = errors.New("restore this backup into a new data directory with nornicdb-admin database restore")

ErrOfflineDatabaseRestore identifies a restore that requires a new data directory.

View Source
var ErrPropertyIndexValueOrderUnavailable = errors.New("property index value order unavailable")

ErrPropertyIndexValueOrderUnavailable means an index cannot provide property value order for the requested population. No partial IDs or group callbacks are delivered. Canonical list keys and membership-only unkeyable values are not property values and must never be ordered by their encoded text.

View Source
var ErrReadSnapshotUnsupported = errors.New("storage: read snapshots are not supported by this engine")

ErrReadSnapshotUnsupported reports an engine that cannot open a read snapshot (CompositeEngine and RemoteEngine span other stores). A search build over it does not queue live writes: they wait for the build.

View Source
var ErrStoreKeyTooLong = errors.New("storage: key exceeds the store's key limit")

ErrStoreKeyTooLong reports a commit refused before anything of it was journaled because the store cannot hold one of its keys.

View Source
var ErrStoreValueTooLarge = errors.New("storage: value exceeds the store's value limit")

ErrStoreValueTooLarge reports a commit refused before anything of it was journaled because the store cannot hold one of its values.

View Source
var ErrStreamingSnapshotUnsupported = errors.New("streaming snapshots require storage.StreamingEngine")
View Source
var ErrWALKeyRequired = errors.New("wal: encryption key required")
View Source
var ErrWALUnsupportedVersion = errors.New("unsupported WAL format")

ErrWALUnsupportedVersion means the selected reader cannot use the WAL frame version. Supported older frames can be converted by the V4 upgrade; unknown formats are never treated as a torn current record.

Functions

func ApplyAcceptedEntityTransaction

func ApplyAcceptedEntityTransaction(engine Engine, data []byte) error

ApplyAcceptedEntityTransaction waits for the full accepted apply, including notifications. State-machine drivers use Submit and its physical boundary. The application takes the applying engine's work context (replay has no caller context), so that engine's Close bounds it.

func ApplyDecayProfileOptions

func ApplyDecayProfileOptions(bundle knowledgepolicy.DecayProfileBundle, updates map[string]interface{}) (knowledgepolicy.DecayProfileBundle, error)

ApplyDecayProfileOptions returns a validated updated bundle without modifying the input. Invalid options return an error and the original bundle. For example, updated, err := ApplyDecayProfileOptions(bundle, map[string]interface{}{"halfLifeSeconds": int64(3600)}) changes its half life.

func ApplyEntityChange

func ApplyEntityChange(ctx context.Context, target entityWriter, op Operation, updateNode func(context.Context, NodeUpdateRequest) error, deleteNode func(context.Context, NodeID) error) error

func ApplyNodeUpdate

func ApplyNodeUpdate(ctx context.Context, tx *BadgerTransaction, updateRequest NodeUpdateRequest) error

ApplyNodeUpdate is UpdateNode's upsert in a transaction: an update, or a create when the node doesn't exist.

func ApplyPromotionProfileOptions

func ApplyPromotionProfileOptions(profile knowledgepolicy.PromotionProfileDef, updates map[string]interface{}) (knowledgepolicy.PromotionProfileDef, error)

ApplyPromotionProfileOptions returns a validated updated profile without modifying the input. Invalid options return an error and the input profile.

Example:

updated, err := ApplyPromotionProfileOptions(profile, map[string]interface{}{"scoreFloor": 0.5})

func BeginQueryRevealScopeContext

func BeginQueryRevealScopeContext(ctx context.Context, engine Engine, reveal bool) (context.Context, func())

BeginQueryRevealScopeContext owns the existing physical-store reveal mutex, recording an opaque, live lease on ctx. Nested work on the same physical engine reuses that lease, preserving the outer query's reveal mode; distinct engines acquire independent scopes. Database property policy is not cached in this marker: projections still resolve their supplied database engine. Release exactly once with defer; contexts borrowed from it must not outlive it. The acquisition waits with ctx: a cancelled or expired caller returns without a lease instead of waiting for unrelated reveal work, and the returned context is then ctx itself, so the caller's own cancellation stops its reads. For example: ctx, release := BeginQueryRevealScopeContext(ctx, engine, false).

func ClassifyIndexName added in v1.1.0

func ClassifyIndexName(internal string) string

ClassifyIndexName is the exported alias used by the observation sites in pkg/cypher / cmd/nornicdb / future plan 04-05 search-engine plumbing. The internal-only `classifyIndexName` is the single source of truth; this alias keeps the public API surface uppercase per Go convention without duplicating the closed-enum logic.

func CoerceTemporalTime

func CoerceTemporalTime(value interface{}) (time.Time, bool)

CoerceTemporalTime reads a point in time from a temporal property or argument, in UTC: a time.Time, a Cypher temporal value (anything with TemporalTime(), so datetime(), date() and localdatetime() values alike), an ISO 8601 string (RFC 3339, or a date or local date-time read as UTC), or Unix seconds. It is the one reading used by the TEMPORAL NO OVERLAP constraint and the db.temporal procedures, so a value the constraint accepts is one the procedures read the same way.

func CollectEdgeTypes

func CollectEdgeTypes(ctx context.Context, engine Engine) ([]string, error)

CollectEdgeTypes collects all unique edge types using streaming.

func CollectLabels

func CollectLabels(ctx context.Context, engine Engine) ([]string, error)

CollectLabels collects all unique labels using streaming.

func CompositeDatabaseOf

func CompositeDatabaseOf(engine Engine) string

CompositeDatabaseOf identifies a composite through read/admission wrappers; it does not unwrap the actual operation or bypass those owners.

func ConstraintContractEntryName

func ConstraintContractEntryName(contractName string, idx int) string

ConstraintContractEntryName is the name of the primitive constraint compiled from the entry at index idx (0-based) of a contract.

func CoordinatorOwnsTransaction

func CoordinatorOwnsTransaction(ctx context.Context) bool

func CopyValue

func CopyValue(value any, mapCopied func(source, copied map[string]any)) any

CopyValue returns an independent caller-owned copy of a value. It is the generic copy owner: durable property normalization is a different contract and belongs to ownRetainedValue (property_ownership.go). Concrete types, pointer, map, slice and array shapes and Go scalar widths are preserved, nil containers stay nil, and a caller-declared type that owns a copy protocol is asked once, after which its own copy is used as is.

Result holders can use this same owner at their retention and delivery boundaries without durable serialization or type normalization. For example:

owned := storage.CopyValue(map[string]any{"tags": []string{"graph"}}, nil).(map[string]any)

mapCopied, when non-nil, observes plain string-keyed maps copied by the structural walk, allowing a result owner to rebind map-identity metadata. Domain-owned Node, Edge and CallerCopy values retain their own copy contract. Callers must synchronize access to a value while it is being copied.

func CountAdjacentEdges

func CountAdjacentEdges(ctx context.Context, engine interface {
	ReadAdjacentEdges(context.Context, AdjacentEdgeRead) ([]*Edge, error)
}, selection AdjacentEdgeRead) (int, error)

CountAdjacentEdges counts the selection admitted by the supplied view.

func CountNodesWithLabel

func CountNodesWithLabel(ctx context.Context, engine Engine, label string) (int64, error)

CountNodesWithLabel counts nodes with a specific label, using metadata when available and streaming otherwise. ctx must be nonnil and owns both paths.

func CountPendingEmbeddingIDs

func CountPendingEmbeddingIDs(ctx context.Context, engine Engine, accept func([]byte) bool) int

CountPendingEmbeddingIDs preserves the storage capability's fallback for engines without a durable pending index, using selection's eligibility rule.

func CreatePreparedDatabaseDirectory

func CreatePreparedDatabaseDirectory(root, database string) (id, directory string, err error)

CreatePreparedDatabaseDirectory allocates a private store on the server's filesystem without opening or locking the server's main Badger directory.

func DatabaseOf

func DatabaseOf(engine Engine) string

DatabaseOf follows the same wrapper boundary as QualifiedEntityID. It does not infer provenance from a stored ID, which may itself contain colons.

func DecayScoringTime added in v1.1.0

func DecayScoringTime() int64

DecayScoringTime returns a frozen nanosecond timestamp for use as the scoring time across a single query. Call once per query and pass to all filter calls.

func DecidePublication

func DecidePublication(ctx context.Context, action func() error) error

DecidePublication encloses the authoritative storage action. A successful action cannot subsequently become a rollback because cancellation won later.

func DecodeCommandPayload

func DecodeCommandPayload(data []byte, value any) error

DecodeCommandPayload decodes exactly one replication message. Structural validation rejects forged collection lengths before the decoder allocates.

func DecodeEntityTransaction

func DecodeEntityTransaction(data []byte) (EntityTransactionEnvelope, []Operation, error)

DecodeEntityTransaction validates and restores one semantic transaction.

func DecodeNamedMetadata

func DecodeNamedMetadata(data []byte) (map[string]any, error)

DecodeNamedMetadata preserves the body metadata codec's scalar/array Go representations, rather than applying property integer/list normalization.

func DecodeNamedProperties

func DecodeNamedProperties(data []byte) (map[string]any, error)

DecodeNamedProperties restores authoritative stored property representations from a dictionary-independent semantic map, including named-zone instants.

func DecodeSchemaDefinition

func DecodeSchemaDefinition(data []byte, def *SchemaDefinition) error

DecodeSchemaDefinition reads a complete persisted schema document. Versions 0/1 retain the former float64 meaning; version 2 preserves exact number kinds. Decoding bytes from EncodeSchemaDefinition also provides an isolated deep copy for transaction publication without introducing another schema copy format.

func EmbeddingSourceMatches

func EmbeddingSourceMatches(source, current *Node, legacy EmbeddingTextPolicy) bool

EmbeddingSourceMatches is the single validity decision for a computed result, a retained result, or persisted managed vectors. The first node owns the consumed-source record; legacy vectors retain their engine text policy.

func EncodeCommandPayload

func EncodeCommandPayload(value any) ([]byte, error)

EncodeCommandPayload encodes one replication message as MessagePack.

func EncodeEdgePayload

func EncodeEdgePayload(edge *Edge) ([]byte, error)

EncodeEdgePayload encodes a complete edge image for replication.

func EncodeEntityTransaction

func EncodeEntityTransaction(request EntityTransactionRequest) ([]byte, error)

EncodeEntityTransaction encodes the current semantic transaction format. Prepared input reads the accepted private snapshot without allocating the detached public Operations view. Raw input retains its original validation.

func EncodeNamedProperties

func EncodeNamedProperties(properties map[string]any) ([]byte, error)

EncodeNamedProperties encodes semantic property names and values without dictionary IDs, using the same temporal and numeric owner as stored bodies.

func EncodeNodePayload

func EncodeNodePayload(node *Node) ([]byte, error)

EncodeNodePayload encodes a complete node image for replication.

func EncodeSchemaDefinition

func EncodeSchemaDefinition(def *SchemaDefinition) ([]byte, error)

EncodeSchemaDefinition writes the current persisted schema format. All schema writers, including transaction snapshots and exported sidecars, use this owner. A decoded legacy definition is rewritten from its FLOAT values as version 2.

func EncryptSnapshotFile

func EncryptSnapshotFile(ctx context.Context, path string, key []byte) error

EncryptSnapshotFile upgrades a pre-encryption snapshot in place. The old snapshot remains untouched until a complete authenticated replacement has been written, synced, and atomically published. A restart can therefore repeat an interrupted conversion safely. Existing encrypted snapshots are authenticated before they are accepted.

func EncryptWALDirectory

func EncryptWALDirectory(ctx context.Context, dir string, key []byte) error

EncryptWALDirectory upgrades the retained segments and the active file of one journal directory, then publishes the manifest with the converted segment sizes. A segment the manifest lists must exist: a directory whose journal files disagree with its manifest is not converted. A directory that holds no journal files is left alone.

func EncryptWALFile

func EncryptWALFile(ctx context.Context, path string, key []byte) error

EncryptWALFile upgrades one plaintext journal file in place. The plaintext file remains untouched until a complete authenticated replacement has been written, synced and atomically published. An already-converted file is authenticated with key before it is accepted.

func EnsureDatabasePrefix

func EnsureDatabasePrefix(dbName, id string) string

EnsureDatabasePrefix adds "<dbName>:" to id if id has no existing valid prefix.

If id already has a prefix (even a different database), id is returned unchanged to avoid accidentally rewriting cross-database IDs.

func EntityIdentityKey

func EntityIdentityKey(database, id string) string

EntityIdentityKey is an unambiguous key for a database-local stored ID. Keep unscoped IDs unchanged for engines without a database namespace.

func EntryPayloadJSON

func EntryPayloadJSON(entry WALEntry) (string, error)

EntryPayloadJSON renders a WAL entry for db.txlog. Binary commit keys are base64-encoded byte strings so every physical key remains distinguishable. Invalid payloads are reported rather than returned as arbitrary text.

func EventNotificationsSettled

func EventNotificationsSettled(engine Engine) bool

EventNotificationsSettled reports whether every previously visible mutation has finished delivering its events. An engine that cannot report it returns false. Consumers may establish a new revision/event baseline only at such a point, and must sample the graph revision again after sampling their event counter. It never waits for callbacks, which may themselves be waiting on the reader.

func ExtractNamespaceFromID added in v1.1.0

func ExtractNamespaceFromID(id string) string

ExtractNamespaceFromID returns the namespace prefix of an entity ID.

func FromNeo4jExport

func FromNeo4jExport(export *Neo4jExport) ([]*Node, []*Edge)

FromNeo4jExport converts Neo4j JSON export format to NornicDB nodes and edges.

This function imports data exported from Neo4j, extracting NornicDB-specific properties (those with "_" prefix) back into their dedicated fields.

Supports both export formats:

  • neo4j-admin database dump (flat format)
  • apoc.export.json (nested format)

Example:

// Load Neo4j export file
data, _ := os.ReadFile("neo4j-export.json")

var export storage.Neo4jExport
json.Unmarshal(data, &export)

// Convert to NornicDB format
nodes, edges := storage.FromNeo4jExport(&export)

// Import into NornicDB
if err := engine.BulkCreateNodes(nodes); err != nil {
	log.Fatal(err)
}
if err := engine.BulkCreateEdges(edges); err != nil {
	log.Fatal(err)
}

// emit "Imported N nodes, M edges" via the configured logger

Returns nodes and edges ready for storage engine insertion.

func GenericSaveToNeo4jExport

func GenericSaveToNeo4jExport(engine ExportableEngine, path string) error

GenericSaveToNeo4jExport works with any ExportableEngine.

func GetEntryTxID

func GetEntryTxID(entry WALEntry) string

GetEntryTxID extracts the transaction ID from a WAL entry, if present.

func IndexLookupValue

func IndexLookupValue(value interface{}) interface{}

IndexLookupValue returns value in the form the indexes key it by when it is a number, so a caller that counts and then reads the same number converts it once; any other value is returned unchanged. Lookups accept either form.

func InheritQueryRevealScopes

func InheritQueryRevealScopes(ctx context.Context, scopes RevealScopes) context.Context

InheritQueryRevealScopes carries the genuine live leases held by scopes into a derived evaluator context without changing its cancellation, deadline or values. An empty handle cannot manufacture a lease; released leases are ignored. Only use this while the owner is active, e.g. when restoring a statement's expression-failure context before a nested service call.

func IsEmbeddingMetadataProperty

func IsEmbeddingMetadataProperty(key string) bool

IsEmbeddingMetadataProperty reports whether key is embedding bookkeeping, a timestamp or the id: a property that never feeds embedding text.

func IsEncryptedSnapshot

func IsEncryptedSnapshot(path string) (bool, error)

IsEncryptedSnapshot reports whether the snapshot file at path carries the encrypted envelope. A missing file returns the open error, like IsStreamingSnapshot; a file too short to hold the magic is not encrypted.

func IsStreamingSnapshot added in v1.3.1

func IsStreamingSnapshot(path string) (bool, error)

func IsTransactionTooBig

func IsTransactionTooBig(err error) bool

IsTransactionTooBig reports whether err is Badger's "Txn is too big" (the writes exceed one Badger batch), wrapped or only kept as text by a wrapper that dropped the chain.

func KnowsPropertyName

func KnowsPropertyName(engine Engine, property string) bool

KnowsPropertyName reports whether the native namespace has used a property name. The name remains known after the last entity holding it is deleted.

func LoadFromNeo4jExport

func LoadFromNeo4jExport(engine Engine, path string) error

LoadFromNeo4jExport loads data from a combined Neo4j export file.

This function loads data from a single JSON file containing both nodes and relationships in a combined format. This is the format produced by SaveToNeo4jExport() and provides a more compact representation.

Parameters:

  • engine: Storage engine to load data into
  • path: Path to the combined JSON export file

Returns:

  • Error if file cannot be read or data is invalid

Example:

// Load from combined export file
engine := storage.NewMemoryEngine()
err := storage.LoadFromNeo4jExport(engine, "./data-export.json")
if err != nil {
	log.Fatalf("Failed to load export: %v", err)
}

// emit "Successfully loaded data from export file" via the configured logger

File Format:

{
  "nodes": [
    {"id":"0","labels":["Person"],"properties":{"name":"Alice"}},
    {"id":"1","labels":["Person"],"properties":{"name":"Bob"}}
  ],
  "relationships": [
    {"id":"0","type":"KNOWS","startNode":"0","endNode":"1","properties":{}}
  ]
}

Performance:

  • Loads entire file into memory for parsing
  • Uses bulk operations for efficient storage
  • Suitable for moderate-sized datasets

Use Cases:

  • Restoring NornicDB backups
  • Migrating data between environments
  • Loading test datasets
  • Data exchange with Neo4j systems

func LoadFromNeo4jJSON

func LoadFromNeo4jJSON(engine Engine, dir string) error

LoadFromNeo4jJSON loads nodes and edges from Neo4j APOC JSON export format.

This function reads the standard Neo4j APOC export format consisting of nodes.json and relationships.json files. This format is produced by Neo4j's APOC library using `apoc.export.json.all()` or similar procedures.

File Format:

  • nodes.json: One JSON object per line (JSONL format)
  • relationships.json: One JSON object per line (JSONL format)

Parameters:

  • engine: Storage engine to load data into
  • dir: Directory containing nodes.json and relationships.json files

Returns:

  • Error if files cannot be read or data is invalid

Example:

// Load from Neo4j APOC export directory
engine := storage.NewMemoryEngine()
err := storage.LoadFromNeo4jJSON(engine, "./neo4j-export/")
if err != nil {
	log.Fatalf("Failed to load Neo4j data: %v", err)
}

// emit "Successfully loaded Neo4j data into NornicDB" via the configured logger

Expected Directory Structure:

neo4j-export/
├── nodes.json
└── relationships.json

Node Format (nodes.json):

{"id":"0","labels":["Person"],"properties":{"name":"Alice","age":30}}
{"id":"1","labels":["Company"],"properties":{"name":"Acme Corp"}}

Relationship Format (relationships.json):

{"id":"0","type":"WORKS_FOR","startNode":"0","endNode":"1","properties":{"since":2020}}

Performance:

  • Processes files sequentially (nodes first, then relationships)
  • Uses streaming JSON parsing for memory efficiency
  • Bulk operations for optimal storage performance

func MarkNewTemporalConstraintsForEngine

func MarkNewTemporalConstraintsForEngine(engine Engine, schema *SchemaManager, constraints []Constraint) error

MarkNewTemporalConstraintsForEngine makes the history index of the temporal node constraints DDL just created complete, and records it:

  • on an empty label (the usual schema-first load) there is nothing to index, and every later write maintains the index;
  • over existing nodes, which were written before the constraint and have no entries, their entries are written now, so the index never stays incomplete across a restart that skips the rebuild (a clean shutdown certifies the derived indexes as current).

Only an engine that doesn't unwrap to a BadgerEngine leaves a constraint over existing nodes incomplete; it is validated by label scan until a rebuild.

The entries belong to the statement that published the constraint. When engine is a schema statement's own transaction view, the pass stages them in that transaction (stageTemporalBackfillForLabel): they publish with the constraint and are discarded with it, and the statement's begin already holds the engine's exclusive lifecycle admission from before its snapshot, so the pass takes none. Every other view backfills as a maintenance write (beginMaintenanceWrite), the engine's own pass that no statement's admission covers.

func NamespaceRelationshipCount

func NamespaceRelationshipCount(ctx context.Context, engine Engine, namespace, edgeType, label string, tier RelationshipCountTier) (int64, error)

NamespaceRelationshipCount dispatches to the physical namespace counter contract. A missing capability is an error: the engine's global counters cannot answer for a database, and scanning would discard the count-store point-read guarantee. Transparent decorators forward here without unwrapping transaction, composite or other views that own different read semantics.

func NewCommitReceipt

func NewCommitReceipt(settle func(CommitOutcome)) (*CommitReceipt, CommitReceiptOwner)

func NewSnapshotDecryptingReader

func NewSnapshotDecryptingReader(reader io.Reader, key []byte) (io.Reader, error)

NewSnapshotDecryptingReader authenticates and decrypts a chunked snapshot envelope, returning the plaintext NDS2 stream. The reader fails closed: the key must be SnapshotEncryptionKeySize bytes, the envelope header must be present, every chunk must authenticate in order, and the final completion frame must be present before io.EOF is returned. A plaintext snapshot is refused rather than read, and the first chunk is authenticated before the reader is returned so a wrong key is reported as such.

func NodeElementID

func NodeElementID(database string, id NodeID) string

NodeElementID returns the opaque Cypher element identifier for a node in a database. Already-formatted node element identifiers are preserved.

func NodeNeedsEmbedding

func NodeNeedsEmbedding(node *Node) bool

NodeNeedsEmbedding checks if a node needs an embedding to be generated. Returns true if the node should have an embedding generated, false if it should be skipped.

A node is skipped (returns false) if:

  • It has an internal label (starts with '_')
  • It already has an embedding
  • It has the "embedding_skipped" property set
  • It has a persisted permanent embedding failure

Example:

for _, node := range nodes {
    if storage.NodeNeedsEmbedding(node) {
        generateEmbedding(node)
    }
}

func OldestSnapshotVersionsByNamespace

func OldestSnapshotVersionsByNamespace(readers []SnapshotReaderInfo) map[string]MVCCVersion

OldestSnapshotVersionsByNamespace returns the oldest snapshot version per namespace (SnapshotVersionsByNamespace).

func ParseDatabasePrefix

func ParseDatabasePrefix(id string) (db string, unprefixed string, ok bool)

ParseDatabasePrefix splits an ID formatted as "<db>:<id>" into database and unprefixed ID.

Returns ok=false if there is no valid prefix (no ':', empty db, or empty id).

func ParseElementID

func ParseElementID(value string) (kind, database, id string, ok bool)

ParseElementID reads the database and local identity from a native element ID. Local IDs may contain colons; only the two structural separators are split.

func PersistEmbeddingOutcome

func PersistEmbeddingOutcome(ctx context.Context, node *Node, persist func(context.Context) error) error

PersistEmbeddingOutcome separates commit from callback delivery across the outermost provider or WAL lease. Nested owners share the same boundary.

func PrepareDeclaredRelationshipPropertyEqualityIndexForEngine

func PrepareDeclaredRelationshipPropertyEqualityIndexForEngine(ctx context.Context, engine Engine, relationshipType string, properties []string) error

PrepareDeclaredRelationshipPropertyEqualityIndexForEngine prepares the shared derived equality index for a relationship RANGE declaration. Constraint and standalone declarations use the same population and committed-write owner. Views without that owner retain the complete scan, as constraint indexes do.

func PrepareRelationshipPropertyEqualityIndexForEngine

func PrepareRelationshipPropertyEqualityIndexForEngine(ctx context.Context, engine Engine, constraint Constraint) error

PrepareRelationshipPropertyEqualityIndexForEngine builds the relationship equality index a new relationship constraint answers reads from, the way a node constraint's owned property index is filled from the stored nodes (#875). An engine that keeps no such index (a transaction, a tiered composite store, write-behind or decay-filtered views, a namespace-less store) keeps its complete scan, so this is a no-op there rather than an error.

func PreparedDatabaseDirectory

func PreparedDatabaseDirectory(root, id string) (string, error)

PreparedDatabaseDirectory resolves only a canonical preparation ID within the server-owned store directory.

func PreparedDatabasesDirectory

func PreparedDatabasesDirectory(root string) string

PreparedDatabasesDirectory is the independent storage area beneath the data root.

func ProbeUnprefixedEntityIDs

func ProbeUnprefixedEntityIDs(ctx context.Context, engine Engine) (found, supported bool, err error)

ProbeUnprefixedEntityIDs checks physical node and relationship keys in native storage. The supported result distinguishes engines that require a logical scan from a native store with no unprefixed entities.

func PruneOldSnapshotFiles

func PruneOldSnapshotFiles(dir string, cfg *WALConfig) error

PruneOldSnapshotFiles removes old snapshot files in dir according to cfg retention. Keeps at most SnapshotRetentionMaxCount snapshots (newest by mtime) and deletes any older than SnapshotRetentionMaxAge. Idempotent; safe to call after each save.

func PublicRemoteMap

func PublicRemoteMap(value map[string]interface{}) map[string]interface{}

PublicRemoteMap removes sealed internal transport metadata from a map converted from RemoteEntityValue. Ordinary maps, including a user string under the same key, are returned unchanged without copying or graph identity. Use valueconvert.PropertyJSON.Marshal(PublicRemoteMap(map[string]interface{}(entity))) when a Go integration explicitly needs an ordinary public map rather than the marker.

func QualifiedEntityID

func QualifiedEntityID(engine Engine, id string) string

QualifiedEntityID maps an ID exposed by a database-scoped engine to the ID used by the underlying store's access metadata and knowledge policies. It follows EngineUnwrapper layers to find the database namespace; an unscoped engine leaves the supplied ID unchanged. An already qualified ID is not prefixed again, and a colon inside a local ID does not change its database.

For example, for tenant := NewNamespacedEngine(base, "tenant"):

QualifiedEntityID(tenant, "a:b")        // "tenant:a:b"
QualifiedEntityID(tenant, "tenant:a:b") // "tenant:a:b"

func ReadIndexSourceStamp

func ReadIndexSourceStamp(ctx context.Context, view any) (string, error)

ReadIndexSourceStamp obtains an optional durable source certificate from the actual engine or captured read view. Custom Engine implementations need not add a new method: absent capability means rebuild through their own readers after restart. Wrappers may forward only when they preserve their inner committed rows.

func ReadPendingEmbeddingCount

func ReadPendingEmbeddingCount(ctx context.Context, engine Engine, accept func([]byte) bool) (int, error)

ReadPendingEmbeddingCount returns the count and any error from the pending index or node scan. Callers must check the error before treating zero as drained.

func ReadPublicationSettled

func ReadPublicationSettled(engine Engine) bool

ReadPublicationSettled reports the absence of an in-flight native logical publication through a proven committed view. A ready notification has already published its data and graph token; delivery to listeners may still be running or blocked. Buffered ACKs reserve their hold before publishing the overlay and release it after advancing the graph token. This does not certify journal coverage: buffered event delivery still cannot satisfy EventNotificationsSettled, because ACK/event counts are different.

func ReadTemporalBounds

func ReadTemporalBounds(startValue, endValue interface{}) (start, end time.Time, hasEnd, ok bool)

ReadTemporalBounds reads a half-open epoch. A nil start is unbounded past; a nil end is unbounded future. At least one bound must be present. Non-nil bounds must be valid temporal values; two finite bounds must increase. A zero start in the returned representation denotes unbounded past only.

func RecordConstraintAdmission

func RecordConstraintAdmission(ctx context.Context, kind ConstraintEntityType, labels []string, constraints []Constraint)

RecordConstraintAdmission records the first schema view checked for each label/type in this write. A later precheck in a bulk write cannot widen that view for an earlier entity after an administrator adds a constraint.

func RecoverBufferedCommits

func RecoverBufferedCommits(engine Engine, wal *WAL) (int, error)

RecoverBufferedCommits replays accepted semantic transactions and write-behind commits that were acknowledged into the WAL but never reached Badger before a crash lost the in-memory buffer. It runs at engine open, after both the engine and the WAL are constructed and before the engine serves traffic.

Idempotency: every flushed generation writes a per-commit flush marker key (prefixBufferedFlush) inside the same Badger transaction as its data, so a commit whose marker exists has already been applied and is skipped. A replayed commit writes its own marker in the same transaction that applies it, so a subsequent restart skips it too.

Derived counts are rebuilt after replay rather than re-applying the stored deltas: crash recovery is rare, and the authoritative rebuild is the same recovery boundary the sync path uses.

func RecoverBufferedCommitsAtOpen

func RecoverBufferedCommitsAtOpen(engine Engine, wal *WAL) (int, error)

RecoverBufferedCommitsAtOpen replays both accepted record kinds and is exclusively the constructor's recovery of a store's own configured WAL directory, before traffic. That structural authority preserves unstamped historical upgrades; a foreign-populated store cannot use it.

func RecoverBufferedCommitsAtOpenAfter

func RecoverBufferedCommitsAtOpenAfter(engine Engine, wal *WAL, afterSeq uint64) (int, error)

RecoverBufferedCommitsAtOpenAfter replays accepted records newer than a durable storage replacement boundary. A native restore replaces the physical receipts that older WAL records refer to; those records belong to the prior store and must not be submitted against the restored image. Later accepted records still receive normal crash recovery.

func RecoverFromWALWithResult

func RecoverFromWALWithResult(ctx context.Context, walDir, snapshotPath string) (*MemoryEngine, ReplayResult, error)

RecoverFromWALWithResult recovers database state and returns detailed results. Use this for programmatic access to replay statistics and errors. ctx must be non-nil; values survive but cancellation is detached to finish recovery.

func RecoverFromWALWithResultWithKey

func RecoverFromWALWithResultWithKey(ctx context.Context, walDir, snapshotPath string, key []byte) (*MemoryEngine, ReplayResult, error)

RecoverFromWALWithResultWithKey is RecoverFromWALWithResult for a journal written with key. An empty key recovers a plaintext journal.

func RecoverIntoEngine added in v1.3.1

func RecoverIntoEngine(ctx context.Context, destination Engine, walDir, snapshotPath string) (ReplayResult, RecoveryStreamStatus, error)

RecoverIntoEngine restores a snapshot and subsequent WAL entries directly into destination. Framed snapshots and WAL files are processed one record at a time. Physical bodies and name authority are retained one record at a time. The destination must be quiescent until recovery completes; it must not serve concurrent application writers while bodies and derived counts are restored. ctx must be non-nil. Recovery retains its values and detaches cancellation so restoring acknowledged data completes independently of the initiator.

func RecoverIntoEngineWithKey

func RecoverIntoEngineWithKey(ctx context.Context, destination Engine, walDir, snapshotPath string, key []byte) (ReplayResult, RecoveryStreamStatus, error)

RecoverIntoEngineWithKey is RecoverIntoEngine for a journal written with key. An empty key recovers a plaintext journal.

func RecoverWithTransactions

func RecoverWithTransactions(ctx context.Context, walDir, snapshotPath string) (*MemoryEngine, *TransactionRecoveryResult, error)

RecoverWithTransactions performs transaction-aware WAL recovery. Incomplete transactions (no commit/abort) are rolled back using undo data. Returns the engine state and recovery statistics. Recovery preserves ctx values but completes independently of its cancellation once restoring accepted data.

func RecoverWithTransactionsWithKey

func RecoverWithTransactionsWithKey(ctx context.Context, walDir, snapshotPath string, key []byte) (*MemoryEngine, *TransactionRecoveryResult, error)

RecoverWithTransactionsWithKey is RecoverWithTransactions for a journal written with key. An empty key recovers a plaintext journal.

func RefreshUniqueConstraintValuesForConstraintsForEngine

func RefreshUniqueConstraintValuesForConstraintsForEngine(ctx context.Context, engine Engine, schema *SchemaManager, constraints []Constraint) error

RefreshUniqueConstraintValuesForConstraintsForEngine rebuilds the value caches of just the given single-property UNIQUE constraints (other constraint types are ignored) and marks them complete, so writes validate through the cache instead of the label-scan fallback. Used after a constraint contract with IS UNIQUE entries is admitted: refreshing only the contract's own constraints keeps a schema of many contracts from rescanning every constrained label on each DDL.

func RefreshUniqueConstraintValuesForEngine added in v1.0.43

func RefreshUniqueConstraintValuesForEngine(ctx context.Context, engine Engine, schema *SchemaManager) error

RefreshUniqueConstraintValuesForEngine rebuilds single-property UNIQUE value caches from the engine during preparation. A failed or canceled rebuild preserves existing caches; successful publication marks every selected cache complete.

func RelationshipElementID

func RelationshipElementID(database string, id EdgeID) string

RelationshipElementID returns the opaque Cypher element identifier for a relationship in a database. Already-formatted relationship element identifiers are preserved.

func ReplayWALEntry

func ReplayWALEntry(ctx context.Context, engine Engine, entry WALEntry) error

ReplayWALEntry applies a single WAL entry to the engine as its own recovery boundary. Uses the database name from the entry if present, otherwise wraps with default database. As with batch recovery, destination must be quiescent: no concurrent application writers may change the recovered graph or counts.

A physical buffered commit transports entity bodies without the destination-local count deltas that justified them, so this boundary ends with the same authoritative count reconciliation the recovery batch owners run. A caller replaying a sequence as one recovery batch applies each record with replayWALEntry and completes the batch itself, so that reconciliation stays once per batch rather than once per record. ctx must be non-nil; its values are retained, while cancellation is detached to finish recovery.

func ResetGlobalEdgeMetaStore

func ResetGlobalEdgeMetaStore()

ResetGlobalEdgeMetaStore resets the global edge meta store. Primarily for testing.

func ResetGlobalNodeConfigStore

func ResetGlobalNodeConfigStore()

ResetGlobalNodeConfigStore resets the global node config store. Primarily for testing.

func SameEventView

func SameEventView(a, b Engine) bool

SameEventView reports whether a and b are proven views of one event stream with one ID space and the same committed rows: the same physical publisher behind the same namespace translation, reached only through forwarders. An engine it cannot resolve proves nothing, so callers keep their conservative path for it.

func SaveSnapshot

func SaveSnapshot(snapshot *Snapshot, path string) error

SaveSnapshot writes a snapshot to disk with full durability guarantees. It writes lossless NDS2 v2 frames using write-to-temp + atomic rename. Older binaries reject this format; retain a pre-upgrade backup for rollback.

func SaveStreamingSnapshot added in v1.3.1

func SaveStreamingSnapshot(ctx context.Context, engine Engine, path string, options SnapshotOptions) error

SaveStreamingSnapshot writes a framed snapshot using temp-file, sync, and atomic-rename durability semantics. options.EncryptionKey encrypts the temporary file while it is written; the plaintext stream never reaches it.

func SaveToNeo4jExport

func SaveToNeo4jExport(engine Engine, path string) error

SaveToNeo4jExport exports all data from the storage engine to a Neo4j-compatible JSON file.

This function creates a complete export of all nodes and relationships in the storage engine, formatted for compatibility with Neo4j tools and for backup/restore operations.

Parameters:

  • engine: Storage engine to export data from
  • path: Output file path for the JSON export

Returns:

  • Error if export fails or file cannot be written

Example:

// Export all data to JSON file
err := storage.SaveToNeo4jExport(engine, "./backup.json")
if err != nil {
	log.Fatalf("Export failed: %v", err)
}

// emit "Data exported successfully" via the configured logger

// The exported file can be loaded back with:
// storage.LoadFromNeo4jExport(newEngine, "./backup.json")

Output Format:

{
  "nodes": [
    {
      "id": "node-123",
      "labels": ["Person", "Employee"],
      "properties": {
        "name": "Alice Smith",
        "age": 30,
        "email": "alice@example.com"
      }
    }
  ],
  "relationships": [
    {
      "id": "rel-456",
      "type": "WORKS_FOR",
      "startNode": "node-123",
      "endNode": "node-789",
      "properties": {
        "since": "2020-01-15",
        "role": "Developer"
      }
    }
  ]
}

Use Cases:

  • Creating backups of NornicDB data
  • Migrating data to Neo4j
  • Data analysis with Neo4j tools
  • Sharing datasets in a standard format

Performance:

  • Reads all data into memory before export
  • Uses pretty-printed JSON for readability
  • Suitable for datasets that fit in memory

Note: Currently only supports MemoryEngine. Other storage engines will return an error indicating unsupported engine type.

func SealPreparedDatabase

func SealPreparedDatabase(directory string, graph PreparedDatabase) error

SealPreparedDatabase publishes the readiness marker after the builder has synced and closed its Badger handle.

func ServerTransactionTimeoutOf

func ServerTransactionTimeoutOf(engine Engine) time.Duration

ServerTransactionTimeoutOf is the server's transaction timeout for an explicit transaction opened on engine, whatever its kind: the first engine that states it (the physical engine, or a composite, which carries the value its database manager configured), looking through wrappers (EngineUnwrapper). Zero when none states it.

func SetSchemaIndexFillHookForTesting

func SetSchemaIndexFillHookForTesting(hook func(indexName, label string) error) (restore func())

SetSchemaIndexFillHookForTesting makes hook run at the entry of every composite index fill, so tests outside this package can observe a schema declaration whose fill is in progress (or make that fill fail) instead of ordering concurrent work by timing. hook returning an error fails that fill; the statement that declared the index then publishes no schema change. The hook is called once per fill with the filled index's name and label, so a test can arm itself for one declaration and let other fills through. The returned function restores the previous hook.

func SetUniqueKeyLockWaitHookForTesting

func SetUniqueKeyLockWaitHookForTesting(hook func()) (restore func())

SetUniqueKeyLockWaitHookForTesting makes hook run whenever a transaction starts waiting for a constraint key lock another transaction holds (a MERGE of a key a concurrent MERGE holds), so tests outside this package can order concurrent statements by the wait itself instead of by timing. The returned function restores the previous hook.

func SnapshotVersionsByNamespace

func SnapshotVersionsByNamespace(readers []SnapshotReaderInfo) map[string][]MVCCVersion

SnapshotVersionsByNamespace returns every reader's snapshot version per namespace, oldest first. It is the one reader-floor computation: the lifecycle registry and the engine's prune both read it. A namespace appears only when it has a reader; "" collects readers registered without a namespace.

func SourceNodeElementID

func SourceNodeElementID(database string, id NodeID) string

SourceNodeElementID qualifies a stored local ID whose source is known. Unlike NodeElementID's legacy convenience form, an ID resembling an element ID is still local data here and cannot replace the authoritative source database.

func SourceRelationshipElementID

func SourceRelationshipElementID(database string, id EdgeID) string

SourceRelationshipElementID qualifies a relationship's stored local ID.

func StoredEntityCountDelta

func StoredEntityCountDelta(namespace string, changes []StoredEntityChange) (nodes, edges int64)

StoredEntityCountDelta folds physical stored presence in namespace. Hidden entities still consume capacity. Empty namespace selects all images. For example, an absent prior and present final node contribute one node.

func StreamEdgesByType

func StreamEdgesByType(ctx context.Context, engine Engine, edgeType string, visit func(*Edge) error) error

StreamEdgesByType visits every relationship of edgeType visible through engine, one at a time.

It uses EdgeTypeStreamer when engine implements it. Otherwise it falls back to engine.GetEdgesByType(edgeType) and visits the returned slice: that fallback still reads only the one relationship type through the type index, never the whole graph (AllEdges), but it holds the type's edges in memory at once. Engines on hot paths (Badger, WAL, Async, Namespaced, Composite and the transaction wrappers) implement the streaming interface.

func StreamEdgesWithFallback

func StreamEdgesWithFallback(ctx context.Context, engine Engine, chunkSize int, fn EdgeVisitor) error

StreamEdgesWithFallback provides streaming iteration with fallback.

func StreamNodesWithFallback

func StreamNodesWithFallback(ctx context.Context, engine Engine, chunkSize int, fn NodeVisitor) error

StreamNodesWithFallback provides streaming iteration with fallback. If the engine supports StreamingEngine, it uses that. Otherwise, it loads all nodes but processes them in chunks.

func StreamStoredEdgesByType

func StreamStoredEdgesByType(ctx context.Context, engine Engine, edgeType string, visit func(*Edge) error) error

StreamStoredEdgesByType visits edgeType's relationships for integrity work ("" visits every relationship): the stored ones when engine can read hidden entities (StoredReader), else those its type or whole-graph edge stream visits.

func StreamStoredNodes

func StreamStoredNodes(ctx context.Context, engine Engine, opts StreamNodesOptions, visit func(*Node) error) error

StreamStoredNodes visits every node for integrity work, with StreamNodesWithOptions' options: every engine can stream stored nodes (ApplyDecayFilter false), so it only rules the visibility out.

func StreamStoredNodesByLabelProjected

func StreamStoredNodesByLabelProjected(ctx context.Context, engine Engine, label string, properties []string, visit func(*Node) error) error

StreamStoredNodesByLabelProjected visits label's nodes for integrity work, decoding only properties: the stored ones when engine can read hidden entities (StoredReader), else those its projected label stream visits.

func StripDatabasePrefix

func StripDatabasePrefix(dbName, id string) string

StripDatabasePrefix removes "<db>:" from id only if it matches dbName. If dbName is empty, or id does not have the matching prefix, id is returned unchanged.

func SubscribeEvents

func SubscribeEvents(engine Engine, handlers EventHandlers) error

SubscribeEvents subscribes handlers to engine, or reports that it cannot deliver events. It checks engine only, never unwrapping it: a wrapper that does not forward the capability is an error, not a silent gap.

func SupportsReadSnapshot

func SupportsReadSnapshot(ctx context.Context, engine any) bool

SupportsReadSnapshot reports whether engine can open a read snapshot, by opening one and closing it at once (a read-timestamp registration).

func SyncDir

func SyncDir(dir string) error

SyncDir makes directory metadata durable using the platform policy shared with WAL and snapshot persistence. Windows validates the directory without attempting the unsupported directory fsync; Unix syncs the directory.

func TemporalIntervalsOverlap

func TemporalIntervalsOverlap(aStart, aEnd time.Time, aHasEnd bool, bStart, bEnd time.Time, bHasEnd bool) bool

TemporalIntervalsOverlap compares half-open epochs. A zero start denotes unbounded past and hasEnd=false denotes unbounded future. Callers admitting external values validate them with ReadTemporalBounds first.

func TemporalKeyAndWindow

func TemporalKeyAndWindow(properties []string) (keyProps []string, startProp, endProp string, ok bool)

TemporalKeyAndWindow splits a temporal no-overlap constraint's properties into the grouping key and the validity window: the last two properties are always (valid_from, valid_to) and every property before them forms the key (the layout temporalKeySpec and enforcement read). It is how a rendered declaration finds the two parts the two spellings of the requirement name separately: SHOW CONSTRAINTS and the Neo4j CSV schema export write the key after GROUP BY and the window in temporal.epoch( … ). ok is false when properties name no window (fewer than two), which no declaration admits.

func TranscodeV4EntityChange

func TranscodeV4EntityChange(kind EntityCommandKind, data []byte) ([]byte, error)

TranscodeV4EntityChange upgrades a historical direct entity command for replication WAL migration. Current command readers never invoke gob.

func TranscodeV4EntityTransaction

func TranscodeV4EntityTransaction(payload []byte) ([]byte, error)

TranscodeV4EntityTransaction converts one historical gob transaction into the current semantic MessagePack representation at the V4 upgrade boundary.

func UndoWALEntry

func UndoWALEntry(ctx context.Context, engine Engine, entry WALEntry) error

UndoWALEntry reverses a WAL entry using its stored before image during crash recovery. ctx must be non-nil; its values are retained, while cancellation is detached so compensation completes. Missing undo data returns ErrNoUndoData.

func UpgradeWALV4

func UpgradeWALV4(dir string, options WALV4UpgradeOptions) (bool, error)

UpgradeWALV4 stages every converted file before publication, and publishes the durable pre-upgrade backup only once every file has converted. A crash after any replacement is resumed from that backup; an externally changed file is rejected rather than overwritten, and a failed conversion leaves every source file as it was with no backup published.

func ValidateConstraintContractExpressions

func ValidateConstraintContractExpressions(contract ConstraintContract) error

ValidateConstraintContractExpressions compiles every boolean entry of a contract so unsupported predicates fail at creation, even on an empty graph.

func ValidateConstraintContractOnCreationForEngine

func ValidateConstraintContractOnCreationForEngine(ctx context.Context, engine Engine, contract ConstraintContract) error

func ValidateConstraintOnCreationForEngine

func ValidateConstraintOnCreationForEngine(ctx context.Context, engine Engine, c Constraint) error

ValidateConstraintOnCreationForEngine validates constraints using the Engine interface. This allows callers (like Cypher) to validate through wrapper engines (namespaced, WAL, etc.).

func ValidatePromotionPolicyOptions

func ValidatePromotionPolicyOptions(updates map[string]interface{}) error

ValidatePromotionPolicyOptions accepts only a boolean enabled option. For example, ValidatePromotionPolicyOptions(map[string]interface{}{"enabled": false}) succeeds, while unknown options and non-boolean enabled values return errors.

func ValidatePropertyType

func ValidatePropertyType(value interface{}, expectedType PropertyType) error

ValidatePropertyType checks if a value matches the expected type: one property type, LIST<T NOT NULL>, or a union of them (any member). Handles JSON/MessagePack serialization quirks where integers become float64.

func ValidatePropertyTypeConstraintOnCreationForEngine

func ValidatePropertyTypeConstraintOnCreationForEngine(ctx context.Context, engine Engine, ptc PropertyTypeConstraint) error

ValidatePropertyTypeConstraintOnCreationForEngine validates type constraints using Engine.

func ValidateWALFormat

func ValidateWALFormat(dir string, mode WALFormatValidation) error

ValidateWALFormat checks the active file and retained segments without repairing or rewriting them. Upgrade validation also checks checksums and historical property-authority boundaries before the storage is opened. It validates a store journal, whose upgrade has no payload transform: a record over one frame is admitted whole.

func ValidateWALFormatForEncryptionUpgrade

func ValidateWALFormatForEncryptionUpgrade(dir string, key []byte, allowLegacy bool) error

ValidateWALFormatForEncryptionUpgrade checks a journal that may be only partially converted after an interrupted encrypted-store upgrade. Each file must be wholly readable as either the old plaintext format or the new authenticated format. It changes nothing and runs before Badger may upgrade its own files; EncryptWALDirectory performs the later atomic conversion.

func ValidateWALFormatWithKey

func ValidateWALFormatWithKey(dir string, mode WALFormatValidation, key []byte) error

ValidateWALFormatWithKey is ValidateWALFormat for a journal written with key. An empty key validates a plaintext journal. The format check authenticates every complete encrypted frame, so a wrong key is refused here instead of at the first replay.

func VerifyBadgerEncryptionKey

func VerifyBadgerEncryptionKey(dataDir string, key []byte) error

VerifyBadgerEncryptionKey checks an existing registry without taking the graph store lock or writing data. The engine remains the registry owner.

func VerifyPreparedDatabaseManifest

func VerifyPreparedDatabaseManifest(dir string) error

VerifyPreparedDatabaseManifest verifies that opening the native engine will use its existing manifest instead of silently creating a new one.

func VisitWALEntriesAfterFromDir added in v1.3.1

func VisitWALEntriesAfterFromDir(ctx context.Context, walDir string, afterSeq uint64, visit func(WALEntry) error) error

VisitWALEntriesAfterFromDir visits WAL entries after the given sequence in segment order without retaining the complete WAL in memory.

func VisitWALEntriesAfterFromDirWithKey

func VisitWALEntriesAfterFromDirWithKey(ctx context.Context, walDir string, afterSeq uint64, key []byte, visit func(WALEntry) error) error

VisitWALEntriesAfterFromDirWithKey is VisitWALEntriesAfterFromDir for a journal written with key.

func WithConstraintAdmission

func WithConstraintAdmission(ctx context.Context, denied error) context.Context

WithConstraintAdmission binds a fine-grained write's schema observation to the storage validation of that same write. If a new uniqueness rule appears between authorization and validation, storage refuses before comparing any values. The caller supplies its own authorization error classification.

func WithCoordinatorOwnedTransaction

func WithCoordinatorOwnedTransaction(ctx context.Context) context.Context

func WithPublicationDecision

func WithPublicationDecision(ctx context.Context, decision PublicationDecision) context.Context

WithPublicationDecision carries a semantic decision on the exact commit context. A nil decision clears an outer owner for preparation or replay.

func WithRestrictedConstraintDiagnostics

func WithRestrictedConstraintDiagnostics(ctx context.Context) context.Context

WithRestrictedConstraintDiagnostics suppresses holder identities in uniqueness diagnostics for a request with graph access filtering.

func WriteDatabaseBackupArchive

func WriteDatabaseBackupArchive(ctx context.Context, path string, stores map[string]Engine) error

WriteDatabaseBackupArchive writes a versioned collection of native Badger streams. The empty key identifies the root, which includes the catalog and all shared databases. Other keys are the catalog's physical store IDs.

func WriteNativeDatabaseBackup

func WriteNativeDatabaseBackup(ctx context.Context, path string, store NativeBackupStreamer) error

WriteNativeDatabaseBackup publishes one native stream in the single-store format.

func WriteSnapshot added in v1.3.1

func WriteSnapshot(ctx context.Context, engine Engine, writer io.Writer, options SnapshotOptions) error

WriteSnapshot writes lossless NDS2 v2 entity frames using streaming enumeration. A node is exported with the managed vectors its reads return: a vector kept beside the node's body (EmbeddingSidecarUpdater) is part of the store's state, and automatic compaction truncates the journal after this snapshot, so a snapshot that left the vector out would rebuild the node without it (or with an older inline image) and leave it unable to say it needs embedding.

A record may be as large as the frame format carries (materializedSnapshotRecordSize), the limit the recovery readers read with (the callers of readSnapshot in wal.go and wal_recovery_stream.go). The snapshot automatic compaction takes is written with this default (NOR-412). options.MaxRecordBytes can only lower that, for a caller that wants a bounded export.

options.EncryptionKey encrypts the stream when set: the NDS2 frames pass through the chunked AES-256-GCM envelope of snapshot_encryption.go directly to writer, so no plaintext copy is staged anywhere. A nil key writes the plaintext NDS2 stream unchanged.

Types

type AcceptedCommitError

type AcceptedCommitError struct {
	State     CommitOutcomeState
	LogicalID string
	Err       error
}

AcceptedCommitError reports an error after a command was accepted. It must not be treated as a definite rejection or used to roll back an admission. State preserves an applied acknowledgement failure versus recovery-pending work. A native cause must never classify this outcome as a rejection.

Identify an accepted outcome with errors.As, then read Err for the native diagnostic. Err retains that diagnostic while public text describes only the accepted outcome, without republishing a rejection phrase that text-based clients would retry. AcceptedCommitError has no Unwrap: errors.Is, errors.As and errors.Unwrap stop at this durable acceptance boundary, so the enclosed diagnostic never confers a retryable rejection identity on the outcome.

func AcceptedOutcome

func AcceptedOutcome(state CommitOutcomeState, logicalID string, err error) *AcceptedCommitError

AcceptedOutcome is the one constructor of the accepted-outcome barrier. An error that already is this barrier, in the same state and for the same (or an unnamed) command, is returned unchanged. Anything else is enclosed whole, including an accepted error nested beside a raw sibling in errors.Join, so no rejection escapes the barrier. An unnamed caller keeps the logical ID of an enclosed accepted error. Author: NOR-288 lane (Claude), 2026-10-30.

func (*AcceptedCommitError) Error

func (e *AcceptedCommitError) Error() string

Author: NOR-288 lane (Codex), 2026-10-26. Preserve accepted uncertainty on the wire instead of disguising it as a new command's retryable rejection.

type AcceptedEntityCommitHandle

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

AcceptedEntityCommitHandle is the one local owner of an accepted entity command between its outer log (WAL, Standalone, HA or Raft) and native application. Transports reach staging and authority only through it: Apply runs the initial native submission or an ordered replay, Settle and Join join a recorded or uncertain transport outcome (parking an unstarted frame for recovery), Reject discards a command no log recorded, and Settled releases the frame and authority when the outer receipt settles. Author: NOR-288 lane (Claude), 2026-10-29.

func AcceptEntityCommit

func AcceptEntityCommit(ctx context.Context, engine Engine, request EntityTransactionRequest) (*AcceptedEntityCommitHandle, []byte, error)

AcceptEntityCommit encodes the prepared snapshot once and retains its accepted authority for the returned owner. On error nothing is retained and the caller still owns the unaccepted prepared frame.

func (*AcceptedEntityCommitHandle) AppliesTo

func (h *AcceptedEntityCommitHandle) AppliesTo(engine Engine) bool

AppliesTo reports whether this owner applies its command on engine. A command from another process or engine has no local owner.

func (*AcceptedEntityCommitHandle) ApplyContext

func (h *AcceptedEntityCommitHandle) ApplyContext(ctx context.Context, data []byte) error

ApplyContext runs this command's native application for an outer log entry: the initial submission, or an ordered replay of the same entry. A replay of a still-pending entry resumes the registered native owner from data.

ctx is the caller's work context, so its owner's Close cancels an initial native submission it would otherwise wait on. A cancelled submission parks the frame for recovery. The waits on the native receipt outlive the caller's request and take the frame engine's own lifetime (h.work.work); its Close ends them as recovery-pending, never as applied or discarded.

func (*AcceptedEntityCommitHandle) Close

Close is a closing transport's cut. Native staging is released without settling the accepted record, which stays pending for recovery: an unstarted frame is parked, and an attempt not yet staged natively fails and parks.

func (*AcceptedEntityCommitHandle) Discard

func (h *AcceptedEntityCommitHandle) Discard(settle func(CommitOutcome), err error)

Discard drops a command before any outer receipt exists: the unstarted frame is aborted, authority released, and settle (if any) sees the discard.

func (*AcceptedEntityCommitHandle) Identity

func (h *AcceptedEntityCommitHandle) Identity() (namespace, logicalID string)

Identity returns the immutable database and logical transaction identity retained when this command was accepted. It remains available after native settlement retires the prepared frame, so publication retries use the same key.

func (*AcceptedEntityCommitHandle) JoinContext

func (h *AcceptedEntityCommitHandle) JoinContext(ctx context.Context, outer CommitReceiptOwner, transportErr error)

JoinContext is Settle for a caller already on its own goroutine and holding no locks: the same recording, with the native join run inline and bounded by ctx (the caller's work context). When ctx ends first, the outer receipt is left pending and settles from the native owner's terminal callback.

The caller keeps its own join lifetime, so this entrypoint has no enrolment for the join to end; it is the released three-argument Go API. A transport whose inline join runs inside its own accepted work calls JoinContextWithRelease instead.

func (*AcceptedEntityCommitHandle) JoinContextWithRelease

func (h *AcceptedEntityCommitHandle) JoinContextWithRelease(ctx context.Context, outer CommitReceiptOwner, transportErr error, release func())

JoinContextWithRelease is JoinContext for a caller whose inline join runs inside its own accepted work enrolment: release ends that enrolment and is idempotent, and the join runs it exactly once before it notifies the outer settlement owner, because that observer may re-enter Close or Shutdown, which joins that enrolment. When ctx ends first, the outer receipt is left pending and settles from the native owner's terminal callback.

For example, a transport worker defers its idempotent release for early exits, then lets the inline join release before notifying its settlement observer:

defer release()
handle.JoinContextWithRelease(work.Context(), owner, transportErr, release)

func (*AcceptedEntityCommitHandle) NativeFrameRetained

func (h *AcceptedEntityCommitHandle) NativeFrameRetained() bool

NativeFrameRetained reports whether this owner still references its native frame. Terminal settlement and parking drop it; diagnostics use this.

func (*AcceptedEntityCommitHandle) ObservePending

func (h *AcceptedEntityCommitHandle) ObservePending(outer CommitReceiptOwner, err error)

ObservePending reports accepted uncertainty to the outer receipt without settling it: a recorded entry's acknowledgement cannot certify rejection.

func (*AcceptedEntityCommitHandle) Reject

func (h *AcceptedEntityCommitHandle) Reject(outer CommitReceiptOwner, err error)

Reject discards a command its outer log never recorded. A command already applying or parked is accepted work and is settled instead.

The definite branch retires this command's native frame and accepted authority before Reject returns. Only the terminal notification leaves that frame: the settlement observer may re-enter the transport's Shutdown. A transport can end its own work enrolment before calling Reject, so transport quiescence is not a delivered-receipt signal. Done closes only after the observer returns.

func (*AcceptedEntityCommitHandle) Settle

func (h *AcceptedEntityCommitHandle) Settle(outer CommitReceiptOwner, transportErr error)

Settle joins a recorded or uncertain transport outcome to the native owner. A transport error before native submission parks the frame and publishes recovery-pending at once, so recovery of the record resumes this owner and settles the original receipt. A started attempt reports its own native outcome through the join. Settle never waits: the join runs as accepted work of the engine's lifecycle owner, outside the caller's locks.

func (*AcceptedEntityCommitHandle) Settled

func (h *AcceptedEntityCommitHandle) Settled()

Settled is the outer receipt's terminal settlement: it retires the native frame and releases accepted authority. Transports call it from their own settle callback before observers run.

func (*AcceptedEntityCommitHandle) Terminal

func (h *AcceptedEntityCommitHandle) Terminal(settle func(CommitOutcome)) func(CommitOutcome)

Terminal wraps settle with Settled for transports without their own callback.

type AcceptedWork

type AcceptedWork interface {
	Enter() bool
	Leave()
	Context() context.Context
}

AcceptedWork is the lifecycle owner of a native engine's accepted work (lifecycle.WorkLifetime). Enter admits one unit before it launches and reports false once Close has sealed admission; each admitted unit calls Leave exactly once when it returns, and Close waits for all of them. Context is the owner's work context, cancelled by Close. A continuation enters, then runs on its own goroutine with a deferred Leave, so it allocates nothing beyond that goroutine's closure.

func AcceptedWorkFor

func AcceptedWorkFor(engine Engine) (AcceptedWork, error)

AcceptedWorkFor returns the accepted-work owner of the native engine behind engine's wrappers: that engine's Close cancels its context and joins its admitted work, so accepted work stays bounded by the engine that applies it. A chain without a native engine cannot apply accepted work and returns the same error as BeginEntityTransaction; there is no substitute. Author: NOR-288 lane (Claude), 2026-10-30.

type AdjacentEdgeDirection

type AdjacentEdgeDirection uint8

AdjacentEdgeDirection selects which incident relationships an AdjacentEdgeRead lists.

const (
	// AdjacentOutgoing lists the relationships whose start node is the
	// request's node.
	AdjacentOutgoing AdjacentEdgeDirection = iota
	// AdjacentIncoming lists the relationships whose end node is the
	// request's node.
	AdjacentIncoming
	// AdjacentBoth lists every relationship incident to the request's node
	// once: the outgoing ones first, then the incoming ones, with a
	// self-relationship appearing only in the outgoing half. It is the
	// undirected expansion's one-orientation contract.
	AdjacentBoth
	// AdjacentBetween lists the relationships directed from the request's
	// node to its Other.
	AdjacentBetween
)

type AdjacentEdgeRead

type AdjacentEdgeRead struct {
	Direction AdjacentEdgeDirection
	Node      NodeID
	// Other, when nonempty, restricts the far endpoint in any direction.
	// AdjacentBetween requires it and remains a directed outgoing pair read.
	Other   NodeID
	Types   []string
	Headers bool
	// ReadPolicy leaves ordinary reads pinned by default. Mutation decisions
	// may request the current committed adjacency while retaining staged writes.
	ReadPolicy EdgeMatchReadPolicy
}

AdjacentEdgeRead is the one request for a node's adjacent relationships: the node, the direction, an optional far endpoint, the relationship types it may list, and whether the caller needs only headers.

Types nil or empty lists every type. A non-empty Types set is a filter the reader applies before it hydrates a relationship: the current adjacency index value carries the relationship's type, so an entry of another type is rejected without reading its record. Headers reports that the caller needs each relationship only for its ID, type and endpoints, so a reader may answer without reading the relationship's record or its properties.

The pinned readers take the same request. A pinned adjacency entry carries only its tombstone bit, so a pinned reader validates the current header against the relationship's MVCC head version and resolves the historical relationship when that header is stale; a current type is never taken as evidence of a historical type.

type AffectedFact

type AffectedFact struct {
	NodeID    NodeID
	EdgeID    EdgeID
	StartNode NodeID
	EndNode   NodeID
	Type      string
	Label     string
	Deleted   bool
	Before    bool
}

AffectedFact is immutable, payload-free publication metadata. NodeID names a body or label membership; EdgeID names a relationship body, with the known before/after endpoints and type. Deleted marks tombstones, including cascades for which older accepted WAL records contain only an ID. No visitor reads storage.

type AffectedFacts

type AffectedFacts interface {
	VisitAffectedFacts(func(AffectedFact))
}

AffectedFacts is the contract consumed by cache, order and authority projections. The release publication-key producer supplies these facts in this layer. #1676 completes discovery/recheck from that producer, rather than adding a parallel one.

type BadgerEngine

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

BadgerEngine provides persistent storage using BadgerDB.

Features:

  • ACID transactions for all operations
  • Persistent storage to disk
  • Secondary indexes for efficient queries
  • Thread-safe concurrent access
  • Automatic crash recovery

Key Structure:

  • Nodes: 0x01 + nodeID -> JSON(Node)
  • Edges: 0x02 + edgeID -> JSON(Edge)
  • Label Index: 0x03 + label + 0x00 + nodeID -> empty
  • Outgoing Index: 0x04 + nodeID + 0x00 + edgeID -> empty
  • Incoming Index: 0x05 + nodeID + 0x00 + edgeID -> empty
  • Edge-Between Set: 0x18 + startID + 0x00 + endID + 0x00 + type + 0x00 + edgeID -> empty
  • Edge-Between Head: 0x19 + startID + 0x00 + endID + 0x00 + type -> edgeID

Example:

engine, err := storage.NewBadgerEngine("/path/to/data")
if err != nil {
	log.Fatal(err)
}
defer engine.Close()

node := &storage.Node{
	ID:     "user-123",
	Labels: []string{"User"},
	Properties: map[string]any{"name": "Alice"},
}
engine.CreateNode(node)

func NewBadgerEngine

func NewBadgerEngine(dataDir string) (*BadgerEngine, error)

NewBadgerEngine creates a new persistent storage engine with default settings.

This is the simplest way to create a storage engine. The engine uses BadgerDB for persistent disk storage with ACID transaction guarantees. All data is stored in the specified directory and persists across restarts.

Parameters:

  • dataDir: Directory path for storing data files. Created if it doesn't exist.

Returns:

  • *BadgerEngine on success
  • error if database cannot be opened (e.g., permissions, disk space)

Example 1 - Basic Usage:

engine, err := storage.NewBadgerEngine("./data/nornicdb")
if err != nil {
	log.Fatal(err)
}
defer engine.Close()

// Engine is ready - create nodes
node := &storage.Node{
	ID:     "user-1",
	Labels: []string{"User"},
	Properties: map[string]any{"name": "Alice"},
}
engine.CreateNode(node)

Example 2 - Production Application:

// Use absolute path for production
dataDir := filepath.Join(os.Getenv("APP_HOME"), "data", "nornicdb")
engine, err := storage.NewBadgerEngine(dataDir)
if err != nil {
	return fmt.Errorf("failed to open database: %w", err)
}
defer engine.Close()

Example 3 - Multiple Databases:

// Main application database
mainDB, _ := storage.NewBadgerEngine("./data/main")
defer mainDB.Close()

// Test database
testDB, _ := storage.NewBadgerEngine("./data/test")
defer testDB.Close()

// Cache database
cacheDB, _ := storage.NewBadgerEngine("./data/cache")
defer cacheDB.Close()

ELI12:

Think of NewBadgerEngine like setting up a filing cabinet in your room. You tell it "put the cabinet here" (the dataDir), and it creates folders and organizes everything. Even if you turn off your computer, the cabinet stays there with all your files inside. Next time you start up, all your data is still there!

Disk Usage:

  • Approximately 2-3x the size of your actual data
  • Includes write-ahead log and compaction overhead

Thread Safety:

Safe for concurrent use from multiple goroutines.

func NewBadgerEngineInMemory

func NewBadgerEngineInMemory() (*BadgerEngine, error)

NewBadgerEngineInMemory creates an in-memory BadgerDB for testing.

Data is not persisted and is lost when the engine is closed. Useful for unit tests that need persistent storage semantics without actual disk I/O.

Example:

engine, err := storage.NewBadgerEngineInMemory()
if err != nil {
	t.Fatal(err)
}
defer engine.Close()

// Use engine for testing...

func NewBadgerEngineWithOptions

func NewBadgerEngineWithOptions(opts BadgerOptions) (*BadgerEngine, error)

NewBadgerEngineWithOptions creates a BadgerEngine with custom configuration.

Use this function when you need fine-grained control over the storage engine behavior, such as enabling in-memory mode for testing, forcing synchronous writes for maximum durability, or reducing memory usage.

Parameters:

  • opts: BadgerOptions struct with configuration settings

Returns:

  • *BadgerEngine on success
  • error if database cannot be opened

Example 1 - In-Memory Database for Testing:

engine, err := storage.NewBadgerEngineWithOptions(storage.BadgerOptions{
	DataDir:  "./test", // Still needs a path but won't be used
	InMemory: true,     // All data in RAM, lost on shutdown
})
defer engine.Close()

// Perfect for unit tests - fast and clean
testCreateNodes(engine)

Example 2 - Maximum Durability for Financial Data:

engine, err := storage.NewBadgerEngineWithOptions(storage.BadgerOptions{
	DataDir:    "./data/transactions",
	SyncWrites: true, // Force fsync after each write (slower but safer)
})
// Guaranteed data persistence even if power fails

Example 3 - Low Memory Mode for Embedded Devices:

engine, err := storage.NewBadgerEngineWithOptions(storage.BadgerOptions{
	DataDir:   "./data/nornicdb",
	LowMemory: true, // Reduces RAM usage by 50-70%
})
// Uses ~50MB instead of ~150MB for typical workloads

Example 4 - Custom Logger Integration:

logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
engine, err := storage.NewBadgerEngineWithOptions(storage.BadgerOptions{
	DataDir: "./data/nornicdb",
	Logger:  &BadgerLogger{zlog: logger}, // Custom logging
})

ELI12:

NewBadgerEngine is like getting a basic backpack for school. NewBadgerEngineWithOptions is like customizing your backpack - you can:

  • Make it waterproof (SyncWrites = true)
  • Make it lighter but less storage (LowMemory = true)
  • Use it as a temporary bag (InMemory = true)
  • Add custom labels (Logger)

Configuration Trade-offs:

  • SyncWrites=true: Slower writes (2-5x) but maximum safety
  • LowMemory=true: Less RAM but slightly slower
  • InMemory=true: Fastest but data lost on shutdown

Thread Safety:

Safe for concurrent use from multiple goroutines.

func OpenBadgerForOfflineImport

func OpenBadgerForOfflineImport(dataDir, namespace string, encryptionKey ...[]byte) (*BadgerEngine, error)

OpenBadgerForOfflineImport opens the native store for a single offline graph import. The importer owns the handle and is the only producer of graph writes until the bulk creates are complete. An existing store uses ordinary bulk validation, including when the requested namespace is empty. For encrypted storage, supply the installation's encryption key as the optional third argument.

func (*BadgerEngine) ActiveReaders added in v1.1.0

func (b *BadgerEngine) ActiveReaders() int64

ActiveReaders returns the count of currently-open MVCC reader snapshots. Always non-nil; returns 0 when the engine has no active readers.

Plan 04-04-01 RISK-2 fix — used by the observability MVCC bag's active_readers GaugeFunc callback.

func (*BadgerEngine) AddToPendingEmbeddings

func (b *BadgerEngine) AddToPendingEmbeddings(nodeID NodeID)

AddToPendingEmbeddings adds a node to the pending embeddings index. Call this when creating a node that needs embedding.

func (*BadgerEngine) AllEdges

func (b *BadgerEngine) AllEdges(ctx context.Context) ([]*Edge, error)

AllEdges returns all edges (implements Engine interface).

func (*BadgerEngine) AllNodes

func (b *BadgerEngine) AllNodes(ctx context.Context) ([]*Node, error)

AllNodes returns all nodes (implements Engine interface).

func (*BadgerEngine) AppendEdgeTombstone

func (b *BadgerEngine) AppendEdgeTombstone(id EdgeID, version MVCCVersion) error

func (*BadgerEngine) AppendEdgeVersion

func (b *BadgerEngine) AppendEdgeVersion(edge *Edge, version MVCCVersion) error

func (*BadgerEngine) AppendNodeTombstone

func (b *BadgerEngine) AppendNodeTombstone(id NodeID, version MVCCVersion) error

func (*BadgerEngine) AppendNodeVersion

func (b *BadgerEngine) AppendNodeVersion(node *Node, version MVCCVersion) error

The MVCCAppendEngine methods below are the exported, context-free append contract: each is its own entry, so each passes its own explicit unbounded lifetime rather than a caller's request context, which the interface does not carry. Extending them to a request lifetime is a separate public contract decision.

func (*BadgerEngine) AttachMetrics added in v1.1.0

func (b *BadgerEngine) AttachMetrics(storage *observability.StorageMetrics, mvcc *observability.MVCCMetrics)

AttachMetrics injects the observability bags into the engine and pre-binds the per-op observers. Idempotent: subsequent calls overwrite the previously-bound observers, which is safe because BoundLatency Observer is value-typed and concurrent Observe calls on either the new or old observer are race-clean (client_golang HistogramVec promise).

Plan 04-04-07 calls AttachMetrics from cmd/nornicdb startup AFTER constructing the bags but BEFORE starting the supervisor.

Ordering discipline (D-02c): metricsAttached flag is set LAST to prevent race where metricsAttached=true but observer fields are still being initialized. This ensures that once metricsAttached is true, all observer fields are guaranteed to be bound.

func (*BadgerEngine) Backup

func (b *BadgerEngine) Backup(path string) error

Backup creates a backup of the database to the specified file path. Uses BadgerDB's streaming backup which creates a consistent snapshot. The backup file is a self-contained, portable copy of the database.

func (*BadgerEngine) BackupTo

func (b *BadgerEngine) BackupTo(ctx context.Context, dst io.Writer) error

BackupTo emits the same native snapshot as Backup to a caller-owned stream.

func (*BadgerEngine) BatchGetNodes

func (b *BadgerEngine) BatchGetNodes(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

BatchGetNodes materializes a batch through one capture, with no overlay map or transaction when every requested body is cached.

func (*BadgerEngine) BatchGetNodesLatestVisible

func (b *BadgerEngine) BatchGetNodesLatestVisible(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

func (*BadgerEngine) BatchGetNodesWithoutEmbeddings added in v1.3.3

func (b *BadgerEngine) BatchGetNodesWithoutEmbeddings(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

func (*BadgerEngine) BeginQueryRevealScope added in v1.1.0

func (b *BadgerEngine) BeginQueryRevealScope(reveal bool) func()

BeginQueryRevealScope guards a query's reveal mode against concurrent queries on the same engine. Reveal queries take an exclusive scope while normal queries take a shared scope so they cannot observe revealAll=true. The caller holds no lifetime here, so the acquisition waits until the scope is granted; context-owning callers use BeginQueryRevealScopeContext.

func (*BadgerEngine) BeginTransaction

func (b *BadgerEngine) BeginTransaction(ctx context.Context, request BeginRequest) (*BadgerTransaction, error)

BeginTransaction starts a new Badger transaction with ACID guarantees for the admission its request selects.

At begin time the namespace is unknown. The unpinned scan boundary includes the captured namespaces' logical high-water marks as well as wall time, so coarse or backward clocks cannot hide rows in the physical snapshot. The first prefixed write, point read, or SetNamespace rebinds this boundary to that namespace's exact begin-time version.

OrdinaryBegin states that the snapshot needs no lifecycle admission: an explicit BEGIN keeps its own snapshot and its commit-time conflict guards. AutocommitSchemaBegin states that an autocommit schema statement publishes a schema definition built from this snapshot. The engine admits that statement exclusively before capturing the snapshot (admitTransactionBegin), and the returned transaction owns that lease until its single release at publication or rollback.

func (*BadgerEngine) BuildRelationshipPropertyEqualityIndex

func (b *BadgerEngine) BuildRelationshipPropertyEqualityIndex(ctx context.Context, namespace, relationshipType string, properties []string) error

BuildRelationshipPropertyEqualityIndex builds and publishes the index one (namespace, relationship type, property set) answers with, from the stored relationships of the type. The statement that declares the relationship constraint calls it, so a match after the declaration is an exact-value lookup rather than the type's first read paying for the build.

func (*BadgerEngine) BulkCreateEdges

func (b *BadgerEngine) BulkCreateEdges(ctx context.Context, edges []*Edge) error

BulkCreateEdges creates edges as one transaction, all of them or none, of any size (#703). An existing edge ID fails the call with ErrAlreadyExists, a missing endpoint with ErrNotFound; nothing is written.

func (*BadgerEngine) BulkCreateNodes

func (b *BadgerEngine) BulkCreateNodes(ctx context.Context, nodes []*Node) error

BulkCreateNodes creates nodes as one transaction (BadgerTransaction): all of them or none, with the transaction's existence and constraint checks, and of any size (#703). A node whose ID exists fails the call with ErrAlreadyExists and nothing is written. Nodes of one call share a namespace.

func (*BadgerEngine) BulkDeleteEdges

func (b *BadgerEngine) BulkDeleteEdges(ctx context.Context, ids []EdgeID) error

BulkDeleteEdges deletes relationships as one transaction of any size (#703). IDs that do not exist, or repeat within the call, are skipped.

func (*BadgerEngine) BulkDeleteNodes

func (b *BadgerEngine) BulkDeleteNodes(ctx context.Context, ids []NodeID) error

BulkDeleteNodes deletes nodes, with their relationships, as one transaction of any size (#703). IDs that do not exist, or repeat within the call, are skipped.

func (*BadgerEngine) ChangeBounds

func (b *BadgerEngine) ChangeBounds(namespace string) (earliest, last uint64, err error)

ChangeBounds returns the commitSeq of a database's earliest retained event and of its last committed one; 0, 0 when it has none.

func (*BadgerEngine) ChangeCapture

func (b *BadgerEngine) ChangeCapture(namespace string) ChangeCaptureMode

ChangeCapture returns a database's capture mode.

func (*BadgerEngine) ChangeEvents

func (b *BadgerEngine) ChangeEvents(namespace string, commitSeq uint64, seq uint32, limit int) ([]ChangeEvent, error)

ChangeEvents returns up to limit of a database's events after (commitSeq, seq), in commit order; limit <= 0 is no limit.

func (*BadgerEngine) CheckIDDictionary

func (b *BadgerEngine) CheckIDDictionary() (*IDDictionaryReport, error)

CheckIDDictionary reports the stored entities with no ID-dictionary entry, and those whose entry holds a number none of their index keys use: a labelled node in no label index key, a relationship in no outgoing key. Read-only.

func (*BadgerEngine) ClearAllEmbeddings

func (b *BadgerEngine) ClearAllEmbeddings() (int, error)

ClearAllEmbeddings removes embeddings from all nodes, allowing them to be regenerated. Returns the number of nodes that had their embeddings cleared. See ClearAllEmbeddingsForPrefix for the per-node, non-atomic progress this count reports and for the partial-count error.

func (*BadgerEngine) ClearAllEmbeddingsForPrefix

func (b *BadgerEngine) ClearAllEmbeddingsForPrefix(idPrefix string) (int, error)

ClearAllEmbeddingsForPrefix removes embeddings from nodes whose IDs start with the given prefix. This is used to clear embeddings for a single logical database namespace (e.g., "nornic:").

If idPrefix is empty, clears embeddings for all nodes.

The reset is per node and not atomic. It first scans every in-scope node record and collects the key IDs of the nodes that currently carry an embedding, then clears each one through the native transaction mutation owner, which is also the single owner of the node's pending-embedding marker. A successful call reports the number of selected nodes reset successfully, and leaves each queued for regeneration by its own update. A body the scan cannot decode, or that does not belong to the key it was found under, fails the scan with ErrInvalidData before anything is written. A node the reset cannot read or write stops the reset and returns the number already cleared together with the error, so a partial reset is never reported as a clean one. Concurrent disappearance is a read failure, not a completed reset.

func (*BadgerEngine) Close

func (b *BadgerEngine) Close() error

Close closes the BadgerDB database. It is the engine owner's one stop: the first caller stops the producers and seals admission, and every caller, first or repeated, joins the same retirement and receives the same outcome.

func (*BadgerEngine) ConsumeCleanShutdownMarker

func (b *BadgerEngine) ConsumeCleanShutdownMarker(ctx context.Context) (bool, error)

ConsumeCleanShutdownMarker atomically reads and removes the durable clean shutdown marker. Removing it before serving traffic makes an ungraceful exit conservative: the next startup cannot mistake the crashed run for a clean one.

func (*BadgerEngine) CountPendingEmbeddingIDs

func (b *BadgerEngine) CountPendingEmbeddingIDs(ctx context.Context, accept func([]byte) bool) int

func (*BadgerEngine) CreateEdge

func (b *BadgerEngine) CreateEdge(ctx context.Context, edge *Edge) (err error)

CreateEdge creates a new edge between two nodes.

func (*BadgerEngine) CreateNode

func (b *BadgerEngine) CreateNode(ctx context.Context, node *Node) (NodeID, error)

CreateNode creates a new node in persistent storage. REQUIRES: node.ID must be prefixed with namespace (e.g., "nornic:node-123"). This enforces that all nodes are namespaced at the storage layer.

func (*BadgerEngine) DB added in v1.1.0

func (b *BadgerEngine) DB() *badger.DB

DB returns the underlying *badger.DB handle. Used by Plan 04-04-04 bytes_metrics_sweeper to call EstimateSize(prefix). Read-only handle — callers must not invoke lifecycle methods (Close/DropAll) on the returned pointer; the engine owns lifecycle. Badger runs in managed mode (see managedBadgerDB): transactions and writes must go through the engine, never through this handle.

func (*BadgerEngine) DataDirFreeSpace

func (b *BadgerEngine) DataDirFreeSpace() (int64, error)

DataDirFreeSpace returns free bytes available to the current process for the underlying Badger data directory.

func (*BadgerEngine) DeleteAccessMeta added in v1.1.0

func (b *BadgerEngine) DeleteAccessMeta(ctx context.Context, entityID string) error

DeleteAccessMeta removes one entity's access state, retaining its index catalog state. ctx owns admission and preparation; an admitted deletion completes in the store.

func (*BadgerEngine) DeleteByPrefix

func (b *BadgerEngine) DeleteByPrefix(prefix string) (nodesDeleted int64, edgesDeleted int64, err error)

DeleteByPrefix deletes all nodes and edges with IDs starting with the given prefix. Used for DROP DATABASE operations to delete all data in a namespace.

This uses Badger's native prefix drop for db-scoped keyspaces to avoid per-node decoding and DeleteNode/DeleteEdge loops. Secondary indexes that don't begin with the node/edge ID (label and edge-type indexes) are cleaned up by scanning those index keyspaces and deleting entries whose suffix IDs match the prefix.

func (*BadgerEngine) DeleteDeindexWorkItem added in v1.1.0

func (b *BadgerEngine) DeleteDeindexWorkItem(ctx context.Context, workItemID string) error

DeleteDeindexWorkItem retires one work item under the caller's lifetime. A canceled retirement leaves the item pending, so a later run retries it.

func (*BadgerEngine) DeleteEdge

func (b *BadgerEngine) DeleteEdge(ctx context.Context, id EdgeID) error

DeleteEdge removes an edge.

func (*BadgerEngine) DeleteIndexEntryCatalog added in v1.1.0

func (b *BadgerEngine) DeleteIndexEntryCatalog(entityID string) error

DeleteIndexEntryCatalog is the catalog write's exported context-free entry, as PutIndexEntryCatalog is: its own unbounded lifetime, not a default for a context a caller did supply.

func (*BadgerEngine) DeleteMVCCVersion

func (b *BadgerEngine) DeleteMVCCVersion(ctx context.Context, logicalKey []byte, version MVCCVersion) error

DeleteMVCCVersion deletes a single MVCC version for a logical key. ctx keeps its values and cancellation while waiting for write admission.

func (*BadgerEngine) DeleteNode

func (b *BadgerEngine) DeleteNode(ctx context.Context, id NodeID) error

DeleteNode removes a node and all its edges.

func (*BadgerEngine) EdgeCount

func (b *BadgerEngine) EdgeCount(ctx context.Context) (int64, error)

EdgeCount returns the total number of valid, decodable edges. This is consistent with AllEdges() - only counts edges that can be successfully decoded.

func (*BadgerEngine) EdgeCountByEndLabel

func (b *BadgerEngine) EdgeCountByEndLabel(ctx context.Context, label, edgeType string) (int64, error)

EdgeCountByEndLabel returns the count of edges of the given type whose physical END endpoint carries the label, across all namespaces.

func (*BadgerEngine) EdgeCountByEndLabelInNamespace

func (b *BadgerEngine) EdgeCountByEndLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)

EdgeCountByEndLabelInNamespace returns the count of edges of the given type whose physical END endpoint carries the label, in one namespace.

func (*BadgerEngine) EdgeCountByPrefix

func (b *BadgerEngine) EdgeCountByPrefix(ctx context.Context, prefix string) (int64, error)

EdgeCountByPrefix counts edges whose EdgeID begins with the provided prefix. The prefix refers to the EdgeID string prefix (e.g., database namespace "nornic:").

func (*BadgerEngine) EdgeCountByStartLabel

func (b *BadgerEngine) EdgeCountByStartLabel(ctx context.Context, label, edgeType string) (int64, error)

EdgeCountByStartLabel returns the count of edges of the given type whose physical START endpoint carries the label, across all namespaces.

func (*BadgerEngine) EdgeCountByStartLabelInNamespace

func (b *BadgerEngine) EdgeCountByStartLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)

EdgeCountByStartLabelInNamespace returns the count of edges of the given type whose physical START endpoint carries the label, in one namespace.

func (*BadgerEngine) EdgeCountByType

func (b *BadgerEngine) EdgeCountByType(ctx context.Context, edgeType string) (int64, error)

EdgeCountByType returns the total count of edges of the given type across all namespaces. This is the O(#namespaces) point-read fast path behind MATCH ()-[r:T]->() RETURN count(r).

func (*BadgerEngine) EdgeCountByTypeInNamespace

func (b *BadgerEngine) EdgeCountByTypeInNamespace(ctx context.Context, namespace, edgeType string) (int64, error)

EdgeCountByTypeInNamespace returns the persisted count of edges of the given type in one namespace (0 when absent).

func (*BadgerEngine) EnqueueDeindexIfSuppressed added in v1.1.0

func (b *BadgerEngine) EnqueueDeindexIfSuppressed(ctx context.Context, entityID string, isEdge bool) (bool, error)

EnqueueDeindexIfSuppressed evaluates the entity's current decay score. If below the visibility threshold, it marks the entity as suppressed and creates a pending deindex work item. If above threshold and currently suppressed, it clears the suppression and deletes any tombstones. The returned bool is true only when the entity transitioned into the suppressed state during this call.

ctx belongs to the callback that owns the rescore: an accepted access write or decay job passes its own admitted lifetime. ctx owns admission, the buffered-order drain and the score/rewrite preparation; once the publishing update is admitted, the transition, its work item and its publication complete in the store, so a canceled ctx reports no transition.

func (*BadgerEngine) EnsureNamespaceMVCC added in v1.1.5

func (b *BadgerEngine) EnsureNamespaceMVCC(namespace string) error

EnsureNamespaceMVCC eagerly loads the per-namespace MVCC state so a subsequent BeginTransaction snapshots the namespace's current sequence instead of treating it like a post-begin namespace.

func (*BadgerEngine) EstimateSize

func (b *BadgerEngine) EstimateSize(prefix []byte) (keys, values uint64)

EstimateSize returns the approximate key and value bytes under prefix, or zero once Close sealed admission.

func (*BadgerEngine) EventNotificationsSettled

func (b *BadgerEngine) EventNotificationsSettled() bool

EventNotificationsSettled observes the canonical notification queue. Native synchronous commits reserve their queue entry before publishing graph data. Buffered commits acknowledge data before their per-operation events exist, and one acknowledgement can stand for several events; those cannot certify this baseline and conservatively return false.

func (*BadgerEngine) FilterEdgePropertyByDecay added in v1.1.0

func (b *BadgerEngine) FilterEdgePropertyByDecay(edgeID EdgeID, edgeType, propKey string, createdAtNanos, versionAtNanos, nowNanos int64) bool

FilterEdgePropertyByDecay returns true if the edge property should be hidden from results.

func (*BadgerEngine) FilterPropertyByDecay added in v1.1.0

func (b *BadgerEngine) FilterPropertyByDecay(nodeID NodeID, labels []string, propKey string, createdAtNanos, versionAtNanos, nowNanos int64) bool

FilterPropertyByDecay returns true if the property should be hidden from results.

func (*BadgerEngine) FindNodeNeedingEmbedding

func (b *BadgerEngine) FindNodeNeedingEmbedding(ctx context.Context) (*Node, error)

FindNodeNeedingEmbedding returns a node that needs embedding. The durable prefixPendingEmbed index is authoritative. A derived candidate heap avoids reopening/rewinding that range for every claim: Badger's rewind and read-ahead revisit deleted marker versions even with a prefix bound. After one lazy index load, a live candidate needs only point validation; stale candidates are removed once. Each returned node is validated in the engine write that cleans the markers before it; cleanup larger than one Badger batch commits batch by batch, so it always makes progress. Claim serialization remains with the worker. This exported optional-interface method carries the worker job context through catalog admission, iteration and cleanup preparation. An actual storage error is returned, while no eligible candidate is (nil, nil).

func (*BadgerEngine) FlushWriteBehind

func (b *BadgerEngine) FlushWriteBehind(ctx context.Context) error

FlushWriteBehind drains every buffered generation synchronously. It is a no-op when write-behind is disabled. It holds the write barrier shared while it drains, so Close does not release Badger under it (Close's own final drain is admitted), and delivers the drained commits' notifications once it released it, so no listener runs while a barrier waiter waits for it. Cancellation ends this wait; independently accepted replay retains its terminal and settlement ownership. Callers supply a non-nil context; context.Background selects a non-cancellable flush. Accepted replay retains its separate completion lifetime.

func (*BadgerEngine) ForEachNodeIDByLabel

func (b *BadgerEngine) ForEachNodeIDByLabel(ctx context.Context, label string, visit func(NodeID) bool) error

ForEachNodeIDByLabel streams node IDs for a label without decoding nodes. Stops early when visit returns false.

func (*BadgerEngine) ForEachNodeIDByLabelInScope

func (b *BadgerEngine) ForEachNodeIDByLabelInScope(ctx context.Context, scope, label string, visit func(NodeID) bool) error

ForEachNodeIDByLabelInScope streams only this database's label IDs. Empty scope preserves the unscoped interface's behavior.

func (*BadgerEngine) GetDeindexWorkItem added in v1.1.0

func (b *BadgerEngine) GetDeindexWorkItem(workItemID string) (*DeindexWorkItem, error)

func (*BadgerEngine) GetEdge

func (b *BadgerEngine) GetEdge(ctx context.Context, id EdgeID) (*Edge, error)

GetEdge retrieves an edge by ID.

func (*BadgerEngine) GetEdgeBetween

func (b *BadgerEngine) GetEdgeBetween(ctx context.Context, source, target NodeID, edgeType string) (*Edge, error)

GetEdgeBetween returns an edge between two nodes with the given type. A missing relationship is (nil, nil); the caller's context owns admission and the point read's materialization.

func (*BadgerEngine) GetEdgeCurrentHead

func (b *BadgerEngine) GetEdgeCurrentHead(ctx context.Context, id EdgeID) (MVCCHead, error)

GetEdgeCurrentHead reads the edge's persisted head under the caller's context.

func (*BadgerEngine) GetEdgeLatestVisible

func (b *BadgerEngine) GetEdgeLatestVisible(ctx context.Context, id EdgeID) (*Edge, error)

func (*BadgerEngine) GetEdgeVisibleAt

func (b *BadgerEngine) GetEdgeVisibleAt(ctx context.Context, id EdgeID, version MVCCVersion) (*Edge, error)

func (*BadgerEngine) GetEdgesByType

func (b *BadgerEngine) GetEdgesByType(ctx context.Context, edgeType string) ([]*Edge, error)

GetEdgesByType returns all edges of a specific type using the edge type index. This is MUCH faster than AllEdges() for queries like mutual follows. Relationship types match exactly, as in Neo4j (#862). Results are cached per type to speed up repeated queries.

func (*BadgerEngine) GetEdgesByTypeVisibleAt

func (b *BadgerEngine) GetEdgesByTypeVisibleAt(ctx context.Context, edgeType string, version MVCCVersion) ([]*Edge, error)

func (*BadgerEngine) GetEntityMeta added in v1.1.0

func (b *BadgerEngine) GetEntityMeta(ctx context.Context, entityID string) (knowledgepolicy.EntityMeta, error)

GetEntityMeta returns the metadata needed by the access flusher to resolve ON ACCESS policies and property visibility for either nodes or edges.

func (*BadgerEngine) GetFirstNodeByLabel

func (b *BadgerEngine) GetFirstNodeByLabel(ctx context.Context, label string) (*Node, error)

GetFirstNodeByLabel returns the first node with the specified label. This is optimized for MATCH...LIMIT 1 patterns - stops after first match.

func (*BadgerEngine) GetFirstNodeByLabelInScope

func (b *BadgerEngine) GetFirstNodeByLabelInScope(ctx context.Context, scope, label string) (*Node, error)

GetFirstNodeByLabelInScope is GetFirstNodeByLabel within one database (ScopedLabelNodeReader).

func (*BadgerEngine) GetInDegree

func (b *BadgerEngine) GetInDegree(ctx context.Context, nodeID NodeID) (int, error)

GetInDegree returns the number of incoming edges to a node.

func (*BadgerEngine) GetIndexEntryCatalog added in v1.1.0

func (b *BadgerEngine) GetIndexEntryCatalog(entityID string) (*IndexEntryCatalog, error)

func (*BadgerEngine) GetNode

func (b *BadgerEngine) GetNode(ctx context.Context, id NodeID) (*Node, error)

GetNode retrieves a node by ID.

func (*BadgerEngine) GetNodeCurrentHead

func (b *BadgerEngine) GetNodeCurrentHead(ctx context.Context, id NodeID) (MVCCHead, error)

GetNodeCurrentHead reads the node's persisted head under the caller's context, which owns admission of the point read.

func (*BadgerEngine) GetNodeEmbeddingMeta

func (b *BadgerEngine) GetNodeEmbeddingMeta(ctx context.Context, id NodeID) (map[string]any, error)

GetNodeEmbeddingMeta returns a node's embedding metadata without its vectors, as GetNode reads it: the fresh sidecar record, else the body's own. An embedding-free read (GetNodeWithoutEmbeddings) leaves the sidecar out; a search hit's chunk places and kept chunk texts are read here. A node buffered by write-behind answers with its buffered state, as GetNode does; a buffered delete is gone.

func (*BadgerEngine) GetNodeLatestVisible

func (b *BadgerEngine) GetNodeLatestVisible(ctx context.Context, id NodeID) (*Node, error)

func (*BadgerEngine) GetNodeProjected added in v1.1.8

func (b *BadgerEngine) GetNodeProjected(ctx context.Context, id NodeID, properties []string) (*Node, error)

GetNodeProjected retrieves a node while decoding only the requested user properties. Metadata fields such as ID, labels, timestamps, and embedding metadata are still decoded from the node body. A nil properties slice falls back to the full GetNode path; an empty non-nil slice returns no user properties.

func (*BadgerEngine) GetNodeVisibleAt

func (b *BadgerEngine) GetNodeVisibleAt(ctx context.Context, id NodeID, version MVCCVersion) (*Node, error)

func (*BadgerEngine) GetNodeWithoutEmbeddings added in v1.3.3

func (b *BadgerEngine) GetNodeWithoutEmbeddings(ctx context.Context, id NodeID) (*Node, error)

GetNodeWithoutEmbeddings retrieves a node without following separately stored embedding vectors. User properties and node metadata are preserved. The decoded node is not cached, so an embedding-free read can never poison the cache for later full reads.

func (*BadgerEngine) GetNodesByLabel

func (b *BadgerEngine) GetNodesByLabel(ctx context.Context, label string) ([]*Node, error)

GetNodesByLabel returns all nodes with the specified label.

func (*BadgerEngine) GetNodesByLabelInScope

func (b *BadgerEngine) GetNodesByLabelInScope(ctx context.Context, scope, label string) ([]*Node, error)

GetNodesByLabelInScope is GetNodesByLabel within one database (ScopedLabelNodeReader).

func (*BadgerEngine) GetNodesByLabelVisibleAt

func (b *BadgerEngine) GetNodesByLabelVisibleAt(ctx context.Context, label string, version MVCCVersion) ([]*Node, error)

func (*BadgerEngine) GetNodesByLabelVisibleAtInScope

func (b *BadgerEngine) GetNodesByLabelVisibleAtInScope(ctx context.Context, scope, label string, version MVCCVersion) ([]*Node, error)

GetNodesByLabelVisibleAtInScope is GetNodesByLabelVisibleAt within one database (ScopedLabelNodeReader).

func (*BadgerEngine) GetOrAttachManagedEntityRuntime

func (b *BadgerEngine) GetOrAttachManagedEntityRuntime(namespace string, candidate any) any

GetOrAttachManagedEntityRuntime attaches the namespace's one existing managed usage/policy runtime. A later manager receives that same runtime rather than installing another ledger. The owning package checks its concrete type. A nil candidate only queries the current attachment.

func (*BadgerEngine) GetOutDegree

func (b *BadgerEngine) GetOutDegree(ctx context.Context, nodeID NodeID) (int, error)

GetOutDegree returns the number of outgoing edges from a node.

func (*BadgerEngine) GetQueryNode

func (b *BadgerEngine) GetQueryNode(ctx context.Context, id NodeID) (*Node, error)

GetQueryNode implements QueryNodeReader with GetNode's reads (the write-behind overlay, the node cache, the stored body) and its embedding metadata, without reading separately stored chunk vectors. In-memory inline vectors belong to the returned caller-owned copy. The lightweight image is cached apart from the full image (queryNodeCache), so warming a full read cannot make later metadata reads copy separately stored chunks; full reads never take the lightweight entry and still return all vectors.

func (*BadgerEngine) GetSchema

func (b *BadgerEngine) GetSchema() *SchemaManager

GetSchema returns the schema manager.

func (*BadgerEngine) GetSchemaForNamespace

func (b *BadgerEngine) GetSchemaForNamespace(namespace string) *SchemaManager

GetSchemaForNamespace returns the schema for a specific database namespace. If no schema exists yet, an empty schema is created (and will be persisted once mutated).

func (*BadgerEngine) GetStoredEdge

func (b *BadgerEngine) GetStoredEdge(ctx context.Context, id EdgeID) (*Edge, error)

GetStoredEdge is GetEdge for integrity work: it also returns a relationship the visibility layer hides (StoredEntityReader).

func (*BadgerEngine) GetStoredEdgesByType

func (b *BadgerEngine) GetStoredEdgesByType(ctx context.Context, edgeType string) ([]*Edge, error)

GetStoredEdgesByType is GetEdgesByType for integrity work: it also returns the relationships the visibility layer hides (StoredEntityReader). It never reads or fills the per-type cache, which holds visible results.

func (*BadgerEngine) GetStoredNode

func (b *BadgerEngine) GetStoredNode(ctx context.Context, id NodeID) (*Node, error)

GetStoredNode returns the physical body through the same captured read view.

func (*BadgerEngine) GetStoredNodesByLabel

func (b *BadgerEngine) GetStoredNodesByLabel(ctx context.Context, label string) ([]*Node, error)

GetStoredNodesByLabel is GetNodesByLabel for integrity work: it also returns the nodes the visibility layer hides (StoredEntityReader).

func (*BadgerEngine) GetStoredNodesByLabelInScope

func (b *BadgerEngine) GetStoredNodesByLabelInScope(ctx context.Context, scope, label string) ([]*Node, error)

GetStoredNodesByLabelInScope is GetStoredNodesByLabel within one database (ScopedStoredEntityReader).

func (*BadgerEngine) GetTemporalNodeAsOfInNamespace

func (b *BadgerEngine) GetTemporalNodeAsOfInNamespace(ctx context.Context, namespace, label, keyProp string, keyValue interface{}, validFromProp, validToProp string, asOf time.Time) (*Node, error)

func (*BadgerEngine) GraphMutationVersion added in v1.3.3

func (b *BadgerEngine) GraphMutationVersion() (uint64, bool)

GraphMutationVersion reports all graph mutations published by this engine.

func (*BadgerEngine) GraphMutationVersionInNamespace added in v1.3.3

func (b *BadgerEngine) GraphMutationVersionInNamespace(namespace string) (uint64, bool)

GraphMutationVersionInNamespace reports graph mutations for one database.

func (*BadgerEngine) HasLabelBatch

func (b *BadgerEngine) HasLabelBatch(ids []NodeID, label string) (map[NodeID]bool, error)

HasLabelBatch checks label membership for a batch of node IDs using the label index. This avoids decoding node records and is significantly faster for large batches.

func (*BadgerEngine) HasManualSuppressions

func (b *BadgerEngine) HasManualSuppressions() bool

HasManualSuppressions reports whether any entity is suppressed on demand, for callers that skip visibility filtering when nothing can be hidden.

func (*BadgerEngine) IDDictCounters added in v1.1.0

func (b *BadgerEngine) IDDictCounters() (nodes, edges uint64)

IDDictCounters exposes the dict's counter state for observability probes. Package-level method on BadgerEngine routes through here.

func (*BadgerEngine) IDDictFreelistPending added in v1.1.0

func (b *BadgerEngine) IDDictFreelistPending() (nodes, edges int64)

IDDictFreelistPending exposes the freelist pending counters for observability probes.

func (*BadgerEngine) IndexSourceStamp

func (b *BadgerEngine) IndexSourceStamp(ctx context.Context) (string, error)

IndexSourceStamp uses the existing capture owner, including its pending-write cut. The digest identifies immutable physical record versions plus the durable property-source identity that changes on replacement/restore. It is not a checksum of a second projection of the graph.

func (*BadgerEngine) InitializeStoredEntityObserver

func (b *BadgerEngine) InitializeStoredEntityObserver(namespace string, initialize func(StoredEntitySnapshot) (StoredEntityObserver, error), boundary StoredEntityReadBoundary) error

InitializeStoredEntityObserver owns one exclusive stored snapshot/install cut. The caller must not hold its admission lock while waiting for this cut. The initializer streams initial images, atomically initializes its own ledger and returns the observer installed before any subsequent writer is admitted. Neither initializer nor observer may reenter storage or write admission.

func (*BadgerEngine) InvalidateEdgeTypeCache

func (b *BadgerEngine) InvalidateEdgeTypeCache(edgeTypes ...string)

InvalidateEdgeTypeCache removes the selected types, or clears the entire type cache when called with no arguments. Explicit empty types are no-ops. For example, InvalidateEdgeTypeCache("KNOWS") invalidates only KNOWS.

func (*BadgerEngine) InvalidatePendingEmbeddingsIndex

func (b *BadgerEngine) InvalidatePendingEmbeddingsIndex()

InvalidatePendingEmbeddingsIndex discards only the derived candidate catalog. The durable pending index is unchanged. The generation needs no queue lock, including during Restore while new read transactions are held off.

func (*BadgerEngine) IsCurrentTemporalNode

func (b *BadgerEngine) IsCurrentTemporalNode(ctx context.Context, node *Node, asOf time.Time) (bool, error)

IsCurrentTemporalNode reports whether the given temporal node is the live/current version.

func (*BadgerEngine) IsCurrentTemporalNodeInNamespace

func (b *BadgerEngine) IsCurrentTemporalNodeInNamespace(ctx context.Context, namespace string, node *Node, asOf time.Time) (bool, error)

IsCurrentTemporalNodeInNamespace reports whether the given temporal node is the live/current version.

func (*BadgerEngine) IsDatabaseEmbeddingsEnabled

func (b *BadgerEngine) IsDatabaseEmbeddingsEnabled(namespace string) bool

IsDatabaseEmbeddingsEnabled reports per-database generation admission.

func (*BadgerEngine) IsDecayEnabled added in v1.1.0

func (b *BadgerEngine) IsDecayEnabled() bool

IsDecayEnabled reports whether knowledge-layer decay scoring is active.

func (*BadgerEngine) IsEmbeddingsEnabled added in v1.1.0

func (b *BadgerEngine) IsEmbeddingsEnabled() bool

IsEmbeddingsEnabled reports whether the engine should maintain the pending- embed index.

func (*BadgerEngine) IsInMemory

func (b *BadgerEngine) IsInMemory() bool

IsInMemory returns true if the engine is running in memory-only mode. In-memory mode is used for testing - there's no disk to fsync to.

func (*BadgerEngine) IterateLatestVisibleEdges

func (b *BadgerEngine) IterateLatestVisibleEdges(yield func(*Edge) error) error

func (*BadgerEngine) IterateLatestVisibleNodes

func (b *BadgerEngine) IterateLatestVisibleNodes(ctx context.Context, yield func(*Node) error) error

func (*BadgerEngine) IterateMVCCHeads

func (b *BadgerEngine) IterateMVCCHeads(ctx context.Context, yield func(logicalKey []byte, head MVCCHead) error) error

IterateMVCCHeads iterates all persisted MVCC heads.

func (*BadgerEngine) IterateMVCCVersions

func (b *BadgerEngine) IterateMVCCVersions(ctx context.Context, logicalKey []byte, yield func(version MVCCVersion, tombstoned bool, sizeBytes int64) error) error

IterateMVCCVersions iterates all versions for a logical key.

func (*BadgerEngine) IterateNodes

func (b *BadgerEngine) IterateNodes(fn func(*Node) bool) error

IterateNodes iterates through all nodes one at a time without loading all into memory. The callback returns true to continue, false to stop.

func (*BadgerEngine) LifecycleStatus

func (b *BadgerEngine) LifecycleStatus() map[string]interface{}

LifecycleStatus reports lifecycle status when enabled.

func (*BadgerEngine) ListNamespaces

func (b *BadgerEngine) ListNamespaces() []string

ListNamespaces returns the set of database namespaces currently present in this Badger engine, derived from the cached per-namespace node/edge counters.

Namespaces are returned without the trailing ':' (e.g., "nornic", "db2").

func (*BadgerEngine) Logger added in v1.1.0

func (b *BadgerEngine) Logger() *slog.Logger

Logger returns the BadgerEngine's structured logger (D-01 accessor). Used by NamespacedEngine and other wrappers to derive child loggers without an additional ctor parameter. Returns a discard logger if no logger was supplied at construction.

func (*BadgerEngine) LookupEdgesByPropertyEqualityInNamespace

func (b *BadgerEngine) LookupEdgesByPropertyEqualityInNamespace(ctx context.Context, namespace, relationshipType string, properties []string, values []interface{}) ([]*Edge, bool, error)

LookupEdgesByPropertyEqualityInNamespace answers one exact-value relationship lookup from the retained index of namespace, building that index from the stored relationships of the type when it is not retained yet. Only matching relationship bodies are read.

func (*BadgerEngine) MarkCleanShutdown

func (b *BadgerEngine) MarkCleanShutdown(ctx context.Context) error

MarkCleanShutdown durably records that all writers were stopped and flushed. It must be called only at the end of an orderly owner shutdown.

func (*BadgerEngine) MarkNodeEmbedded

func (b *BadgerEngine) MarkNodeEmbedded(nodeID NodeID)

MarkNodeEmbedded removes a node from the pending embeddings index. Call this after successfully embedding a node.

func (*BadgerEngine) MatchEdgesBetween

func (b *BadgerEngine) MatchEdgesBetween(ctx context.Context, startID, endID NodeID, edgeType string, properties []string, match func(*Edge) bool, policy EdgeMatchReadPolicy) ([]*Edge, error)

MatchEdgesBetween matches the engine's edges between two nodes. Under write-behind it overlays the buffer the same way a between adjacent-edge request does: a buffered endpoint delete hides committed rows, a buffered edge delete hides that row, and buffered live edges of the type are appended (PR #1043 read-overlay parity — MERGE identity reads).

func (*BadgerEngine) NodeCount

func (b *BadgerEngine) NodeCount(ctx context.Context) (int64, error)

func (*BadgerEngine) NodeCountByLabel added in v1.1.3

func (b *BadgerEngine) NodeCountByLabel(ctx context.Context, label string) (int64, error)

NodeCountByLabel reads the label cardinality across namespaces under ctx.

func (*BadgerEngine) NodeCountByLabelInNamespace added in v1.1.3

func (b *BadgerEngine) NodeCountByLabelInNamespace(ctx context.Context, namespace, label string) (int64, error)

NodeCountByLabelInNamespace reads the stored namespace count and pending deltas under ctx, including any required derived-count repair.

func (*BadgerEngine) NodeCountByPrefix

func (b *BadgerEngine) NodeCountByPrefix(ctx context.Context, prefix string) (int64, error)

NodeCountByPrefix counts nodes whose NodeID begins with the provided prefix. The prefix refers to the NodeID string prefix (e.g., database namespace "nornic:").

This is an optional fast-path used by NamespacedEngine to provide accurate per-database counts without decoding values.

func (*BadgerEngine) NotePropertyKeysInNamespace

func (b *BadgerEngine) NotePropertyKeysInNamespace(namespace string, properties map[string]interface{})

NotePropertyKeysInNamespace records the keys of properties that hold a value as used in namespace (PropertyKeyRegistry). Writes that encode allocate their names; buffered ones (BadgerTransaction, AsyncEngine) call this when they take the write.

func (*BadgerEngine) OfflineImportBulkContext

func (b *BadgerEngine) OfflineImportBulkContext(ctx context.Context) context.Context

OfflineImportBulkContext scopes the fresh-store proof to one import's node and relationship creates. The importer uses its original context for schema and search indexing, which may perform independent writes.

func (*BadgerEngine) OldestReaderAgeSeconds added in v1.1.0

func (b *BadgerEngine) OldestReaderAgeSeconds() float64

OldestReaderAgeSeconds returns the wall-clock age (in seconds) of the oldest still-open MVCC reader snapshot. Returns 0 when no readers are active or no controller is wired (atomic-counter fallback does not track per-reader StartTime).

Plan 04-04-01 RISK-2 fix — used by the observability MVCC bag's oldest_reader_age_seconds GaugeFunc callback.

func (*BadgerEngine) OnEdgeCreated

func (b *BadgerEngine) OnEdgeCreated(callback EdgeEventCallback)

OnEdgeCreated adds a callback to be invoked when edges are created. Implements StorageEventNotifier interface.

func (*BadgerEngine) OnEdgeDeleted

func (b *BadgerEngine) OnEdgeDeleted(callback EdgeDeleteCallback)

OnEdgeDeleted adds a callback to be invoked when edges are deleted. Implements StorageEventNotifier interface.

func (*BadgerEngine) OnEdgeUpdated

func (b *BadgerEngine) OnEdgeUpdated(callback EdgeEventCallback)

OnEdgeUpdated adds a callback to be invoked when edges are updated. Implements StorageEventNotifier interface.

func (*BadgerEngine) OnNamespaceReset

func (b *BadgerEngine) OnNamespaceReset(callback NamespaceResetCallback)

OnNamespaceReset registers a callback for DeleteByPrefix. It is called in commit order with the other storage event callbacks.

func (*BadgerEngine) OnNodeCreated

func (b *BadgerEngine) OnNodeCreated(callback NodeEventCallback)

OnNodeCreated adds a callback to be invoked when nodes are created. Implements StorageEventNotifier interface.

func (*BadgerEngine) OnNodeDeleted

func (b *BadgerEngine) OnNodeDeleted(callback NodeDeleteCallback)

OnNodeDeleted adds a callback to be invoked when nodes are deleted. Implements StorageEventNotifier interface.

func (*BadgerEngine) OnNodeUpdated

func (b *BadgerEngine) OnNodeUpdated(callback NodeEventCallback)

OnNodeUpdated adds a callback to be invoked when nodes are updated. Implements StorageEventNotifier interface.

func (*BadgerEngine) OpenReadSnapshot

func (b *BadgerEngine) OpenReadSnapshot(ctx context.Context) (ReadSnapshotView, error)

OpenReadSnapshot captures a long-lived read view and, at the same point, the whole write-behind overlay (captureReadView).

func (*BadgerEngine) PauseLifecycle

func (b *BadgerEngine) PauseLifecycle()

PauseLifecycle pauses lifecycle work.

func (*BadgerEngine) PendingEmbeddingsCount

func (b *BadgerEngine) PendingEmbeddingsCount() int

PendingEmbeddingsCount returns the number of nodes waiting for embedding. Note: This requires a scan of the pending index, so use sparingly.

func (*BadgerEngine) PinnedBytes added in v1.1.0

func (b *BadgerEngine) PinnedBytes() int64

PinnedBytes returns the cumulative byte count pinned by all active MVCC readers. Returns 0 when no controller is wired (fallback path tracks counts only, not bytes). Always non-nil.

Plan 04-04-01 RISK-2 fix — used by the observability MVCC bag's pinned_bytes GaugeFunc callback.

func (*BadgerEngine) PropKeyDictCounters added in v1.1.0

func (b *BadgerEngine) PropKeyDictCounters() map[string]uint64

PropKeyDictCounters exposes per-namespace counter usage for observability probes.

func (*BadgerEngine) PropertyKeyKnownInNamespace

func (b *BadgerEngine) PropertyKeyKnownInNamespace(namespace, name string) bool

PropertyKeyKnownInNamespace reports whether a write in namespace has stored a value under name (PropertyKeyRegistry).

func (*BadgerEngine) PruneChangeEvents

func (b *BadgerEngine) PruneChangeEvents(ctx context.Context, namespace string, cutoff time.Time) (int, error)

PruneChangeEvents deletes a database's events of transactions committed before cutoff, returning how many it deleted. The last transaction's events are always kept: they are where db.cdc.current() stands.

ctx is the retention job's admitted lifetime, not an initiating request: it bounds the scan and admission of every delete batch. A batch that was admitted completes in the store; a canceled ctx stops before the next batch and returns the count actually deleted.

func (*BadgerEngine) PruneMVCCVersions

func (b *BadgerEngine) PruneMVCCVersions(ctx context.Context, opts MVCCPruneOptions) (int64, error)

PruneMVCCVersions deletes the historical versions that retention no longer keeps and no registered snapshot can read. Passes are ordered against each other; readers and writers never wait for one (see the file comment).

MaxRuntime bounds this engine's call. Waiting for another pass, storage admission, conflict retries and the walk over long chains all end when it is spent; the call then returns what it committed, and the next bounded call resumes after the last committed decision. Reading the reader floors takes short engine locks without a deadline. The first key the call decides is committed at once, and a later candidate waits for at most an eighth of MaxRuntime of further discovery plus the scan of the key in progress before it is committed, so the call commits progress unless that first key's own work exceeds MaxRuntime. A step's update that storage has already admitted runs to completion, because a commit is indivisible: a call can exceed MaxRuntime by that one commit, which deletes up to mvccPruneChunk records plus a final tombstone marker. The budget is per engine: a wrapper that prunes several engines (a composite database) gives each its own MaxRuntime.

func (*BadgerEngine) PruneTemporalHistory

func (b *BadgerEngine) PruneTemporalHistory(ctx context.Context, opts TemporalPruneOptions) (int64, error)

PruneTemporalHistory removes older closed temporal versions according to opts.

func (*BadgerEngine) PutDeindexWorkItem added in v1.1.0

func (b *BadgerEngine) PutDeindexWorkItem(ctx context.Context, item *DeindexWorkItem) error

PutDeindexWorkItem queues one retryable work item under the caller's lifetime.

func (*BadgerEngine) PutIndexEntryCatalog added in v1.1.0

func (b *BadgerEngine) PutIndexEntryCatalog(ctx context.Context, entityID string, cat *IndexEntryCatalog) error

PutIndexEntryCatalog records an entity's secondary-index keys under the caller's operation lifetime. ctx owns admission; an admitted catalog write completes in the store and a canceled ctx returns its own error unwritten.

func (*BadgerEngine) ReadAccessMeta

ReadAccessMeta is the one implementation of committed access metadata reads and their DROP admission. A point read returns the entry stored for the request's entity ID; it retains work and tombstone entries. An all read exposes only entity access state, skipping internal work keys, from one captured transaction and a single iterator. The read mode is validated before any read happens.

func (*BadgerEngine) ReadAdjacentEdges

func (b *BadgerEngine) ReadAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadAdjacentEdges answers one adjacent-edge request from the engine's current view: the node's relationships in the requested direction, of the requested types, as full relationships or as headers, whichever the request asks for.

On a hot path the per-node adjacency cache short-circuits the Badger iterator entirely; a miss falls back to a single view transaction for every direction the request lists. An entry of another type is rejected from the adjacency value before its relationship is read or allocated.

func (*BadgerEngine) ReadAdjacentEdgesVisibleAt

func (b *BadgerEngine) ReadAdjacentEdgesVisibleAt(ctx context.Context, request AdjacentEdgeRead, version MVCCVersion) ([]*Edge, error)

ReadAdjacentEdgesVisibleAt answers one adjacent-edge request at the exact requested version.

func (*BadgerEngine) ReadCountStore

func (b *BadgerEngine) ReadCountStore(ctx context.Context, request CountStoreReadRequest) (CountStoreRead, error)

ReadCountStore answers one count-store read: the counter value and whether that value describes the rows a read in the same scope returns, both from one persisted snapshot and one buffered view, under the count families' read holds. A persisted count that cannot be decoded is repaired by its family's canonical rebuild and read again, as the other derived-count readers do.

A request carrying a Scope (CountStoreReadScope) belongs to one explicit transaction and is answered at that transaction's snapshot instead (CountStoreReadScope.readCountStore): the current counters describe that transaction's rows only until a peer commits, and its snapshot's counters describe them always. Such a read is never repaired from a newer view.

func (*BadgerEngine) ReadMVCCHead

func (b *BadgerEngine) ReadMVCCHead(ctx context.Context, logicalKey []byte) (MVCCHead, error)

ReadMVCCHead loads the current MVCC head for a logical key.

func (*BadgerEngine) ReadPendingEmbeddingCount

func (b *BadgerEngine) ReadPendingEmbeddingCount(ctx context.Context, accept func([]byte) bool) (int, error)

ReadPendingEmbeddingCount reports the count or the error preventing the read.

func (*BadgerEngine) ReadStoredAdjacentEdges

func (b *BadgerEngine) ReadStoredAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadStoredAdjacentEdges is ReadAdjacentEdges over the physically stored relationships, the hidden bodies an integrity read needs included (StoredEntityReader).

func (*BadgerEngine) RebuildMVCCHeads

func (b *BadgerEngine) RebuildMVCCHeads(ctx context.Context) error

RebuildMVCCHeads rebuilds every MVCC head from the stored versions and bodies. It replaces the heads wholesale, so it runs as a maintenance write (beginMaintenanceWrite): no write runs across it, and every write-behind commit acknowledged before it is applied first.

func (*BadgerEngine) RebuildTemporalIndexes

func (b *BadgerEngine) RebuildTemporalIndexes(ctx context.Context) error

RebuildTemporalIndexes recreates the temporal history and current-pointer indexes from stored nodes.

func (*BadgerEngine) ReconcileDecaySuppression added in v1.1.0

func (b *BadgerEngine) ReconcileDecaySuppression(namespace string) error

ReconcileDecaySuppression re-evaluates current suppression state for all entities in a namespace after knowledge-policy changes.

The reconciliation is accepted engine work triggered by an accepted schema change, not a request: it runs under its own explicit unbounded lifetime so a finished caller cannot abandon half of the namespace. Making it cancelable needs its own context-first contract decision.

func (*BadgerEngine) ReconcileDecaySuppressionWithChanges added in v1.1.0

func (b *BadgerEngine) ReconcileDecaySuppressionWithChanges(namespace string) ([]SuppressionStateChange, error)

ReconcileDecaySuppressionWithChanges re-evaluates suppression state and returns the entities whose visibility-suppressed state changed.

Like ReconcileDecaySuppression it is accepted engine work under its own explicit unbounded lifetime.

func (*BadgerEngine) RecordMaterializedAccess added in v1.1.0

func (b *BadgerEngine) RecordMaterializedAccess(entityID string)

RecordMaterializedAccess records an access only after the query executor has fully materialized the entity into a result row.

func (*BadgerEngine) RefreshPendingEmbeddingsIndex

func (b *BadgerEngine) RefreshPendingEmbeddingsIndex() int

RefreshPendingEmbeddingsIndex rebuilds the pending embeddings index. This scans all nodes and adds any missing ones to the index. It also removes stale entries for nodes that no longer exist or already have embeddings. Use this on startup or after bulk imports. Its caller context is erased by the exported optional interface, so this entry passes its own explicit unbounded lifetime for the index rebuild's writes.

func (*BadgerEngine) RegisterManagedEntityPreparer

func (b *BadgerEngine) RegisterManagedEntityPreparer(namespace string, prepare ManagedEntityPrepare, initialize ManagedEntityInitialize)

RegisterManagedEntityPreparer registers managed leader admission without scanning storage or waiting for the exclusive initialization cut. First registration owns both preparation and initialization; later wrappers retain their own routing while sharing that namespace owner. For example, a database wrapper registers its existing prepare/admit coordinator here.

func (*BadgerEngine) RegisterSnapshotReader

func (b *BadgerEngine) RegisterSnapshotReader(info SnapshotReaderInfo) func()

RegisterSnapshotReader delegates reader registration when lifecycle is enabled. The caller may read history through fresh views, as an as-of read does, so its registration waits for a prune step in flight (beginMVCCSnapshotRead), never for a whole prune pass; that step's scan of its key's remaining history grows with the chain's length.

func (*BadgerEngine) RelationshipEndpointVisible

func (b *BadgerEngine) RelationshipEndpointVisible(id NodeID) (visible, answered bool)

RelationshipEndpointVisible implements RelationshipEndpointChecker with the lookups GetNode starts with: the node caches, else whether the node's record key exists, without reading or decoding the record. It doesn't answer while decay filtering can hide a node at read time, or when the lookup fails.

func (*BadgerEngine) RepairIDDictionary

func (b *BadgerEngine) RepairIDDictionary() (*IDDictionaryReport, error)

RepairIDDictionary restores the original numeric ID of each entity CheckIDDictionary reports, when the index keys left behind identify it unambiguously, so the existing index keys are valid again:

  • a node: the one unresolved numeric ID in the label index of every one of its labels;
  • a relationship: the one unresolved numeric ID in its start node's outgoing keys, its end node's incoming keys and its type's index.

A mismatched entity's entry is pointed back at the original number the same way, and its MVCC head moved with it.

Nodes are repaired first, so relationships between repaired nodes resolve. An entity that isn't identified unambiguously (an unlabelled node, two lost relationships alike) is listed as unresolved and left unchanged.

func (*BadgerEngine) Restore

func (b *BadgerEngine) Restore(path string) error

Restore loads a Badger streaming backup into the engine. The backup format is the protobuf stream emitted by Backup, not the legacy JSON export.

The store is offline while it is replaced (#1020). Restore stops the background index backfills, holds off writes (writeBarrier) and reads (holdReads: a read or write that starts meanwhile fails at once with ErrStorageRestoring, which is transient), and waits up to restoreReadDrainTimeout for the reads and transactions already open. If they are still open then, Restore fails and changes nothing. Otherwise no reader sees a half-restored store or decodes with a half-built dictionary: the in-memory state (ID and property-key dictionaries, MVCC floors and sequence, schemas, caches, counts) is rebuilt from the restored store before reads resume. The backfills then start again if the restored store needs them.

func (*BadgerEngine) RestoreFrom

func (b *BadgerEngine) RestoreFrom(ctx context.Context, src io.Reader) (restoreErr error)

RestoreFrom loads the same native stream as Restore. The caller owns src.

func (*BadgerEngine) ResumeLifecycle

func (b *BadgerEngine) ResumeLifecycle()

ResumeLifecycle resumes lifecycle work.

func (*BadgerEngine) RetireManagedEntityRuntime

func (b *BadgerEngine) RetireManagedEntityRuntime(namespace string)

RetireManagedEntityRuntime is called only after successful catalog DROP persistence. It releases callback claims for recreation while retaining the canonical runtime object, so previously returned views cannot own orphan usage.

func (*BadgerEngine) RunGC

func (b *BadgerEngine) RunGC() error

RunGC runs garbage collection on the BadgerDB value log. Should be called periodically for long-running applications.

func (*BadgerEngine) RunOnStartMigrations added in v1.1.0

func (b *BadgerEngine) RunOnStartMigrations(allowUpgrade bool) error

RunOnStartMigrations advances the on-disk schema version to storageVersionCurrent if (and only if) the operator has authorized the upgrade via allowUpgrade. Without authorization, an out-of-date store causes RunOnStartMigrations to return ErrStorageUpgradeRequired and the engine refuses to open.

Migrations run in order based on the on-disk version, each preserving the prior step's invariants:

V0 → V1: extracts legacy access state into AccessMeta records.
V1 → V2: eager rewrite of every node and edge body to the tokenized
         property-key codec; bumps the version after a clean pass.
V2 → V3: restore versioned adjacency and exact-case label/type indexes.

Manual invocations cannot perform a V4 catalog payload upgrade: reopening is required before any manager can retain the legacy catalog snapshot. Existing V0/V1/V2/V3 manual migration behavior is retained.

Sets engine.storageVersion to the post-migration version so the encode path can deterministically pick codecs from it.

func (*BadgerEngine) ScanPendingDeindexWorkItems added in v1.1.0

func (b *BadgerEngine) ScanPendingDeindexWorkItems() ([]*DeindexWorkItem, error)

ScanPendingDeindexWorkItems returns all work items with status "pending".

func (*BadgerEngine) ScorerForNamespace added in v1.1.0

func (b *BadgerEngine) ScorerForNamespace(namespace string) *knowledgepolicy.Scorer

ScorerForNamespace returns a Scorer for the given namespace, or nil.

func (*BadgerEngine) ServerTransactionTimeout

func (b *BadgerEngine) ServerTransactionTimeout() time.Duration

ServerTransactionTimeout is the server's transaction timeout (EngineOptions.LockWait.Timeout); zero or negative means none. An explicit transaction idle this long is ended by its owner (pkg/cypher, NOR-284).

func (*BadgerEngine) SetAccessAccumulator added in v1.1.0

func (b *BadgerEngine) SetAccessAccumulator(acc accessIncrementor)

SetAccessAccumulator wires the P-local accumulator so read paths can record access events for nodes that survive visibility filtering.

func (*BadgerEngine) SetBufferedCommitWAL

func (b *BadgerEngine) SetBufferedCommitWAL(w *WAL)

SetBufferedCommitWAL installs the WAL that receives the durable payload of every acknowledged write-behind commit. It is called once, at construction, by NewWALEngine before the engine serves traffic.

func (*BadgerEngine) SetChangeCapture

func (b *BadgerEngine) SetChangeCapture(namespace string, mode ChangeCaptureMode)

SetChangeCapture sets a database's capture mode (its txLogEnrichment). The first capturing database starts the retention job.

func (*BadgerEngine) SetChangeRetention

func (b *BadgerEngine) SetChangeRetention(retention time.Duration)

SetChangeRetention sets how long change events are kept; 0 or less is the default, 2 days (Neo4j's default transaction log retention).

func (*BadgerEngine) SetDatabaseEmbeddingsEnabled

func (b *BadgerEngine) SetDatabaseEmbeddingsEnabled(namespace string, enabled bool) bool

SetDatabaseEmbeddingsEnabled changes admission for one database without deleting its existing vectors. Returns whether the setting changed.

func (*BadgerEngine) SetDecayEnabled added in v1.1.0

func (b *BadgerEngine) SetDecayEnabled(enabled bool)

SetDecayEnabled enables or disables knowledge-layer decay scoring on read paths.

func (*BadgerEngine) SetEmbeddingLabelPolicy

func (b *BadgerEngine) SetEmbeddingLabelPolicy(namespace string, include, exclude []string)

SetEmbeddingLabelPolicy sets the managed-embedding label filter for a database. An empty include list allows all labels; exclusion always takes precedence.

func (*BadgerEngine) SetEmbeddingTextPolicy

func (b *BadgerEngine) SetEmbeddingTextPolicy(policy EmbeddingTextPolicy)

SetEmbeddingTextPolicy sets the policy of the engine's managed embedding text. Until it is set, every property but the metadata ones feeds the text, and the labels do too.

func (*BadgerEngine) SetEmbeddingsEnabled added in v1.1.0

func (b *BadgerEngine) SetEmbeddingsEnabled(enabled bool)

SetEmbeddingsEnabled toggles the pending-embed index. When false, CreateNode and UpsertNode skip the pendingEmbedKey write on user nodes — no embed worker will consume the marker when embeddings are globally disabled, so the Set is pure write amplification. Wired from the server at startup alongside the decay flag (see pkg/nornicdb/db.go).

func (*BadgerEngine) SetIndexTombstones

func (b *BadgerEngine) SetIndexTombstones(ctx context.Context, keys [][]byte, present bool) error

SetIndexTombstones changes visibility markers for the original index keys atomically. present=true hides entries; present=false removes their markers. An empty batch performs no write. Keys and stored marker bytes are unchanged. ctx is the owning job's admitted lifetime: it owns admission, while an admitted batch completes in the store, so a canceled ctx returns its own error and writes no marker.

func (*BadgerEngine) SetLifecycleController

func (b *BadgerEngine) SetLifecycleController(controller MVCCLifecycleController)

SetLifecycleController injects the MVCC lifecycle controller.

func (*BadgerEngine) SetLifecycleSchedule

func (b *BadgerEngine) SetLifecycleSchedule(interval time.Duration) error

SetLifecycleSchedule updates lifecycle cadence when supported by the controller.

func (*BadgerEngine) SetManualSuppression

func (b *BadgerEngine) SetManualSuppression(ctx context.Context, entityKind StoredEntityKind, id string, suppressed bool) error

SetManualSuppression hides or shows a stored node or relationship without deleting its data. Hidden entities remain available under reveal(). Changes publish an update for search consumers, whether or not decay is enabled. Unknown kinds return ErrInvalidData; missing entities return ErrNotFound.

ctx is the caller's operation lifetime: it owns admission, buffered-order drain and the stored-body read. An admitted suppression write, its in-memory flag and its publication complete in the store, so a canceled ctx returns its own error and changes nothing.

func (*BadgerEngine) SetRevealAll added in v1.1.0

func (b *BadgerEngine) SetRevealAll(reveal bool)

SetRevealAll disables decay suppression for all entities in the current query. Call ClearRevealAll after the query completes.

func (*BadgerEngine) Size

func (b *BadgerEngine) Size() (lsm, vlog int64)

Size returns the approximate size of the database in bytes.

func (*BadgerEngine) StartLifecycleManager

func (b *BadgerEngine) StartLifecycleManager(ctx context.Context)

StartLifecycleManager starts the injected lifecycle manager.

func (*BadgerEngine) StreamEdges

func (b *BadgerEngine) StreamEdges(ctx context.Context, fn func(edge *Edge) error) error

StreamEdges implements StreamingEngine.StreamEdges for memory-efficient iteration. Iterates through all edges one at a time without loading all into memory.

func (*BadgerEngine) StreamEdgesByType

func (b *BadgerEngine) StreamEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamEdgesByType iterates the edge type index in one read transaction and decodes one edge record at a time (EdgeTypeStreamer).

func (*BadgerEngine) StreamEdgesByTypeInScope

func (b *BadgerEngine) StreamEdgesByTypeInScope(ctx context.Context, scope, edgeType string, visit func(*Edge) error) error

StreamEdgesByTypeInScope is StreamEdgesByType within one database (ScopedEdgeTypeStreamer). Index entries of edges outside scope are skipped after resolving the edge ID from the in-memory ID dictionary, before their records are read or decoded. An empty edgeType streams every edge, matching GetEdgesByType("").

func (*BadgerEngine) StreamNodeChunks

func (b *BadgerEngine) StreamNodeChunks(ctx context.Context, chunkSize int, fn func(nodes []*Node) error) error

StreamNodeChunks implements StreamingEngine.StreamNodeChunks for batch processing. It batches the node stream, so a chunk holds exactly the nodes StreamNodes publishes: the same bodies, vectors and visibility.

func (*BadgerEngine) StreamNodes

func (b *BadgerEngine) StreamNodes(ctx context.Context, fn func(node *Node) error) error

StreamNodes implements StreamingEngine.StreamNodes for memory-efficient iteration. Iterates through all nodes one at a time without loading all into memory.

func (*BadgerEngine) StreamNodesByLabelProjected added in v1.3.2

func (b *BadgerEngine) StreamNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error

StreamNodesByLabelProjected iterates label-matching nodes in a single read transaction while decoding only the requested user properties.

func (*BadgerEngine) StreamNodesByLabelProjectedInScope

func (b *BadgerEngine) StreamNodesByLabelProjectedInScope(ctx context.Context, scope, label string, properties []string, visit func(*Node) error) error

StreamNodesByLabelProjectedInScope is StreamNodesByLabelProjected within one database (ScopedLabelNodeReader).

Nodes are visited in label-index order. Scans that continue past labelScanPointLookups switch to one pass over the node records when the label is on at least half of the scope's nodes.

func (*BadgerEngine) StreamNodesByPrefix

func (b *BadgerEngine) StreamNodesByPrefix(ctx context.Context, prefix string, fn func(node *Node) error) error

StreamNodesByPrefix streams nodes whose IDs start with prefix. This is significantly faster than full StreamNodes + callback filtering when tenants/databases share a physical store.

func (*BadgerEngine) StreamNodesByPrefixProjected added in v1.3.3

func (b *BadgerEngine) StreamNodesByPrefixProjected(ctx context.Context, prefix string, properties []string, fn func(node *Node) error) error

StreamNodesByPrefixProjected streams nodes whose IDs start with prefix while decoding only the requested user properties. It preserves StreamNodesByPrefix semantics: nil properties reads full nodes, and ErrIterationStopped ends the scan successfully.

func (*BadgerEngine) StreamNodesByPrefixWithoutEmbeddings

func (b *BadgerEngine) StreamNodesByPrefixWithoutEmbeddings(ctx context.Context, prefix string, fn func(node *Node) error) error

StreamNodesByPrefixWithoutEmbeddings streams node metadata without loading separate or legacy inline vector payloads.

func (*BadgerEngine) StreamNodesWithOptions

func (b *BadgerEngine) StreamNodesWithOptions(ctx context.Context, opts StreamNodesOptions, fn func(node *Node) error) error

StreamNodesWithOptions iterates nodes one at a time without materializing them, honoring prefix scoping, property projection, embedding and decay options. Full scans use value prefetching; prefix scans use key-only seeks.

func (*BadgerEngine) StreamNodesWithoutEmbeddings

func (b *BadgerEngine) StreamNodesWithoutEmbeddings(ctx context.Context, fn func(node *Node) error) error

StreamNodesWithoutEmbeddings iterates complete node records without reading the separate vector keyspace. User properties are retained for snapshots.

func (*BadgerEngine) StreamParkedEmbeddingFailures

func (b *BadgerEngine) StreamParkedEmbeddingFailures(ctx context.Context, visit func(nodeID NodeID, meta map[string]any) error) (int, error)

StreamParkedEmbeddingFailures visits only parked failure keys once the durable index is ready. Older stores use the authoritative metadata scan until their one-time backfill finishes. Neither path decodes node bodies.

func (*BadgerEngine) StreamStoredEdgesByType

func (b *BadgerEngine) StreamStoredEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamStoredEdgesByType is StreamEdgesByType for integrity work: it also visits the relationships the visibility layer hides (StoredEntityReader).

func (*BadgerEngine) StreamStoredEdgesByTypeInScope

func (b *BadgerEngine) StreamStoredEdgesByTypeInScope(ctx context.Context, scope, edgeType string, visit func(*Edge) error) error

StreamStoredEdgesByTypeInScope is StreamStoredEdgesByType within one database (ScopedStoredEntityReader).

func (*BadgerEngine) StreamStoredNodesByLabelProjected

func (b *BadgerEngine) StreamStoredNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error

StreamStoredNodesByLabelProjected is StreamNodesByLabelProjected for integrity work: it also visits the nodes the visibility layer hides (StoredEntityReader).

func (*BadgerEngine) StreamStoredNodesByLabelProjectedInScope

func (b *BadgerEngine) StreamStoredNodesByLabelProjectedInScope(ctx context.Context, scope, label string, properties []string, visit func(*Node) error) error

StreamStoredNodesByLabelProjectedInScope is StreamStoredNodesByLabelProjected within one database (ScopedStoredEntityReader).

func (*BadgerEngine) SubmitEntityCommit

func (b *BadgerEngine) SubmitEntityCommit(ctx context.Context, prepared *PreparedEntityCommit, settle func(CommitOutcome)) (*CommitReceipt, error)

SubmitEntityCommit owns a prepared native commit when no outer replication or journal wrapper owns submission. Receipt cancellation never reaches Commit.

func (*BadgerEngine) SubscribeEvents

func (b *BadgerEngine) SubscribeEvents(handlers EventHandlers) error

SubscribeEvents registers handlers with the commit-ordered callbacks.

func (*BadgerEngine) Sync

func (b *BadgerEngine) Sync() error

Sync forces a sync of all data to disk. This is useful for ensuring durability before a crash. A commit's settlement can call it after its worker left the lifecycle owner, so it takes its own short admission: Close joins a Sync in progress and refuses a later one, and it holds nothing a settlement that closes the engine would wait for. Author: NOR-288 lane (Claude), 2026-10-31.

func (*BadgerEngine) TopLifecycleDebtKeys

func (b *BadgerEngine) TopLifecycleDebtKeys(limit int) []MVCCLifecycleDebtKey

TopLifecycleDebtKeys returns the highest-debt keys when supported by the controller.

func (*BadgerEngine) TriggerPruneNow

func (b *BadgerEngine) TriggerPruneNow(ctx context.Context) error

TriggerPruneNow runs an immediate lifecycle prune.

func (*BadgerEngine) UpdateEdge

func (b *BadgerEngine) UpdateEdge(ctx context.Context, updateRequest EdgeUpdateRequest) error

UpdateEdge updates an existing edge.

func (*BadgerEngine) UpdateEdgeCurrentHead

func (b *BadgerEngine) UpdateEdgeCurrentHead(id EdgeID, version MVCCVersion, tombstoned bool) error

func (*BadgerEngine) UpdateNode

func (b *BadgerEngine) UpdateNode(ctx context.Context, updateRequest NodeUpdateRequest) error

UpdateNode updates an existing node or creates it if it doesn't exist (upsert).

func (*BadgerEngine) UpdateNodeCurrentHead

func (b *BadgerEngine) UpdateNodeCurrentHead(id NodeID, version MVCCVersion, tombstoned bool) error

func (*BadgerEngine) UpdateNodeEmbeddingSidecar

func (b *BadgerEngine) UpdateNodeEmbeddingSidecar(ctx context.Context, node *Node) error

UpdateNodeEmbeddingSidecar persists only the embedding payload of an existing node in the dedicated embedding key space:

  • chunk vectors under embeddingKey (old chunks replaced atomically, #703)
  • EmbedMeta under embedMetaKey, stamped with the body UpdatedAt the embedding was generated from
  • the pending-embeddings index entry is removed

The node record (nodeKey, MVCC head, version history) is never written and no MVCC version is created. The commit first reads the stored node in its first batch, whose reads Badger conflict-checks before anything is written (commitWriter): when the node is gone the result is ErrNotFound, and when its properties or labels differ from node's the embedding describes old content, so the result is ErrEmbeddingSourceChanged and the pending marker the business write set stays (#889). A business write committing between that read and this commit fails the commit with a conflict, reported as ErrEmbeddingSourceChanged too.

func (*BadgerEngine) ValidateRelationshipConstraint

func (b *BadgerEngine) ValidateRelationshipConstraint(ctx context.Context, rc RelationshipConstraint) error

ValidateRelationshipConstraint validates relationship property constraints while ctx owns preparation, before the new constraint is accepted.

func (*BadgerEngine) WriteAccessMeta

func (b *BadgerEngine) WriteAccessMeta(ctx context.Context, request knowledgepolicy.AccessMetaWriteRequest) (bool, error)

WriteAccessMeta stores access state through the existing publication owner. RecordState preserves unconditional restore/work-key semantics. A flush holds native entity authority for both typed IDs, drains preceding buffered writes, then checks stored-inclusive presence and writes in the same transaction. A skipped flush returns false without changing retained metadata.

ctx belongs to the operation that owns the write: an access flush passes its own cycle lifetime. ctx owns admission, buffered-order drain and presence preparation; once the publishing update is admitted the write and its notification complete in the store, and a canceled ctx returns its own error with no published entry.

func (*BadgerEngine) WriteMVCCHead

func (b *BadgerEngine) WriteMVCCHead(ctx context.Context, logicalKey []byte, head MVCCHead) error

WriteMVCCHead writes an updated MVCC head for a logical key. A head never moves backwards: when the stored head is newer than head (a commit of the entity landed after the caller read it, as the lifecycle pruner does), its version and tombstone stay and only the floor is raised. It is ordered after the entity's acknowledged write-behind commits (orderAfterBufferedCommits), so none of them lands over it afterwards.

type BadgerOptions

type BadgerOptions struct {
	// ExperimentalLayout selects experimental property and SST encodings for this store.
	ExperimentalLayout bool
	// Projected selects the opt-in physical projected-read format for a new store.
	// It is independent of ExperimentalLayout and absent for existing stores.
	Projected bool
	// CatalogUpgradeV4 is the optional exact catalog migration plan. It is
	// captured at open; startup integration decides when V4 is authorized.
	CatalogUpgradeV4 *CatalogUpgradeV4

	// DataDir is the directory for storing data files.
	// Required.
	DataDir string

	// InMemory runs BadgerDB in memory-only mode.
	// Useful for testing. Data is not persisted. Unless HighPerformance or
	// LowMemory is set, in-memory engines use a smaller test-oriented profile
	// so large test suites do not retain one default-sized Badger arena per
	// fixture while still accepting normal-sized schema and node values.
	InMemory bool

	// SyncWrites forces fsync after each write.
	// Slower but more durable.
	SyncWrites bool

	// WriteBehind buffers implicit autocommit transaction commits in the
	// engine's rotating commit buffer and replays them into Badger in
	// background batches. Explicit transactions and snapshot opens drain the
	// buffer first. Off by default.
	WriteBehind bool

	// WriteBehindInterval rotates the active buffer generation this often.
	// Defaults to 50ms when WriteBehind is set and this is <= 0.
	WriteBehindInterval time.Duration

	// WriteBehindMaxOps rotates the active generation once it holds this
	// many buffered operations. 0 selects auto sizing against the engine's
	// default cap (defaultWriteBehindMaxOps); a positive value is a manual
	// cap for operators with unusual hardware.
	WriteBehindMaxOps int
	// MemoryPolicy is the optional shared application budget. Buffered commit
	// payloads reserve before their replayable WAL record is written.
	MemoryPolicy *memory.Policy

	// BadgerInternalLogger is the logger handed to BadgerDB itself for its
	// own internal logging (compaction, value-log GC, etc.). If nil, BadgerDB's
	// quiet/default logger is used. This field replaces the previous
	// BadgerOptions.Logger which collided with the new structured *slog.Logger
	// field below; rename is internal-only (no external setter ever existed
	// outside doc comments — verified 2026-05-01).
	BadgerInternalLogger badger.Logger

	// Logger is the structured *slog.Logger threaded into the storage engine.
	// D-01 logger DI: optional; nil falls back to a discard handler at ctor
	// entry per D-01a so existing callers (and tests) compile unchanged.
	// Once set, BadgerEngine emits all operational diagnostics through this
	// logger tagged with component=storage, engine=badger.
	Logger *slog.Logger

	// LowMemory enables memory-constrained settings.
	// Reduces MemTableSize and other buffers to use less RAM.
	LowMemory bool

	// HighPerformance enables aggressive caching and larger buffers.
	// Uses more RAM but significantly faster writes/reads.
	HighPerformance bool

	// EncryptionKey is the 16, 24, or 32 byte key for AES encryption.
	// If provided, all data will be encrypted at rest using AES-CTR.
	// WARNING: If you lose this key, your data is irrecoverable!
	// Leave empty to disable encryption.
	EncryptionKey []byte

	// AllowStorageUpgrade authorizes the engine to advance the on-disk
	// storage version through whichever migration arms this binary
	// understands. Without it, a binary that opens a data directory
	// older than its own version refuses to start. The upgrade is
	// one-way; operators should back up before passing this flag.
	AllowStorageUpgrade bool

	// NodeCacheMaxEntries is the maximum number of nodes held in the in-process
	// hot node cache (used by GetNode). When exceeded, the cache is cleared.
	// Set to 0 to use the default.
	NodeCacheMaxEntries int
	// NodeCacheMaxBytes bounds the estimated retained bytes across full and
	// query node images, including vectors. Zero selects the 256 MiB default.
	NodeCacheMaxBytes int64

	// NodeBodyCacheMaxBytes bounds decoded MVCC node bodies by retained bytes.
	// Entries larger than the budget are not cached. Set to 0 for the default.
	NodeBodyCacheMaxBytes int64

	// EdgeTypeCacheMaxTypes is the maximum number of distinct edge types cached
	// for GetEdgesByType. When exceeded, the cache is cleared.
	// Set to 0 to use the default.
	EdgeTypeCacheMaxTypes int

	// LabelFirstNodeCacheMaxEntries is the maximum number of labels cached for
	// fast label-first lookups. When exceeded, the cache is cleared.
	// Set to 0 to use the default.
	LabelFirstNodeCacheMaxEntries int

	// EngineOptions holds engine-wide MVCC retention defaults and similar policies.
	EngineOptions EngineOptions
}

BadgerOptions configures the BadgerDB engine.

type BadgerTransaction

type BadgerTransaction struct {

	// Transaction identity
	ID        string
	StartTime time.Time
	Status    TransactionStatus

	// CommitVersion is assigned once for a successful commit that mutates storage.
	CommitVersion MVCCVersion

	// Transaction metadata (for logging/debugging)
	Metadata map[string]interface{}
	// contains filtered or unexported fields
}

BadgerTransaction wraps Badger's native transaction with constraint validation.

Provides ACID guarantees:

  • Atomicity: All operations commit together or none do
  • Consistency: Constraints are validated before commit
  • Isolation: Changes invisible until commit
  • Durability: Badger's WAL ensures persistence

func BeginEntityTransaction

func BeginEntityTransaction(ctx context.Context, engine Engine, mode EntityCommitMode) (*BadgerTransaction, error)

BeginEntityTransaction obtains one native frame through the actual wrapper chain and binds its durability mode before exposing it to a caller.

func (*BadgerTransaction) AcknowledgedBuffered

func (tx *BadgerTransaction) AcknowledgedBuffered() bool

AcknowledgedBuffered reports whether the commit was acknowledged through the write-behind buffer rather than made durable. The executor's implicit path reads it after Commit to decide whether durable receipt metadata applies; the WAL begin/commit markers still run, only the receipt is suppressed on the eventual-consistency ACK.

func (*BadgerTransaction) AdmitWrite

func (tx *BadgerTransaction) AdmitWrite() error

AdmitWrite asks the transaction's write admission (SetWriteAdmission) for a write the transaction is about to make that is no data or schema write of its own: a change applied when it commits.

func (*BadgerTransaction) AdvanceImplicitSnapshot

func (tx *BadgerTransaction) AdvanceImplicitSnapshot() error

AdvanceImplicitSnapshot advances an unwritten implicit statement after an independently committed child batch. For example, CALL IN TRANSACTIONS uses it before its next outer clause reads the child's committed nodes. Explicit transactions and transactions holding mutations retain their pinned snapshot.

func (*BadgerTransaction) AllEdges

func (tx *BadgerTransaction) AllEdges(ctx context.Context) ([]*Edge, error)

AllEdges returns all visible edges including pending transaction writes. Admission follows IncidentEdges: the caller's context ends a wait for the transaction's lock, and a closed transaction reports ErrTransactionClosed first.

func (*BadgerTransaction) AllNodes added in v1.0.42

func (tx *BadgerTransaction) AllNodes(ctx context.Context) ([]*Node, error)

AllNodes returns all visible nodes including pending transaction writes. Admission follows IncidentEdges: the caller's context ends a wait for the transaction's lock, and a closed transaction reports ErrTransactionClosed first.

func (*BadgerTransaction) BulkCreateEdges added in v1.1.0

func (tx *BadgerTransaction) BulkCreateEdges(ctx context.Context, edges []*Edge) error

BulkCreateEdges buffers many edges in one pass, amortizing the lock, the lifecycle check, and — most importantly — the committed-node reads that check each endpoint and supply its labels. A batch of N edges that share K distinct endpoint nodes (K ≪ 2N in practice for graph fan-in/fan-out) reads K nodes instead of up to 2N.

Every edge is checked as CreateEdge checks one (validateNewEdgeLocked) before any is buffered, so a rejected edge leaves the batch unwritten instead of the edges before it buffered, and each edge is then buffered as CreateEdge buffers one (bufferNewEdgeLocked).

func (*BadgerTransaction) BulkCreateMintedEdges

func (tx *BadgerTransaction) BulkCreateMintedEdges(ctx context.Context, edges []*Edge) error

BulkCreateMintedEdges is BulkCreateEdges for relationships whose IDs the caller minted for this create (CreateMintedEdge).

func (*BadgerTransaction) ChangeBounds

func (tx *BadgerTransaction) ChangeBounds(namespace string) (earliest, last uint64, err error)

ChangeBounds is BadgerEngine.ChangeBounds at the transaction's snapshot: the last change it reports is the last one the transaction can see.

func (*BadgerTransaction) ChangeEvents

func (tx *BadgerTransaction) ChangeEvents(namespace string, commitSeq uint64, seq uint32, limit int) ([]ChangeEvent, error)

ChangeEvents is BadgerEngine.ChangeEvents at the transaction's snapshot: only changes committed before it began (or before its snapshot last moved, for an implicit transaction that continues after independent commits), so each listed change is visible to the transaction's reads. Change events are written in the same Badger commit as the data they describe, and a capturing database never commits through the write-behind buffer, so the physical snapshot alone bounds them. The transaction's own writes are not change events until it commits.

func (*BadgerTransaction) Commit

func (tx *BadgerTransaction) Commit() error

Commit is the context-free commit: it has no caller to cancel it, so its own lifetime (context.Background) is the boundary commit-time validation reads run on. CommitContext carries the caller's context instead.

func (*BadgerTransaction) CommitContext

func (tx *BadgerTransaction) CommitContext(ctx context.Context) error

Commit applies all changes atomically with full constraint validation. Explicit transactions get strict ACID durability with immediate fsync. CommitContext is Commit, cancellable by ctx while the transaction is validated: if ctx is cancelled (TERMINATE TRANSACTIONS, a disconnected client) before the writes are applied, the commit fails with ctx's error and nothing is stored. Once the writes are being applied the commit runs to completion, so a commit is never partially applied.

func (*BadgerTransaction) CreateEdge

func (tx *BadgerTransaction) CreateEdge(ctx context.Context, edge *Edge) error

CreateEdge adds an edge to the transaction.

func (*BadgerTransaction) CreateMintedEdge

func (tx *BadgerTransaction) CreateMintedEdge(ctx context.Context, edge *Edge) error

CreateMintedEdge is CreateEdge for a relationship whose ID the caller minted for this create, as CreateMintedNode is for a node.

func (*BadgerTransaction) CreateMintedNode

func (tx *BadgerTransaction) CreateMintedNode(ctx context.Context, node *Node) (NodeID, error)

CreateMintedNode is CreateNode for a node whose ID the caller minted for this create from a random UUID, as Cypher CREATE and MERGE do. No stored entity, visible or hidden, can hold such an ID, so storage is not read for one. A stable or imported ID, UUID-shaped or not, takes CreateNode.

func (*BadgerTransaction) CreateNode

func (tx *BadgerTransaction) CreateNode(ctx context.Context, node *Node) (NodeID, error)

CreateNode adds a node to the transaction with constraint validation. REQUIRES: node.ID must be prefixed with namespace (e.g., "nornic:node-123"). This enforces that all nodes are namespaced at the storage layer.

func (*BadgerTransaction) CurrentNodeIndexMatchesSnapshot

func (tx *BadgerTransaction) CurrentNodeIndexMatchesSnapshot(ctx context.Context) (bool, error)

CurrentNodeIndexMatchesSnapshot reports whether current node postings still describe this transaction's read view. Callers must check again after an index read: a peer may commit while the posting is being acquired. The write-behind read-committed view follows current state, like derived counts.

func (*BadgerTransaction) DeleteEdge

func (tx *BadgerTransaction) DeleteEdge(ctx context.Context, edgeID EdgeID) error

DeleteEdge deletes an edge from the transaction.

func (*BadgerTransaction) DeleteGraphNode

func (tx *BadgerTransaction) DeleteGraphNode(ctx context.Context, nodeID NodeID, mode NodeDeletionMode) error

DeleteGraphNode stages node deletion using the selected relationship policy. CascadeEdges removes all incident relationships. RejectConnected defers the connectivity check until commit so later clauses may remove relationships. Until then the node is absent from scans but remains a relationship endpoint. Invalid modes return ErrInvalidData without changing the transaction.

Examples:

tx.DeleteGraphNode(ctx, id, CascadeEdges) // DETACH DELETE
tx.DeleteGraphNode(ctx, id, RejectConnected) // DELETE

func (*BadgerTransaction) EdgeCreateWasNoOp

func (tx *BadgerTransaction) EdgeCreateWasNoOp(id EdgeID) bool

EdgeCreateWasNoOp reports whether CreateEdge found a stored hidden predecessor and staged only a possible no-op candidate. Callers use this disposition to avoid premature CREATE stats; same-transaction writes may still complete the candidate image. The candidate never enters a visible read overlay, and commit is the sole identity decision.

func (*BadgerTransaction) GetEdge

func (tx *BadgerTransaction) GetEdge(ctx context.Context, edgeID EdgeID) (*Edge, error)

GetEdge retrieves an edge with read-your-writes semantics.

Like GetNode, reads pin the transaction to the edge's namespace so the readTS is bound to the namespace's actual sequence rather than the pre-pin sequence-0 placeholder.

func (*BadgerTransaction) GetEdgeBetween

func (tx *BadgerTransaction) GetEdgeBetween(ctx context.Context, startID, endID NodeID, edgeType string) (*Edge, error)

GetEdgeBetween returns a matching edge including pending transaction writes.

func (*BadgerTransaction) GetEdgesByType

func (tx *BadgerTransaction) GetEdgesByType(ctx context.Context, edgeType string) ([]*Edge, error)

GetEdgesByType returns edges of a given type including pending transaction writes. Admission follows IncidentEdges: the caller's context ends a wait for the transaction's lock, and a closed transaction reports ErrTransactionClosed first.

func (*BadgerTransaction) GetFirstNodeByLabel added in v1.0.42

func (tx *BadgerTransaction) GetFirstNodeByLabel(ctx context.Context, label string) (*Node, error)

GetFirstNodeByLabel returns the first visible node with the given label.

func (*BadgerTransaction) GetMetadata

func (tx *BadgerTransaction) GetMetadata() map[string]interface{}

GetMetadata returns transaction metadata copy.

func (*BadgerTransaction) GetNode

func (tx *BadgerTransaction) GetNode(ctx context.Context, nodeID NodeID) (*Node, error)

GetNode retrieves a node (read-your-writes).

Reads pin the transaction to the node's namespace if it isn't already pinned. Without this, a transaction's pre-pin readTS sits at sequence 0 and visibility checks against a head whose FloorVersion is non-zero reject every committed value as "not yet visible" — which manifests as lost updates under the Read-Modify-Write retry loop in DB.Update.

func (*BadgerTransaction) GetNodeProjected

func (tx *BadgerTransaction) GetNodeProjected(ctx context.Context, nodeID NodeID, properties []string) (*Node, error)

GetNodeProjected implements ProjectedNodeReader inside the transaction: it decodes only the requested user properties (none when properties is an empty non-nil slice) while preserving ID, labels, timestamps and embedding metadata, and without hydrating stored embedding vectors. A nil properties slice means "full node". Visibility is the transaction's own: pending writes, deletes, connected deletes and the MVCC snapshot all apply exactly as in GetNode.

func (*BadgerTransaction) GetNodesByLabel added in v1.0.42

func (tx *BadgerTransaction) GetNodesByLabel(ctx context.Context, label string) ([]*Node, error)

GetNodesByLabel returns nodes with the given label including pending transaction writes. Admission follows IncidentEdges: the caller's context ends a wait for the transaction's lock, and a closed transaction reports ErrTransactionClosed first.

func (*BadgerTransaction) GetQueryNode

func (tx *BadgerTransaction) GetQueryNode(ctx context.Context, nodeID NodeID) (*Node, error)

GetQueryNode implements QueryNodeReader inside the transaction: GetNode's visibility (pending writes, deletes, connected deletes, the MVCC snapshot) and the node's settled embedding metadata, the worker sidecar's included, without reading separately stored chunk vectors. Vectors already in memory (pending nodes, snapshot caches, the body) may be present and are caller-owned; a caller that needs the vectors reads with GetNode. Query execution reads nodes this way: rows never carry vectors, and an update reconciles embeddings against the stored node (reconcileManagedEmbeddingsLocked), not the caller's copy.

func (*BadgerTransaction) GetStoredEdge

func (tx *BadgerTransaction) GetStoredEdge(ctx context.Context, id EdgeID) (*Edge, error)

GetStoredEdge is GetStoredNode for a relationship.

func (*BadgerTransaction) GetStoredNode

func (tx *BadgerTransaction) GetStoredNode(ctx context.Context, id NodeID) (*Node, error)

GetStoredNode reads a node through the transaction's snapshot and pending writes, without applying suppression or decay to its committed body.

func (*BadgerTransaction) GetStoredNodesByLabel

func (tx *BadgerTransaction) GetStoredNodesByLabel(ctx context.Context, label string) ([]*Node, error)

GetStoredNodesByLabel collects the transaction's unfiltered label stream.

func (*BadgerTransaction) HasKnowledgePolicyChanges

func (tx *BadgerTransaction) HasKnowledgePolicyChanges() bool

HasKnowledgePolicyChanges reports native schema mutations pending commit. Callers can combine it with OperationCount when deciding whether an otherwise entity-empty transaction can be discarded without committing.

func (*BadgerTransaction) HasPendingEdgeMutations

func (tx *BadgerTransaction) HasPendingEdgeMutations() bool

HasPendingEdgeMutations reports whether the transaction has staged any edge creates, updates, or deletes. Typed-count fast paths use it to decide whether the underlying per-type counters still describe the transaction-visible state (issue #638).

func (*BadgerTransaction) HasPendingNodeMutations added in v1.0.42

func (tx *BadgerTransaction) HasPendingNodeMutations() bool

func (*BadgerTransaction) IncidentEdges

func (tx *BadgerTransaction) IncidentEdges(ctx context.Context, nodeID NodeID) ([]*Edge, error)

IncidentEdges lists every relationship that connects nodeID as the transaction sees storage, those the visibility layer hides included (IncidentEdgeLister): the relationships a DETACH DELETE of the node removes, and the ones that keep a non-DETACH DELETE from removing it.

It is a bulk read, so ctx is the caller's: it admits the transaction's read lock and the enumeration polls it, so a canceled or expired request returns its own error and no partial relationship list, and the enumeration stops instead of materializing the rest.

Admission is cancellable as the transaction's other context-carrying admission is: a request canceled or expired while it waits for another holder returns its own error instead of waiting for that holder to finish. The holder is never preempted, and a canceled waiter leaves no hold behind. The transaction's own state keeps its precedence: a released client reports ErrTransactionClosed even for a canceled request, and once the read is admitted the locked lifecycle guard runs before anything is read. This is the same ownership order PublishCommit uses at tx.mu.

func (*BadgerTransaction) IsActive

func (tx *BadgerTransaction) IsActive() bool

IsActive returns true if the transaction is still active.

func (*BadgerTransaction) IsCommitted

func (tx *BadgerTransaction) IsCommitted() bool

IsCommitted reports whether the transaction committed: a composite statement's participant tells its coordinator so once its commit failed or panicked, after its storage commit or before it.

func (*BadgerTransaction) LockEdgeForWrite

func (tx *BadgerTransaction) LockEdgeForWrite(ctx context.Context, id EdgeID) (*Edge, error)

LockEdgeForWrite takes relationship id's write lock for the transaction (EntityWriteLocker), as LockNodeForWrite does for a node.

func (*BadgerTransaction) LockNodeForWrite

func (tx *BadgerTransaction) LockNodeForWrite(ctx context.Context, id NodeID) (*Node, error)

LockNodeForWrite takes node id's write lock for the transaction (EntityWriteLocker). A node the transaction created, already wrote or deleted needs none.

func (*BadgerTransaction) LookupEdgesByPropertyEquality

func (tx *BadgerTransaction) LookupEdgesByPropertyEquality(ctx context.Context, relationshipType string, properties []string, values []interface{}) ([]*Edge, bool, error)

LookupEdgesByPropertyEquality answers a relationship-property equality lookup inside the transaction: the index's committed postings merged with the transaction's own pending relationship writes and minus its deletions, so a match sees the same relationships this transaction's GetEdgesByType returns. handled is false when the committed index cannot answer the lookup, and the caller keeps its complete scan.

func (*BadgerTransaction) LookupNodesByEquality

func (tx *BadgerTransaction) LookupNodesByEquality(ctx context.Context, label string, properties map[string]interface{}) ([]*Node, bool, error)

LookupNodesByEquality reuses the pinned label reader and the existing equality-key index. Only matching candidates escape as copies. Transaction writes shadow committed IDs and join through the live pending-node index.

func (*BadgerTransaction) MatchEdgesBetween

func (tx *BadgerTransaction) MatchEdgesBetween(ctx context.Context, startID, endID NodeID, edgeType string, properties []string, match func(*Edge) bool, policy EdgeMatchReadPolicy) ([]*Edge, error)

MatchEdgesBetween matches the engine's edges as this transaction sees them: its deleted edges are gone, and its created or updated ones replace the stored versions, as in a between adjacent-edge request.

func (*BadgerTransaction) MergePendingCompositeMatches

func (tx *BadgerTransaction) MergePendingCompositeMatches(ctx context.Context, ids []NodeID, label string, properties []string, values []interface{}) ([]NodeID, error)

MergePendingCompositeMatches is MergePendingPropertyMatches for a composite index: committed IDs the transaction rewrote or deleted are dropped, and pending nodes that carry label and match the leading values of the index's properties (full or prefix) are added (pendingCompositeMatchesLocked). values are raw pattern values; they are canonicalized the same way IndexNode/LookupFull canonicalize, so a pending node equals a committed entry exactly when it keys identically.

func (*BadgerTransaction) MergePendingPropertyMatches

func (tx *BadgerTransaction) MergePendingPropertyMatches(ctx context.Context, ids []NodeID, label, property string, value interface{}) ([]NodeID, error)

MergePendingPropertyMatches turns ids, a property-index lookup of label's property = value against committed state, into what this transaction sees: the IDs of nodes the transaction has rewritten or deleted are dropped, and the transaction's own pending nodes that have label and the value are added. ids is filtered in place. A transaction without node writes returns ids unchanged.

func (*BadgerTransaction) Namespace added in v1.1.1

func (tx *BadgerTransaction) Namespace() string

Namespace returns the database namespace this transaction is pinned to, or "" if no namespaced write has been recorded yet. Once set, every subsequent write must share this namespace.

func (*BadgerTransaction) OperationCount

func (tx *BadgerTransaction) OperationCount() int

OperationCount returns the number of buffered operations.

func (*BadgerTransaction) PendingChanges

func (tx *BadgerTransaction) PendingChanges(includeEntities bool) TransactionChanges

PendingChanges returns a private copy for commit admission and accounting. With includeEntities=false it returns only the allocation-free admission summary; request entities only when enforcing capacity or tracking bytes. For example, a database quota wrapper can compare these final entities with committed storage before calling CommitContext. Callers must exclusively own the transaction until that commit completes.

func (*BadgerTransaction) PendingCompositeMatchCount

func (tx *BadgerTransaction) PendingCompositeMatchCount(ctx context.Context, label string, properties []string, values []interface{}) (int, error)

PendingCompositeMatchCount is PendingPropertyMatchCount for a composite index read: at most how many pending nodes MergePendingCompositeMatches adds for values (the leading properties' values), from the same pending read (pendingCompositeMatchesLocked) without listing them. Once the transaction indexes its pending nodes it reads one value bucket per property, not the pending nodes.

func (*BadgerTransaction) PendingCountStoreDelta

func (tx *BadgerTransaction) PendingCountStoreDelta(ctx context.Context, request CountStoreReadRequest) (CountStoreRead, bool, error)

PendingCountStoreDelta returns the transaction's staged contribution and visibility for one count request under its staging lock. Positional counts with staged writes retain the existing row-scan contract.

func (*BadgerTransaction) PendingEdgeTypeCountDelta

func (tx *BadgerTransaction) PendingEdgeTypeCountDelta(namespace, edgeType string) (delta int64, ok bool)

PendingEdgeTypeCountDelta returns what the transaction's staged writes add to the count of relationships of edgeType in namespace.

func (*BadgerTransaction) PendingNodeLabelCountDelta

func (tx *BadgerTransaction) PendingNodeLabelCountDelta(namespace, label string) (delta int64, ok bool)

PendingNodeLabelCountDelta returns what the transaction's staged writes add to the count of nodes with label in namespace.

func (*BadgerTransaction) PendingPropertyMatchCount

func (tx *BadgerTransaction) PendingPropertyMatchCount(ctx context.Context, label, property string, value interface{}) (int, error)

PendingPropertyMatchCount is how many of this transaction's pending nodes have label and property = value: the nodes MergePendingPropertyMatches adds to a committed lookup, counted from the same pending index without copying them. A planner adds it to the committed posting's length for an upper bound of what the transaction's lookup returns.

func (*BadgerTransaction) PrepareEntityCommit

func (tx *BadgerTransaction) PrepareEntityCommit(ctx context.Context, request EntityCommitRequest) (*PreparedEntityCommit, error)

PrepareEntityCommit observes the logical receipt once, stages new entity work, and runs the native commit pipeline up to its prephysical boundary. A staging error leaves cleanup with the caller. Schema transactions use ordinary Commit. ctx retains the caller lifetime until publication acceptance.

func (*BadgerTransaction) PrepareMergeKey

func (tx *BadgerTransaction) PrepareMergeKey(ctx context.Context, label, property string, value interface{}) error

PrepareMergeKey readies the transaction for a MERGE that looks up the node whose key under label's UNIQUE constraint on property is value, so that concurrent MERGEs of one key behave as in Neo4j: one creates the node and the others match it, without an error or a retry (#961).

It applies to every MERGE of the transaction, before or after it has read or written, and to any number of keys (a MERGE per UNWIND row):

  • when the key's node was committed after the transaction's snapshot, the MERGE can't see it, so it must not create the key again (catchUpToNode): a transaction that hasn't read through its snapshot or written anything moves the snapshot forward to now, so the MERGE sees the node and everything committed with it, and matches; any other fails with ErrConflict, a transient error, and its retry matches the node;
  • when the key has no node, the transaction locks the key until it ends, so a concurrent MERGE of the key waits for it to finish; a node committed while this one waited is handled as above.

A wait ends with ErrDeadlock, also transient, when it would close a cycle of transactions waiting for each other, with ctx's error, or, after the server's transaction timeout (EngineOptions.LockWait), with ErrLockWaitTimeout.

func (*BadgerTransaction) PrepareMergeNode

func (tx *BadgerTransaction) PrepareMergeNode(ctx context.Context, labels []string, props map[string]interface{}) error

PrepareMergeNode admits every complete UNIQUE / NODE KEY tuple in a MERGE node's property map before its snapshot lookup. It uses commit's canonical key projection and registry, retaining acquired keys until transaction end. A peer committed after an unobserved snapshot is caught up; a snapshot that has already been read or written returns retryable ErrConflict instead. A wait for a key another transaction holds ends as PrepareMergeKey says: with ErrDeadlock, ctx's error, or ErrLockWaitTimeout at the server's transaction timeout; a wait past the slow-query threshold is logged.

func (*BadgerTransaction) PrepareMergeNodeForWrite

func (tx *BadgerTransaction) PrepareMergeNodeForWrite(ctx context.Context, labels []string, props map[string]interface{}) error

PrepareMergeNodeForWrite admits a MERGE node like PrepareMergeNode, for a statement that writes the node the MERGE matches (ON MATCH SET, or a later SET, REMOVE or DELETE of it). It takes each key's lock even when the key's node exists, so concurrent MERGE writers of one node serialize as in Neo4j: each waits for the one before it to end, then catches up to its commit and writes on top of it, instead of failing at commit because both wrote the node from the same snapshot (NOR-117). A commit of the node still in the write-behind buffer is landed first (settleBufferedNode).

func (*BadgerTransaction) PublishCommit

func (tx *BadgerTransaction) PublishCommit(ctx context.Context, request CommitPublication) (commitErr error)

PublishCommit commits atomically, then invokes AfterPublication once on success after publication locks are released and before synchronous listeners. Failed commits never invoke it. Buffered commits use their acknowledged publication boundary. The callback must not panic.

func (*BadgerTransaction) ReadEdges

func (tx *BadgerTransaction) ReadEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadEdges answers one adjacent-edge request from the transaction's view: its snapshot (or write-behind, read-committed) view of the committed adjacency overlaid with its own pending writes and excluding its pending deletes. A write-locked node reads current adjacency and transfers that authority to the returned relationships and endpoints for subsequent by-ID reads.

The request's direction selects the adjacency, its type set filters the relationships before they are hydrated, and Headers asks for ID, type and endpoints without the relationship records.

Admission follows IncidentEdges: the caller's context ends a wait for the transaction's lock, and a closed transaction reports ErrTransactionClosed first.

func (*BadgerTransaction) ReadStoredAdjacentEdges

func (tx *BadgerTransaction) ReadStoredAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadStoredAdjacentEdges answers one adjacent-edge request over the transaction's physically stored incidence: hidden bodies included, the request's direction, endpoints and types selecting the relationships.

func (*BadgerTransaction) RelationshipEndpointVisible

func (tx *BadgerTransaction) RelationshipEndpointVisible(id NodeID) (visible, answered bool)

RelationshipEndpointVisible implements RelationshipEndpointChecker with the same answer GetNode gives inside this transaction. While the visibility layer can hide an image (knowledge-policy decay or an entity suppressed on demand, with no reveal scope open) the check declines, so GetNode keeps the answer: its completion applies that filter to every image it can return, overlay images included. Otherwise the transaction's own delete or write decides first. A committed node is decided from its MVCC head alone when the snapshot is at or after the head's version: visible unless the head is a tombstone. An older snapshot, a node without a head and a read error also leave the answer to GetNode.

func (*BadgerTransaction) ReleaseMergeKeys

func (tx *BadgerTransaction) ReleaseMergeKeys()

ReleaseMergeKeys releases the MERGE key locks the transaction holds (PrepareMergeKey). A transaction a statement failed in can no longer commit, so its keys protect nothing, and other MERGEs of them must not wait until the client rolls it back.

func (*BadgerTransaction) RequiresCommitValidation

func (tx *BadgerTransaction) RequiresCommitValidation() bool

RequiresCommitValidation reports whether a transaction with no physical operations still has a staged decision that only the commit owner can make. Hidden-edge CREATE candidates are deliberately operation-free until their final image is compared, so implicit transactions must not discard them as empty before validateSnapshotIsolationConflicts runs.

func (*BadgerTransaction) ResumeAfterIndependentCommit

func (tx *BadgerTransaction) ResumeAfterIndependentCommit(ctx context.Context) error

ResumeAfterIndependentCommit advances an implicit caller's read view while retaining its entire pending write set and rollback ownership. Explicit transactions never enter this path. Before advancing, old pending mutations are checked against their old snapshot so a batch cannot mask a conflict.

func (*BadgerTransaction) Rollback

func (tx *BadgerTransaction) Rollback() error

Rollback discards all changes.

func (*BadgerTransaction) Schema

func (tx *BadgerTransaction) Schema(purpose SchemaPurpose) (*SchemaManager, error)

Schema returns the transaction's isolated schema for purpose. Ordinary DDL admits its writer before creating the view and cannot mix with entity writes. Knowledge-policy reads claim no writer; persisting a policy change admits it. For example, view, err := tx.Schema(KnowledgePolicyChanges) obtains a view for view.CreatePromotionPolicy; rollback discards its persisted changes. DDL uses tx.Schema(OrdinarySchemaChanges), then StageSchemaChanges and Commit.

func (*BadgerTransaction) ScopeCountStoreRead

func (tx *BadgerTransaction) ScopeCountStoreRead(ctx context.Context, request CountStoreReadRequest) (CountStoreReadRequest, bool, error)

ScopeCountStoreRead issues one count-store read at the transaction's own snapshot, for callers that read through a reader chain rather than through the transaction directly.

described is false when the transaction cannot prove that a counter read at its snapshot describes the rows it reads: a request for another namespace, a write-behind transaction (whose reads are read-committed), a transaction without a pinned snapshot of its own read version, or a read whose answer needs the positional (label, type) counters while the transaction's cut holds an unpublished version. The caller then answers from the rows it reads.

The read is declined for the same reason a closed transaction's rows read is refused: a transaction that ended, handed its native client handle to an accepted commit, or whose snapshot reader expired reads no counter at its snapshot. Issuance takes the transaction's exclusive lock, because that lifecycle owner closes an expired transaction where it decides.

The returned request carries the capability; the caller's request is not modified. What the transaction's own staged writes contribute is composed by the native kernel at consumption, under the transaction's lock, so a write the caller's reader stages after planning is part of the answer.

func (*BadgerTransaction) SetImplicit added in v1.1.0

func (tx *BadgerTransaction) SetImplicit(implicit bool) error

SetImplicit marks this transaction as implicit (auto-opened by the executor for a single Cypher statement, no user BEGIN). Implicit transactions skip the per-Commit engine.Sync() because the Bolt session end and the async flush loop coalesce durability for them.

func (*BadgerTransaction) SetMetadata

func (tx *BadgerTransaction) SetMetadata(metadata map[string]interface{}) error

SetMetadata sets transaction metadata (same as Transaction).

func (*BadgerTransaction) SetNamespace added in v1.1.1

func (tx *BadgerTransaction) SetNamespace(ns string) error

SetNamespace eagerly pins the transaction to ns. Callers that already know the target namespace at BeginTransaction time (the cypher executor's transactionStorageWrapper, for example) use this to fail fast on misrouted writes instead of waiting for the first prefixed mutation. Returns an error if the transaction is already pinned to a different namespace.

SetNamespace deliberately does not call ensureOperationAllowedLocked before the namespace bind: lifecycle expiration is meaningless for a transaction that has not yet registered against any namespace. We only require Status==active.

func (*BadgerTransaction) SetValidationSetting

func (tx *BadgerTransaction) SetValidationSetting(setting TransactionValidationSetting, enabled bool) error

SetValidationSetting changes one policy without resetting the other. For example, tx.SetValidationSetting(DeferredConstraintValidation, true) defers constraints; tx.SetValidationSetting(SkipCreateCommitHeadReload, true) selects the minted-create optimization. Closed transactions reject either request.

func (*BadgerTransaction) SetWriteAdmission

func (tx *BadgerTransaction) SetWriteAdmission(admit func() error)

SetWriteAdmission makes admit the transaction's write admission: the decision, taken before the transaction's first write, whether it may write at all. Every data write and the first schema change ask it (AdmitWrite); once it admits, later writes don't ask again, and while it refuses, the write fails with its error and changes nothing. A knowledge-policy change asks it when it is persisted to the transaction. A composite statement's transaction on one of its databases admits a write only when that database can be the statement's one write database.

Admission is attached to the existing data/schema mutation boundary. A query matching no rows never reaches that boundary and claims no writer.

The callback runs with the transaction's lock held, before anything the write stages is changed, and exactly once: it must not call back into this transaction or storage.

func (*BadgerTransaction) StageSchemaChanges

func (tx *BadgerTransaction) StageSchemaChanges() error

StageSchemaChanges captures ordinary DDL and its runtime backfills for commit. Obtain the isolated view with Schema(OrdinarySchemaChanges), apply and backfill the schema change, then call StageSchemaChanges before Commit. Rollback discards the captured state; unchanged committed indexes keep their live caches.

func (*BadgerTransaction) StagedMemoryBytes

func (tx *BadgerTransaction) StagedMemoryBytes() int64

StagedMemoryBytes estimates storage-owned data retained by an open transaction. It counts the serialized write copies and pending entity copies once each. Historical operation bodies are distinct from the pending map's current version and remain owned until the transaction ends. The value is sampled at statement boundaries while the transaction session owns the transaction.

func (*BadgerTransaction) StoredEdgeImage

func (tx *BadgerTransaction) StoredEdgeImage(edge *Edge) (*Edge, error)

StoredEdgeImage is StoredNodeImage for a relationship.

func (*BadgerTransaction) StoredNodeImage

func (tx *BadgerTransaction) StoredNodeImage(node *Node) (*Node, error)

StoredNodeImage returns the image the storage codec gives node, a body the transaction has staged: the body a stored read returns once it commits. Every acknowledged body already is such an image (writtenNodeImage), so commit admission images only what it stages. The caller owns the transaction until admission and commit finish.

func (*BadgerTransaction) StreamEdgesByType

func (tx *BadgerTransaction) StreamEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamEdgesByType visits the relationships of edgeType visible to the transaction one at a time (EdgeTypeStreamer): the committed edges of its snapshot overlaid with its own pending edge writes and deletes, exactly as GetEdgesByType merges them, without collecting the type into a slice. Committed reads are scoped to the transaction's database. Visited edges are copies, so the callback may keep them. Admission follows IncidentEdges: the caller's context ends a wait for the transaction's lock, and a closed transaction reports ErrTransactionClosed first. It also ends the retake after each visitor callback, so a canceled stream stops when its visitor returns rather than waiting for that lock, and a transaction the client closed or detached while the visitor ran is reported the same way, before that retake waits.

func (*BadgerTransaction) StreamNodesByLabelProjected

func (tx *BadgerTransaction) StreamNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error

StreamNodesByLabelProjected visits label matches from the transaction's pinned snapshot and overlays pending writes as one stream. The callback can stop iteration without forcing the transaction to resolve or copy the rest of the label population. Admission follows IncidentEdges: the caller's context ends a wait for the transaction's lock, and a closed transaction reports ErrTransactionClosed first. It also ends the retake after each visitor callback, so a canceled stream stops when its visitor returns rather than waiting for that lock, and a transaction the client closed or detached while the visitor ran is reported the same way, before that retake waits.

func (*BadgerTransaction) StreamNodesWithOptions

func (tx *BadgerTransaction) StreamNodesWithOptions(ctx context.Context, opts StreamNodesOptions, visit func(*Node) error) error

StreamNodesWithOptions streams the transaction's view of every node (its snapshot overlaid with its own pending writes) with the engine scan's options: prefix, projection, PropertyFilter, embeddings and decay. Committed nodes are streamed from the pinned snapshot and never materialised as a population: AllNodes did, so a property match without a label inside a transaction, which includes every write statement, decoded every node in full (#824). A transaction built without a pinned snapshot reads the committed view its other reads take (getAllCommittedNodesLocked). Pending writes replace their committed versions and are not filtered (callers test every node they receive); ErrIterationStopped from visit ends the stream. Admission follows IncidentEdges: the caller's context ends a wait for the transaction's lock, and a closed transaction reports ErrTransactionClosed first. It also ends the retake after each visitor callback, so a canceled stream stops when its visitor returns rather than waiting for that lock, and a transaction the client closed or detached while the visitor ran is reported the same way, before that retake waits.

func (*BadgerTransaction) StreamStoredEdgesByType

func (tx *BadgerTransaction) StreamStoredEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamStoredEdgesByType preserves the transaction's type stream and overlay while including suppressed and decayed committed relationships.

func (*BadgerTransaction) StreamStoredNodesByLabelProjected

func (tx *BadgerTransaction) StreamStoredNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error

StreamStoredNodesByLabelProjected preserves label-index and transaction overlay reads while including suppressed and decayed committed nodes.

func (*BadgerTransaction) UpdateEdge

func (tx *BadgerTransaction) UpdateEdge(ctx context.Context, updateRequest EdgeUpdateRequest) error

UpdateEdge updates an existing edge within the transaction.

This is required so Cypher can do CREATE ... SET r.prop = ... in a single query while using implicit/explicit transactions (writes must remain isolated until commit).

Error contract:

  • ErrNotFound: the edge does not exist at this transaction's snapshot and is not live at latest-committed state either (never existed, or a peer deleted it).
  • ErrConflict ("edge <id> changed after transaction start"): the edge is live at latest-committed state but was committed AFTER this transaction began, so this transaction cannot update it. This is the same retryable conflict shape checkEdgeWriteConflict produces at commit time; callers (and Bolt clients, via Neo.TransientError.Transaction.Outdated) should retry on a fresh snapshot.

func (*BadgerTransaction) UpdateGraphNode

func (tx *BadgerTransaction) UpdateGraphNode(ctx context.Context, updateRequest NodeUpdateRequest) error

UpdateGraphNode stages a node using the supplied image interpretation. ClientNodeEdits reconciles managed embeddings; StoredNodeImages installs a complete authoritative image. Policies may differ between operations in one frame.

func (*BadgerTransaction) UpsertGraphNode

func (tx *BadgerTransaction) UpsertGraphNode(ctx context.Context, node *Node, boundary func(Operation, func() error) error) error

UpsertGraphNode stages a client node image, creating an absent ID or updating its stored predecessor even when that predecessor is suppressed. Updates preserve the original creation timestamp and use ClientNodeEdits semantics. The transaction resolves the predecessor before staging, so an intervening change is subject to the normal observed-image conflict checks.

boundary, when provided, receives the resolved operation before staging and must invoke apply synchronously exactly once on success. Returning an error aborts the caller's operation; callers must roll back the transaction on failure. This hook lets existing accounting policies surround the actual write.

For example, a catalog writer can call tx.UpsertGraphNode(ctx, metadata, nil) and then prepare and publish the transaction through its normal commit owner.

type BatchNodeWithoutEmbeddingsCapability added in v1.3.3

type BatchNodeWithoutEmbeddingsCapability interface {
	BatchGetNodesWithoutEmbeddingsSupported() bool
}

BatchNodeWithoutEmbeddingsCapability lets wrappers expose whether their current inner engine can satisfy batched light node reads without falling back to one call per ID.

type BatchNodeWithoutEmbeddingsReader added in v1.3.3

type BatchNodeWithoutEmbeddingsReader interface {
	BatchGetNodesWithoutEmbeddings(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)
}

BatchNodeWithoutEmbeddingsReader is an optional extension interface for fetching several nodes without stored embedding vectors in one storage operation. Missing IDs are omitted from the returned map, matching BatchGetNodes semantics.

type BatchWriter

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

BatchWriter provides explicit batch commit control for bulk operations. Instead of syncing after each write (even in batch mode), BatchWriter buffers all writes and only syncs when Commit() is called.

This dramatically improves bulk write throughput by reducing fsync calls. Use for imports, migrations, or any operation writing many records.

Example:

batch := wal.NewBatch()
for _, node := range nodes {
    batch.AppendNode(OpCreateNode, node)
}
if err := batch.Commit(); err != nil {
    batch.Rollback() // Discard uncommitted entries
}

Performance:

  • Single fsync at end instead of per-write
  • 10-100x faster for bulk operations
  • Memory usage proportional to batch size

IMPORTANT: Sequence numbers are assigned at commit time, not append time. This ensures entries are written in sequence order, preventing replay issues when mixing batch and non-batch operations.

func (*BatchWriter) AppendDelete

func (b *BatchWriter) AppendDelete(op OperationType, id string) error

AppendDelete adds a delete operation to the batch.

func (*BatchWriter) AppendEdge

func (b *BatchWriter) AppendEdge(op OperationType, edge *Edge) error

AppendEdge adds an edge operation to the batch.

func (*BatchWriter) AppendNode

func (b *BatchWriter) AppendNode(op OperationType, node *Node) error

AppendNode adds a node operation to the batch.

func (*BatchWriter) Commit

func (b *BatchWriter) Commit() error

Commit writes all batched entries and syncs to disk. Sequence numbers are assigned here to ensure proper ordering. This is the only fsync in the batch - much faster than per-write sync.

func (*BatchWriter) CommitWithSeq

func (b *BatchWriter) CommitWithSeq() (uint64, uint64, error)

CommitWithSeq writes all batched entries, syncs to disk, and returns the sequence range assigned to the batch. If the batch is empty or WAL is disabled, returns (0, 0, nil).

func (*BatchWriter) Len

func (b *BatchWriter) Len() int

Len returns the number of pending entries.

func (*BatchWriter) Rollback

func (b *BatchWriter) Rollback()

Rollback discards all uncommitted entries.

type BeginRequest

type BeginRequest uint8

BeginRequest is the typed request a native transaction begin carries. It selects the lifecycle admission the engine takes before it captures the transaction's snapshot; it never changes the transaction's own semantics afterwards.

const (
	// OrdinaryBegin opens an ordinary transaction: an explicit BEGIN or a data
	// autocommit. Its snapshot is captured with no lifecycle admission, so the
	// transaction keeps its own snapshot and its commit-time conflict guards
	// (snapshot isolation, the schema snapshot check, unique keys).
	OrdinaryBegin BeginRequest = iota
	// AutocommitSchemaBegin opens an autocommit schema statement. The engine
	// applies the write-behind commits acknowledged before it and then holds
	// its exclusive lifecycle write barrier from before the snapshot until the
	// statement's publication or rollback, so no data commit and no peer schema
	// publication can land inside the statement's window: the population its
	// fill reads stays current to its commit. The transaction owns that lease
	// and releases it exactly once, at its terminal outcome.
	AutocommitSchemaBegin
)

type BufferedMutation

type BufferedMutation struct {
	Kind BufferedOpKind
	ID   string // node or edge ID derived by Append, or the raw delete key
	Node *Node  // payload for BufferedOpNode
	Edge *Edge  // payload for BufferedOpEdge
}

BufferedMutation is one transient committed mutation submitted to Append. Append derives ID from the payload of a node or edge request, so a caller sets the payload matching Kind and leaves ID empty; a delete request sets only ID. It is a request value, not the generation replay record: the replay log keeps its own private bufferedMutation entries.

type BufferedOpKind

type BufferedOpKind uint8

BufferedOpKind identifies one committed mutation kind: a node image, an edge image, or a raw delete key.

const (
	// BufferedOpNode admits a node image in BufferedMutation.Node.
	BufferedOpNode BufferedOpKind = iota
	// BufferedOpEdge admits an edge image in BufferedMutation.Edge.
	BufferedOpEdge
	// BufferedOpDelete admits a raw delete key in BufferedMutation.ID.
	BufferedOpDelete
)

type BytesMetricsSource

type BytesMetricsSource interface {
	EstimateSize(prefix []byte) (keys, values uint64)
	Size() (lsm, vlog int64)
}

BytesMetricsSource is what the sweeper reads from storage.

type BytesMetricsSweeper added in v1.1.0

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

BytesMetricsSweeper is the lifecycle.Component that populates the nornicdb_storage_bytes{kind} gauges every interval via the engine's EstimateSize(prefix), which Close joins or refuses.

func NewBytesMetricsSweeper added in v1.1.0

func NewBytesMetricsSweeper(metrics *observability.StorageMetrics, db BytesMetricsSource, searchSize SearchSizeFn, interval time.Duration) *BytesMetricsSweeper

NewBytesMetricsSweeper constructs the sweeper. interval ≤ 0 falls back to DefaultBytesMetricsInterval. metrics or db nil disables the sweep (Start returns nil immediately) — defensive for partial-init.

func (*BytesMetricsSweeper) Name added in v1.1.0

func (s *BytesMetricsSweeper) Name() string

Name implements lifecycle.Component.

func (*BytesMetricsSweeper) Shutdown added in v1.1.0

func (s *BytesMetricsSweeper) Shutdown(ctx context.Context) error

Shutdown implements lifecycle.Component. It is the owner's one stop: every caller joins the running loop's actual return; ctx bounds only the wait.

func (*BytesMetricsSweeper) Start added in v1.1.0

func (s *BytesMetricsSweeper) Start(ctx context.Context) error

Start implements lifecycle.Component. Blocks until ctx is cancelled or Shutdown is called. Performs an initial sweep immediately so the gauges have non-zero values by the first scrape.

type CatalogUpgradeV4

type CatalogUpgradeV4 struct {
	NodeID    NodeID
	Transform func(context.Context, string) (string, bool, error)
}

CatalogUpgradeV4 identifies the one configured catalog record transformed by the V3-to-V4 storage upgrade. NodeID is fully namespace-qualified. Transform validates and transforms only the record's data string; storage owns native decoding, atomic publication and the version marker. It must not reenter the storage engine or mutate external state. For example, a catalog owner supplies its configured metadata ID and a pure credential-representation transformer.

type ChangeCaptureEngine

type ChangeCaptureEngine interface {
	ChangeFeed
	// SetChangeCapture sets a database's capture mode.
	SetChangeCapture(namespace string, mode ChangeCaptureMode)
	// ChangeCapture returns a database's capture mode.
	ChangeCapture(namespace string) ChangeCaptureMode
	// SetChangeRetention sets how long change events are kept.
	SetChangeRetention(retention time.Duration)
}

ChangeCaptureEngine is implemented by engines that capture changes; the storage wrappers forward it.

func ChangeCaptureOf

func ChangeCaptureOf(engine Engine) (ChangeCaptureEngine, bool)

ChangeCaptureOf returns the change-capturing engine under engine's wrappers (namespace, async, WAL, tracing), if it has one.

type ChangeCaptureMode

type ChangeCaptureMode uint8

ChangeCaptureMode is a database's txLogEnrichment.

const (
	// ChangeCaptureOff captures nothing (Neo4j's default).
	ChangeCaptureOff ChangeCaptureMode = iota
	// ChangeCaptureDiff records the changed properties and labels of an update.
	ChangeCaptureDiff
	// ChangeCaptureFull records the whole state before and after.
	ChangeCaptureFull
)

func ParseChangeCaptureMode

func ParseChangeCaptureMode(value string) ChangeCaptureMode

ParseChangeCaptureMode reads a txLogEnrichment value; anything but DIFF or FULL is OFF.

func (ChangeCaptureMode) String

func (m ChangeCaptureMode) String() string

type ChangeEvent

type ChangeEvent struct {
	// CommitSeq is the transaction's place in its database's commit order
	// (Neo4j's txId); Seq the change's place in the transaction.
	CommitSeq  uint64            `msgpack:"c"`
	Seq        uint32            `msgpack:"s"`
	StartTime  int64             `msgpack:"ts"` // the transaction's start, Unix nanoseconds
	CommitTime int64             `msgpack:"tc"` // its commit, Unix nanoseconds
	Mode       ChangeCaptureMode `msgpack:"m"`
	TxMetadata map[string]any    `msgpack:"md,omitempty"`
	// Node is true for a node's change, false for a relationship's.
	Node bool `msgpack:"n"`
	// Operation is 'c', 'u' or 'd'.
	Operation byte `msgpack:"o"`
	// ID is the entity's ID without its database prefix.
	ID string `msgpack:"i"`
	// Labels are a node's labels: after the change, or before a delete.
	Labels []string `msgpack:"l,omitempty"`
	// Type, Start and End are a relationship's type and endpoints (IDs
	// without the database prefix), with the endpoints' labels.
	Type        string       `msgpack:"t,omitempty"`
	Start       string       `msgpack:"a,omitempty"`
	End         string       `msgpack:"b,omitempty"`
	StartLabels []string     `msgpack:"al,omitempty"`
	EndLabels   []string     `msgpack:"bl,omitempty"`
	Before      *ChangeState `msgpack:"bf,omitempty"`
	After       *ChangeState `msgpack:"af,omitempty"`
	// Keys are the entity's key-constraint property values, as Neo4j's
	// events carry them: a node's per label (one map per NODE KEY
	// constraint it satisfies), a relationship's as a list (RELATIONSHIP
	// KEY), and each endpoint's per label. Taken from the entity's whole
	// state (after the change, or before a delete), so a DIFF update
	// carries them too.
	Keys      map[string][]map[string]any `msgpack:"k,omitempty"`
	EdgeKeys  []map[string]any            `msgpack:"ek,omitempty"`
	StartKeys map[string][]map[string]any `msgpack:"ak,omitempty"`
	EndKeys   map[string][]map[string]any `msgpack:"bk,omitempty"`
}

ChangeEvent is one committed change of a node or relationship.

type ChangeFeed

type ChangeFeed interface {
	// ChangeEvents returns up to limit of a database's events after
	// (commitSeq, seq), in commit order; limit <= 0 is no limit.
	ChangeEvents(namespace string, commitSeq uint64, seq uint32, limit int) ([]ChangeEvent, error)
	// ChangeBounds returns the commitSeq of a database's earliest retained
	// event and of its last committed one; 0, 0 when it has none.
	ChangeBounds(namespace string) (earliest, last uint64, err error)
}

ChangeFeed reads a database's committed change events at one view of the store: the engine reads the latest committed state, a transaction its snapshot (BadgerTransaction.ChangeEvents), so that every change it lists is visible to the transaction's own reads.

type ChangeState

type ChangeState struct {
	Properties map[string]any `msgpack:"p"`
	Labels     []string       `msgpack:"l,omitempty"`
}

ChangeState is an entity's state in a change event: its properties, and a node's labels.

type CommitBuffer

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

CommitBuffer is one generation of buffered committed writes. It is append-only while active and read-only while draining.

func (*CommitBuffer) AddCommit

func (b *CommitBuffer) AddCommit(c bufferedCommit)

AddCommit appends one committed statement and folds its operations into the read overlay. The caller must hand over ownership of the payload. The overlay stores the same node/edge pointers as the replay log: nothing mutates them after the ACK (replay encodes read-only and copies before normalizing; the engine's overlay reads copy before returning), so no second copy is paid per operation.

func (*CommitBuffer) Commits

func (b *CommitBuffer) Commits() []bufferedCommit

Commits returns the generation's buffered commits in append order.

func (*CommitBuffer) IsApplied

func (b *CommitBuffer) IsApplied() bool

IsApplied reports whether this generation has been replayed into the underlying engine.

func (*CommitBuffer) Mutations

func (b *CommitBuffer) Mutations() []bufferedMutation

Mutations returns the generation's replay log in append order.

func (*CommitBuffer) Settled

func (b *CommitBuffer) Settled() <-chan struct{}

Settled is closed once the generation is applied and its notifications are delivered (or, for a drain that does not dispatch, handed to the caller that drained it): a waiter that needs the generation's listeners to have run before it continues waits on it, not on IsApplied.

type CommitFailureError

type CommitFailureError struct {
	Cause error
}

CommitFailureError identifies an infrastructure read or decoding failure encountered while validating a commit. It preserves the original cause and is distinct from ordinary retryable conflicts and constraint violations. Protocol consumers classify it through the shared errors package.

func (*CommitFailureError) Error

func (failure *CommitFailureError) Error() string

func (*CommitFailureError) Unwrap

func (failure *CommitFailureError) Unwrap() error

type CommitOutcome

type CommitOutcome struct {
	State CommitOutcomeState
	Err   error
}

CommitOutcome carries acknowledgement errors without disguising an applied write.

type CommitOutcomeState

type CommitOutcomeState uint8

CommitOutcomeState separates a physical result from caller wait cancellation.

const (
	CommitRecoveryPending CommitOutcomeState = iota
	CommitApplied
	CommitDiscarded
)

type CommitPublication

type CommitPublication struct {
	AfterPublication func()
	// contains filtered or unexported fields
}

CommitPublication specifies the single post-publication callback. The private preparation continuation belongs solely to accepted entity-commit admission.

type CommitReceipt

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

CommitReceipt owns accepted work until physical application or definite discard. Wait cancellation never discards accepted work or releases its admission lease.

func SubmitAcceptedEntityTransaction

func SubmitAcceptedEntityTransaction(ctx context.Context, engine Engine, envelope EntityTransactionEnvelope, ops []Operation, settle func(CommitOutcome)) (*CommitReceipt, error)

SubmitAcceptedEntityTransaction applies an already-decoded durable command. The existing native owner settles it without accepting another log entry. Author: NOR-288 lane (Codex), 2026-10-29; preserves the merged decoded API.

func (*CommitReceipt) Decision

func (r *CommitReceipt) Decision() (CommitOutcome, <-chan struct{})

Decision returns the outcome recorded for this receipt together with the channel that closes at its next recorded state change. Reading both under the receipt's mutex is the snapshot an observer needs, because every recording closes exactly the channel a prior snapshot returned, so an observer that re-reads after waking cannot miss a change. A recovery-pending outcome is an observation, not a decision: an observer leaves only on a terminal state. This is the signal for work the transport's own Shutdown joins, which must leave on the decision and cannot wait for the foreign settlement observer that Done covers. External callers keep waiting on Done. For example, a Raft transport waiting for an accepted command snapshots Decision on each iteration and waits on the returned channel while pending. It retains one timeout across those observations and leaves on a terminal outcome, so a settlement observer can call Shutdown without joining itself. Author: NOR-288 lane (Claude), 2026-10-30.

func (*CommitReceipt) Done

func (r *CommitReceipt) Done() <-chan struct{}

func (*CommitReceipt) OnSettled

func (r *CommitReceipt) OnSettled(settle func(CommitOutcome))

OnSettled attaches a consumer to the existing terminal owner. Pending errors do not invoke it. Callbacks complete before Done closes; callers must not wait on this receipt from their callback. This joins recovery without parking a goroutine for the lifetime of an unresolved accepted command.

func (*CommitReceipt) Outcome

func (r *CommitReceipt) Outcome() CommitOutcome

func (*CommitReceipt) Wait

func (r *CommitReceipt) Wait(ctx context.Context) error

func (*CommitReceipt) WaitOutcome

func (r *CommitReceipt) WaitOutcome(ctx context.Context) CommitOutcome

WaitOutcome is for an accepted outer owner composing this physical owner. It returns a recovery-pending error without falsely settling the receipt; ordinary callers use Wait, which only completes on a terminal outcome.

func (*CommitReceipt) WaitPhysicalOutcome

func (r *CommitReceipt) WaitPhysicalOutcome(ctx context.Context) CommitOutcome

WaitPhysicalOutcome is the state-machine boundary before listener delivery. Receipt Wait still waits for the accepted owner's full terminal completion.

type CommitReceiptOwner

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

NewCommitReceipt returns the waiter view and a terminal-owner resolver. Only the accepted command coordinator retains the resolver.

func (CommitReceiptOwner) PublishPhysical

func (owner CommitReceiptOwner) PublishPhysical(outcome CommitOutcome)

func (CommitReceiptOwner) Resolve

func (owner CommitReceiptOwner) Resolve(outcome CommitOutcome) error

resolve is called only by the accepted command owner, never by a waiter.

type CompositeEngine

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

CompositeEngine is a storage engine that spans multiple constituent databases. It implements the Engine interface by routing operations to constituents and merging results.

This enables composite databases (similar to Neo4j Fabric) where a single database view spans multiple physical databases.

func NewCompositeEngine

func NewCompositeEngine(
	constituents map[string]Engine,
	constituentNames map[string]string,
	accessModes map[string]string,
) *CompositeEngine

NewCompositeEngine creates a new composite engine that spans multiple constituent databases.

Parameters:

  • constituents: Map of alias -> storage engine for each constituent
  • constituentNames: Map of alias -> actual database name
  • accessModes: Map of alias -> access mode ("read", "write", "read_write")

func (*CompositeEngine) AllEdges

func (c *CompositeEngine) AllEdges(ctx context.Context) ([]*Edge, error)

AllEdges returns all edges from all constituents. Each readable source is selected once; equal local IDs across databases remain distinct.

func (*CompositeEngine) AllNodes

func (c *CompositeEngine) AllNodes(ctx context.Context) ([]*Node, error)

AllNodes returns all nodes from all constituents. Each readable source is selected once; equal local IDs across databases remain distinct.

func (*CompositeEngine) BatchGetNodes

func (c *CompositeEngine) BatchGetNodes(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

BatchGetNodes retrieves multiple nodes from all constituents.

func (*CompositeEngine) BulkCreateEdges

func (c *CompositeEngine) BulkCreateEdges(ctx context.Context, edges []*Edge) error

BulkCreateEdges creates edges in bulk. Routes edges to constituents containing their start nodes.

func (*CompositeEngine) BulkCreateNodes

func (c *CompositeEngine) BulkCreateNodes(ctx context.Context, nodes []*Node) error

BulkCreateNodes creates nodes in bulk. Routes nodes to appropriate constituents based on routing rules.

func (*CompositeEngine) BulkDeleteEdges

func (c *CompositeEngine) BulkDeleteEdges(ctx context.Context, ids []EdgeID) error

BulkDeleteEdges deletes edges in bulk from all constituents.

func (*CompositeEngine) BulkDeleteNodes

func (c *CompositeEngine) BulkDeleteNodes(ctx context.Context, ids []NodeID) error

BulkDeleteNodes deletes nodes in bulk from all constituents.

func (*CompositeEngine) Close

func (c *CompositeEngine) Close() error

Close closes all constituent engines.

func (*CompositeEngine) CompositeName

func (c *CompositeEngine) CompositeName() string

CompositeName is the composite database's name, or "" if not recorded.

func (*CompositeEngine) ConstituentDatabaseForEdge

func (c *CompositeEngine) ConstituentDatabaseForEdge(ctx context.Context, id EdgeID) (string, error)

ConstituentDatabaseForEdge returns the backing database name of the constituent that holds edgeID, or "" when none of the readable constituents holds it. It mirrors ConstituentDatabaseForNode for relationships (#745 §3: HTTP row/meta element ids on composite results).

func (*CompositeEngine) ConstituentDatabaseForNode

func (c *CompositeEngine) ConstituentDatabaseForNode(ctx context.Context, id NodeID) (string, error)

ConstituentDatabaseForNode returns the backing database name of the constituent that holds nodeID, or "" when none of the readable constituents holds it. It also resolves nodes created directly on a constituent (the nodeToConstituent index only records writes routed through the composite), so element-id projections on a composite coordinator can name the entity's own database (#745 §3).

func (*CompositeEngine) ConstituentStorage

func (c *CompositeEngine) ConstituentStorage(database string) (Engine, error)

ConstituentStorage resolves a native entity's database through the same selector as qualified reads, retaining the statement's participant view.

func (*CompositeEngine) ConsumeCleanShutdownMarker

func (c *CompositeEngine) ConsumeCleanShutdownMarker(ctx context.Context) (bool, error)

func (*CompositeEngine) CountPendingEmbeddingIDs

func (c *CompositeEngine) CountPendingEmbeddingIDs(ctx context.Context, accept func([]byte) bool) int

func (*CompositeEngine) CreateEdge

func (c *CompositeEngine) CreateEdge(ctx context.Context, edge *Edge) error

CreateEdge creates an edge. Routes to the constituent containing the start node. Following Neo4j TransactionState pattern: check if nodes were created in current transaction, and if so, try that constituent first. Otherwise try all constituents.

func (*CompositeEngine) CreateNode

func (c *CompositeEngine) CreateNode(ctx context.Context, node *Node) (NodeID, error)

CreateNode creates a node. Routes to the appropriate constituent based on routing rules.

func (*CompositeEngine) DeleteByPrefix

func (c *CompositeEngine) DeleteByPrefix(prefix string) (nodesDeleted int64, edgesDeleted int64, err error)

DeleteByPrefix is not supported for composite databases. Composite databases don't have their own data - they're virtual views.

func (*CompositeEngine) DeleteEdge

func (c *CompositeEngine) DeleteEdge(ctx context.Context, id EdgeID) error

DeleteEdge deletes an edge from the constituent containing it.

func (*CompositeEngine) DeleteNode

func (c *CompositeEngine) DeleteNode(ctx context.Context, id NodeID) error

DeleteNode deletes a node from the constituent that contains it.

func (*CompositeEngine) EdgeCount

func (c *CompositeEngine) EdgeCount(ctx context.Context) (int64, error)

EdgeCount returns the total edge count across all constituents.

func (*CompositeEngine) EdgeCountByEndLabel

func (c *CompositeEngine) EdgeCountByEndLabel(ctx context.Context, label, edgeType string) (int64, error)

EdgeCountByEndLabel returns the positional (label, type) count summed across all constituents' counters (issue #638).

func (*CompositeEngine) EdgeCountByStartLabel

func (c *CompositeEngine) EdgeCountByStartLabel(ctx context.Context, label, edgeType string) (int64, error)

EdgeCountByStartLabel returns the positional (label, type) count summed across all constituents' counters (issue #638).

func (*CompositeEngine) EdgeCountByType

func (c *CompositeEngine) EdgeCountByType(ctx context.Context, edgeType string) (int64, error)

EdgeCountByType returns the typed edge count summed across all constituents' per-type counters (issue #638).

func (*CompositeEngine) ForEachNodeIDByLabel

func (c *CompositeEngine) ForEachNodeIDByLabel(ctx context.Context, label string, visit func(NodeID) bool) error

func (*CompositeEngine) GetConstituentByAlias

func (c *CompositeEngine) GetConstituentByAlias(alias string) (Engine, error)

GetConstituentByAlias returns the storage engine for a specific constituent within this composite database. This is used by the Cypher executor to resolve USE composite.alias references.

func (*CompositeEngine) GetEdge

func (c *CompositeEngine) GetEdge(ctx context.Context, id EdgeID) (*Edge, error)

GetEdge retrieves an edge. Searches all constituents.

func (*CompositeEngine) GetEdgeBetween

func (c *CompositeEngine) GetEdgeBetween(ctx context.Context, startID, endID NodeID, edgeType string) (*Edge, error)

GetEdgeBetween returns an edge between two nodes from any constituent.

func (*CompositeEngine) GetEdgeCurrentHead

func (c *CompositeEngine) GetEdgeCurrentHead(ctx context.Context, id EdgeID) (MVCCHead, error)

func (*CompositeEngine) GetEdgeLatestEffective

func (c *CompositeEngine) GetEdgeLatestEffective(ctx context.Context, id EdgeID) (*Edge, error)

GetEdgeLatestEffective routes latest-effective edge reads to the first constituent that resolves the ID.

func (*CompositeEngine) GetEdgeLatestVisible

func (c *CompositeEngine) GetEdgeLatestVisible(ctx context.Context, id EdgeID) (*Edge, error)

func (*CompositeEngine) GetEdgeVisibleAt

func (c *CompositeEngine) GetEdgeVisibleAt(ctx context.Context, id EdgeID, version MVCCVersion) (*Edge, error)

func (*CompositeEngine) GetEdgesByType

func (c *CompositeEngine) GetEdgesByType(ctx context.Context, edgeType string) ([]*Edge, error)

GetEdgesByType returns edges of the given type from all constituents. Each readable source is selected once; equal local IDs across databases remain distinct.

func (*CompositeEngine) GetEdgesByTypeVisibleAt

func (c *CompositeEngine) GetEdgesByTypeVisibleAt(ctx context.Context, edgeType string, version MVCCVersion) ([]*Edge, error)

func (*CompositeEngine) GetFirstNodeByLabel

func (c *CompositeEngine) GetFirstNodeByLabel(ctx context.Context, label string) (*Node, error)

GetFirstNodeByLabel returns the first node with the given label from any constituent.

func (*CompositeEngine) GetInDegree

func (c *CompositeEngine) GetInDegree(ctx context.Context, nodeID NodeID) (int, error)

GetInDegree returns the in-degree of a node across all constituents.

func (*CompositeEngine) GetInnerEngine

func (c *CompositeEngine) GetInnerEngine() Engine

GetInnerEngine returns the composite itself: a composite spans several constituent engines, so there is no single inner engine to unwrap. Callers that unwrap for capability probes get the same engine back and fall through to its own capability methods.

func (*CompositeEngine) GetNode

func (c *CompositeEngine) GetNode(ctx context.Context, id NodeID) (*Node, error)

GetNode retrieves a node. Searches all readable constituents.

func (*CompositeEngine) GetNodeCurrentHead

func (c *CompositeEngine) GetNodeCurrentHead(ctx context.Context, id NodeID) (MVCCHead, error)

func (*CompositeEngine) GetNodeLatestEffective

func (c *CompositeEngine) GetNodeLatestEffective(ctx context.Context, id NodeID) (*Node, error)

GetNodeLatestEffective routes latest-effective node reads to the first constituent that resolves the ID.

func (*CompositeEngine) GetNodeLatestVisible

func (c *CompositeEngine) GetNodeLatestVisible(ctx context.Context, id NodeID) (*Node, error)

func (*CompositeEngine) GetNodeProjected

func (c *CompositeEngine) GetNodeProjected(ctx context.Context, id NodeID, properties []string) (*Node, error)

func (*CompositeEngine) GetNodeVisibleAt

func (c *CompositeEngine) GetNodeVisibleAt(ctx context.Context, id NodeID, version MVCCVersion) (*Node, error)

func (*CompositeEngine) GetNodesByLabel

func (c *CompositeEngine) GetNodesByLabel(ctx context.Context, label string) ([]*Node, error)

GetNodesByLabel returns nodes with the given label from all constituents. Each readable source is selected once; equal local IDs across databases remain distinct. Returns empty slice if no readable constituents are available.

func (*CompositeEngine) GetNodesByLabelVisibleAt

func (c *CompositeEngine) GetNodesByLabelVisibleAt(ctx context.Context, label string, version MVCCVersion) ([]*Node, error)

func (*CompositeEngine) GetOutDegree

func (c *CompositeEngine) GetOutDegree(ctx context.Context, nodeID NodeID) (int, error)

GetOutDegree returns the out-degree of a node across all constituents.

func (*CompositeEngine) GetSchema

func (c *CompositeEngine) GetSchema() *SchemaManager

GetSchema returns a schema only if all configured readable constituents can be admitted. An empty composite has a non-nil, empty schema. Call ReadSchema to obtain the error when the merged schema is unavailable.

func (*CompositeEngine) GetSchemaForNamespace

func (c *CompositeEngine) GetSchemaForNamespace(namespace string) *SchemaManager

func (*CompositeEngine) GraphMutationVersion

func (c *CompositeEngine) GraphMutationVersion() (uint64, bool)

func (*CompositeEngine) IsComposite

func (c *CompositeEngine) IsComposite() bool

IsComposite returns true, identifying this engine as a composite database. This enables type-assertion-free composite detection via interface check:

type compositeChecker interface { IsComposite() bool }
if cc, ok := engine.(compositeChecker); ok && cc.IsComposite() { ... }

func (*CompositeEngine) IterateNodes

func (c *CompositeEngine) IterateNodes(fn func(*Node) bool) error

func (*CompositeEngine) LifecycleStatus

func (c *CompositeEngine) LifecycleStatus() map[string]interface{}

func (*CompositeEngine) ListNamespaces

func (c *CompositeEngine) ListNamespaces() []string

func (*CompositeEngine) MarkCleanShutdown

func (c *CompositeEngine) MarkCleanShutdown(ctx context.Context) error

func (*CompositeEngine) MatchEdgesBetween

func (c *CompositeEngine) MatchEdgesBetween(ctx context.Context, startID, endID NodeID, edgeType string, properties []string, match func(*Edge) bool, policy EdgeMatchReadPolicy) ([]*Edge, error)

MatchEdgesBetween matches the edges of every readable constituent, each once, as a between adjacent-edge request reads them.

func (*CompositeEngine) NodeCount

func (c *CompositeEngine) NodeCount(ctx context.Context) (int64, error)

NodeCount returns the total node count across all constituents.

func (*CompositeEngine) OnEdgeCreated

func (c *CompositeEngine) OnEdgeCreated(callback EdgeEventCallback)

func (*CompositeEngine) OnEdgeDeleted

func (c *CompositeEngine) OnEdgeDeleted(callback EdgeDeleteCallback)

func (*CompositeEngine) OnEdgeUpdated

func (c *CompositeEngine) OnEdgeUpdated(callback EdgeEventCallback)

func (*CompositeEngine) OnNodeCreated

func (c *CompositeEngine) OnNodeCreated(callback NodeEventCallback)

func (*CompositeEngine) OnNodeDeleted

func (c *CompositeEngine) OnNodeDeleted(callback NodeDeleteCallback)

func (*CompositeEngine) OnNodeUpdated

func (c *CompositeEngine) OnNodeUpdated(callback NodeEventCallback)

func (*CompositeEngine) PauseLifecycle

func (c *CompositeEngine) PauseLifecycle()

func (*CompositeEngine) PendingEmbeddingsCount

func (c *CompositeEngine) PendingEmbeddingsCount() int

func (*CompositeEngine) PruneMVCCVersions

func (c *CompositeEngine) PruneMVCCVersions(ctx context.Context, opts MVCCPruneOptions) (int64, error)

func (*CompositeEngine) PruneTemporalHistory

func (c *CompositeEngine) PruneTemporalHistory(ctx context.Context, opts TemporalPruneOptions) (int64, error)

func (*CompositeEngine) ReadAdjacentEdges

func (c *CompositeEngine) ReadAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadAdjacentEdges answers one adjacent-edge request from all constituents. Each readable source is selected once; equal local IDs across databases remain distinct. A bounded request is qualified to the one constituent that owns both nodes when the pair names one.

func (*CompositeEngine) ReadAdjacentEdgesVisibleAt

func (c *CompositeEngine) ReadAdjacentEdgesVisibleAt(ctx context.Context, request AdjacentEdgeRead, version MVCCVersion) ([]*Edge, error)

ReadAdjacentEdgesVisibleAt answers one adjacent-edge request at version from the constituents that can resolve it, one direction per call.

func (*CompositeEngine) ReadPendingEmbeddingCount

func (c *CompositeEngine) ReadPendingEmbeddingCount(ctx context.Context, accept func([]byte) bool) (int, error)

ReadPendingEmbeddingCount requires a successful read of every constituent.

func (*CompositeEngine) RebuildMVCCHeads

func (c *CompositeEngine) RebuildMVCCHeads(ctx context.Context) error

func (*CompositeEngine) RebuildTemporalIndexes

func (c *CompositeEngine) RebuildTemporalIndexes(ctx context.Context) error

func (*CompositeEngine) RegisterSnapshotReader

func (c *CompositeEngine) RegisterSnapshotReader(info SnapshotReaderInfo) func()

func (*CompositeEngine) ResumeLifecycle

func (c *CompositeEngine) ResumeLifecycle()

func (*CompositeEngine) ServerTransactionTimeout

func (c *CompositeEngine) ServerTransactionTimeout() time.Duration

ServerTransactionTimeout is the server's transaction timeout for explicit transactions on the composite (ServerTransactionTimeoutOf).

func (*CompositeEngine) SetCompositeName

func (c *CompositeEngine) SetCompositeName(name string)

SetCompositeName records the composite database's name, the name its queries run under (a USE target is in its scope; graph.names() lists its constituents).

func (*CompositeEngine) SetLabelRouting

func (c *CompositeEngine) SetLabelRouting(label string, constituents []string)

SetLabelRouting configures label-based routing for a specific label. This allows explicit configuration of which constituents should handle nodes with a given label.

func (*CompositeEngine) SetLifecycleSchedule

func (c *CompositeEngine) SetLifecycleSchedule(interval time.Duration) error

func (*CompositeEngine) SetPropertyDefault

func (c *CompositeEngine) SetPropertyDefault(propertyName string, constituent string)

SetPropertyDefault sets the default constituent for a property when the value is not found in routing rules.

func (*CompositeEngine) SetPropertyRouting

func (c *CompositeEngine) SetPropertyRouting(propertyName string, value interface{}, constituent string)

SetPropertyRouting configures property-based routing for a specific property value. This enables routing based on property values (e.g., database_id).

func (*CompositeEngine) SetServerTransactionTimeout

func (c *CompositeEngine) SetServerTransactionTimeout(timeout time.Duration)

SetServerTransactionTimeout records the server's transaction timeout for explicit transactions on the composite; its database manager sets the value it configures for every database (NOR-284).

func (*CompositeEngine) StatementOwner

func (c *CompositeEngine) StatementOwner() any

StatementOwner identifies the statement to which this routing view belongs.

func (*CompositeEngine) StreamEdges

func (c *CompositeEngine) StreamEdges(ctx context.Context, fn func(edge *Edge) error) error

StreamEdges streams edges from all constituents.

func (*CompositeEngine) StreamEdgesByType

func (c *CompositeEngine) StreamEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamEdgesByType streams deduplicated edges of edgeType from the readable constituents, one constituent at a time.

func (*CompositeEngine) StreamNodeChunks

func (c *CompositeEngine) StreamNodeChunks(ctx context.Context, chunkSize int, fn func(nodes []*Node) error) error

StreamNodeChunks streams nodes in chunks from all constituents.

func (*CompositeEngine) StreamNodes

func (c *CompositeEngine) StreamNodes(ctx context.Context, fn func(node *Node) error) error

StreamNodes streams nodes from all constituents.

func (*CompositeEngine) StreamNodesByLabelProjected

func (c *CompositeEngine) StreamNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error

StreamNodesByLabelProjected streams deduplicated projected nodes from readable constituents.

func (*CompositeEngine) StreamNodesWithOptions

func (c *CompositeEngine) StreamNodesWithOptions(ctx context.Context, opts StreamNodesOptions, fn func(*Node) error) error

StreamNodesWithOptions broadcasts the options-driven scan across every readable constituent, preserving early-stop semantics. Constituents without the options kernel fall back to a materialized scan with the same transforms.

func (*CompositeEngine) StreamParkedEmbeddingFailures

func (c *CompositeEngine) StreamParkedEmbeddingFailures(ctx context.Context, visit func(nodeID NodeID, meta map[string]any) error) (int, error)

StreamParkedEmbeddingFailures aggregates sidecar failure scans across constituents.

func (*CompositeEngine) TriggerPruneNow

func (c *CompositeEngine) TriggerPruneNow(ctx context.Context) error

func (*CompositeEngine) UpdateEdge

func (c *CompositeEngine) UpdateEdge(ctx context.Context, updateRequest EdgeUpdateRequest) error

UpdateEdge updates an edge. Routes to the constituent containing it.

func (*CompositeEngine) UpdateNode

func (c *CompositeEngine) UpdateNode(ctx context.Context, updateRequest NodeUpdateRequest) error

UpdateNode updates a node. Routes to the constituent that contains it.

func (*CompositeEngine) UpdateNodeEmbeddingSidecar

func (c *CompositeEngine) UpdateNodeEmbeddingSidecar(ctx context.Context, node *Node) error

UpdateNodeEmbeddingSidecar routes the embedding-only sidecar write to the constituent holding the node, without touching any node record. It belongs to this file's maintenance class: the derived embedding state is written through the readable participant that holds the node, not through the constituent's writer admission, because the node record itself is never mutated.

func (*CompositeEngine) WithConstituentAccess

func (c *CompositeEngine) WithConstituentAccess(owner any, access func(string, Engine, bool) (Engine, error)) *CompositeEngine

WithConstituentAccess creates a statement-owned composite view. Access chooses the physical read/write participant by constituent alias while the composite retains routing and provenance ownership. Only catalog/routing configuration is copied, never graph entities or a graph-sized identity set.

type CompositeIndex

type CompositeIndex struct {
	Name       string
	Label      string
	Properties []string // Ordered list of property names

	// OwningConstraint names the uniqueness or node key constraint whose
	// index this is (#875): its equality and IN seeks use it like any
	// property index. It is listed, persisted and dropped as the
	// constraint's RANGE index, not as an index of its own. Empty for an
	// index created on its own.
	OwningConstraint string
	// contains filtered or unexported fields
}

CompositeIndex represents an index on multiple properties for efficient multi-property queries. This is Neo4j's composite index equivalent.

Composite indexes support:

  • Full key lookups (all properties specified)
  • Prefix lookups (leading properties specified, for ordered access)
  • Range queries on the last property in a prefix

func (*CompositeIndex) IndexNode

func (idx *CompositeIndex) IndexNode(ctx context.Context, nodeID NodeID, properties map[string]interface{}) error

IndexNode files a node in the index. An arity-1 index files the node under its canonical single-property key (values, the encoding ORDER BY / range / equality seeks read); an arity >= 2 index files it under its full and every leading-prefix composite key. Call this when creating or updating a node with the indexed properties.

ctx is the lifetime of the caller filing the node: index admission, every canonical key and the acceptance of the prepared keys observe it. Every key is staged before the first posting is written, so a cancelled or failed preparation files nothing and leaves the values, full and prefix populations, dirty flag and fill state untouched. A retry on a live lifetime files the node normally.

A write the engine already accepted carries that write's lifetime rather than a request's: context-free native maintenance passes context.Background(). Request-driven backfills retain their request context. Preparation made for a caller's request passes that request's context, so cancellation stops it instead of filing a partially prepared attempt.

func (*CompositeIndex) LookupFull

func (idx *CompositeIndex) LookupFull(ctx context.Context, values ...interface{}) ([]NodeID, error)

LookupFull returns the committed postings of nodes matching all property values exactly. All properties in the composite index must be specified.

The postings describe committed state: an acknowledged but unflushed write is not listed until it reaches the engine. A reader that must see the final acknowledged membership (an indexed MATCH/MERGE candidate set) uses SchemaManager.CompositeIndexLookup, which merges the attached pending writes. A consumer that already holds the pending view - constraint validation's captured view - reads the postings here and merges the candidates it captured itself.

func (*CompositeIndex) LookupPrefix

func (idx *CompositeIndex) LookupPrefix(ctx context.Context, values ...interface{}) ([]NodeID, error)

LookupPrefix returns the committed postings of nodes matching a prefix of property values. Specify 1 to N-1 property values (where N is total properties in index). Returns all nodes that match the prefix. For an arity-1 index a one-value lookup is a full match. Like LookupFull, these are committed postings; SchemaManager.CompositeIndexLookup is the merged read that also sees acknowledged but unflushed writes.

Example: For index on (country, city, zipcode)

  • LookupPrefix(ctx, "US") returns all nodes in the US
  • LookupPrefix(ctx, "US", "NYC") returns all nodes in NYC, US

func (*CompositeIndex) LookupWithFilter

func (idx *CompositeIndex) LookupWithFilter(ctx context.Context, filter func(NodeID) bool, values ...interface{}) ([]NodeID, error)

LookupWithFilter finds nodes using a prefix and applies a filter function. This enables more complex queries like range queries on the last property.

Example: Find all users in "US", "NYC" with zipcode > "10000"

idx.LookupWithFilter(func(n NodeID, props map[string]interface{}) bool {
    zip := props["zipcode"].(string)
    return zip > "10000"
}, "US", "NYC")

func (*CompositeIndex) RemoveNode

func (idx *CompositeIndex) RemoveNode(nodeID NodeID, properties map[string]interface{})

RemoveNode removes a node from the composite index. Call this when deleting a node or updating its indexed properties.

func (*CompositeIndex) ReplaceNode

func (idx *CompositeIndex) ReplaceNode(ctx context.Context, nodeID NodeID, oldProperties, newProperties map[string]interface{}) error

ReplaceNode moves a node from the entries of oldProperties to those of newProperties atomically for readers. Nil properties file nothing: pass nil old properties for a node the index did not cover, and nil new properties for one it no longer covers. Entries both sides share stay in place; the new entries are always (re)filed, so a node missing from the index is repaired.

ctx is the lifetime of the write that moved the node: idx.mu admission and every canonical key of both sides are prepared before the first posting changes, so a cancelled or failed preparation moves nothing and leaves the values, full and prefix populations, dirty flag and fill state untouched.

func (*CompositeIndex) Stats

func (idx *CompositeIndex) Stats() map[string]interface{}

Stats returns statistics about the composite index. valueEntries counts equality-key buckets; membership-only unkeyable values are excluded.

type CompositeKey

type CompositeKey struct {
	Hash   string        // Process-local HMAC-SHA256 of framed values (for map lookup)
	Values []interface{} // Original values (for debugging/display)
}

CompositeKey represents a key composed of multiple property values. The key is a hash of all property values in order for efficient lookup.

func NewCompositeKey

func NewCompositeKey(ctx context.Context, values ...interface{}) (CompositeKey, error)

NewCompositeKey creates a composite key from multiple property values.

Composite keys enable uniqueness constraints and indexes on multiple properties together (e.g., unique combination of firstName + lastName). The key is hashed using process-local HMAC-SHA256 for map lookups while preserving the values. Each value is length-framed by the shared digest owner. Hash is an ephemeral cache/lock identity; it must not be persisted. Temporal storage keys use their separate process-independent owner and are unchanged.

ctx is the lifetime the key belongs to: a request context for statement work, or the owning maintenance/write lifetime where there is no request. Preparation observes ctx, so a caller that has already been cancelled does no digest work and receives no key at all rather than a partially framed one.

Parameters:

  • ctx: Lifetime of the caller the key is prepared for
  • values: Variable number of property values to combine

Returns:

  • CompositeKey with hash for lookup and original values
  • ctx's error, with no key, when ctx cancels before the key is complete

Example 1 - Unique Person Name:

// Ensure no two people have the same first AND last name combination
key, err := storage.NewCompositeKey(ctx, "Alice", "Johnson")
// key.Hash = "a1b2c3..." (HMAC-SHA256 hex)
// key.Values = ["Alice", "Johnson"]

// Can store in map for O(1) lookup
uniqueKeys := make(map[string]bool)
uniqueKeys[key.Hash] = true

Example 2 - Multi-Column Unique Constraint:

// Email + domain must be unique together
key1, err := storage.NewCompositeKey(ctx, "user", "example.com")
key2, err := storage.NewCompositeKey(ctx, "user", "different.com")
// key1.Hash != key2.Hash (different combinations)

key3, err := storage.NewCompositeKey(ctx, "user", "example.com")
// key3.Hash == key1.Hash (same combination)

Example 3 - Geographic Uniqueness:

// Store locations - no duplicate (lat, lon) pairs
locations := make(map[string]storage.NodeID)

loc1, err := storage.NewCompositeKey(ctx, 40.7128, -74.0060) // NYC
locations[loc1.Hash] = storage.NodeID("loc-nyc")

loc2, err := storage.NewCompositeKey(ctx, 40.7128, -74.0060) // Same coords
if _, exists := locations[loc2.Hash]; exists {
	// the configured logger should emit "Location already exists!"
	_ = exists
}

ELI12:

Imagine you're making sure no two people in your class have the SAME full name (first + last together):

  • Alice Smith → Create a "fingerprint" (hash) from "Alice" + "Smith"
  • Bob Johnson → Different fingerprint
  • Alice Smith → SAME fingerprint as the first Alice Smith!

The hash is like a unique barcode for the combination. If two combinations have the same barcode, they're duplicates!

Why hash instead of just combining strings?

  • Fast lookups (constant time)
  • Handles any data types (numbers, strings, booleans)
  • Consistent length (SHA-256 always 64 hex chars)

Use Cases:

  • Composite unique constraints (email + database_id)
  • Multi-column indexes
  • Deduplication of complex records

func (CompositeKey) String

func (ck CompositeKey) String() string

String returns a human-readable representation of the composite key.

type ConnectedNodeDeleter

type ConnectedNodeDeleter interface {
	DeleteGraphNode(ctx context.Context, id NodeID, mode NodeDeletionMode) error
}

ConnectedNodeDeleter is a store that can delete a node that relationships still connect, failing the commit unless they are deleted first (BadgerTransaction.DeleteGraphNode with RejectConnected).

type Constraint

type Constraint struct {
	Name          string               `json:"name"`
	Type          ConstraintType       `json:"type"`
	EntityType    ConstraintEntityType `json:"entity_type,omitempty"` // defaults to NODE when empty
	Label         string               `json:"label"`                 // label for nodes, relationship type for relationships
	Properties    []string             `json:"properties,omitempty"`
	OwnedIndex    string               `json:"owned_index,omitempty"`    // name of the owned backing index (for uniqueness/key)
	AllowedValues []interface{}        `json:"allowed_values,omitempty"` // for DOMAIN constraints: list of allowed values
	MaxCount      int                  `json:"max_count,omitempty"`      // for CARDINALITY constraints: maximum edge count per node
	Direction     string               `json:"direction,omitempty"`      // for CARDINALITY constraints: "OUTGOING" or "INCOMING"
	SourceLabel   string               `json:"source_label,omitempty"`   // for RELATIONSHIP_POLICY constraints: required source node label
	TargetLabel   string               `json:"target_label,omitempty"`   // for RELATIONSHIP_POLICY constraints: required target node label
	PolicyMode    string               `json:"policy_mode,omitempty"`    // for RELATIONSHIP_POLICY constraints: "ALLOWED" or "DISALLOWED"
}

Constraint represents a Neo4j-compatible schema constraint.

func (Constraint) EffectiveEntityType

func (c Constraint) EffectiveEntityType() ConstraintEntityType

EffectiveEntityType returns the entity type, defaulting to NODE for backward compatibility.

type ConstraintContract

type ConstraintContract struct {
	Name              string                    `json:"name"`
	TargetEntityType  string                    `json:"target_entity_type"`
	TargetLabelOrType string                    `json:"target_label_or_type"`
	Definition        string                    `json:"definition"`
	Entries           []ConstraintContractEntry `json:"entries,omitempty"`
}

type ConstraintContractEntry

type ConstraintContractEntry struct {
	Kind          string   `json:"kind"`
	PrimitiveType string   `json:"primitive_type,omitempty"`
	Properties    []string `json:"properties,omitempty"`
	Property      string   `json:"property,omitempty"`
	ExpectedType  string   `json:"expected_type,omitempty"`
	Expression    string   `json:"expression,omitempty"`
}

type ConstraintEntityType

type ConstraintEntityType string

ConstraintEntityType distinguishes node constraints from relationship constraints.

const (
	ConstraintEntityNode         ConstraintEntityType = "NODE"
	ConstraintEntityRelationship ConstraintEntityType = "RELATIONSHIP"
)

type ConstraintType

type ConstraintType string

ConstraintType represents the type of constraint.

const (
	ConstraintUnique          ConstraintType = "UNIQUE"
	ConstraintNodeKey         ConstraintType = "NODE_KEY"
	ConstraintExists          ConstraintType = "EXISTS"
	ConstraintPropertyType    ConstraintType = "PROPERTY_TYPE"
	ConstraintTemporal        ConstraintType = "TEMPORAL_NO_OVERLAP"
	ConstraintRelationshipKey ConstraintType = "RELATIONSHIP_KEY"
	ConstraintDomain          ConstraintType = "DOMAIN"
	ConstraintCardinality     ConstraintType = "CARDINALITY"
	ConstraintPolicy          ConstraintType = "RELATIONSHIP_POLICY"
)

type ConstraintViolationError

type ConstraintViolationError struct {
	Type       ConstraintType
	Label      string
	Properties []string
	Message    string
	Cause      error
}

ConstraintViolationError is returned when a constraint is violated.

Cause is set when the violation is detected at a non-validation layer — currently used by the snapshot-isolation check when a MERGE's UpdateNode hits a peer-committed node that already carries the matching unique value. Surfacing the underlying ErrConflict via Unwrap keeps errors.Is(err, ErrConflict) and the transient classifier working so retry-aware drivers still see the transient sentinel even though the visible message is the consumer-pinned constraint shape.

func (*ConstraintViolationError) Error

func (e *ConstraintViolationError) Error() string

func (*ConstraintViolationError) Unwrap added in v1.1.1

func (e *ConstraintViolationError) Unwrap() error

type CorruptionDiagnostics

type CorruptionDiagnostics struct {
	Timestamp      time.Time `json:"timestamp"`
	WALPath        string    `json:"wal_path"`
	CorruptedSeq   uint64    `json:"corrupted_seq"`
	Operation      string    `json:"operation"`
	ExpectedCRC    uint32    `json:"expected_crc"`
	ActualCRC      uint32    `json:"actual_crc"`
	FileSize       int64     `json:"file_size"`
	LastGoodSeq    uint64    `json:"last_good_seq"`
	SuspectedCause string    `json:"suspected_cause"`
	BackupPath     string    `json:"backup_path,omitempty"`
	RecoveryAction string    `json:"recovery_action"`
}

CorruptionDiagnostics captures detailed information about WAL corruption to help diagnose root causes (disk failure, split-brain, bugs, etc.)

type CountStoreRead

type CountStoreRead struct {
	// Count is the raw derived counter value. It is a query result only when
	// DescribesRows is true; otherwise the caller counts visible rows.
	Count int64
	// DescribesRows reports whether Count describes the rows a read in the same
	// scope returns. False leaves the count to the rows themselves.
	DescribesRows bool
}

CountStoreRead is the answer to one count-store read.

type CountStoreReadEngine

type CountStoreReadEngine interface {
	ReadCountStore(ctx context.Context, request CountStoreReadRequest) (CountStoreRead, error)
}

CountStoreReadEngine is an optional extension interface for count-store reads whose counter value and visibility describe one consistent observation.

Implementations answer Count from one persisted snapshot and one buffered view. Endpoints, reads with a decay filter or a temporal viewport, and scopes the store cannot prove are the caller's to decline.

A request carrying a Scope belongs to one explicit transaction: the native implementation answers it at that transaction's snapshot, through the same reader chain a caller reads everything else through. An implementation that forwards the request unchanged lets the native engine answer it; an implementation that builds its own answer, or changes the request, leaves the capability unconsumed, and the caller must not treat the answer as the transaction's.

Example:

reader, ok := engine.(storage.CountStoreReadEngine)
if ok {
	answer, err := reader.ReadCountStore(ctx, storage.CountStoreReadRequest{
		Kind:              storage.CountStoreNodesByLabel,
		Name:              "Person",
		HiddenLabelPrefix: "_",
	})
	if err == nil && answer.DescribesRows {
		return answer.Count
	}
}

type CountStoreReadKind

type CountStoreReadKind uint8

CountStoreReadKind selects the counter family a count-store read asks for.

const (
	// CountStoreNodesByLabel counts the nodes carrying Name as a label.
	CountStoreNodesByLabel CountStoreReadKind = iota + 1
	// CountStoreRelationshipsByType counts the relationships of Types, or of
	// every relationship type the scope holds when Types is empty.
	CountStoreRelationshipsByType
	// CountStoreRelationshipsByStartLabel counts the relationships of Types
	// whose start endpoint carries Name as a label.
	CountStoreRelationshipsByStartLabel
	// CountStoreRelationshipsByEndLabel counts the relationships of Types
	// whose end endpoint carries Name as a label.
	CountStoreRelationshipsByEndLabel
)

type CountStoreReadRequest

type CountStoreReadRequest struct {
	// Kind is the counter family to read.
	Kind CountStoreReadKind
	// Namespace is the database to count. An empty Namespace counts across
	// every namespace, as NodeCountByLabel and EdgeCountByType do.
	Namespace string
	// Name is the node label of a CountStoreNodesByLabel read, or the endpoint
	// label of a positional (label, type) read.
	Name string
	// Types are the relationship types to sum, or empty for every type.
	Types []string
	// HiddenLabelPrefix is the label prefix of the nodes the reading scope
	// hides: the counters describe the read's rows only while the scope holds
	// no relevant node carrying such a label. An empty prefix hides none, as
	// the system database's reads do, and the counters answer directly.
	HiddenLabelPrefix string
	// Scope is the snapshot capability of the explicit transaction this read
	// belongs to: when set, the native engine answers Count at that
	// transaction's own snapshot, plus the contribution the transaction's
	// staged writes hold when the capability is consumed, instead of from the
	// current counters. Only BadgerTransaction.ScopeCountStoreRead issues one;
	// it is opaque, it is valid only for the originating engine and for this
	// exact read, and it certifies nothing unless the native counter kernel
	// consumed it (CountStoreReadScope.DescribesSnapshot). A reader that does
	// not consume it returns an answer this field cannot certify.
	Scope *CountStoreReadScope
}

CountStoreReadRequest is one count-store read.

type CountStoreReadScope

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

CountStoreReadScope is one explicit transaction's capability to read a count family at its own snapshot.

A caller obtains it for one read from BadgerTransaction.ScopeCountStoreRead, installs it in that read's request, and hands the request to the reader it reads everything else through. The reader chain forwards the request as it is, and the native engine answers the counter from the transaction's snapshot plus the transaction's own staged contribution. The capability is opaque: it cannot be built or inspected by its caller, and it exposes no view of the transaction's storage.

Each use takes the originating transaction's lock for the whole read and asks the transaction's lifecycle owner whether it may still read, so a use cannot outlive the snapshot it reads: a transaction that has closed, rolled back, handed its native client handle to an accepted commit, or been expired by resource pressure declines, exactly as its rows reads refuse, instead of reaching a disposed view; one that continued onto another snapshot declines instead of certifying the newer one. The lock is taken before the counter family locks, in the order a commit takes them, and it is never held while a caller's own reader runs.

func (*CountStoreReadScope) DescribesSnapshot

func (scope *CountStoreReadScope) DescribesSnapshot() bool

DescribesSnapshot reports whether the native counter kernel consumed this capability and answered from the transaction's snapshot.

It is false for a capability a reader did not consume — one whose request it answered itself, refused, or rewrote — and for a nil capability, so an answer from such a reader is never certified as the transaction's own read.

type DatabaseBackupArchive

type DatabaseBackupArchive struct {
	Stores             map[string]*zip.File
	RequiresEncryption bool
}

DatabaseBackupArchive holds native streams keyed by physical store ID. The empty ID identifies the root store.

func ReadDatabaseBackupArchive

func ReadDatabaseBackupArchive(file *os.File) (*DatabaseBackupArchive, error)

ReadDatabaseBackupArchive opens the archive. A nil result identifies a legacy file.

type DeindexCleanupJob added in v1.1.0

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

DeindexCleanupJob periodically drains pending deindex work items, writes tombstones for their secondary-index keys, and marks them completed.

func NewDeindexCleanupJob added in v1.1.0

func NewDeindexCleanupJob(engine *BadgerEngine, interval time.Duration) *DeindexCleanupJob

NewDeindexCleanupJob creates a cleanup job. Default interval is 24h.

func (*DeindexCleanupJob) RunOnce added in v1.1.0

func (j *DeindexCleanupJob) RunOnce(ctx context.Context) (int, error)

RunOnce processes all pending deindex work items. Returns the number of entities successfully deindexed.

func (*DeindexCleanupJob) Start added in v1.1.0

func (j *DeindexCleanupJob) Start(ctx context.Context)

Start runs the job, as accepted engine work, until Stop, the engine's stop or ctx ends.

func (*DeindexCleanupJob) Stop added in v1.1.0

func (j *DeindexCleanupJob) Stop()

Stop stops the job and waits for its actual return.

type DeindexWorkItem added in v1.1.0

type DeindexWorkItem = knowledgepolicy.DeindexWorkItem

DeindexWorkItem is a pending deindex task for an entity whose visibility score has dropped below the threshold. The background cleanup job drains these items and writes tombstones for the entity's secondary-index keys.

type Edge

type Edge struct {
	// Database owns this relationship and both endpoint identities.
	Database string `json:"-" msgpack:"-"`

	ID         EdgeID         `json:"id"`
	StartNode  NodeID         `json:"startNode"`
	EndNode    NodeID         `json:"endNode"`
	Type       string         `json:"type"`
	Properties map[string]any `json:"properties"`

	// NornicDB extensions
	CreatedAt            time.Time `json:"-"`
	UpdatedAt            time.Time `json:"-"`
	Confidence           float64   `json:"-"`
	AutoGenerated        bool      `json:"-"`
	VisibilitySuppressed bool      `json:"-"`
}

Edge represents a directed graph relationship (arc) between two nodes.

Edges are directed connections that link nodes together, representing relationships like "Alice KNOWS Bob" or "Document CITES Paper". They follow the Neo4j relationship model with NornicDB extensions for automatic relationship inference and confidence scoring.

Core Neo4j Fields:

  • ID: Unique identifier for the relationship
  • StartNode: Source node ID (where the arrow starts)
  • EndNode: Target node ID (where the arrow points)
  • Type: Relationship type (e.g., "KNOWS", "FOLLOWS", "CONTAINS")
  • Properties: Key-value data about the relationship

NornicDB Extensions:

  • CreatedAt: When the relationship was created
  • Confidence: How certain we are this relationship exists (0.0-1.0)
  • AutoGenerated: True if detected by ML/inference, false if manually created

Example 1 - Social Network Relationship:

edge := &storage.Edge{
	ID:         storage.EdgeID("friendship-123"),
	StartNode:  storage.NodeID("alice"),
	EndNode:    storage.NodeID("bob"),
	Type:       "KNOWS",
	Properties: map[string]any{
		"since":    "2020-01-15",
		"strength": "close_friend",
		"mutuality": true,
	},
	CreatedAt:     time.Now(),
	Confidence:    1.0,  // Manually created = 100% certain
	AutoGenerated: false,
}
engine.CreateEdge(edge)

Example 2 - Document Citation:

citation := &storage.Edge{
	ID:        storage.EdgeID("cite-paper-5"),
	StartNode: storage.NodeID("paper-123"),
	EndNode:   storage.NodeID("paper-456"),
	Type:      "CITES",
	Properties: map[string]any{
		"context":    "Methods section",
		"page":       12,
		"importance": "high",
	},
	CreatedAt: time.Now(),
	Confidence: 1.0,
}

Example 3 - Auto-Detected Semantic Relationship:

// NornicDB inference engine detected similarity
autoEdge := &storage.Edge{
	ID:            storage.EdgeID("similar-42"),
	StartNode:     storage.NodeID("note-1"),
	EndNode:       storage.NodeID("note-2"),
	Type:          "SIMILAR_TO",
	Confidence:    0.87,  // 87% confidence from embedding similarity
	AutoGenerated: true,  // Created automatically
	Properties: map[string]any{
		"similarity":  0.87,
		"method":      "cosine_similarity",
		"detected_at": time.Now(),
		"reason":      "High semantic similarity in embeddings",
	},
}

ELI12:

Think of an Edge like a string connecting two beads (nodes):

  • StartNode: The first bead (where you start)
  • EndNode: The second bead (where the string goes to)
  • Type: What kind of string? ("FRIENDS_WITH", "PARENT_OF", "LIKES")
  • Properties: Info about the connection ("since when?", "how strong?")

The arrow matters! "Alice KNOWS Bob" is different from "Bob KNOWS Alice" (they could both be true, but they're separate relationships).

NornicDB's cool additions:

  • Confidence: "I'm 85% sure these two things are related"
  • AutoGenerated: "I found this connection myself!" vs "A human told me"

Imagine your brain automatically connecting ideas: "Oh, these two notes seem related!" That's what AutoGenerated edges do - the system notices patterns and creates connections for you!

Neo4j Compatibility:

  • Type maps to Neo4j relationship type (e.g., -[:KNOWS]->)
  • StartNode/EndNode map to Neo4j node IDs
  • Properties map to Neo4j relationship properties
  • Direction is always preserved (Neo4j requirement)

Thread Safety:

Edge structs are NOT thread-safe. The storage engine handles concurrency.

func CollectStoredEdges

func CollectStoredEdges(ctx context.Context, engine Engine) ([]*Edge, error)

CollectStoredEdges is CollectStoredNodes for relationships (StreamStoredEdgesByType).

func CopyEdge

func CopyEdge(edge *Edge) *Edge

CopyEdge is the exported version of copyEdge for use by other packages.

func DecodeEdgePayload

func DecodeEdgePayload(data []byte) (*Edge, error)

DecodeEdgePayload restores an edge image from the current replication format.

func GetStoredEdge

func GetStoredEdge(ctx context.Context, engine Engine, id EdgeID) (*Edge, error)

GetStoredEdge is GetStoredNode for relationship id.

func MatchEdgesBetween

func MatchEdgesBetween(ctx context.Context, engine Engine, startID, endID NodeID, edgeType string, properties []string, match func(*Edge) bool, policy EdgeMatchReadPolicy) ([]*Edge, error)

MatchEdgesBetween is engine's EdgesBetweenMatcher, or the between adjacent-edge request and the same filter for an engine without one: both give the same edges.

func ReadStoredAdjacentEdges

func ReadStoredAdjacentEdges(ctx context.Context, engine Engine, request AdjacentEdgeRead) ([]*Edge, error)

ReadStoredAdjacentEdges is GetStoredNode for a node's adjacent relationships: the stored ones when engine can read hidden entities (StoredReader), else those its current adjacent-edge read returns.

func (*Edge) ElementID

func (e *Edge) ElementID(fallback string) string

ElementID uses source provenance, falling back only for unscoped values.

func (*Edge) EndElementID

func (e *Edge) EndElementID(fallback string) string

EndElementID identifies the target endpoint in the relationship's database.

func (*Edge) EndIdentity

func (e *Edge) EndIdentity() EntityIdentity

func (*Edge) ExtractInternalProperties

func (edge *Edge) ExtractInternalProperties()

ExtractInternalProperties consumes graph-import metadata using the shared numeric reader. Both combined and JSON-lines imports use this contract.

func (*Edge) Identity

func (e *Edge) Identity() EntityIdentity

func (*Edge) IdentityKey

func (e *Edge) IdentityKey() string

IdentityKey identifies a native relationship independently of its snapshots.

func (*Edge) SetEndpoints

func (edge *Edge) SetEndpoints(start, end *Node) error

SetEndpoints binds an edge to native endpoint identities before storage can discard their source. A stored relationship cannot span physical databases.

func (*Edge) StartElementID

func (e *Edge) StartElementID(fallback string) string

StartElementID identifies the source endpoint in the relationship's database.

func (*Edge) StartIdentity

func (e *Edge) StartIdentity() EntityIdentity

type EdgeDeleteCallback

type EdgeDeleteCallback func(edgeID EdgeID)

EdgeDeleteCallback is called when an edge is successfully deleted from storage.

type EdgeEventCallback

type EdgeEventCallback func(edge *Edge)

EdgeEventCallback is called when edge storage operations complete successfully.

type EdgeID

type EdgeID string

EdgeID is a strongly-typed unique identifier for graph edges (relationships).

Similar to NodeID, provides type safety and API clarity.

Example:

id := storage.EdgeID("follows-456")
edge, err := engine.GetEdge(id)

type EdgeMatchReadPolicy

type EdgeMatchReadPolicy uint8

EdgeMatchReadPolicy selects the committed view used for relationship matching. Ordinary reads retain their transaction snapshot; MERGE resolves against the current committed population before its mutation owner acquires write locks.

const (
	SnapshotEdgeMatch EdgeMatchReadPolicy = iota
	CurrentEdgeMatch
)

type EdgeMeta

type EdgeMeta struct {
	// Edge identification
	EdgeID string `json:"edge_id"`
	Src    string `json:"src"`
	Dst    string `json:"dst"`
	Label  string `json:"label"`

	// Confidence and scoring
	Score         float64 `json:"score"`
	SignalType    string  `json:"signal_type"` // "coaccess", "similarity", "topology", "llm-infer", "manual"
	EvidenceCount int     `json:"evidence_count"`
	DecayState    float64 `json:"decay_state"`

	// Temporal
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id,omitempty"`

	// Lifecycle
	Materialized bool   `json:"materialized"`
	Origin       string `json:"origin"` // agent/commit ID that created this

	// TLP-specific (topology link prediction)
	TopologyAlgorithm string  `json:"topology_algorithm,omitempty"`
	TopologyScore     float64 `json:"topology_score,omitempty"`
	SemanticScore     float64 `json:"semantic_score,omitempty"`

	// Method that generated this edge (detailed)
	Method string `json:"method,omitempty"`
	Reason string `json:"reason,omitempty"`

	// Additional metadata
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

EdgeMeta stores provenance for auto-generated edges. This is append-only for auditability.

type EdgeMetaKey

type EdgeMetaKey struct {
	Src   string
	Dst   string
	Label string
}

EdgeMetaKey uniquely identifies an edge for provenance lookup.

func (EdgeMetaKey) String

func (k EdgeMetaKey) String() string

String returns a string representation of the key.

type EdgeMetaStats

type EdgeMetaStats struct {
	TotalRecords      int64
	TotalMaterialized int64
	UniqueEdges       int64
	BySignalType      map[string]int64
}

EdgeMetaStats provides observability into provenance tracking.

type EdgeMetaStore

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

EdgeMetaStore manages edge provenance. Thread-safe and append-only for auditability.

func GlobalEdgeMetaStore

func GlobalEdgeMetaStore() *EdgeMetaStore

GlobalEdgeMetaStore returns the global edge meta store singleton.

func NewEdgeMetaStore

func NewEdgeMetaStore() *EdgeMetaStore

NewEdgeMetaStore creates a new edge metadata store.

func NewEdgeMetaStoreWithOptions

func NewEdgeMetaStoreWithOptions(opts ...EdgeMetaStoreOption) *EdgeMetaStore

NewEdgeMetaStoreWithOptions creates a store with functional options.

func (*EdgeMetaStore) Append

func (s *EdgeMetaStore) Append(ctx context.Context, meta EdgeMeta) error

Append adds a new evidence record (immutable). This is the primary method for recording edge provenance.

func (*EdgeMetaStore) AppendFromSuggestion

func (s *EdgeMetaStore) AppendFromSuggestion(
	ctx context.Context,
	src, dst, label string,
	score float64,
	signalType, method, reason, sessionID, origin string,
	materialized bool,
) error

AppendFromSuggestion creates an EdgeMeta from inference suggestion data. Convenience method for inference engine integration.

func (*EdgeMetaStore) Cleanup

func (s *EdgeMetaStore) Cleanup(maxAge time.Duration) int

Cleanup removes records older than maxAge. Returns the number of records removed.

func (*EdgeMetaStore) Clear

func (s *EdgeMetaStore) Clear()

Clear removes all provenance records. Use with caution - audit trail will be lost.

func (*EdgeMetaStore) CountHistory

func (s *EdgeMetaStore) CountHistory(src, dst, label string) int

CountHistory returns the number of provenance records for an edge.

func (*EdgeMetaStore) Export

func (s *EdgeMetaStore) Export() []*EdgeMeta

Export returns all provenance records for backup/export.

func (*EdgeMetaStore) GetByOrigin

func (s *EdgeMetaStore) GetByOrigin(ctx context.Context, origin string, limit int) ([]*EdgeMeta, error)

GetByOrigin returns provenance records by origin (agent/commit ID).

func (*EdgeMetaStore) GetBySession

func (s *EdgeMetaStore) GetBySession(ctx context.Context, sessionID string, limit int) ([]*EdgeMeta, error)

GetBySession returns provenance records by session.

func (*EdgeMetaStore) GetBySignalType

func (s *EdgeMetaStore) GetBySignalType(ctx context.Context, signalType string, limit int) ([]*EdgeMeta, error)

GetBySignalType filters by how edges were created.

func (*EdgeMetaStore) GetByTimeRange

func (s *EdgeMetaStore) GetByTimeRange(ctx context.Context, start, end time.Time, limit int) ([]*EdgeMeta, error)

GetByTimeRange returns provenance records within a time range.

func (*EdgeMetaStore) GetHistory

func (s *EdgeMetaStore) GetHistory(ctx context.Context, src, dst, label string) ([]*EdgeMeta, error)

GetHistory returns all evidence for an edge.

func (*EdgeMetaStore) GetLatest

func (s *EdgeMetaStore) GetLatest(ctx context.Context, src, dst, label string) (*EdgeMeta, error)

GetLatest returns the most recent provenance record for an edge.

func (*EdgeMetaStore) GetMaterialized

func (s *EdgeMetaStore) GetMaterialized(ctx context.Context, limit int) ([]*EdgeMeta, error)

GetMaterialized returns all materialized edges.

func (*EdgeMetaStore) HasHistory

func (s *EdgeMetaStore) HasHistory(src, dst, label string) bool

HasHistory returns true if any provenance records exist for this edge.

func (*EdgeMetaStore) Import

func (s *EdgeMetaStore) Import(records []*EdgeMeta) int

Import loads provenance records from backup/import. Existing records are NOT cleared - use Clear() first if needed.

func (*EdgeMetaStore) MarkMaterialized

func (s *EdgeMetaStore) MarkMaterialized(ctx context.Context, src, dst, label, origin string) error

MarkMaterialized marks an edge as materialized (actually created). Appends a new record with Materialized=true.

func (*EdgeMetaStore) Size

func (s *EdgeMetaStore) Size() int

Size returns the total number of provenance records.

func (*EdgeMetaStore) Stats

func (s *EdgeMetaStore) Stats() EdgeMetaStats

Stats returns current provenance store statistics.

func (*EdgeMetaStore) UniqueEdgeCount

func (s *EdgeMetaStore) UniqueEdgeCount() int

UniqueEdgeCount returns the number of unique edges with provenance.

type EdgeMetaStoreOption

type EdgeMetaStoreOption func(*EdgeMetaStore)

EdgeMetaStoreOption configures an EdgeMetaStore.

type EdgeTypeStreamer

type EdgeTypeStreamer interface {
	StreamEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error
}

EdgeTypeStreamer is an optional extension interface for visiting the relationships of one type one at a time, without first materializing them into a slice. It is the edge counterpart of ProjectedLabelNodeReader.

Engines that wrap another engine forward the stream (merging their own pending state, e.g. AsyncEngine's unflushed writes, or filtering to their database, e.g. NamespacedEngine). The callback must treat the edge as read-only; returning an error stops the stream and that error is returned.

Example:

err := storage.StreamEdgesByType(ctx, engine, "KNOWS", func(e *storage.Edge) error {
	counts[e.StartNode]++
	return nil
})

type EdgeUpdateRequest

type EdgeUpdateRequest struct {
	Before *Edge
	After  *Edge
	// PropertyWrites has the same meaning as in NodeUpdateRequest.
	PropertyWrites PropertyWriteIntent
}

EdgeUpdateRequest carries a relationship mutation. Before is the immutable observed image, or nil for a deliberate blind image write; After is the complete new image. Observations belong to writes, never to ordinary reads.

func (EdgeUpdateRequest) InScope

func (request EdgeUpdateRequest) InScope(scope string) EdgeUpdateRequest

InScope qualifies both observation and replacement IDs at the same namespace boundary. It copies only headers whose IDs need qualification; property maps remain immutable inputs owned by the caller. For example, request.InScope("tenant:") maps a->b to tenant:a->tenant:b in both Before and After, without changing request's original records.

func (EdgeUpdateRequest) Operation

func (request EdgeUpdateRequest) Operation() Operation

Operation projects relationship mutation input for a managed coordinator.

type EdgeVisitor

type EdgeVisitor func(edge *Edge) error

EdgeVisitor is a function called for each edge during streaming.

type EdgesBetweenMatcher

type EdgesBetweenMatcher interface {
	MatchEdgesBetween(ctx context.Context, startID, endID NodeID, edgeType string, properties []string, match func(*Edge) bool, policy EdgeMatchReadPolicy) ([]*Edge, error)
}

EdgesBetweenMatcher finds the edges of one type from a start node to an end node that satisfy a predicate over some of their properties: a relationship MERGE with bound endpoints compares every candidate's identity properties, and Neo4j's Expand(Into) reads just those.

match sees each candidate with its ID, Type, StartNode, EndNode and at least the listed properties it has; the candidate is valid only during the call, and match must not change or keep it. The edges it accepts are returned whole, as a between adjacent-edge request returns them, from the same read.

type EmbeddingAttempt

type EmbeddingAttempt struct {
	ProviderGeneration uint64
	ClaimEpoch         uint64
	BodyRevision       EmbeddingBodyRevision
	RequireExactBody   bool // A caller policy can depend on otherwise unused fields.
	// contains filtered or unexported fields
}

EmbeddingAttempt is the immutable identity of one selected provider's work. It is carried through decorators, never encoded in a node body. begin leases the queue identity through the storage commit; body/source acceptance belongs to that same commit. All outcome publication uses its authoritative body.

func NewEmbeddingAttempt

func NewEmbeddingAttempt(generation, epoch uint64, revision EmbeddingBodyRevision, begin func() (func(), bool), publish func(*Node)) *EmbeddingAttempt

func (*EmbeddingAttempt) IsCurrent

func (attempt *EmbeddingAttempt) IsCurrent() bool

IsCurrent avoids sending already-invalid work to decorators. It uses the identical attempt lease as final storage acceptance, which always rechecks after decorators; this observation alone never authorizes publication.

type EmbeddingBodyRevision

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

EmbeddingBodyRevision is an opaque snapshot identity. A durable read uses Badger's body-key version. An acknowledged buffered read uses its existing MVCC commit sequence, which remains the same when replay materializes it. Neither representation depends on the caller-controlled UpdatedAt.

func (EmbeddingBodyRevision) MatchesNode

func (revision EmbeddingBodyRevision) MatchesNode(ctx context.Context, node *Node) (bool, error)

MatchesNode is the common body-change decision for claims, DLQ recovery and publication. A buffered ACK and its materialized body are the same revision; caller timestamps and notification delivery are not revision evidence. The capture read that resolves a buffered revision runs under the caller's context, so a cancelled operation stops it; a comparison the revision already answers performs no read.

type EmbeddingCountProvider

type EmbeddingCountProvider interface {
	PendingEmbeddingsCount() int
}

EmbeddingCountProvider reports the pending embedding work-item count.

type EmbeddingFailureStreamer

type EmbeddingFailureStreamer interface {
	StreamParkedEmbeddingFailures(ctx context.Context, visit func(nodeID NodeID, meta map[string]any) error) (int, error)
}

EmbeddingFailureStreamer streams parked embedding failures from the embedding metadata key space without decoding node bodies.

type EmbeddingSidecarUpdater

type EmbeddingSidecarUpdater interface {
	UpdateNodeEmbeddingSidecar(ctx context.Context, node *Node) error
}

EmbeddingSidecarUpdater writes managed embedding state (chunk vectors and embedding metadata) for an existing node WITHOUT touching the node record: no MVCC version, no body rewrite, no UpdatedAt bump. node carries the properties and labels the embedding was computed from; the write lands only while the stored node still has them. Returns ErrNotFound when the node does not exist and ErrEmbeddingSourceChanged when it changed since it was read (#889); either way nothing is written.

type EmbeddingTextPolicy

type EmbeddingTextPolicy struct {
	// Include, when non-empty, lists the only properties that feed the text.
	Include []string
	// Exclude lists properties that never feed it.
	Exclude []string
	// IncludeLabels prepends the node's labels to the text.
	IncludeLabels bool
}

EmbeddingTextPolicy says which of a node's properties and labels feed its managed embedding text (NORNICDB_EMBEDDING_PROPERTIES_INCLUDE / _EXCLUDE and NORNICDB_EMBEDDING_INCLUDE_LABELS). It is the one rule the text builder (embeddingutil.BuildText) and storage's "did the embedding source change" decisions share (#963): an update that leaves every property and label the policy feeds unchanged keeps the node's embeddings, and one that changes any of them invalidates them.

func (EmbeddingTextPolicy) FeedsText

func (p EmbeddingTextPolicy) FeedsText(key string) bool

FeedsText reports whether property key feeds the embedding text.

func (EmbeddingTextPolicy) SameSource

func (p EmbeddingTextPolicy) SameSource(x, y *Node) bool

SameSource reports whether two copies of a node have the same embedding source under the policy: the same labels (in any order) when it feeds labels, and the same values for every property it feeds, comparing values as stored values rather than by Go type (a copy taken from a cache may hold an int or a []string where a decoded one holds an int64 or a []any). Writers that decide themselves whether to keep a node's embeddings use it with the engine's policy (#963).

type Engine

type Engine interface {
	// Context contract for every method that takes one: the caller's context
	// controls admission, preparation and read materialization. Durable work
	// accepted by an earlier call, its publication, callbacks and their
	// ordering keep their existing independent completion lifetime.
	//
	// Node operations
	CreateNode(ctx context.Context, node *Node) (NodeID, error) // Returns the actual stored ID (may be prefixed for namespaced engines)
	GetNode(ctx context.Context, id NodeID) (*Node, error)
	UpdateNode(ctx context.Context, updateRequest NodeUpdateRequest) error
	DeleteNode(ctx context.Context, id NodeID) error

	// Edge operations
	CreateEdge(ctx context.Context, edge *Edge) error
	GetEdge(ctx context.Context, id EdgeID) (*Edge, error)
	UpdateEdge(ctx context.Context, updateRequest EdgeUpdateRequest) error
	DeleteEdge(ctx context.Context, id EdgeID) error

	// Query operations
	GetNodesByLabel(ctx context.Context, label string) ([]*Node, error)
	GetFirstNodeByLabel(ctx context.Context, label string) (*Node, error) // Optimized for LIMIT 1
	// ReadAdjacentEdges lists the relationships one request selects: the
	// node's relationships in the requested direction (or between it and
	// Other), of the requested types, as full relationships or as headers
	// (AdjacentEdgeRead). It is the one adjacent-edge read of the engine
	// contract; whole-population reads (AllEdges, GetEdgesByType) are
	// different operations and stay separate.
	ReadAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)
	GetEdgeBetween(ctx context.Context, startID, endID NodeID, edgeType string) (*Edge, error)
	GetEdgesByType(ctx context.Context, edgeType string) ([]*Edge, error) // Fast lookup by edge type
	AllNodes(ctx context.Context) ([]*Node, error)
	AllEdges(ctx context.Context) ([]*Edge, error)

	// Streaming operations
	// StreamNodesWithOptions iterates nodes one at a time without materializing
	// them, honoring prefix scoping, property projection, embedding and decay
	// options. Every engine must implement it; the legacy stream variants are
	// thin wrappers over this kernel.
	StreamNodesWithOptions(ctx context.Context, opts StreamNodesOptions, fn func(node *Node) error) error

	// Degree operations (for graph algorithms)
	GetInDegree(ctx context.Context, nodeID NodeID) (int, error)
	GetOutDegree(ctx context.Context, nodeID NodeID) (int, error)

	// Schema operations
	GetSchema() *SchemaManager

	// Bulk operations (for import)
	BulkCreateNodes(ctx context.Context, nodes []*Node) error
	BulkCreateEdges(ctx context.Context, edges []*Edge) error

	// Bulk delete operations (for async flush performance)
	BulkDeleteNodes(ctx context.Context, ids []NodeID) error
	BulkDeleteEdges(ctx context.Context, ids []EdgeID) error

	// Batch read operations (for traversal performance)
	// BatchGetNodes fetches multiple nodes in a single operation
	// Returns a map for O(1) lookup by ID
	BatchGetNodes(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

	// Lifecycle
	Close() error

	// Stats
	NodeCount(ctx context.Context) (int64, error)
	EdgeCount(ctx context.Context) (int64, error)

	// EdgeCountByType returns the number of edges of the given relationship
	// type. Every engine maintains this per type so typed relationship counts
	// are answered from counters (O(1) point reads), never by materializing
	// edges (issue #638). The caller context owns admission of the counter
	// read, including any namespace fan-out it performs.
	EdgeCountByType(ctx context.Context, edgeType string) (int64, error)

	// EdgeCountByStartLabel / EdgeCountByEndLabel return the number of edges
	// of the given type whose physical start / end endpoint carries the label.
	// These are the positional (label, type) counters behind the
	// one-labeled-endpoint count shapes (issue #638), e.g.
	// MATCH (s:Label)-[:T]->() and MATCH ()-[:T]->(e:Label). The caller context
	// owns admission of the counter read.
	EdgeCountByStartLabel(ctx context.Context, label, edgeType string) (int64, error)
	EdgeCountByEndLabel(ctx context.Context, label, edgeType string) (int64, error)

	// DeleteByPrefix deletes all nodes and edges with IDs starting with the given prefix.
	// Used for DROP DATABASE operations to delete all data in a namespace.
	// Returns the number of nodes and edges deleted.
	//
	// This is an optional interface - engines that don't support it will return an error.
	// For multi-database support, this must be implemented.
	DeleteByPrefix(prefix string) (nodesDeleted int64, edgesDeleted int64, err error)
}

Engine defines the storage engine interface for graph database operations.

All Engine implementations MUST be:

  • Thread-safe: Safe for concurrent access from multiple goroutines
  • ACID-like: Operations are atomic within their scope
  • Idempotent where appropriate: CreateNode fails if ID exists

The interface provides standard graph database operations:

  • CRUD for nodes and edges
  • Label-based queries
  • Graph traversal (adjacent-edge reads in any direction)
  • Bulk operations for import/export
  • Statistics

Implementations:

  • MemoryEngine: In-memory storage for testing and small datasets
  • BadgerEngine: Persistent disk storage (planned)

Example Usage:

var engine storage.Engine
engine = storage.NewMemoryEngine()
defer engine.Close()

// Create data
node := &storage.Node{
	ID:     "n1",
	Labels: []string{"Person"},
	Properties: map[string]any{"name": "Alice"},
}
if _, err := engine.CreateNode(node); err != nil {
	log.Fatal(err)
}

// Query
people, _ := engine.GetNodesByLabel("Person")
// emit "Found N people" via the configured logger

// Traversal
outgoing, _ := engine.ReadAdjacentEdges(ctx, storage.AdjacentEdgeRead{Node: "n1"})
for _, edge := range outgoing {
	// emit "<start> -> <end> [<type>]" via the configured logger
	_ = edge
}

func OpenHistoricalRead

func OpenHistoricalRead(ctx context.Context, engine Engine, at time.Time) (Engine, error)

OpenHistoricalRead returns a read-only Engine that answers every read at one fixed MVCC cutoff over one pinned snapshot of engine's native store and its acknowledged write-behind commits.

The cutoff is the requested wall-clock time at.UTC() with the maximum commit sequence, so a read sees every commit that completed at or before that instant and no commit after it. The returned engine holds exactly one pinned physical admission (the snapshot capture) and exactly one registered historical reader for its whole lifetime; Close releases both and nothing else, leaving the engine it reads unaffected.

What a historical read answers:

  • Node and relationship labels, properties and embedding metadata are the stored state at the cutoff. Embedding vectors are not available: a historical read never returns vectors, current or historical.
  • An entity is only listed while its current live incarnation existed at the cutoff. A currently deleted entity is absent, even for a time before its deletion, and an ID whose current incarnation began after a retention-retained tombstone is absent at every earlier time: the state before that tombstone belonged to a different incarnation and never answers this read.
  • A relationship is only listed while both of its endpoints are nodes this same read lists at the cutoff.
  • A time before the entity's creation floor is a legitimate absence (ErrNotFound). A time below a floor advanced by pruning reports ErrHistoryNotRetained. A missing retained record at or after the creation floor reports ErrHistoryUnavailable, never a silent absence.

Scans stream the MVCC head keyspaces and then the buffered-only IDs. A current label, property, type or count index cannot narrow a historical population. The returned schema is empty for the same reason, and the current suppression and decay policy is preserved on the entities a read resolves.

Example:

historical, err := storage.OpenHistoricalRead(ctx, engine, time.Now().Add(-24*time.Hour))
if err != nil {
	return err
}
defer historical.Close()
nodes, err := historical.GetNodesByLabel(ctx, "Person")

func OpenHistoricalReadAtVersion

func OpenHistoricalReadAtVersion(ctx context.Context, engine Engine, version MVCCVersion) (Engine, error)

OpenHistoricalReadAtVersion pins the exact committed version, including its sequence, for every entity and adjacency read in the returned view.

func UnwrapEngine

func UnwrapEngine(engine Engine) Engine

UnwrapEngine peels decorator layers until reaching an engine that does not implement EngineUnwrapper. It returns the engine unchanged when it is not wrapped and never loops on self-referencing wrappers.

type EngineOptions

type EngineOptions struct {
	RetentionPolicy RetentionPolicy
	// IDFreelistTTL debounces numID recycling: after a node/edge is
	// pruned, its numID stays parked for this long before allocations
	// can reclaim it. Zero = engine default (30 seconds).
	IDFreelistTTL time.Duration
	// LockWait bounds and reports a MERGE's wait for a UNIQUE / NODE KEY key
	// another transaction holds. The zero value waits until the key is
	// released, the wait would close a deadlock, or the statement ends.
	LockWait LockWaitOptions
}

EngineOptions contains storage-engine-wide options shared across engine implementations.

type EngineUnwrapper

type EngineUnwrapper interface {
	GetInnerEngine() Engine
}

EngineUnwrapper is implemented by storage engines that decorate another Engine (WAL, Async, Namespaced, Composite, size-tracking and transaction wrappers). GetInnerEngine is the single canonical accessor for the wrapped engine. Callers that walk wrapper layers MUST use this interface (directly or via UnwrapEngine) instead of type-switching over accessor variants.

type EntityCommandKind

type EntityCommandKind uint8
const (
	EntityUnknown EntityCommandKind = iota
	EntityCreateNode
	EntityUpdateNode
	EntityDeleteNode
	EntityCreateEdge
	EntityDeleteEdge
	EntityUpdateEdge
)

type EntityCommitAdmissionGate

type EntityCommitAdmissionGate interface{ CheckEntityCommitAdmission() error }

EntityCommitRoute describes whether an outer owner must process submission. RequiresSubmission is false only for canonical native storage owners. EntityCommitAdmissionGate enforces wrapper policy before preparation/admission.

type EntityCommitMode

type EntityCommitMode uint8

EntityCommitMode retains the current producer's durability and ACK policy. It belongs to the transaction/command, not to individual entities.

const (
	CommitModeExplicit EntityCommitMode = iota // explicit durability, no buffered ACK
	CommitModeImplicit                         // existing autocommit/bulk policy, buffered ACK eligible
	CommitModeDirect                           // native direct policy, no extra explicit Sync or buffered ACK
)

type EntityCommitRequest

type EntityCommitRequest struct {
	LogicalID  string
	Operations []Operation
	// VectorReferences is copied from a decoded envelope; zero stages complete images.
	VectorReferences ManagedVectorReferences
}

EntityCommitRequest identifies an accepted commit and optional decoded changes. Operations are staged only when LogicalID has not already been acknowledged. An already-staged transaction leaves Operations nil; replay passes its existing operation slice without copying it or allocating a staging callback.

type EntityCommitRoute

type EntityCommitRoute struct {
	ForwardDirect      func(context.Context, []Operation, EntityCommitMode) error
	CheckAdmission     func() error
	Submitter          EntityCommitSubmitter
	RequiresSubmission bool
}

func EntityCommitSubmitterFor

func EntityCommitSubmitterFor(engine Engine) (EntityCommitRoute, bool)

EntityCommitSubmitterFor returns the first authoritative wrapper owner. A journal wrapper is a routing boundary even before it exposes the capability: discovering an inner native engine must never bypass that wrapper's journal.

type EntityCommitSubmitter

type EntityCommitSubmitter interface {
	SubmitEntityCommit(context.Context, *PreparedEntityCommit, func(CommitOutcome)) (*CommitReceipt, error)
}

EntityCommitSubmitter is discovered before unwrapping a storage wrapper. A non-nil error means definitely not accepted; accepted callers receive a receipt whose terminal owner survives waiter cancellation.

type EntityDirectForwarder

type EntityDirectForwarder interface {
	ForwardEntityChanges(context.Context, []Operation, EntityCommitMode) error
}

type EntityIdentity

type EntityIdentity struct {
	Database string
	LocalID  string
}

EntityIdentity is the source-qualified identity of a stored native value. A stored local ID is opaque: only an explicit external element ID is parsed.

func EntityIdentityFromKey

func EntityIdentityFromKey(key string) EntityIdentity

EntityIdentityFromKey decodes only the internal key produced by Key. External string arguments belong to their API's ID domain and must not enter here.

func (EntityIdentity) InDatabase

func (id EntityIdentity) InDatabase(database string) string

InDatabase encodes the identity in an existing projection's ID domain. Local IDs remain local inside that database's catalog; foreign values are qualified.

func (EntityIdentity) Key

func (id EntityIdentity) Key() string

func (EntityIdentity) LookupID

func (id EntityIdentity) LookupID(engine Engine, kind string) (string, bool)

LookupID translates an identity for a storage read without dropping a source selection when the engine is composite. kind is the element ID entity kind.

func (EntityIdentity) NodeLookupID

func (id EntityIdentity) NodeLookupID(engine Engine) (NodeID, bool)

NodeLookupID preserves source identity at the engine boundary. A qualified foreign value cannot be reinterpreted as a local ID in a namespaced engine.

type EntityImagePolicy

type EntityImagePolicy uint8

EntityImagePolicy selects the interpretation of one transaction node update.

const (
	// ClientNodeEdits reconciles client edits with stored embedding metadata.
	ClientNodeEdits EntityImagePolicy = iota
	// StoredNodeImages applies a complete image normalized by its coordinator.
	StoredNodeImages
)

type EntityReadSnapshot

type EntityReadSnapshot interface {
	ReadSnapshotView
	ReadNode(context.Context, NodeID) (*Node, error)
	ReadEdge(context.Context, EdgeID) (*Edge, error)
}

EntityReadSnapshot materializes procedure output from the same committed capture as its admitted scoring inputs. It uses native stream hydration and visibility, rather than current caches or a later live point read.

func OpenEntityReadSnapshot

func OpenEntityReadSnapshot(ctx context.Context, engine any, relationships bool) (EntityReadSnapshot, error)

OpenEntityReadSnapshot opens the canonical snapshot for one entity kind. Capturing a node request never constructs the relationship overlay, and vice versa. Unsupported views leave their caller on its original acquisition.

type EntityTransactionEnvelope

type EntityTransactionEnvelope struct {
	Mode        EntityCommitMode
	Version     uint16
	Namespace   string
	LogicalTxID string

	// VectorReferences must accompany Operations when restaging this decoded command.
	VectorReferences ManagedVectorReferences
	// contains filtered or unexported fields
}

EntityTransactionEnvelope identifies a decoded semantic transaction.

type EntityTransactionRequest

type EntityTransactionRequest struct {
	Namespace  string
	LogicalID  string
	Operations []Operation
	Mode       EntityCommitMode
	Prepared   *PreparedEntityCommit
	// VectorReferences carries validated WAL-local image references; zero keeps full images.
	VectorReferences ManagedVectorReferences
}

EntityTransactionRequest selects raw decoded operations or one immutable prepared transaction. Prepared must be used alone; combining both sources is rejected instead of silently choosing metadata or images from one of them.

type EntityWriteBoundary

type EntityWriteBoundary interface {
	WithEntityChange(Operation, func() error) error
}

EntityWriteBoundary preserves a decorator's per-operation admission policy while the supplied mutation stages in an atomic native transaction. Return a policy error without calling apply, or invoke apply exactly once and return its result. The callback must not issue an independent storage write.

For example, a tenant policy can reject an Operation's node ID and otherwise return apply(). Nested policy wrappers are invoked from outermost to innermost.

type EntityWriteLocker

type EntityWriteLocker interface {
	LockNodeForWrite(ctx context.Context, id NodeID) (*Node, error)
	LockEdgeForWrite(ctx context.Context, id EdgeID) (*Edge, error)
}

EntityWriteLocker is the capability of a transactional storage view that takes the write lock of an existing node or relationship before a statement changes it, as Neo4j does: the lock is held until the transaction ends, so a concurrent writer of the same entity waits at its write instead of failing at commit because both wrote the entity from the same snapshot (NOR-213).

Each method returns the entity's latest committed image when a transaction committed it after this one's snapshot, and nil otherwise. The caller applies its change to that image: from then on the transaction reads the entity as last committed, and its commit no longer conflicts with the writer it waited for. A wait ends with ErrDeadlock when it would close a cycle of transactions waiting for each other, with ctx's error, or, after the server's transaction timeout (EngineOptions.LockWait), with ErrLockWaitTimeout; a wait past the slow-query threshold is logged. An entity another transaction deleted fails with ErrConflict.

Example:

if locker, ok := store.(storage.EntityWriteLocker); ok {
	latest, err := locker.LockNodeForWrite(ctx, node.ID)
	if err != nil {
		return err
	}
	if latest != nil {
		*node = *latest // apply the change to the committed predecessor
	}
}

type ErrStorageUpgradeRequired added in v1.1.0

type ErrStorageUpgradeRequired struct {
	OnDisk, Current int
}

ErrStorageUpgradeRequired is returned by RunOnStartMigrations when the on-disk schema version is older than the binary's current version and the operator has not authorized an upgrade. Callers should surface this directly to the operator with the recommended remediation: back up the data directory, then restart with the --upgrade-storage flag.

func (*ErrStorageUpgradeRequired) Error added in v1.1.0

func (e *ErrStorageUpgradeRequired) Error() string

type EventHandlers

type EventHandlers struct {
	NodeCreated    NodeEventCallback
	NodeUpdated    NodeEventCallback
	NodeDeleted    NodeDeleteCallback
	EdgeCreated    EdgeEventCallback
	EdgeUpdated    EdgeEventCallback
	EdgeDeleted    EdgeDeleteCallback
	NamespaceReset NamespaceResetCallback
}

EventHandlers are the consumers of one subscription. A nil handler is not registered.

type EventNotificationsSettledReporter

type EventNotificationsSettledReporter interface {
	EventSubscriber
	EventNotificationsSettled() bool
}

EventNotificationsSettledReporter is an EventSubscriber that also reports when its events are a complete baseline. Subscribing is part of the contract: an engine that cannot deliver the events has no baseline to certify. Every storage wrapper forwards the report to the publisher it subscribes to, so a caller holding any layer of the stack gets the publisher's answer.

type EventSubscriber

type EventSubscriber interface {
	SubscribeEvents(handlers EventHandlers) error
}

EventSubscriber delivers every storage event, entity changes and namespace resets alike, to one set of handlers. The engine that publishes implements it; every wrapper forwards it to the engine it wraps (compile-time checked in wrapper_capabilities.go and in the wrapper's own package), so a subscription reaches the publisher through any configuration of wrappers.

type EventViewForwarder

type EventViewForwarder interface {
	EngineUnwrapper
	PreservesEventView()
}

EventViewForwarder is implemented by an engine wrapper whose storage events, entity IDs and committed reads are exactly those of its inner engine: the wrapper forwards them and changes none of them. Accounting, tracing, replication and WAL wrappers qualify. A wrapper that filters, translates or adds uncommitted state must not implement it.

type ExportableEngine

type ExportableEngine interface {
	Engine
	AllNodes(ctx context.Context) ([]*Node, error)
	AllEdges(ctx context.Context) ([]*Edge, error)
}

ExportableEngine extends Engine with export capabilities.

type FulltextIndex

type FulltextIndex struct {
	Name              string   `json:"name"`
	Labels            []string `json:"labels,omitempty"`
	RelationshipTypes []string `json:"relationship_types,omitempty"`
	Properties        []string `json:"properties"`
}

FulltextIndex represents a full-text search index.

An index is scoped by EITHER Labels (a node-scoped index, declared via CREATE FULLTEXT INDEX <name> FOR (n:Label) ON EACH [n.prop]) OR RelationshipTypes (a relationship-scoped index, declared via CREATE FULLTEXT INDEX <name> FOR ()-[r:Type]-() ON EACH [r.prop]). Exactly one of those slices is populated for any well-formed index; the runtime uses the populated slice to decide which storage scan to drive.

Both Labels and RelationshipTypes use omitempty so an index that only carries one kind serializes without a stray empty array for the other. RelationshipTypes was added after the initial release; older databases serialize without it and load cleanly because JSON unmarshal treats missing fields as the zero value.

type GraphMutationVersionProvider added in v1.3.3

type GraphMutationVersionProvider interface {
	GraphMutationVersion() (version uint64, supported bool)
}

GraphMutationVersionProvider reports a process-local revision of visible graph data. It is a cache-invalidation token, not a transaction timestamp or a durable snapshot version.

type HiddenEdgeIdentityConflictError

type HiddenEdgeIdentityConflictError struct {
	EdgeID    EdgeID
	Namespace string
}

HiddenEdgeIdentityConflictError is the permanent result of a CREATE whose physical ID belongs to a hidden relationship but whose final transaction image is not semantically identical. It unwraps to ErrAlreadyExists for storage callers while exposing a non-retryable client status to Bolt/HTTP.

func (*HiddenEdgeIdentityConflictError) BoltErrorCode

func (err *HiddenEdgeIdentityConflictError) BoltErrorCode() string

func (*HiddenEdgeIdentityConflictError) BoltErrorDetail

func (err *HiddenEdgeIdentityConflictError) BoltErrorDetail() string

func (*HiddenEdgeIdentityConflictError) Error

func (*HiddenEdgeIdentityConflictError) Unwrap

func (err *HiddenEdgeIdentityConflictError) Unwrap() error

type IDDictionaryReport

type IDDictionaryReport struct {
	Nodes []NodeID
	Edges []EdgeID
	// The stored entities whose dictionary entry holds a number none of their
	// index keys use: a restart that rebuilt the MVCC heads gave such a lost
	// entity a new number, while its label or adjacency keys keep the old one.
	MismatchedNodes []NodeID
	MismatchedEdges []EdgeID
	// After RepairIDDictionary: the entities whose original numeric ID was
	// restored, and those it could not identify unambiguously.
	RestoredNodes   []NodeID
	RestoredEdges   []EdgeID
	UnresolvedNodes []NodeID
	UnresolvedEdges []EdgeID
}

IDDictionaryReport lists the stored nodes and relationships whose ID has no ID-dictionary entry. Their records are found by ID, but every index keyed by their numeric ID (adjacency, relationship type, label, MVCC heads) points at a number nothing resolves: a relationship isn't traversed and a node isn't found by label. A rolled-back transaction could leave them so before #907's I29 fix.

type IncidentEdgeLister

type IncidentEdgeLister interface {
	IncidentEdges(ctx context.Context, nodeID NodeID) ([]*Edge, error)
}

IncidentEdgeLister is a store that lists every relationship connecting a node, those the visibility layer hides from reads included (BadgerTransaction.IncidentEdges). A DELETE reads them: a hidden relationship still connects its endpoints, so it keeps a non-DETACH DELETE from removing the node, and DETACH DELETE removes and counts it.

The list is a bulk read, so it carries the caller's context: the DELETE checks and the DETACH DELETE count run before the statement is accepted, and both were originated by the request (pipelineApplyDelete). A canceled or expired request returns its own error and no partial relationship list, and the enumeration stops instead of materializing it.

type IndexEntryCatalog added in v1.1.0

type IndexEntryCatalog struct {
	TargetID    string   `msgpack:"targetId"`
	TargetScope string   `msgpack:"targetScope"`
	IndexKeys   [][]byte `msgpack:"indexKeys"`
	Deindexed   bool     `msgpack:"deindexed,omitempty"`
}

IndexEntryCatalog tracks the exact secondary-index Badger keys written for an entity. The deindex cleanup job uses this to write tombstones without scanning the full index keyspace.

type IndexKind

type IndexKind string

IndexKind identifies the durable kind of a schema property index.

const (
	// IndexKindRange is the default property-index kind, including legacy definitions.
	IndexKindRange IndexKind = "RANGE"
	// IndexKindText identifies a single-property text index definition.
	IndexKindText IndexKind = "TEXT"
	// IndexKindPoint identifies a single-property spatial index definition.
	IndexKindPoint IndexKind = "POINT"
)

type IndexSourceStampedView

type IndexSourceStampedView interface {
	IndexSourceStamp(context.Context) (string, error)
}

IndexSourceStampedView is the metadata certificate of an already captured read view. It does not iterate/hydrate candidate nodes, decode properties or read vector payloads. The work is O(number of source metadata keys), with constant working memory. This work must be reported separately from candidate acquisition; a zero node-iterator count does not mean zero validation work.

type IndexStats

type IndexStats struct {
	Name         string   `json:"name"`
	Type         string   `json:"type"`
	Label        string   `json:"label"`
	Property     string   `json:"property,omitempty"`
	Properties   []string `json:"properties,omitempty"`
	TotalEntries int64    `json:"totalEntries"`
	UniqueValues int64    `json:"uniqueValues"`
	Selectivity  float64  `json:"selectivity"` // uniqueValues / totalEntries
}

IndexStats represents statistics about an index. For an arity-one equality index, TotalEntries and UniqueValues describe equality-keyed entries only; they exclude membership-only unkeyable values, preserving their established meaning. They are not a count of complete nonnull candidates.

type LabelConfig

type LabelConfig struct {
	Label         string        `json:"label"`
	MaxEdges      int           `json:"max_edges"`      // 0 = unlimited
	MinConfidence float64       `json:"min_confidence"` // Override default threshold
	Cooldown      time.Duration `json:"cooldown"`       // Override default cooldown
	Disabled      bool          `json:"disabled"`       // Completely disable this label
}

LabelConfig defines per-label edge limits.

type LabelIndexEngine

type LabelIndexEngine interface {
	// HasLabelBatch returns a map of node IDs that have the given label.
	// Labels match exactly: names are case-sensitive, as in Neo4j (#862).
	// Missing nodes are treated as not having the label.
	HasLabelBatch(ids []NodeID, label string) (map[NodeID]bool, error)
}

LabelIndexEngine is an optional interface implemented by engines that can answer label-membership queries via an index, without decoding full nodes.

This is used by performance-sensitive query executors that need to enforce `(n:Label)` semantics while avoiding per-node GetNode/BatchGetNodes overhead.

type LabelNodeIDLookupEngine

type LabelNodeIDLookupEngine interface {
	ForEachNodeIDByLabel(ctx context.Context, label string, visit func(NodeID) bool) error
}

LabelNodeIDLookupEngine is an optional interface for engines that can return node IDs for a label without decoding full nodes.

Labels match exactly: names are case-sensitive, as in Neo4j (#862). The visit function should return true to continue iteration, false to stop.

type LabelStatsEngine added in v1.1.3

type LabelStatsEngine interface {
	NodeCountByLabel(ctx context.Context, label string) (int64, error)
}

LabelStatsEngine is an optional extension interface for fast label-cardinality lookups without materializing rows. The caller context owns admission and any count scan; canceled reads return the original context error.

type LockWaitOptions

type LockWaitOptions struct {
	// Timeout is the server's transaction timeout. A writer that has waited
	// this long for a key fails with Neo4j's TransactionTimedOut status
	// (ErrLockWaitTimeout): its transaction has run at least that long. Zero
	// or negative leaves the wait unbounded. The statement's own deadline
	// and cancellation end the wait either way.
	Timeout time.Duration
	// LogAfter is the slow-query threshold. A writer still waiting after this
	// long is logged once, at WARN, with the transaction holding the key; a
	// wait the Timeout ends first is not. Zero or negative logs nothing.
	LogAfter time.Duration
}

LockWaitOptions bound and report waits for transaction-held UNIQUE, NODE KEY and entity write locks. Competing writers wait until the holding transaction ends (PrepareMergeNode and EntityWriteLocker).

type MVCCAppendEngine

type MVCCAppendEngine interface {
	AppendNodeVersion(node *Node, version MVCCVersion) error
	AppendNodeTombstone(id NodeID, version MVCCVersion) error
	AppendEdgeVersion(edge *Edge, version MVCCVersion) error
	AppendEdgeTombstone(id EdgeID, version MVCCVersion) error
	UpdateNodeCurrentHead(id NodeID, version MVCCVersion, tombstoned bool) error
	UpdateEdgeCurrentHead(id EdgeID, version MVCCVersion, tombstoned bool) error
}

MVCCAppendEngine is an optional extension interface for immutable MVCC writes.

type MVCCEnumerationEngine

type MVCCEnumerationEngine interface {
	BatchGetNodesLatestVisible(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)
	IterateLatestVisibleNodes(ctx context.Context, yield func(*Node) error) error
	IterateLatestVisibleEdges(yield func(*Edge) error) error
}

MVCCEnumerationEngine is an optional extension interface for latest-visible iteration.

type MVCCHead

type MVCCHead struct {
	Version      MVCCVersion
	Tombstoned   bool
	FloorVersion MVCCVersion
}

MVCCHead stores the current persisted head for a logical record.

type MVCCHeadEngine

type MVCCHeadEngine interface {
	GetNodeCurrentHead(ctx context.Context, id NodeID) (MVCCHead, error)
	GetEdgeCurrentHead(ctx context.Context, id EdgeID) (MVCCHead, error)
}

MVCCHeadEngine is an optional extension interface for persisted head lookups under the caller's context, which owns admission of the head read.

type MVCCIndexedVisibilityEngine

type MVCCIndexedVisibilityEngine interface {
	GetNodesByLabelVisibleAt(ctx context.Context, label string, version MVCCVersion) ([]*Node, error)
	// ReadAdjacentEdgesVisibleAt answers one adjacent-edge request at the exact
	// requested version. A pinned adjacency entry carries only its tombstone
	// bit, so a typed request validates the current header against the
	// relationship's head version and resolves the historical relationship
	// when that header is stale.
	ReadAdjacentEdgesVisibleAt(ctx context.Context, request AdjacentEdgeRead, version MVCCVersion) ([]*Edge, error)
	GetEdgesByTypeVisibleAt(ctx context.Context, edgeType string, version MVCCVersion) ([]*Edge, error)
}

MVCCIndexedVisibilityEngine is an optional extension interface for snapshot-visible graph queries that resolve label, type, and topology against MVCC history instead of only the current materialized indexes.

type MVCCLatestEffectiveEngine

type MVCCLatestEffectiveEngine interface {
	GetNodeLatestEffective(ctx context.Context, id NodeID) (*Node, error)
	GetEdgeLatestEffective(ctx context.Context, id EdgeID) (*Edge, error)
}

MVCCLatestEffectiveEngine is an optional extension interface for wrapper-level latest reads that merge pending, in-flight, and persisted state. The caller context owns admission and the read's materialization.

type MVCCLifecycleController

type MVCCLifecycleController interface {
	MVCCLifecycleEngine
	AcquireSnapshotReader(info SnapshotReaderInfo) (func(), error)
	EvaluateSnapshotReader(info SnapshotReaderInfo) (graceful bool, hard bool)
	RunPruneNow(ctx context.Context, opts MVCCPruneOptions) (int64, error)
	StartLifecycle(ctx context.Context)
	StopLifecycle()
	IsLifecycleEnabled() bool
	IsLifecycleRunning() bool
	ReaderRegistry() SnapshotReaderRegistry
}

MVCCLifecycleController is the storage-facing control interface used by engines. A concrete implementation can live outside the storage package and be injected.

type MVCCLifecycleDebtEngine

type MVCCLifecycleDebtEngine interface {
	TopLifecycleDebtKeys(limit int) []MVCCLifecycleDebtKey
}

MVCCLifecycleDebtEngine is an optional extension for inspecting the highest-debt logical keys.

type MVCCLifecycleDebtKey

type MVCCLifecycleDebtKey struct {
	LogicalKey       string `json:"logical_key"`
	Namespace        string `json:"namespace,omitempty"`
	DebtBytes        int64  `json:"debt_bytes"`
	TombstoneDepth   int    `json:"tombstone_depth"`
	FloorLagVersions int    `json:"floor_lag_versions"`
	VersionsToDelete int    `json:"versions_to_delete"`
}

MVCCLifecycleDebtKey describes one logical key contributing lifecycle debt.

type MVCCLifecycleEngine

type MVCCLifecycleEngine interface {
	RegisterSnapshotReader(info SnapshotReaderInfo) func()
	LifecycleStatus() map[string]interface{}
	TriggerPruneNow(ctx context.Context) error
	PauseLifecycle()
	ResumeLifecycle()
}

MVCCLifecycleEngine is an optional extension interface for lifecycle management.

type MVCCLifecycleScheduleEngine

type MVCCLifecycleScheduleEngine interface {
	SetLifecycleSchedule(interval time.Duration) error
}

MVCCLifecycleScheduleEngine is an optional extension for runtime lifecycle cadence control.

type MVCCMaintenanceEngine

type MVCCMaintenanceEngine interface {
	RebuildMVCCHeads(ctx context.Context) error
	PruneMVCCVersions(ctx context.Context, opts MVCCPruneOptions) (int64, error)
}

MVCCMaintenanceEngine is an optional extension interface for rebuild and prune operations.

type MVCCPruneOptions

type MVCCPruneOptions struct {
	MaxVersionsPerKey int
	MinRetentionAge   time.Duration
	// MaxRuntime bounds one engine's prune call, its waits for another pass,
	// for storage admission and for conflict retries included; reading the
	// reader floors takes short engine locks without a deadline. A spent call
	// returns what it committed and the next bounded call resumes after its
	// last committed decision. A commit storage has already admitted
	// completes, so a call can exceed MaxRuntime by that one commit. The
	// budget is per engine: a call that prunes several engines (a composite
	// database) gives each its own MaxRuntime. Zero walks every key.
	MaxRuntime time.Duration
}

MVCCPruneOptions controls pruning of older MVCC versions. Zero values inherit the engine's configured RetentionPolicy.

type MVCCReadMode

type MVCCReadMode string

MVCCReadMode selects latest-visible versus snapshot-visible reads.

const (
	MVCCReadLatest   MVCCReadMode = "latest"
	MVCCReadSnapshot MVCCReadMode = "snapshot"
)

type MVCCReadSelector

type MVCCReadSelector struct {
	Mode    MVCCReadMode
	Version MVCCVersion
}

MVCCReadSelector describes which committed version a read should resolve.

type MVCCVersion

type MVCCVersion struct {
	CommitTimestamp time.Time `json:"commit_timestamp"`
	CommitSequence  uint64    `json:"commit_sequence"`
}

MVCCVersion identifies one committed storage version.

Versions are ordered first by committed timestamp, then by a monotonic sequence allocated at commit time to break same-timestamp ties.

func (MVCCVersion) Compare

func (v MVCCVersion) Compare(other MVCCVersion) int

Compare returns -1, 0, or 1 using MVCC ordering semantics.

func (MVCCVersion) IsZero

func (v MVCCVersion) IsZero() bool

IsZero reports whether the version is uninitialized.

func (MVCCVersion) String

func (v MVCCVersion) String() string

String renders a stable debug form for logs and diagnostics.

type MVCCVisibilityEngine

type MVCCVisibilityEngine interface {
	GetNodeLatestVisible(ctx context.Context, id NodeID) (*Node, error)
	GetNodeVisibleAt(ctx context.Context, id NodeID, version MVCCVersion) (*Node, error)
	GetEdgeLatestVisible(ctx context.Context, id EdgeID) (*Edge, error)
	GetEdgeVisibleAt(ctx context.Context, id EdgeID, version MVCCVersion) (*Edge, error)
}

MVCCVisibilityEngine is an optional extension interface for latest and snapshot-visible node and edge reads under the caller's context, which owns admission and the read's materialization.

type ManagedEntityEngine

type ManagedEntityEngine interface {
	Engine
	BeginTransaction(ctx context.Context, request BeginRequest) (*BadgerTransaction, error)
	InitializeStoredEntityObserver(string, func(StoredEntitySnapshot) (StoredEntityObserver, error), StoredEntityReadBoundary) error
	EntityCommitSubmitter
	ManagedEntityRuntimeRegistry
}

ManagedEntityEngine is the atomic publication capability required by managed database writes that enforce storage quotas, track exact bytes, or cross a journal/replication boundary. Writable database catalogs require native entity preparation and authoritative EntityCommitSubmitter receipts, even when graph quotas are unlimited. Managed graph writes additionally require this complete accounting/observation contract; a catalog-capable engine must not be treated as implicitly providing those graph capabilities.

A transparent EngineUnwrapper may expose these capabilities through its own backing engine. A wrapper with per-operation write policy additionally uses EntityWriteBoundary so staged writes retain that policy on the same store.

type ManagedEntityInitialize

type ManagedEntityInitialize func(context.Context) error

ManagedEntityInitialize completes existing lazy usage initialization before a native write acquires lifecycle/key authority. Read-only BEGIN never calls it.

type ManagedEntityPrepare

type ManagedEntityPrepare func(context.Context, []Operation, EntityCommitMode) (*PreparedEntityCommit, func(CommitOutcome), error)

ManagedEntityPrepare is the authoritative managed leader's prepare/admit capability. Its terminal callback settles the existing usage reservation. Preparation never submits or applies the durable command.

type ManagedEntityRuntimeRegistry

type ManagedEntityRuntimeRegistry interface {
	GetOrAttachManagedEntityRuntime(string, any) any
	RegisterManagedEntityPreparer(string, ManagedEntityPrepare, ManagedEntityInitialize)
	RetireManagedEntityRuntime(string)
}

ManagedEntityRuntimeRegistry keeps one usage/admission owner and its claimed preparation lifetime on the physical engine, shared by namespace views.

type ManagedEntityUsageResetter

type ManagedEntityUsageResetter interface {
	ResetManagedEntityUsage(ManagedEntityUsageTransition)
}

ManagedEntityUsageResetter is implemented by the canonical attached ledger. ResetManagedEntityUsage transitions usage after an empty reset or invalidates it after Restore, retaining policy and pending allowances. It must not enter storage/admission or dispatch listeners.

type ManagedEntityUsageTransition

type ManagedEntityUsageTransition uint8

ManagedEntityUsageTransition distinguishes a known empty graph from replacement by arbitrary restored contents. Both retain policy and accepted allowances.

const (
	ManagedEntityUsageEmpty ManagedEntityUsageTransition = iota
	ManagedEntityUsageRestored
)

type ManagedVectorReferences

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

ManagedVectorReferences carries validated WAL-local image references from a decoded transaction into accepted staging. Its zero value means full images. Callers cannot construct references to arbitrary storage state.

type ManualSuppressionEngine

type ManualSuppressionEngine interface {
	SetManualSuppression(ctx context.Context, kind StoredEntityKind, id string, suppressed bool) error
}

ManualSuppressionEngine hides and shows nodes and relationships on demand (kp.suppress / unsuppress, #1064).

type MemoryEngine

type MemoryEngine struct {
	*BadgerEngine
}

MemoryEngine is a thread-safe in-memory graph storage implementation. It wraps BadgerDB's in-memory mode for testing purposes.

Use Cases:

  • Unit testing (no disk I/O, fast cleanup)
  • Loading Neo4j exports into memory for analysis
  • Small datasets that fit entirely in RAM
  • Development and prototyping

Implementation Note:

MemoryEngine is a thin wrapper around BadgerEngine with InMemory=true.
This ensures tests use the exact same code path as production.

func NewMemoryEngine

func NewMemoryEngine() *MemoryEngine

NewMemoryEngine creates a new in-memory storage engine for testing. It uses BadgerDB's in-memory mode internally.

Example:

engine := storage.NewMemoryEngine()
defer engine.Close()

Note: For tests, prefer storage.NewTestEngine(t) which handles cleanup.

func NewMemoryEngineWithMVCCHistory added in v1.1.0

func NewMemoryEngineWithMVCCHistory() *MemoryEngine

NewMemoryEngineWithMVCCHistory creates an in-memory engine that retains historical MVCC versions. Use this for tests and callers that exercise the multi-version surface (temporal.asOf, time-travel reads, prior-version snapshots). The default NewMemoryEngine runs head-only, matching the production default.

func NewMemoryEngineWithOptions

func NewMemoryEngineWithOptions(opts BadgerOptions) (*MemoryEngine, error)

NewMemoryEngineWithOptions creates an in-memory storage engine with opts, such as the engine-wide policy (EngineOptions) and logger a database opens with; opts.InMemory is implied.

func RecoverFromWAL

func RecoverFromWAL(ctx context.Context, walDir, snapshotPath string) (*MemoryEngine, error)

RecoverFromWAL recovers database state from a snapshot and WAL. Returns a new MemoryEngine with the recovered state. Recovery retains ctx values but completes independently of its cancellation.

Uses a discard *slog.Logger for diagnostics. Callers wanting structured recovery visibility should use RecoverFromWALWithLogger.

func RecoverFromWALWithLogger added in v1.1.0

func RecoverFromWALWithLogger(ctx context.Context, walDir, snapshotPath string, logger *slog.Logger) (*MemoryEngine, error)

RecoverFromWALWithLogger is the slog-aware variant of RecoverFromWAL. Recovery retains ctx values but completes independently of its cancellation. D-07: pass a child logger tagged subsystem=wal_recovery so completion- with-errors records land in the structured stream. Operator-actionable fields: failed, errors, summary; per-error attributes seq, operation, error.

func (*MemoryEngine) Backup

func (m *MemoryEngine) Backup(path string) error

Backup delegates to the embedded Badger engine's consistent streaming backup.

func (*MemoryEngine) BeginTransaction

func (m *MemoryEngine) BeginTransaction(ctx context.Context, request BeginRequest) (*BadgerTransaction, error)

BeginTransaction starts a new transaction. Returns *BadgerTransaction for compatibility with the executor.

func (*MemoryEngine) DeleteByPrefix

func (m *MemoryEngine) DeleteByPrefix(prefix string) (nodesDeleted int64, edgesDeleted int64, err error)

DeleteByPrefix delegates to the underlying BadgerEngine.

func (*MemoryEngine) GetInnerEngine

func (m *MemoryEngine) GetInnerEngine() Engine

GetInnerEngine exposes the actual storage owner to canonical capability discovery, including query reveal scopes through namespaced decorators.

func (*MemoryEngine) Restore

func (m *MemoryEngine) Restore(path string) error

Restore delegates to the embedded Badger engine's streaming restore.

type MergeNodePreparer

type MergeNodePreparer interface {
	PrepareMergeNode(ctx context.Context, labels []string, props map[string]interface{}) error
	PrepareMergeNodeForWrite(ctx context.Context, labels []string, props map[string]interface{}) error
}

MergeNodePreparer is the capability of a transactional storage view that admits a MERGE node's unique keys before the MERGE looks the node up: the transaction itself, and the views that route a statement's writes to one. Callers discover it on the storage a statement runs against instead of asserting a concrete engine type, so every view that owns a transaction queues concurrent MERGEs of one key the same way.

type NamespaceEdgeTypeStatsProvider

type NamespaceEdgeTypeStatsProvider interface {
	EdgeCountByTypeInNamespace(ctx context.Context, namespace, edgeType string) (int64, error)
	EdgeCountByStartLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)
	EdgeCountByEndLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)
}

NamespaceEdgeTypeStatsProvider is an optional extension interface for namespace-scoped relationship-type counts (issue #638). Engines that keep per-(namespace, type) counters implement it; NamespacedEngine uses it to stay exact in multi-database deployments.

type NamespaceGraphMutationVersionProvider added in v1.3.3

type NamespaceGraphMutationVersionProvider interface {
	GraphMutationVersionInNamespace(namespace string) (version uint64, supported bool)
}

NamespaceGraphMutationVersionProvider reports graph revisions by database.

type NamespaceLabelStatsProvider added in v1.1.3

type NamespaceLabelStatsProvider interface {
	NodeCountByLabelInNamespace(ctx context.Context, namespace, label string) (int64, error)
}

NamespaceLabelStatsProvider is an optional extension interface for fast namespace-scoped label-cardinality lookups under the caller context.

type NamespaceLister

type NamespaceLister interface {
	ListNamespaces() []string
}

NamespaceLister is an optional extension interface that reports the known database namespaces stored in an engine.

Returned values are unqualified namespace names (e.g., "nornic", "db2"), not ID prefixes (e.g., "nornic:").

type NamespaceResetCallback

type NamespaceResetCallback func(prefix string)

NamespaceResetCallback reports that every node and relationship whose ID starts with prefix was removed at once (DeleteByPrefix), without a per-entity event.

type NamespaceResetNotifier

type NamespaceResetNotifier interface {
	OnNamespaceReset(callback NamespaceResetCallback)
}

NamespaceResetNotifier is implemented by engines that report DeleteByPrefix. Consumers that derive state from the stored entities (search indexes) drop that state for the namespace.

type NamespaceSchemaProvider

type NamespaceSchemaProvider interface {
	GetSchemaForNamespace(namespace string) *SchemaManager
}

NamespaceSchemaProvider is an optional extension interface that provides per-namespace schema.

This enables multi-database deployments to maintain isolated constraints/indexes per database, matching Neo4j’s per-database schema model.

type NamespaceTemporalCurrentNodeProvider

type NamespaceTemporalCurrentNodeProvider interface {
	IsCurrentTemporalNodeInNamespace(ctx context.Context, namespace string, node *Node, asOf time.Time) (bool, error)
}

NamespaceTemporalCurrentNodeProvider is an optional extension interface that evaluates current/live temporal versions within a namespace.

type NamespaceTemporalLookupProvider

type NamespaceTemporalLookupProvider interface {
	GetTemporalNodeAsOfInNamespace(ctx context.Context, namespace, label, keyProp string, keyValue interface{}, validFromProp, validToProp string, asOf time.Time) (*Node, error)
}

NamespaceTemporalLookupProvider is an optional extension interface that provides efficient temporal lookups scoped to a storage namespace.

type NamespacedEngine

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

NamespacedEngine wraps a storage engine with database namespace isolation. All node and edge IDs are automatically prefixed with the namespace.

This provides logical database separation within a single physical storage:

  • Keys are prefixed: "tenant_a:node:123" instead of "node:123"
  • Queries only see data in the current namespace
  • DROP DATABASE = delete all keys with prefix

Thread-safe: delegates to underlying engine's thread safety.

func NewNamespacedEngine

func NewNamespacedEngine(inner Engine, namespace string) *NamespacedEngine

NewNamespacedEngine creates a namespaced view of the storage engine.

Parameters:

  • inner: The underlying storage engine (shared across all namespaces)
  • namespace: The database name (e.g., "tenant_a", "nornic")

The namespace is used as a key prefix for all operations.

func (*NamespacedEngine) AddToPendingEmbeddings

func (n *NamespacedEngine) AddToPendingEmbeddings(nodeID NodeID)

AddToPendingEmbeddings adds a node back to the pending embeddings index (e.g. after a failed embed so it can be retried).

func (*NamespacedEngine) AllEdges

func (n *NamespacedEngine) AllEdges(ctx context.Context) ([]*Edge, error)

func (*NamespacedEngine) AllNodes

func (n *NamespacedEngine) AllNodes(ctx context.Context) ([]*Node, error)

func (*NamespacedEngine) Backup

func (n *NamespacedEngine) Backup(path string) error

Backup delegates to the wrapped storage engine while preserving the namespace view used by query execution. The native Badger backup contains the complete physical store, including system and user databases.

func (*NamespacedEngine) BatchGetNodes

func (n *NamespacedEngine) BatchGetNodes(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

func (*NamespacedEngine) BatchGetNodesWithoutEmbeddings added in v1.3.3

func (n *NamespacedEngine) BatchGetNodesWithoutEmbeddings(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

func (*NamespacedEngine) BatchGetNodesWithoutEmbeddingsSupported added in v1.3.3

func (n *NamespacedEngine) BatchGetNodesWithoutEmbeddingsSupported() bool

func (*NamespacedEngine) BulkCreateEdges

func (n *NamespacedEngine) BulkCreateEdges(ctx context.Context, edges []*Edge) error

func (*NamespacedEngine) BulkCreateNodes

func (n *NamespacedEngine) BulkCreateNodes(ctx context.Context, nodes []*Node) error

func (*NamespacedEngine) BulkDeleteEdges

func (n *NamespacedEngine) BulkDeleteEdges(ctx context.Context, ids []EdgeID) error

func (*NamespacedEngine) BulkDeleteNodes

func (n *NamespacedEngine) BulkDeleteNodes(ctx context.Context, ids []NodeID) error

func (*NamespacedEngine) Close

func (n *NamespacedEngine) Close() error

func (*NamespacedEngine) ConsumeCleanShutdownMarker

func (n *NamespacedEngine) ConsumeCleanShutdownMarker(ctx context.Context) (bool, error)

ConsumeCleanShutdownMarker forwards the engine-wide shutdown-marker read.

func (*NamespacedEngine) CountPendingEmbeddingIDs

func (n *NamespacedEngine) CountPendingEmbeddingIDs(ctx context.Context, accept func([]byte) bool) int

func (*NamespacedEngine) CreateEdge

func (n *NamespacedEngine) CreateEdge(ctx context.Context, edge *Edge) error

func (*NamespacedEngine) CreateNode

func (n *NamespacedEngine) CreateNode(ctx context.Context, node *Node) (NodeID, error)

func (*NamespacedEngine) DeleteByPrefix

func (n *NamespacedEngine) DeleteByPrefix(prefix string) (nodesDeleted int64, edgesDeleted int64, err error)

DeleteByPrefix is not supported for NamespacedEngine. Use the underlying engine's DeleteByPrefix with the namespace prefix instead.

func (*NamespacedEngine) DeleteEdge

func (n *NamespacedEngine) DeleteEdge(ctx context.Context, id EdgeID) error

func (*NamespacedEngine) DeleteNode

func (n *NamespacedEngine) DeleteNode(ctx context.Context, id NodeID) error

func (*NamespacedEngine) EdgeCount

func (n *NamespacedEngine) EdgeCount(ctx context.Context) (int64, error)

EdgeCount is NodeCount for relationships, on the same caller context.

func (*NamespacedEngine) EdgeCountByEndLabel

func (n *NamespacedEngine) EdgeCountByEndLabel(ctx context.Context, label, edgeType string) (int64, error)

EdgeCountByEndLabel returns the namespace-scoped count of edges of the given type whose physical end endpoint carries the label (issue #638).

func (*NamespacedEngine) EdgeCountByEndLabelInNamespace

func (n *NamespacedEngine) EdgeCountByEndLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)

EdgeCountByEndLabelInNamespace preserves the physical end-label counter.

func (*NamespacedEngine) EdgeCountByPrefix

func (n *NamespacedEngine) EdgeCountByPrefix(ctx context.Context, prefix string) (int64, error)

EdgeCountByPrefix counts edges in this namespace whose ID starts with prefix. The caller-supplied prefix is namespace-relative and the caller context owns admission of the counter read and of the materialized fallback scan.

func (*NamespacedEngine) EdgeCountByStartLabel

func (n *NamespacedEngine) EdgeCountByStartLabel(ctx context.Context, label, edgeType string) (int64, error)

EdgeCountByStartLabel returns the namespace-scoped count of edges of the given type whose physical start endpoint carries the label (issue #638).

func (*NamespacedEngine) EdgeCountByStartLabelInNamespace

func (n *NamespacedEngine) EdgeCountByStartLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)

EdgeCountByStartLabelInNamespace preserves the physical start-label counter.

func (*NamespacedEngine) EdgeCountByType

func (n *NamespacedEngine) EdgeCountByType(ctx context.Context, edgeType string) (int64, error)

EdgeCountByType returns the namespace-scoped count of edges of the given type. It is answered by the inner engine's persisted per-type counters (issue #638), preserving the database namespace through decorators.

func (*NamespacedEngine) EdgeCountByTypeInNamespace

func (n *NamespacedEngine) EdgeCountByTypeInNamespace(ctx context.Context, namespace, edgeType string) (int64, error)

EdgeCountByTypeInNamespace preserves the namespace relationship counter.

func (*NamespacedEngine) EdgeWriteInput

func (n *NamespacedEngine) EdgeWriteInput(ctx context.Context, edge *Edge) (*Edge, error)

EdgeWriteInput qualifies the relationship and both endpoint IDs using the same namespace rule as ordinary writes; "other:id" remains an ID within the current namespace, rather than silently becoming a cross-database request.

func (*NamespacedEngine) EventNotificationsSettled

func (n *NamespacedEngine) EventNotificationsSettled() bool

EventNotificationsSettled forwards the existing publisher's metadata.

func (*NamespacedEngine) FindNodeNeedingEmbedding

func (n *NamespacedEngine) FindNodeNeedingEmbedding(ctx context.Context) (*Node, error)

FindNodeNeedingEmbedding finds a node that needs embedding, but only from this namespace. It only looks for nodes with the current namespace prefix - all IDs must be prefixed.

func (*NamespacedEngine) ForEachNodeIDByLabel

func (n *NamespacedEngine) ForEachNodeIDByLabel(ctx context.Context, label string, visit func(NodeID) bool) error

ForEachNodeIDByLabel streams node IDs for a label, filtered to the namespace. Stops early when visit returns false.

func (*NamespacedEngine) GetEdge

func (n *NamespacedEngine) GetEdge(ctx context.Context, id EdgeID) (*Edge, error)

func (*NamespacedEngine) GetEdgeBetween

func (n *NamespacedEngine) GetEdgeBetween(ctx context.Context, startID, endID NodeID, edgeType string) (*Edge, error)

func (*NamespacedEngine) GetEdgeCurrentHead

func (n *NamespacedEngine) GetEdgeCurrentHead(ctx context.Context, id EdgeID) (MVCCHead, error)

GetEdgeCurrentHead resolves edge head metadata within the namespace.

func (*NamespacedEngine) GetEdgeLatestEffective

func (n *NamespacedEngine) GetEdgeLatestEffective(ctx context.Context, id EdgeID) (*Edge, error)

GetEdgeLatestEffective resolves the latest-effective edge within the namespace, delegating to the wrapped engine when it supports the MVCCLatestEffectiveEngine capability.

func (*NamespacedEngine) GetEdgeLatestVisible

func (n *NamespacedEngine) GetEdgeLatestVisible(ctx context.Context, id EdgeID) (*Edge, error)

GetEdgeLatestVisible resolves the latest visible edge within the namespace.

func (*NamespacedEngine) GetEdgeVisibleAt

func (n *NamespacedEngine) GetEdgeVisibleAt(ctx context.Context, id EdgeID, version MVCCVersion) (*Edge, error)

GetEdgeVisibleAt resolves a snapshot-visible edge within the namespace.

func (*NamespacedEngine) GetEdgesByType

func (n *NamespacedEngine) GetEdgesByType(ctx context.Context, edgeType string) ([]*Edge, error)

func (*NamespacedEngine) GetEdgesByTypeVisibleAt

func (n *NamespacedEngine) GetEdgesByTypeVisibleAt(ctx context.Context, edgeType string, version MVCCVersion) ([]*Edge, error)

GetEdgesByTypeVisibleAt resolves snapshot-visible edge-type queries within the namespace.

func (*NamespacedEngine) GetFirstNodeByLabel

func (n *NamespacedEngine) GetFirstNodeByLabel(ctx context.Context, label string) (*Node, error)

func (*NamespacedEngine) GetInDegree

func (n *NamespacedEngine) GetInDegree(ctx context.Context, nodeID NodeID) (int, error)

func (*NamespacedEngine) GetInnerEngine

func (n *NamespacedEngine) GetInnerEngine() Engine

GetInnerEngine returns the underlying storage engine (unwraps the namespace). This is used by DatabaseManager to create NamespacedEngines for other databases.

func (*NamespacedEngine) GetNode

func (n *NamespacedEngine) GetNode(ctx context.Context, id NodeID) (*Node, error)

func (*NamespacedEngine) GetNodeCurrentHead

func (n *NamespacedEngine) GetNodeCurrentHead(ctx context.Context, id NodeID) (MVCCHead, error)

GetNodeCurrentHead resolves node head metadata within the namespace.

func (*NamespacedEngine) GetNodeEmbeddingMeta

func (n *NamespacedEngine) GetNodeEmbeddingMeta(ctx context.Context, id NodeID) (map[string]any, error)

GetNodeEmbeddingMeta reads the metadata of the node's namespaced ID.

func (*NamespacedEngine) GetNodeLatestEffective

func (n *NamespacedEngine) GetNodeLatestEffective(ctx context.Context, id NodeID) (*Node, error)

GetNodeLatestEffective resolves the latest-effective node within the namespace, delegating to the wrapped engine when it supports the MVCCLatestEffectiveEngine capability.

func (*NamespacedEngine) GetNodeLatestVisible

func (n *NamespacedEngine) GetNodeLatestVisible(ctx context.Context, id NodeID) (*Node, error)

GetNodeLatestVisible resolves the latest visible node within the namespace.

func (*NamespacedEngine) GetNodeProjected added in v1.1.8

func (n *NamespacedEngine) GetNodeProjected(ctx context.Context, id NodeID, properties []string) (*Node, error)

func (*NamespacedEngine) GetNodeVisibleAt

func (n *NamespacedEngine) GetNodeVisibleAt(ctx context.Context, id NodeID, version MVCCVersion) (*Node, error)

GetNodeVisibleAt resolves a snapshot-visible node within the namespace.

func (*NamespacedEngine) GetNodeWithoutEmbeddings added in v1.3.3

func (n *NamespacedEngine) GetNodeWithoutEmbeddings(ctx context.Context, id NodeID) (*Node, error)

func (*NamespacedEngine) GetNodesByLabel

func (n *NamespacedEngine) GetNodesByLabel(ctx context.Context, label string) ([]*Node, error)

func (*NamespacedEngine) GetNodesByLabelVisibleAt

func (n *NamespacedEngine) GetNodesByLabelVisibleAt(ctx context.Context, label string, version MVCCVersion) ([]*Node, error)

GetNodesByLabelVisibleAt resolves snapshot-visible label queries within the namespace.

func (*NamespacedEngine) GetOutDegree

func (n *NamespacedEngine) GetOutDegree(ctx context.Context, nodeID NodeID) (int, error)

func (*NamespacedEngine) GetQueryNode

func (n *NamespacedEngine) GetQueryNode(ctx context.Context, id NodeID) (*Node, error)

GetQueryNode forwards the query-row node read (QueryNodeReader) with the namespace prefix applied, else reads the full node.

func (*NamespacedEngine) GetSchema

func (n *NamespacedEngine) GetSchema() *SchemaManager

func (*NamespacedEngine) GetSchemaForNamespace

func (n *NamespacedEngine) GetSchemaForNamespace(namespace string) *SchemaManager

GetSchemaForNamespace forwards the per-namespace schema lookup.

func (*NamespacedEngine) GetStoredEdge

func (n *NamespacedEngine) GetStoredEdge(ctx context.Context, id EdgeID) (*Edge, error)

GetStoredEdge is GetEdge's stored read (StoredEntityReader).

func (*NamespacedEngine) GetStoredNode

func (n *NamespacedEngine) GetStoredNode(ctx context.Context, id NodeID) (*Node, error)

GetStoredNode is GetNode's stored read (StoredEntityReader).

func (*NamespacedEngine) GetStoredNodesByLabel

func (n *NamespacedEngine) GetStoredNodesByLabel(ctx context.Context, label string) ([]*Node, error)

GetStoredNodesByLabel is GetNodesByLabel's stored read (StoredEntityReader).

func (*NamespacedEngine) GetTemporalNodeAsOf

func (n *NamespacedEngine) GetTemporalNodeAsOf(ctx context.Context, label, keyProp string, keyValue interface{}, validFromProp, validToProp string, asOf time.Time) (*Node, error)

GetTemporalNodeAsOf performs an efficient temporal lookup when the inner engine supports it.

func (*NamespacedEngine) GraphMutationVersion added in v1.3.3

func (n *NamespacedEngine) GraphMutationVersion() (uint64, bool)

GraphMutationVersion reports mutations visible through this namespace.

func (*NamespacedEngine) GraphMutationVersionInNamespace added in v1.3.3

func (n *NamespacedEngine) GraphMutationVersionInNamespace(string) (uint64, bool)

GraphMutationVersionInNamespace keeps nested views scoped to their database.

func (*NamespacedEngine) IndexSourceStamp

func (n *NamespacedEngine) IndexSourceStamp(ctx context.Context) (string, error)

IndexSourceStamp preserves the same namespace composition as capture.

func (*NamespacedEngine) IsCurrentTemporalNode

func (n *NamespacedEngine) IsCurrentTemporalNode(ctx context.Context, node *Node, asOf time.Time) (bool, error)

IsCurrentTemporalNode reports whether node is the current/live temporal version.

func (*NamespacedEngine) IterateNodes

func (n *NamespacedEngine) IterateNodes(fn func(*Node) bool) error

IterateNodes streams this namespace's nodes with namespace prefixes stripped. Engines without IterateNodes fall back to a filtered AllNodes scan so the capability still works over simpler inner engines.

func (*NamespacedEngine) LastWriteTime

func (n *NamespacedEngine) LastWriteTime() time.Time

LastWriteTime returns the last known write time from the underlying engine, if available.

func (*NamespacedEngine) LifecycleStatus

func (n *NamespacedEngine) LifecycleStatus() map[string]interface{}

LifecycleStatus delegates lifecycle status when supported.

func (*NamespacedEngine) ListNamespaces

func (n *NamespacedEngine) ListNamespaces() []string

ListNamespaces reports the database namespaces of the underlying engine. Inner engines without the capability still report this view's namespace.

func (*NamespacedEngine) LookupEdgesByPropertyEquality

func (n *NamespacedEngine) LookupEdgesByPropertyEquality(ctx context.Context, relationshipType string, properties []string, values []interface{}) ([]*Edge, bool, error)

LookupEdgesByPropertyEquality answers a relationship-property equality match within the namespace from the relationship equality index its constraint owns (RelationshipPropertyEqualityLookup). IDs carry the namespace prefix inside the engine and are the user's IDs outside it, as every other namespaced read.

func (*NamespacedEngine) MarkCleanShutdown

func (n *NamespacedEngine) MarkCleanShutdown(ctx context.Context) error

MarkCleanShutdown forwards the engine-wide shutdown-marker write.

func (*NamespacedEngine) MarkNodeEmbedded

func (n *NamespacedEngine) MarkNodeEmbedded(nodeID NodeID)

MarkNodeEmbedded marks a node as embedded (removes from pending index). The node ID should be unprefixed (without namespace).

func (*NamespacedEngine) MatchEdgesBetween

func (n *NamespacedEngine) MatchEdgesBetween(ctx context.Context, startID, endID NodeID, edgeType string, properties []string, match func(*Edge) bool, policy EdgeMatchReadPolicy) ([]*Edge, error)

MatchEdgesBetween matches the engine's edges with this namespace's IDs.

func (*NamespacedEngine) Namespace

func (n *NamespacedEngine) Namespace() string

Namespace returns the current database namespace.

func (*NamespacedEngine) NodeCount

func (n *NamespacedEngine) NodeCount(ctx context.Context) (int64, error)

NodeCount counts this namespace under the caller's context, which owns admission of the prefix counter, the streamed count and the materialized fallback scan. A canceled request gets its own context error, never a total.

func (*NamespacedEngine) NodeCountByLabel added in v1.1.3

func (n *NamespacedEngine) NodeCountByLabel(ctx context.Context, label string) (int64, error)

NodeCountByLabel counts this namespace with the caller-owned metadata or scan path.

func (*NamespacedEngine) NodeCountByLabelInNamespace

func (n *NamespacedEngine) NodeCountByLabelInNamespace(ctx context.Context, namespace, label string) (int64, error)

NodeCountByLabelInNamespace forwards the namespace-scoped label count.

func (*NamespacedEngine) NodeCountByPrefix

func (n *NamespacedEngine) NodeCountByPrefix(ctx context.Context, prefix string) (int64, error)

NodeCountByPrefix counts nodes in this namespace whose ID starts with prefix. The caller-supplied prefix is namespace-relative and the caller context owns admission of the counter read and of the materialized fallback scan.

func (*NamespacedEngine) NodeWriteInput

func (n *NamespacedEngine) NodeWriteInput(ctx context.Context, node *Node) (*Node, error)

NodeWriteInput owns namespace qualification and token registration for both ordinary writes and their prepared transaction path. The caller retains its input; for example a tenant wrapper maps node "n" to "tenant:n".

func (*NamespacedEngine) OnEdgeCreated

func (n *NamespacedEngine) OnEdgeCreated(callback EdgeEventCallback)

func (*NamespacedEngine) OnEdgeDeleted

func (n *NamespacedEngine) OnEdgeDeleted(callback EdgeDeleteCallback)

func (*NamespacedEngine) OnEdgeUpdated

func (n *NamespacedEngine) OnEdgeUpdated(callback EdgeEventCallback)

func (*NamespacedEngine) OnNodeCreated

func (n *NamespacedEngine) OnNodeCreated(callback NodeEventCallback)

Event-callback registration with namespace translation: callbacks only fire for this namespace's entities and receive namespace-stripped IDs.

func (*NamespacedEngine) OnNodeDeleted

func (n *NamespacedEngine) OnNodeDeleted(callback NodeDeleteCallback)

func (*NamespacedEngine) OnNodeUpdated

func (n *NamespacedEngine) OnNodeUpdated(callback NodeEventCallback)

func (*NamespacedEngine) OpenReadSnapshot

func (n *NamespacedEngine) OpenReadSnapshot(ctx context.Context) (ReadSnapshotView, error)

OpenReadSnapshot opens the inner engine's snapshot and scopes it to this namespace, translating IDs as IterateNodes and StreamEdges do.

func (*NamespacedEngine) PauseLifecycle

func (n *NamespacedEngine) PauseLifecycle()

PauseLifecycle delegates lifecycle pause when supported.

func (*NamespacedEngine) PendingEmbeddingsCount

func (n *NamespacedEngine) PendingEmbeddingsCount() int

PendingEmbeddingsCount forwards the pending embedding work-item count.

func (*NamespacedEngine) PrefixEdgeID

func (n *NamespacedEngine) PrefixEdgeID(id EdgeID) EdgeID

PrefixEdgeID adds namespace prefix to an edge ID.

func (*NamespacedEngine) PrefixNodeID

func (n *NamespacedEngine) PrefixNodeID(id NodeID) NodeID

PrefixNodeID adds namespace prefix to a node ID. "123" → "tenant_a:123"

func (*NamespacedEngine) PropertyKeyKnown

func (n *NamespacedEngine) PropertyKeyKnown(name string) bool

PropertyKeyKnown reports whether a write in this view's database has stored a value under name (PropertyKeyLookup): false when the inner engine keeps no PropertyKeyRegistry.

func (*NamespacedEngine) PruneMVCCVersions

func (n *NamespacedEngine) PruneMVCCVersions(ctx context.Context, opts MVCCPruneOptions) (int64, error)

PruneMVCCVersions forwards MVCC housekeeping to the underlying engine.

func (*NamespacedEngine) PruneTemporalHistory

func (n *NamespacedEngine) PruneTemporalHistory(ctx context.Context, opts TemporalPruneOptions) (int64, error)

PruneTemporalHistory forwards temporal-index housekeeping.

func (*NamespacedEngine) QualifyOperation

func (n *NamespacedEngine) QualifyOperation(ctx context.Context, op *Operation) error

QualifyOperation qualifies one prepared entity operation in place exactly as the direct Engine methods qualify their input: nodes with NodeWriteInput, relationships with EdgeWriteInput, a relationship update together with its observation (edgeUpdateInput, shared with UpdateEdge), and delete IDs. It changes only those identity fields. The managed and routed preparation paths use it instead of their own copies. For example, in namespace "tenant" an update of a->b observed as a->b becomes tenant:a->tenant:b in both images.

func (*NamespacedEngine) ReadAdjacentEdges

func (n *NamespacedEngine) ReadAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadAdjacentEdges answers one adjacent-edge request in this namespace: the request's IDs are qualified once, the inner engine reads, and the result is projected back into the caller's ID space.

func (*NamespacedEngine) ReadAdjacentEdgesVisibleAt

func (n *NamespacedEngine) ReadAdjacentEdgesVisibleAt(ctx context.Context, request AdjacentEdgeRead, version MVCCVersion) ([]*Edge, error)

ReadAdjacentEdgesVisibleAt resolves one snapshot-visible adjacent-edge request within the namespace.

func (*NamespacedEngine) ReadCountStore

func (n *NamespacedEngine) ReadCountStore(ctx context.Context, request CountStoreReadRequest) (CountStoreRead, error)

ReadCountStore answers a count-store read for this namespace: the inner engine's counters and visibility read one consistent view, with this namespace as the counted scope, so the answer describes this database's rows.

func (*NamespacedEngine) ReadPendingEmbeddingCount

func (n *NamespacedEngine) ReadPendingEmbeddingCount(ctx context.Context, accept func([]byte) bool) (int, error)

ReadPendingEmbeddingCount counts pending work in this database.

func (*NamespacedEngine) ReadStoredAdjacentEdges

func (n *NamespacedEngine) ReadStoredAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadStoredAdjacentEdges is ReadAdjacentEdges' stored read (StoredEntityReader).

func (*NamespacedEngine) RebuildMVCCHeads

func (n *NamespacedEngine) RebuildMVCCHeads(ctx context.Context) error

RebuildMVCCHeads forwards the MVCC head rebuild.

func (*NamespacedEngine) RebuildTemporalIndexes

func (n *NamespacedEngine) RebuildTemporalIndexes(ctx context.Context) error

RebuildTemporalIndexes forwards the temporal-index rebuild.

func (*NamespacedEngine) RecordMaterializedAccess added in v1.1.0

func (n *NamespacedEngine) RecordMaterializedAccess(entityID string)

RecordMaterializedAccess records a result-materialization access against the fully qualified entity ID in the underlying engine.

func (*NamespacedEngine) RefreshPendingEmbeddingsIndex

func (n *NamespacedEngine) RefreshPendingEmbeddingsIndex() int

RefreshPendingEmbeddingsIndex refreshes the pending embeddings index across the underlying engine and includes staged nodes in this namespace.

func (*NamespacedEngine) RegisterSnapshotReader

func (n *NamespacedEngine) RegisterSnapshotReader(info SnapshotReaderInfo) func()

RegisterSnapshotReader registers a reader scoped to the namespace when supported.

func (*NamespacedEngine) RelationshipEndpointVisible

func (n *NamespacedEngine) RelationshipEndpointVisible(id NodeID) (visible, answered bool)

RelationshipEndpointVisible forwards with the namespace prefix applied.

func (*NamespacedEngine) Restore

func (n *NamespacedEngine) Restore(path string) error

Restore delegates native restore to the wrapped storage engine.

func (*NamespacedEngine) ResumeLifecycle

func (n *NamespacedEngine) ResumeLifecycle()

ResumeLifecycle delegates lifecycle resume when supported.

func (*NamespacedEngine) SetLifecycleSchedule

func (n *NamespacedEngine) SetLifecycleSchedule(interval time.Duration) error

SetLifecycleSchedule delegates lifecycle cadence updates when supported.

func (*NamespacedEngine) SetManualSuppression

func (n *NamespacedEngine) SetManualSuppression(ctx context.Context, kind StoredEntityKind, id string, suppressed bool) error

SetManualSuppression hides or shows an entity within this namespace under the caller's operation lifetime.

func (*NamespacedEngine) StreamEdges

func (n *NamespacedEngine) StreamEdges(ctx context.Context, fn func(edge *Edge) error) error

StreamEdges streams edges in the namespace.

func (*NamespacedEngine) StreamEdgesByType

func (n *NamespacedEngine) StreamEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamEdgesByType streams this namespace's edges of edgeType with user-facing (unprefixed) IDs. The inner stream is scoped to the namespace, so other databases' edges are skipped before they are decoded.

func (*NamespacedEngine) StreamNodeChunks

func (n *NamespacedEngine) StreamNodeChunks(ctx context.Context, chunkSize int, fn func(nodes []*Node) error) error

StreamNodeChunks streams nodes in chunks.

func (*NamespacedEngine) StreamNodes

func (n *NamespacedEngine) StreamNodes(ctx context.Context, fn func(node *Node) error) error

func (*NamespacedEngine) StreamNodesByLabelProjected added in v1.3.2

func (n *NamespacedEngine) StreamNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error

StreamNodesByLabelProjected iterates projected label matches in this namespace.

func (*NamespacedEngine) StreamNodesByPrefix added in v1.3.3

func (n *NamespacedEngine) StreamNodesByPrefix(ctx context.Context, prefix string, fn func(node *Node) error) error

StreamNodesByPrefix streams nodes in the namespace whose user-visible IDs start with prefix.

func (*NamespacedEngine) StreamNodesByPrefixProjected added in v1.3.3

func (n *NamespacedEngine) StreamNodesByPrefixProjected(ctx context.Context, prefix string, properties []string, fn func(node *Node) error) error

StreamNodesByPrefixProjected streams nodes in the namespace whose user-visible IDs start with prefix while decoding only requested properties when the wrapped engine supports projected prefix scans.

func (*NamespacedEngine) StreamNodesByPrefixWithoutEmbeddings

func (n *NamespacedEngine) StreamNodesByPrefixWithoutEmbeddings(ctx context.Context, prefix string, fn func(node *Node) error) error

StreamNodesByPrefixWithoutEmbeddings streams lightweight nodes in this namespace and returns user-visible IDs.

func (*NamespacedEngine) StreamNodesWithOptions

func (n *NamespacedEngine) StreamNodesWithOptions(ctx context.Context, opts StreamNodesOptions, fn func(node *Node) error) error

StreamNodes streams nodes in the namespace. StreamNodesWithOptions streams this namespace's nodes with the options-driven kernel. The caller-supplied prefix is namespace-relative; the physical scan carries the namespace prefix so results stay inside this view. The kernel is part of the Engine contract, so the delegation is direct.

func (*NamespacedEngine) StreamNodesWithoutEmbeddings

func (n *NamespacedEngine) StreamNodesWithoutEmbeddings(ctx context.Context, fn func(node *Node) error) error

StreamNodesWithoutEmbeddings streams complete lightweight nodes in this namespace while preserving user-visible IDs.

func (*NamespacedEngine) StreamParkedEmbeddingFailures

func (n *NamespacedEngine) StreamParkedEmbeddingFailures(ctx context.Context, visit func(nodeID NodeID, meta map[string]any) error) (int, error)

StreamParkedEmbeddingFailures streams this namespace's sidecar failure records with namespace-stripped IDs.

func (*NamespacedEngine) StreamStoredEdgesByType

func (n *NamespacedEngine) StreamStoredEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamStoredEdgesByType is StreamEdgesByType's stored read (StoredEntityReader).

func (*NamespacedEngine) StreamStoredNodesByLabelProjected

func (n *NamespacedEngine) StreamStoredNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error

StreamStoredNodesByLabelProjected is StreamNodesByLabelProjected's stored read (StoredEntityReader).

func (*NamespacedEngine) SubscribeEvents

func (n *NamespacedEngine) SubscribeEvents(handlers EventHandlers) error

SubscribeEvents forwards this namespace's events with namespace-stripped IDs. A reset covering the whole namespace is reported with an empty prefix; one inside it, with the prefix stripped; one elsewhere, not at all.

func (*NamespacedEngine) TopLifecycleDebtKeys

func (n *NamespacedEngine) TopLifecycleDebtKeys(limit int) []MVCCLifecycleDebtKey

TopLifecycleDebtKeys delegates lifecycle debt inspection when supported.

func (*NamespacedEngine) TriggerPruneNow

func (n *NamespacedEngine) TriggerPruneNow(ctx context.Context) error

TriggerPruneNow delegates lifecycle prune-now when supported.

func (*NamespacedEngine) UpdateEdge

func (n *NamespacedEngine) UpdateEdge(ctx context.Context, updateRequest EdgeUpdateRequest) error

func (*NamespacedEngine) UpdateNode

func (n *NamespacedEngine) UpdateNode(ctx context.Context, updateRequest NodeUpdateRequest) error

func (*NamespacedEngine) UpdateNodeEmbeddingSidecar

func (n *NamespacedEngine) UpdateNodeEmbeddingSidecar(ctx context.Context, node *Node) error

UpdateNodeEmbeddingSidecar writes managed embedding state in the dedicated embedding key space without touching the node record. Every production inner engine implements EmbeddingSidecarUpdater (compile-time asserted); anything else is reported as an error rather than silently degraded.

type NativeBackupStreamer

type NativeBackupStreamer interface {
	BackupTo(context.Context, io.Writer) error
}

NativeBackupStreamer writes a complete native storage snapshot.

type Neo4jExport

type Neo4jExport struct {
	Nodes         []Neo4jNode         `json:"nodes"`
	Relationships []Neo4jRelationship `json:"relationships"`
}

Neo4jExport represents the Neo4j JSON export format. This is compatible with `neo4j-admin database dump` JSON output.

func ToNeo4jExport

func ToNeo4jExport(nodes []*Node, edges []*Edge) *Neo4jExport

ToNeo4jExport converts NornicDB nodes and edges to Neo4j JSON export format.

This function prepares data for export that can be imported into Neo4j using neo4j-admin or APOC procedures. NornicDB-specific fields (decay score, embeddings, access counts) are stored with "_" prefix to mark them as system properties.

The output is compatible with:

  • `neo4j-admin database import`
  • `CALL apoc.import.json()`
  • Standard Neo4j JSON format

Example:

// Get all data
nodes, _ := engine.GetNodesByLabel("") // All nodes
edges, _ := engine.AllEdges()

// Convert to Neo4j format
export := storage.ToNeo4jExport(nodes, edges)

// Save as JSON
data, _ := valueconvert.PropertyJSON.MarshalIndent(export, "", "  ")
err := os.WriteFile("neo4j-export.json", data, 0644)

// Import into Neo4j
// $ neo4j-admin database import --nodes=neo4j-export.json full
// Or in Cypher:
// CALL apoc.import.json("file:///neo4j-export.json")

NornicDB extensions are preserved as properties:

_decayScore, _lastAccessed, _accessCount, _confidence, _autoGenerated

type Neo4jNode

type Neo4jNode struct {
	ID         string         `json:"id"`
	Labels     []string       `json:"labels"`
	Properties map[string]any `json:"properties"`
}

Neo4jNode is the Neo4j JSON export format for nodes.

type Neo4jNodeRef

type Neo4jNodeRef struct {
	ID     string   `json:"id"`
	Labels []string `json:"labels,omitempty"`
}

Neo4jNodeRef is a reference to a node in Neo4j relationship format.

type Neo4jRelationship

type Neo4jRelationship struct {
	ID         string         `json:"id"`
	Type       string         `json:"type"`
	Properties map[string]any `json:"properties"`

	// Flat format (neo4j-admin dump)
	StartNode string `json:"startNode,omitempty"`
	EndNode   string `json:"endNode,omitempty"`

	// APOC format (apoc.export.json)
	Start Neo4jNodeRef `json:"start,omitempty"`
	End   Neo4jNodeRef `json:"end,omitempty"`
}

Neo4jRelationship is the Neo4j JSON export format for relationships. Supports both flat format (startNode/endNode strings) and APOC format (start/end objects).

func (*Neo4jRelationship) GetEndID

func (r *Neo4jRelationship) GetEndID() string

GetEndID returns the end node ID regardless of format.

func (*Neo4jRelationship) GetStartID

func (r *Neo4jRelationship) GetStartID() string

GetStartID returns the start node ID supporting both Neo4j export formats.

Neo4j exports can use two formats:

  1. Flat format: startNode/endNode as strings (neo4j-admin dump)
  2. APOC format: start/end as objects (apoc.export.json)

This method abstracts the difference, always returning the start node ID.

Example:

// Flat format
rel := &Neo4jRelationship{
	StartNode: "user-123",
}
// rel.GetStartID() returns "user-123"

// APOC format
rel = &Neo4jRelationship{
	Start: Neo4jNodeRef{ID: "user-456"},
}
// rel.GetStartID() returns "user-456"

type Node

type Node struct {
	ID         NodeID         `json:"id"`
	Labels     []string       `json:"labels"`
	Properties map[string]any `json:"properties"`

	// NornicDB extensions
	CreatedAt       time.Time            `json:"-"`
	UpdatedAt       time.Time            `json:"-"`
	NamedEmbeddings map[string][]float32 `json:"-"` // Named vector embeddings (e.g., "title", "content", "default")
	ChunkEmbeddings [][]float32          `json:"-"` // Chunked embeddings for long documents (legacy, migration support)

	// Embedding metadata (separate from user Properties to avoid namespace pollution)
	// Keys: embedding_model, embedding_dimensions, has_embedding, embedded_at, has_chunks, chunk_count
	EmbedMeta map[string]any `json:"-"`
	// contains filtered or unexported fields
}

Node represents a graph node (vertex) in the labeled property graph.

Nodes follow the Neo4j data model with NornicDB-specific extensions for memory decay, semantic search, and access tracking. Nodes are the fundamental entities in the graph and can represent people, documents, concepts, or any other entity in your domain.

Core Neo4j Fields:

  • ID: Unique identifier (must be unique across all nodes)
  • Labels: Type tags like ["Person", "User"] (Neo4j :Person:User)
  • Properties: Key-value data (any JSON-serializable types) See docs/user-guides/property-data-types.md for complete type reference

NornicDB Extensions (not exported to Neo4j):

  • CreatedAt: When the node was first created
  • UpdatedAt: Last modification timestamp
  • NamedEmbeddings: Named vector embeddings (e.g., "title", "content", "default")
  • ChunkEmbeddings: Chunked embeddings for long documents (legacy, migration support)

Decay scoring is handled by the knowledge-layer scoring system (pkg/knowledgepolicy). Scores are computed at query time from AccessMeta and retention bindings, not stored on the node.

Example 1 - Basic User Node:

node := &storage.Node{
	ID:     storage.NodeID("user-alice"),
	Labels: []string{"Person", "User"},
	Properties: map[string]any{
		"name":     "Alice Johnson",
		"age":      30,
		"email":    "alice@example.com",
		"verified": true,
	},
	CreatedAt: time.Now(),
}
engine.CreateNode(node)

Example 2 - Document Node with Metadata:

doc := &storage.Node{
	ID:     storage.NodeID("doc-readme"),
	Labels: []string{"Document", "Markdown"},
	Properties: map[string]any{
		"title":    "README.md",
		"content":  "# Welcome to...",
		"path":     "./README.md",
		"size":     4096,
		"language": "markdown",
	},
	CreatedAt: time.Now(),
	Embedding: generateEmbedding("# Welcome to..."), // For semantic search
}

Example 3 - Concept Node for Knowledge Graph:

concept := &storage.Node{
	ID:     storage.NodeID("concept-database"),
	Labels: []string{"Concept", "Technology"},
	Properties: map[string]any{
		"name":        "Database Systems",
		"definition":  "Systems for storing and retrieving data",
		"category":    "Software",
		"importance":  "high",
	},
	CreatedAt: time.Now(),
}

ELI12:

Think of a Node like a character card in a trading card game:

  • ID: The card's unique number (no two cards have the same)
  • Labels: The types on the card (["Hero", "Warrior"])
  • Properties: Stats on the card (name: "Alice", strength: 10, health: 100)

NornicDB adds extra info:

  • Embedding: A secret code that helps find similar cards
  • Decay scoring: How "fresh" the card is — computed automatically by knowledge-layer policies

Just like trading cards can be rare or common, frequently used or forgotten, Nodes track their usage and importance in the graph!

Neo4j Compatibility:

  • Labels map to Neo4j labels (e.g., :Person:User)
  • Properties map to Neo4j properties
  • ID must be unique across all nodes
  • Extensions stored with "_" prefix in Neo4j exports

Thread Safety:

Node structs are NOT thread-safe. The storage engine handles concurrency.

func CollectStoredNodes

func CollectStoredNodes(ctx context.Context, engine Engine) ([]*Node, error)

CollectStoredNodes returns every stored node of engine, its separately stored embeddings included, for a backup, snapshot or export: the ones the visibility layer hides are stored data too (StreamStoredNodes).

func CopyNode

func CopyNode(node *Node) *Node

CopyNode is the exported version of copyNode for use by other packages.

func DecodeNodePayload

func DecodeNodePayload(data []byte) (*Node, error)

DecodeNodePayload restores a node image from the current replication format. The decoded image is the node itself; no field-by-field copy is made.

func FindNodeNeedingEmbedding

func FindNodeNeedingEmbedding(ctx context.Context, engine Engine) (*Node, error)

FindNodeNeedingEmbedding finds a single node that needs embedding. This is more efficient than AllNodes() as it stops after finding one.

func FirstNodeResult

func FirstNodeResult(nodes []*Node, err error) (*Node, error)

FirstNodeResult selects the first already filtered node from a label lookup. An empty successful selection has the same result as a missing node.

func GetNodeProjectedThrough

func GetNodeProjectedThrough(ctx context.Context, engine Engine, id NodeID, properties []string) (*Node, error)

GetNodeProjectedThrough reads a projected node through a single engine: a projection-capable reader serves the read directly, and any other engine serves a full read that is projected on the way out. Async, WAL and the composite constituent scan share this tail, so reader preference and error propagation cannot drift between wrappers.

func GetStoredNode

func GetStoredNode(ctx context.Context, engine Engine, id NodeID) (*Node, error)

GetStoredNode reads node id for integrity work: the stored node when engine can read hidden entities (StoredReader), else engine.GetNode.

func GetStoredNodesByLabel

func GetStoredNodesByLabel(ctx context.Context, engine Engine, label string) ([]*Node, error)

GetStoredNodesByLabel is GetStoredNode for a label's nodes.

func SnapshotNodeForEmbedding

func SnapshotNodeForEmbedding(ctx context.Context, node *Node) (*Node, error)

SnapshotNodeForEmbedding binds a body and its revision in one read. Ordinary reads keep their existing write-cache fast path; only an embedding claim needs to acquire a revision when that cache came from a body write. Copies and namespace decorators preserve the private reader provenance. The fallback read runs under ctx, the same lifetime as the read that produced node, so it cannot outlive a cancelled operation.

func (*Node) CopyEmbeddingIdentityFrom

func (node *Node) CopyEmbeddingIdentityFrom(source *Node)

CopyEmbeddingIdentityFrom preserves runtime provenance across detached worker copies, just as storage's node copies do, without creating persisted fields. Only the identity fields are replaced: this image's metadata stays its own.

func (*Node) DecodeMsgpack

func (node *Node) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack reads the unchanged stored node map, including historical maps with absent flags or extra fields. Existing runtime identity is not decoded.

func (*Node) ElementID

func (n *Node) ElementID(fallback string) string

ElementID uses source provenance, falling back only for unscoped values.

func (*Node) EmbeddingAttempt

func (node *Node) EmbeddingAttempt() *EmbeddingAttempt

EmbeddingAttempt returns the process-local acceptance/publication token.

func (*Node) EmbeddingRevision

func (node *Node) EmbeddingRevision() EmbeddingBodyRevision

EmbeddingRevision returns runtime snapshot identity without exposing it as an exported Node field. Every serializer, including legacy gob, ignores it.

func (Node) EncodeMsgpack

func (node Node) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack preserves the stored node map independently of its in-memory runtime representation. Keys, value types and field order match the existing reflected Node codec; query provenance and embedding identity are not stored.

func (*Node) ExtractInternalProperties

func (n *Node) ExtractInternalProperties()

ExtractInternalProperties extracts NornicDB-specific fields from properties.

func (*Node) GetDefaultEmbedding

func (n *Node) GetDefaultEmbedding() []float32

GetDefaultEmbedding returns the default embedding for a node, implementing migration behavior from ChunkEmbeddings to NamedEmbeddings.

Migration behavior (temporary):

  • If NamedEmbeddings["default"] exists, return it
  • Otherwise, if ChunkEmbeddings has at least one vector, treat ChunkEmbeddings[0] as "default"
  • Otherwise, return nil

This allows backward compatibility with existing nodes that only have ChunkEmbeddings while transitioning to the new NamedEmbeddings model.

Example:

node := &storage.Node{
	ID: storage.NodeID("doc-1"),
	NamedEmbeddings: map[string][]float32{
		"default": []float32{0.1, 0.2, 0.3},
	},
}
emb := node.GetDefaultEmbedding() // Returns []float32{0.1, 0.2, 0.3}

// Legacy node with ChunkEmbeddings
legacyNode := &storage.Node{
	ID: storage.NodeID("doc-2"),
	ChunkEmbeddings: [][]float32{{0.4, 0.5, 0.6}},
}
emb = legacyNode.GetDefaultEmbedding() // Returns []float32{0.4, 0.5, 0.6}

func (*Node) HasChunkEmbeddings

func (n *Node) HasChunkEmbeddings() bool

HasChunkEmbeddings reports whether the node has chunk embedding vectors: loaded ones (a non-empty first chunk), or, when none are loaded, the stored ones its embedding metadata counts (chunk_count), which an embedding-free read (NodeWithoutEmbeddingsReader) leaves in storage.

func (*Node) Identity

func (n *Node) Identity() EntityIdentity

func (*Node) IdentityKey

func (n *Node) IdentityKey() string

IdentityKey identifies a native node independently of the executing database.

func (*Node) MarshalNeo4jJSON

func (n *Node) MarshalNeo4jJSON() ([]byte, error)

MarshalNeo4jJSON serializes to Neo4j-compatible JSON.

func (*Node) RuntimeMetadata

func (node *Node) RuntimeMetadata() NodeRuntimeMetadata

RuntimeMetadata returns this node's runtime metadata by value. An unset node has zero metadata, so ordinary graph-data construction needs no runtime record.

func (*Node) SetEmbeddingAttempt

func (node *Node) SetEmbeddingAttempt(attempt *EmbeddingAttempt)

SetEmbeddingAttempt binds selected work to this in-memory snapshot only. Unchanged identity keeps the attached record, so this does not allocate.

func (*Node) SetRuntimeMetadata

func (node *Node) SetRuntimeMetadata(metadata NodeRuntimeMetadata)

SetRuntimeMetadata replaces metadata on this image while preserving embedding identity and publication evidence. Other node copies keep their prior values. Setting unchanged metadata does not allocate. Like other Node field updates, this operation requires exclusive ownership of the node image.

type NodeConfig

type NodeConfig struct {
	// Node identification
	NodeID    string    `json:"node_id"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// Pin/Deny lists
	PinList  []string `json:"pin_list"`  // Target node IDs that never decay
	DenyList []string `json:"deny_list"` // Target node IDs to never connect to

	// Edge caps
	MaxOutEdges   int `json:"max_out_edges"`   // Maximum outgoing edges (0 = unlimited)
	MaxInEdges    int `json:"max_in_edges"`    // Maximum incoming edges (0 = unlimited)
	MaxTotalEdges int `json:"max_total_edges"` // Maximum total edges (0 = unlimited)

	// Current edge counts (for cap enforcement)
	CurrentOutEdges   int `json:"current_out_edges"`
	CurrentInEdges    int `json:"current_in_edges"`
	CurrentTotalEdges int `json:"current_total_edges"`

	// Per-label configuration
	LabelConfigs map[string]LabelConfig `json:"label_configs"`

	// Trust level
	TrustLevel TrustLevel `json:"trust_level"`

	// Global overrides
	MinConfidence float64       `json:"min_confidence"` // Override default threshold (0 = use default)
	Cooldown      time.Duration `json:"cooldown"`       // Override default cooldown (0 = use default)
	Disabled      bool          `json:"disabled"`       // Completely disable edge creation to/from this node

	// Metadata
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

NodeConfig stores per-node edge materialization settings.

func NewNodeConfig

func NewNodeConfig(nodeID string) *NodeConfig

NewNodeConfig creates a new node config with defaults.

func (*NodeConfig) AddToDeny

func (c *NodeConfig) AddToDeny(targetID string)

AddToDeny adds a target to the deny list.

func (*NodeConfig) AddToPin

func (c *NodeConfig) AddToPin(targetID string)

AddToPin adds a target to the pin list.

func (*NodeConfig) CanAddEdge

func (c *NodeConfig) CanAddEdge(isOutgoing bool) bool

CanAddEdge returns true if another edge can be added (checks all caps).

func (*NodeConfig) CanAddInEdge

func (c *NodeConfig) CanAddInEdge() bool

CanAddInEdge returns true if another incoming edge can be added.

func (*NodeConfig) CanAddOutEdge

func (c *NodeConfig) CanAddOutEdge() bool

CanAddOutEdge returns true if another outgoing edge can be added.

func (*NodeConfig) DecrementEdgeCount

func (c *NodeConfig) DecrementEdgeCount(isOutgoing bool)

DecrementEdgeCount decrements the edge count.

func (*NodeConfig) GetEffectiveConfidence

func (c *NodeConfig) GetEffectiveConfidence(label string, baseThreshold float64) float64

GetEffectiveConfidence returns the effective minimum confidence threshold. Considers trust level adjustment and per-label overrides.

func (*NodeConfig) GetLabelConfig

func (c *NodeConfig) GetLabelConfig(label string) (LabelConfig, bool)

GetLabelConfig returns the config for a specific label.

func (*NodeConfig) IncrementEdgeCount

func (c *NodeConfig) IncrementEdgeCount(isOutgoing bool)

IncrementEdgeCount increments the edge count.

func (*NodeConfig) IsDenied

func (c *NodeConfig) IsDenied(targetID string) bool

IsDenied returns true if the target is in the deny list.

func (*NodeConfig) IsPinned

func (c *NodeConfig) IsPinned(targetID string) bool

IsPinned returns true if the target is in the pin list.

func (*NodeConfig) RemoveFromDeny

func (c *NodeConfig) RemoveFromDeny(targetID string) bool

RemoveFromDeny removes a target from the deny list.

func (*NodeConfig) RemoveFromPin

func (c *NodeConfig) RemoveFromPin(targetID string) bool

RemoveFromPin removes a target from the pin list.

func (*NodeConfig) SetLabelConfig

func (c *NodeConfig) SetLabelConfig(label string, cfg LabelConfig)

SetLabelConfig sets the config for a specific label.

type NodeConfigStats

type NodeConfigStats struct {
	TotalConfigs int64
	TotalChecks  int64
	TotalBlocked int64
	BlockRate    float64
}

NodeConfigStats provides observability into per-node config state.

type NodeConfigStore

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

NodeConfigStore manages per-node configurations. Thread-safe for concurrent access.

func GlobalNodeConfigStore

func GlobalNodeConfigStore() *NodeConfigStore

GlobalNodeConfigStore returns the global node config store singleton.

func NewNodeConfigStore

func NewNodeConfigStore() *NodeConfigStore

NewNodeConfigStore creates a new per-node config store.

func NewNodeConfigStoreWithOptions

func NewNodeConfigStoreWithOptions(opts ...NodeConfigStoreOption) *NodeConfigStore

NewNodeConfigStoreWithOptions creates a store with functional options.

func (*NodeConfigStore) AddToNodeDenyList

func (s *NodeConfigStore) AddToNodeDenyList(nodeID, targetID string)

AddToNodeDenyList adds a target to a node's deny list.

func (*NodeConfigStore) AddToNodePinList

func (s *NodeConfigStore) AddToNodePinList(nodeID, targetID string)

AddToNodePinList adds a target to a node's pin list.

func (*NodeConfigStore) Clear

func (s *NodeConfigStore) Clear()

Clear removes all node configs.

func (*NodeConfigStore) Delete

func (s *NodeConfigStore) Delete(nodeID string) bool

Delete removes a node config.

func (*NodeConfigStore) DisableNode

func (s *NodeConfigStore) DisableNode(nodeID string)

DisableNode disables all edge creation to/from a node.

func (*NodeConfigStore) EnableNode

func (s *NodeConfigStore) EnableNode(nodeID string)

EnableNode enables edge creation to/from a node.

func (*NodeConfigStore) Export

func (s *NodeConfigStore) Export() []*NodeConfig

Export returns all configs for backup/export.

func (*NodeConfigStore) Get

func (s *NodeConfigStore) Get(nodeID string) *NodeConfig

Get returns the config for a node, or nil if none exists.

func (*NodeConfigStore) GetAllNodeIDs

func (s *NodeConfigStore) GetAllNodeIDs() []string

GetAllNodeIDs returns all configured node IDs.

func (*NodeConfigStore) GetDeniedTargets

func (s *NodeConfigStore) GetDeniedTargets(nodeID string) []string

GetDeniedTargets returns all denied targets for a node.

func (*NodeConfigStore) GetEffectiveConfidence

func (s *NodeConfigStore) GetEffectiveConfidence(sourceID, targetID, label string, baseThreshold float64) float64

GetEffectiveConfidence returns the effective confidence threshold for an edge.

func (*NodeConfigStore) GetOrCreate

func (s *NodeConfigStore) GetOrCreate(nodeID string) *NodeConfig

GetOrCreate returns the config for a node, creating one if it doesn't exist.

func (*NodeConfigStore) GetPinnedTargets

func (s *NodeConfigStore) GetPinnedTargets(nodeID string) []string

GetPinnedTargets returns all pinned targets for a node.

func (*NodeConfigStore) Import

func (s *NodeConfigStore) Import(configs []*NodeConfig) int

Import loads configs from backup/import. Existing configs are NOT cleared - use Clear() first if needed.

func (*NodeConfigStore) IsEdgeAllowed

func (s *NodeConfigStore) IsEdgeAllowed(sourceID, targetID, label string) bool

IsEdgeAllowed checks if an edge from source to target is allowed. Considers: feature flag, disabled state, deny list, and edge caps.

func (*NodeConfigStore) IsEdgeAllowedWithReason

func (s *NodeConfigStore) IsEdgeAllowedWithReason(sourceID, targetID, label string) (bool, string)

IsEdgeAllowedWithReason checks if an edge is allowed and returns the reason.

func (*NodeConfigStore) IsPinned

func (s *NodeConfigStore) IsPinned(sourceID, targetID string) bool

IsPinned checks if an edge should never decay.

func (*NodeConfigStore) RecordEdgeCreation

func (s *NodeConfigStore) RecordEdgeCreation(sourceID, targetID string)

RecordEdgeCreation updates edge counts after an edge is created.

func (*NodeConfigStore) RecordEdgeDeletion

func (s *NodeConfigStore) RecordEdgeDeletion(sourceID, targetID string)

RecordEdgeDeletion updates edge counts after an edge is deleted.

func (*NodeConfigStore) Set

func (s *NodeConfigStore) Set(cfg NodeConfig)

Set stores a node config.

func (*NodeConfigStore) SetNodeEdgeCaps

func (s *NodeConfigStore) SetNodeEdgeCaps(nodeID string, maxOut, maxIn, maxTotal int)

SetNodeEdgeCaps sets edge caps for a node.

func (*NodeConfigStore) SetNodeTrustLevel

func (s *NodeConfigStore) SetNodeTrustLevel(nodeID string, level TrustLevel)

SetNodeTrustLevel sets the trust level for a node.

func (*NodeConfigStore) Size

func (s *NodeConfigStore) Size() int

Size returns the number of configured nodes.

func (*NodeConfigStore) Stats

func (s *NodeConfigStore) Stats() NodeConfigStats

Stats returns current store statistics.

type NodeConfigStoreOption

type NodeConfigStoreOption func(*NodeConfigStore)

NodeConfigStoreOption configures a NodeConfigStore.

type NodeDeleteCallback

type NodeDeleteCallback func(nodeID NodeID)

NodeDeleteCallback is called when a node is successfully deleted from storage.

type NodeDeletionMode

type NodeDeletionMode uint8

NodeDeletionMode selects how transactional node deletion treats relationships.

const (
	// CascadeEdges removes the node and all incident relationships (DETACH DELETE).
	CascadeEdges NodeDeletionMode = iota
	// RejectConnected checks at commit that later operations removed every
	// incident relationship; otherwise the complete transaction rolls back.
	RejectConnected
)

type NodeEmbeddingMetaReader

type NodeEmbeddingMetaReader interface {
	GetNodeEmbeddingMeta(ctx context.Context, id NodeID) (map[string]any, error)
}

NodeEmbeddingMetaReader is an optional extension interface for reading a node's embedding metadata (EmbedMeta: chunk count, model, kept chunk texts, chunk places) without its vectors, which an embedding-free read may leave out (Badger keeps it in the embedding sidecar).

type NodeEnvelope

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

NodeEnvelope contains borrowed V2 property and metadata payloads. Keep the input alive and unchanged while using either view. Payload interpretation and field selection belong to the consumer; framing belongs to SplitNodeEnvelope.

func SplitNodeEnvelope

func SplitNodeEnvelope(data []byte) (NodeEnvelope, error)

SplitNodeEnvelope validates the V2 format byte and property-length framing. It never decodes properties or metadata and never copies payloads. Full, projected, metadata-only (label) and WAL consumers share this owner; metadata is interpreted only by the stored decoder (decodeValue). Other stored operation clients must reuse it rather than implement another splitter.

func (NodeEnvelope) MetadataPayload

func (e NodeEnvelope) MetadataPayload() []byte

MetadataPayload returns the borrowed metadata payload, including its serializer header.

func (NodeEnvelope) PropertyPayload

func (e NodeEnvelope) PropertyPayload() []byte

PropertyPayload returns the borrowed serialized property payload.

type NodeEventCallback

type NodeEventCallback func(node *Node)

NodeEventCallback is called when storage operations complete successfully. This allows external services (like search indexes) to stay synchronized with storage.

type NodeID

type NodeID string

NodeID is a strongly-typed unique identifier for graph nodes.

Using a custom type provides:

  • Type safety (can't accidentally use EdgeID where NodeID is expected)
  • Clear API semantics
  • Future extensibility (could add methods)

Example:

id := storage.NodeID("user-123")
node, err := engine.GetNode(id)

func EnsureNodeIDDatabasePrefixForEngine added in v1.1.0

func EnsureNodeIDDatabasePrefixForEngine(engine Engine, id NodeID) NodeID

EnsureNodeIDDatabasePrefixForEngine adds the active engine namespace to an unprefixed node ID. Schema backfills use this so cache entries match the storage IDs later seen by transaction commit validation.

func FirstNodeIDByLabel

func FirstNodeIDByLabel(ctx context.Context, engine Engine, label string) (NodeID, error)

FirstNodeIDByLabel returns the first node ID for a label without decoding nodes when possible. Returns ErrNotFound if no node matches.

func NodeIDsByLabel

func NodeIDsByLabel(ctx context.Context, engine Engine, label string, limit int) ([]NodeID, error)

NodeIDsByLabel returns up to limit node IDs that have the label. If limit <= 0, all matches are returned (may be expensive).

type NodeIterator

type NodeIterator interface {
	IterateNodes(fn func(*Node) bool) error
}

NodeIterator streams every node in the engine view.

type NodeRuntimeMetadata

type NodeRuntimeMetadata struct {
	Database                   string
	EmbeddingsStoredSeparately bool
	VisibilitySuppressed       bool
}

NodeRuntimeMetadata carries query provenance and storage visibility state. Database is never persisted; the two flags retain their existing stored keys. These values are not graph properties and do not appear in public JSON.

For example, attach query provenance without changing a node's properties:

metadata := node.RuntimeMetadata()
metadata.Database = "analytics"
node.SetRuntimeMetadata(metadata)

type NodeStillConnectedError

type NodeStillConnectedError struct {
	NodeID NodeID
	// Namespace is the transaction's database: the message names the node
	// as its clients do, without the namespace prefix.
	Namespace string
}

NodeStillConnectedError fails the commit of a transaction that deleted a node with a non-DETACH DELETE while relationships still connected it at commit (BadgerTransaction.DeleteConnectedNode): Neo4j's DeleteConnectedNode constraint, a Neo.ClientError.Schema.ConstraintValidationFailed.

func (*NodeStillConnectedError) BoltErrorCode

func (err *NodeStillConnectedError) BoltErrorCode() string

BoltErrorCode is the status Bolt reports for the error.

func (*NodeStillConnectedError) BoltErrorDetail

func (err *NodeStillConnectedError) BoltErrorDetail() string

BoltErrorDetail names the constraint, as the DELETE-time error does.

func (*NodeStillConnectedError) Error

func (err *NodeStillConnectedError) Error() string

type NodeUpdateRequest

type NodeUpdateRequest struct {
	Before *Node
	After  *Node
	Policy EntityImagePolicy
	// PropertyWrites is consumed by the authorization view before storage.
	PropertyWrites PropertyWriteIntent
}

NodeUpdateRequest carries one node mutation and its image interpretation. Before, when supplied, is the immutable image the caller actually observed; keep it unchanged until the transaction terminates. A nil Before deliberately selects a blind image write. After is the complete image to stage or store. Policy retains the existing per-operation client/authoritative distinction. The request is runtime-only and changes no persistent encoding.

func (NodeUpdateRequest) Operation

func (request NodeUpdateRequest) Operation() Operation

Operation projects client mutation input for a managed coordinator. Native staging captures its own committed preimage before publication or encoding.

type NodeVisitor

type NodeVisitor func(node *Node) error

NodeVisitor is a function called for each node during streaming.

type NodeWithoutEmbeddingsReader added in v1.3.3

type NodeWithoutEmbeddingsReader interface {
	GetNodeWithoutEmbeddings(ctx context.Context, id NodeID) (*Node, error)
}

NodeWithoutEmbeddingsReader is an optional extension interface for read paths that need a node's metadata and user properties but not stored embedding vectors. Implementations must preserve ID, labels, properties, timestamps, and embedding metadata, while avoiding separately stored vector payloads when possible.

type NodeWithoutEmbeddingsStreamer

type NodeWithoutEmbeddingsStreamer interface {
	StreamNodesWithoutEmbeddings(ctx context.Context, fn func(node *Node) error) error
}

NodeWithoutEmbeddingsStreamer streams complete node metadata and user properties without loading separately stored embeddings. Snapshot writers use this optional capability because embeddings are intentionally excluded from snapshot records and are regenerated by the search index.

type Operation

type Operation struct {
	Type      OperationType `json:"type"`
	Timestamp time.Time     `json:"timestamp,omitempty"`

	// For node operations
	NodeID  NodeID `json:"node_id,omitempty"`
	Node    *Node  `json:"node,omitempty"`     // New state (for create/update) or nil
	OldNode *Node  `json:"old_node,omitempty"` // Old state (for update/delete rollback)
	// For delete operations that cascade (e.g., DeleteNode deletes edges).
	EdgesDeleted     int64          `json:"edges_deleted,omitempty"`
	DeletedEdgeIDs   []EdgeID       `json:"deleted_edge_ids,omitempty"`
	DeletedEdgeFacts []AffectedFact `json:"deleted_edge_facts,omitempty"`

	// For edge operations
	EdgeID  EdgeID `json:"edge_id,omitempty"`
	Edge    *Edge  `json:"edge,omitempty"`     // New state (for create/update) or nil
	OldEdge *Edge  `json:"old_edge,omitempty"` // Old state (for update/delete rollback)
	// ReplacesExisting is decode-only compatibility for buffered WAL records
	// acknowledged by the short-lived 68db5d16d release writer. Current
	// writers never set it: CREATE no longer replaces a stored relationship.
	// Recovery must nevertheless preserve those records' zero-cardinality
	// meaning instead of publishing them as a second physical relationship.
	ReplacesExisting bool `json:"replaces_existing,omitempty"`

	// FreshID records proof that a prior MVCC head cannot exist for
	// this create. The commit can use the new version as its floor.
	// Recreated IDs retain the persisted floor.
	FreshID bool `json:"fresh_id,omitempty"`
	// contains filtered or unexported fields
}

Operation represents a single operation within a transaction. Used by BadgerTransaction to track operations for constraint validation. It is also JSON-serialized into the WAL buffered-commit payload, so every field carries a tag.

func DecodeEntityChange

func DecodeEntityChange(kind EntityCommandKind, data []byte) (Operation, error)

DecodeEntityChange decodes one current direct replication command. It never imports numeric dictionary IDs.

func (Operation) EdgeUpdate

func (operation Operation) EdgeUpdate() EdgeUpdateRequest

EdgeUpdate reads relationship mutation input from an operation.

func (Operation) NodeUpdate

func (operation Operation) NodeUpdate() NodeUpdateRequest

NodeUpdate reads client mutation input from an operation. Accepted semantic replay explicitly selects StoredNodeImages at its staging boundary instead.

type OperationType

type OperationType string

OperationType represents the type of operation in a transaction.

const (
	OpCreateNode      OperationType = "create_node"
	OpUpdateNode      OperationType = "update_node"
	OpDeleteNode      OperationType = "delete_node"
	OpCreateEdge      OperationType = "create_edge"
	OpUpdateEdge      OperationType = "update_edge"
	OpDeleteEdge      OperationType = "delete_edge"
	OpUpdateEmbedding OperationType = "update_embedding" // Safe to skip on corruption - regenerable
)
const (
	OpBulkNodes       OperationType = "bulk_create_nodes"
	OpBulkEdges       OperationType = "bulk_create_edges"
	OpBulkDeleteNodes OperationType = "bulk_delete_nodes"
	OpBulkDeleteEdges OperationType = "bulk_delete_edges"
	OpCheckpoint      OperationType = "checkpoint" // Marks snapshot boundaries

	// Transaction boundary markers for ACID compliance
	OpTxBegin  OperationType = "tx_begin"  // Marks transaction start
	OpTxCommit OperationType = "tx_commit" // Marks successful transaction completion
	OpTxAbort  OperationType = "tx_abort"  // Marks explicit transaction rollback

	// OpBufferedCommit records the full payload of an acknowledged
	// write-behind commit. It is appended to the WAL before the ACK so a
	// process crash that loses the in-memory buffer can be recovered by
	// replaying these entries into Badger at open (see
	// RecoverBufferedCommits). The entry is written to the kernel page
	// cache before the ACK (write(2)), so it survives kill -9; power-loss
	// durability still requires the durable synchronous commit path.
	OpBufferedCommit OperationType = "buffered_commit"
)

Additional WAL operation types (extends OperationType from transaction.go)

const OpEntityCommit OperationType = "entity_commit"

OpEntityCommit journals one atomic accepted semantic entity transaction.

const (
	OpRecordPart OperationType = "record_part"
)

A spanned record is one logical WAL record whose encoded payload does not fit one frame (walMaxEntrySize). It is written as count consecutive part frames under one hold of the WAL mutex (NOR-412). Every part:

  • is an ordinary atomic frame whose version byte is walFormatVersionSpanned, so a build that does not know that version refuses the log ("unsupported WAL version") instead of reading the part as a record of an operation it does not know;
  • carries an ordinary entry payload with operation OpRecordPart and the logical record's own sequence, timestamp and database, so sequence-based cuts (snapshot truncation, segment retention) keep or drop the record whole;
  • holds [index:4 LE][count:4 LE] and the next chunk of the logical payload, which is the payload a single frame would have held.

A record that fits one frame is written as one frame of walFormatVersionCurrent, with the payload the one-frame encoder gives it. Only the last part completes a record: a group that ends early is dropped by readers and cut by tail repair.

type OwnedPropertyValue

type OwnedPropertyValue interface {
	StoragePropertyValue() (value any, exact bool)
}

OwnedPropertyValue is implemented by a registered scalar's codec owner. StoragePropertyValue returns an independent value in the representation that the scalar's durable decoder returns. Exact is false when the durable decoder must validate the image instead. Containers remain storage's responsibility.

type PendingEmbeddingCounter

type PendingEmbeddingCounter interface {
	CountPendingEmbeddingIDs(ctx context.Context, accept func([]byte) bool) int
}

PendingEmbeddingCounter counts MAIN in one snapshot. accept may filter IDs without decoding bodies or loading vectors. Key bytes are borrowed for the callback only; callers must not retain or modify them.

ctx is the caller's context: a fallback scan of an engine without the index runs under it, never under a context nobody can end.

type PrefixNodeWithoutEmbeddingsReader

type PrefixNodeWithoutEmbeddingsReader interface {
	StreamNodesByPrefixWithoutEmbeddings(ctx context.Context, prefix string, visit func(*Node) error) error
}

PrefixNodeWithoutEmbeddingsReader streams lightweight nodes by ID prefix while guaranteeing that no embedding vectors are decoded or copied.

type PrefixStatsEngine

type PrefixStatsEngine interface {
	NodeCountByPrefix(ctx context.Context, prefix string) (int64, error)
	EdgeCountByPrefix(ctx context.Context, prefix string) (int64, error)
}

PrefixStatsEngine is an optional extension interface that provides fast per-prefix statistics without scanning and decoding all records.

The prefix refers to the *ID prefix* (e.g., a database namespace prefix like "nornic:") and is applied to stored NodeID/EdgeID values (not the internal key prefix bytes).

This is primarily used by NamespacedEngine so that NodeCount/EdgeCount can remain fast in multi-database deployments while still returning namespace-scoped results. The caller context owns admission and any prefix scan the implementation performs: a canceled request gets its own context error, never a successful count.

type PrefixStreamingEngine

type PrefixStreamingEngine interface {
	StreamingEngine

	// StreamNodesByPrefix streams only nodes whose IDs start with the given prefix.
	StreamNodesByPrefix(ctx context.Context, prefix string, fn func(node *Node) error) error
}

PrefixStreamingEngine extends StreamingEngine with namespace/key-prefix-aware streaming for efficient bounded scans on engines where IDs embed tenant/db prefixes. This avoids full-store scans followed by callback filtering.

type PreparedDatabase

type PreparedDatabase struct {
	Database      string `json:"database"`
	Nodes         int64  `json:"nodes"`
	Relationships int64  `json:"relationships"`
}

PreparedDatabase describes the graph in a closed store before it becomes accessible through the catalog. Counts certify the initial import.

func ReadPreparedDatabase

func ReadPreparedDatabase(root, id, database string) (string, PreparedDatabase, error)

ReadPreparedDatabase looks up a sealed store and checks that it is bound to the requested namespace. Badger may only open a real existing store.

func ReadPreparedDatabaseSeal

func ReadPreparedDatabaseSeal(root, id, database string) (string, PreparedDatabase, error)

ReadPreparedDatabaseSeal checks the namespace binding even when the native store is damaged. Only the published-store recovery path may use it alone.

type PreparedEntityCommit

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

PreparedEntityCommit transfers one validated native transaction to an accepted command. It retains native snapshot/admission ownership until the command chooses physical commit or definite discard. Caller wait cancellation is not a discard decision.

func PrepareEntityChanges

func PrepareEntityChanges(ctx context.Context, engine Engine, namespace string, operations []Operation, mode EntityCommitMode) (*PreparedEntityCommit, func(CommitOutcome), error)

PrepareEntityChanges stages and validates entity changes through the registered namespace coordinator, or the native transaction owner when unmanaged. Callers establish routing and wrapper admission before preparation; this operation neither journals nor publishes the prepared changes.

func (*PreparedEntityCommit) Abort

func (p *PreparedEntityCommit) Abort()

func (*PreparedEntityCommit) Changes

func (*PreparedEntityCommit) Commit

func (p *PreparedEntityCommit) Commit(afterPublication func()) error

func (*PreparedEntityCommit) CountDelta

func (p *PreparedEntityCommit) CountDelta() (nodes, edges int64)

CountDelta projects namespace-scoped physical counts without copying images. The prepared pairs remain private and immutable throughout admission.

func (*PreparedEntityCommit) LogicalID

func (p *PreparedEntityCommit) LogicalID() string

func (*PreparedEntityCommit) MarkRecoveryPending

func (p *PreparedEntityCommit) MarkRecoveryPending()

MarkRecoveryPending preserves accepted authority while making ordinary waiters fail with the existing conflict class, allowing a safe repair cut.

func (*PreparedEntityCommit) Mode

func (*PreparedEntityCommit) Namespace

func (p *PreparedEntityCommit) Namespace() string

func (*PreparedEntityCommit) Operations

func (p *PreparedEntityCommit) Operations() []Operation

Operations returns detached diagnostic images, including before-images and cascading-deletion IDs. Encoders use EntityTransactionRequest{Prepared: p} to read the immutable accepted snapshot without allocating this public copy.

func (*PreparedEntityCommit) RetainAcceptedAuthority

func (p *PreparedEntityCommit) RetainAcceptedAuthority(ctx context.Context) (func(), error)

RetainAcceptedAuthority transfers an additional reentrant hold to a durable command owner. Applied publication releases it before native listeners; recovery-pending commands retain it after an inner native rollback. The returned release is only for definite pre-record/log discard.

The retention is cancellable only while acceptance is still abortable; a nil ctx retains non-cancellably. Accepted continuations use their own lifetime.

type PressureBand

type PressureBand string

PressureBand represents the MVCC storage pressure level.

const (
	PressureNormal   PressureBand = "normal"
	PressureHigh     PressureBand = "high"
	PressureCritical PressureBand = "critical"
)

type ProjectedLabelNodeReader added in v1.3.2

type ProjectedLabelNodeReader interface {
	StreamNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error
}

ProjectedLabelNodeReader is an optional extension interface for iterating label-matching nodes while decoding only a caller-specified subset of user properties. The callback runs against one consistent storage snapshot and must treat the node as read-only.

A nil properties slice requests the full node; an empty non-nil slice requests no user properties.

type ProjectedNodeReader added in v1.1.8

type ProjectedNodeReader interface {
	GetNodeProjected(ctx context.Context, id NodeID, properties []string) (*Node, error)
}

ProjectedNodeReader is an optional extension interface for reading a node while decoding only a caller-specified subset of user properties.

Implementations still return node metadata such as ID, labels, and timestamps, but Properties contains only the requested keys. A nil properties slice means "full node"; an empty non-nil slice means "no user properties".

type ProjectedPrefixNodeReader added in v1.3.3

type ProjectedPrefixNodeReader interface {
	StreamNodesByPrefixProjected(ctx context.Context, prefix string, properties []string, visit func(*Node) error) error
}

ProjectedPrefixNodeReader is an optional extension interface for iterating prefix-matching nodes while decoding only a caller-specified subset of user properties. The prefix is applied to stored NodeID values, matching PrefixStreamingEngine semantics.

A nil properties slice requests the full node; an empty non-nil slice requests no user properties.

type PropertyIndex

type PropertyIndex = CompositeIndex

PropertyIndex is the arity-1 form of a CompositeIndex. It is a type alias so every existing single-property index call site keeps working while the underlying value is the same composite index type used for multi-property indexes. The single-property ordered-scan fields (values, sortedNonNilKeys, sortedKeyKinds, keysDirty) and OwningConstraint live on CompositeIndex.

type PropertyIndexBounds

type PropertyIndexBounds struct {
	Lower, Upper                   interface{}
	HasLower, HasUpper             bool
	LowerInclusive, UpperInclusive bool
}

PropertyIndexBounds selects the values of a property index within a lower and/or an upper bound. Bounds are numbers or strings; a value of another type than a bound never falls within it, as Cypher compares numbers only with numbers and strings only with strings (anything else is null).

type PropertyKeyLookup

type PropertyKeyLookup interface {
	PropertyKeyKnown(name string) bool
}

PropertyKeyLookup is PropertyKeyRegistry's lookup on an engine bound to one namespace (NamespacedEngine).

type PropertyKeyRegistry

type PropertyKeyRegistry interface {
	NotePropertyKeysInNamespace(namespace string, properties map[string]interface{})
	PropertyKeyKnownInNamespace(namespace, name string) bool
}

PropertyKeyRegistry is an optional extension interface for the property-key names each namespace's writes have used: Neo4j's property-key tokens. A name is known once a write stores a value under it, even a write later rolled back or a key later removed, and it stays known (a name no commit stored is forgotten on restart; Neo4j keeps it). Reads, and writes of null, make no name known. Cypher's SET counts a null written for a known key the entity lacks (properties_set, #907).

type PropertyType

type PropertyType string

PropertyType represents the expected type of a property.

const (
	PropertyTypeString   PropertyType = "STRING"
	PropertyTypeInteger  PropertyType = "INTEGER"
	PropertyTypeFloat    PropertyType = "FLOAT"
	PropertyTypeBoolean  PropertyType = "BOOLEAN"
	PropertyTypeDate     PropertyType = "DATE"
	PropertyTypeDateTime PropertyType = "DATETIME" // Legacy alias for zoned datetime
	// Neo4j temporal property type constraints.
	PropertyTypeZonedDateTime PropertyType = "ZONED DATETIME"
	PropertyTypeLocalDateTime PropertyType = "LOCAL DATETIME"
	PropertyTypeLocalTime     PropertyType = "LOCAL TIME"
	PropertyTypeZonedTime     PropertyType = "ZONED TIME"
	PropertyTypeDuration      PropertyType = "DURATION"
	PropertyTypePoint         PropertyType = "POINT"
)

func ListElementPropertyType

func ListElementPropertyType(pt PropertyType) (PropertyType, bool)

ListElementPropertyType reports the element type of a LIST<T NOT NULL> property type.

func ListPropertyType

func ListPropertyType(element PropertyType) PropertyType

ListPropertyType returns the canonical LIST<T NOT NULL> property type for a scalar element type.

type PropertyTypeConstraint

type PropertyTypeConstraint struct {
	Name         string               `json:"name"`
	EntityType   ConstraintEntityType `json:"entity_type,omitempty"` // defaults to NODE when empty
	Label        string               `json:"label"`                 // label for nodes, relationship type for relationships
	Property     string               `json:"property"`
	ExpectedType PropertyType         `json:"expected_type"`
}

PropertyTypeConstraint represents a type constraint on properties.

func (PropertyTypeConstraint) EffectiveEntityType

func (c PropertyTypeConstraint) EffectiveEntityType() ConstraintEntityType

EffectiveEntityType returns the entity type, defaulting to NODE for backward compatibility.

type PropertyTypeConstraintOptions

type PropertyTypeConstraintOptions struct {
	EntityType  ConstraintEntityType
	IfNotExists bool
}

PropertyTypeConstraintOptions selects entity scope and duplicate admission. A zero EntityType retains node scoping; IfNotExists makes an equal rule a no-op.

type PropertyWriteIntent

type PropertyWriteIntent struct {
	Keys    map[string]bool
	Replace bool
}

PropertyWriteIntent records caller-authored keys even when the projected before and after images are identical. A true key value also requires the property token to exist or be creatable. Replace includes omitted keys.

type PublicationDecision

type PublicationDecision func(context.Context, PublicationIdentity, func() error) error

PublicationDecision is the semantic owner's last-abortable call seam. The callback invokes action synchronously once or rejects without invoking it. #1615 owns arbitration; storage owns and returns the actual action outcome.

type PublicationIdentity

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

PublicationIdentity identifies one semantic publication attempt. It is not a physical timestamp, replay identity or persistent idempotency record.

type QueryAnalyzer

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

QueryAnalyzer analyzes queries to extract routing information.

func NewQueryAnalyzer

func NewQueryAnalyzer() *QueryAnalyzer

NewQueryAnalyzer creates a new query analyzer for composite routing.

func (*QueryAnalyzer) AnalyzeQuery

func (a *QueryAnalyzer) AnalyzeQuery(cypher string, writes bool) *QueryInfo

AnalyzeQuery extracts routing information from a Cypher query string and records the statement effect the caller already resolved canonically: writes is true when the statement may write. This is a simplified analyzer - a full implementation would parse the AST - and it never classifies a statement's effects itself.

func (*QueryAnalyzer) RouteQuery

func (a *QueryAnalyzer) RouteQuery(queryInfo *QueryInfo, allConstituents []string) []string

RouteQuery determines which constituents to query based on query info.

Only a complete nonempty label mapping wins. No labels, any unknown label and an all-known mapping whose union is empty all continue into the existing property lookup and finally return the caller slice; label routing never introduces property fallback of its own.

func (*QueryAnalyzer) SetLabelRouting

func (a *QueryAnalyzer) SetLabelRouting(label string, constituents []string)

SetLabelRouting configures label-based routing.

func (*QueryAnalyzer) SetPropertyDefault

func (p *QueryAnalyzer) SetPropertyDefault(propertyName string, constituent string)

SetPropertyDefault sets the default constituent for a property when value not found.

func (*QueryAnalyzer) SetPropertyRouting

func (p *QueryAnalyzer) SetPropertyRouting(propertyName string, value interface{}, constituent string)

SetPropertyRouting configures property-based routing.

type QueryInfo

type QueryInfo struct {
	Labels     []string
	Properties map[string]interface{}
	// IsWrite is the statement effect the caller resolved canonically, reported
	// by AnalyzeQuery and never guessed from the query text.
	IsWrite bool
	// IsFullScan reports a statement with no label token that cannot write.
	IsFullScan bool
}

QueryInfo contains information extracted from a query for routing.

type QueryNodeReader

type QueryNodeReader interface {
	GetQueryNode(ctx context.Context, id NodeID) (*Node, error)
}

QueryNodeReader is an optional extension interface for the node a query row carries: GetNode's visibility, labels, properties and the node's settled embedding metadata (the worker sidecar's included, so Node.HasChunkEmbeddings answers as on a full read), without reading separately stored chunk vectors. Vectors already in memory may be present and belong to the caller; a caller that needs all vectors reads with GetNode. Unlike NodeWithoutEmbeddingsReader, whose read leaves the sidecar out, the metadata is the full read's.

type QueryResultProjection

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

QueryResultProjection applies property decay to detached normal-query values. It never changes engine reads or stored property maps. Remote entities retain their source database's projection instead of being scored against this store. Construct it once per result owner; raw debug/history/export reads omit it.

func BeginQueryResultProjection

func BeginQueryResultProjection(engine Engine) (QueryResultProjection, func())

BeginQueryResultProjection owns a normal-query reveal scope until release. Call it once at an external query boundary, not inside an already scoped query. For example: view, release := BeginQueryResultProjection(engine); defer release() then return view.Node(node). Independent REVEAL queries cannot bypass its filter.

func BeginQueryResultProjectionContext

func BeginQueryResultProjectionContext(ctx context.Context, engine Engine) (context.Context, QueryResultProjection, func())

BeginQueryResultProjectionContext joins an already owned query scope or acquires a normal one for an external query. It is safe for a service called by a scoped Cypher procedure: it never recursively acquires the same RWMutex. The acquisition waits with ctx, so a cancelled caller returns without a lease and must stop its own work; the returned context then reports that cancellation, and the projection applies no scope-derived reveal mode. For example: ctx, view, release := BeginQueryResultProjectionContext(ctx, engine); defer release(); return view.Node(node). A reused scope never reuses another database's policy or namespace. Do not retain ctx or view after release.

func NewNormalEventResultProjection

func NewNormalEventResultProjection(engine Engine) QueryResultProjection

NewNormalEventResultProjection projects normal subscription events without inheriting a mutation producer's REVEAL mode. It does not acquire a query mutex: storage callbacks run synchronously inside the producer's write scope. Supply the source engine and original qualified entity IDs before adapting IDs for a transport. For example, emit(NewNormalEventResultProjection(source).Node(node)). This changes only detached event properties, not stored entities, whole-entity notification membership, or the producer's own REVEAL result.

func NewQueryResultProjection

func NewQueryResultProjection(engine Engine) QueryResultProjection

NewQueryResultProjection resolves the database and storage wrapper once. The caller must already own its query reveal scope (as Cypher does). External query owners should use BeginQueryResultProjection instead. For example, visible := NewQueryResultProjection(engine).Node(node).

func (QueryResultProjection) Edge

func (p QueryResultProjection) Edge(edge *Edge, selection ...[]string) *Edge

Edge projects a detached relationship for a query response. Mutation owners must keep the original edge, so unrelated writes retain suppressed fields.

func (QueryResultProjection) EdgeProperties

func (p QueryResultProjection) EdgeProperties(edge *Edge, selection ...[]string) map[string]interface{}

EdgeProperties is NodeProperties' relationship counterpart, using the edge's database, type, update time and property policy. Stored properties stay intact.

func (QueryResultProjection) Enabled

func (p QueryResultProjection) Enabled() bool

Enabled reports whether this projection applies property decay. Result owners use it to bypass caches whose graph revision cannot represent elapsed decay. For example, do not reuse cached search payloads when view.Enabled() is true.

func (QueryResultProjection) Node

func (p QueryResultProjection) Node(node *Node) *Node

Node projects a detached node for a query response, preserving typed identity. The original pointer is returned without allocation when decay is disabled.

func (QueryResultProjection) NodeProperties

func (p QueryResultProjection) NodeProperties(node *Node, selection ...[]string) map[string]interface{}

NodeProperties returns visible node properties without mutating their source. The optional selection keeps only the named properties: a nil or omitted selection returns all properties, and an empty non-nil selection returns none. For example, a pattern can check just the fields it names without scoring the rest of the node via NodeProperties(node, selection). With decay disabled and no selection it returns the original map without allocating.

type RangeIndex

type RangeIndex struct {
	Name             string
	Kind             IndexKind
	Label            string
	Property         string
	Properties       []string             // composite properties (for multi-property constraint indexes)
	EntityType       ConstraintEntityType // NODE or RELATIONSHIP
	OwningConstraint string               // name of the constraint that owns this index (empty if standalone)
	// contains filtered or unexported fields
}

RangeIndex represents an index for range queries on a single property. It maintains a sorted list of entries for efficient O(log n) range queries.

type ReadSnapshotView

type ReadSnapshotView interface {
	IterateNodes(fn func(*Node) bool) error
	StreamEdges(ctx context.Context, fn func(*Edge) error) error
	Close()
}

ReadSnapshotView is a consistent view of storage opened by OpenReadSnapshot. Its reads may run one after another, each seeing the same point. Close releases it; reads after Close fail.

func OpenReadSnapshot

func OpenReadSnapshot(ctx context.Context, engine any) (ReadSnapshotView, error)

OpenReadSnapshot opens a read snapshot of engine, or returns ErrReadSnapshotUnsupported when engine has no ReadSnapshotter.

type ReadSnapshotter

type ReadSnapshotter interface {
	OpenReadSnapshot(ctx context.Context) (ReadSnapshotView, error)
}

ReadSnapshotter opens one consistent view of storage. Every read through the snapshot sees the store as of one point, acknowledged write-behind entries included, until Close. A search index build reads its whole baseline (nodes and relationships) through one snapshot, so the baseline is a state the store actually had.

type Receipt

type Receipt struct {
	TxID        string    `json:"tx_id"`
	WALSeqStart uint64    `json:"wal_seq_start"`
	WALSeqEnd   uint64    `json:"wal_seq_end"`
	Timestamp   time.Time `json:"timestamp"`
	Database    string    `json:"database,omitempty"`
	Hash        string    `json:"hash"`
}

Receipt represents a mutation receipt tied to WAL sequencing. WALSeqEnd should refer to the commit marker sequence for the transaction.

func NewReceipt

func NewReceipt(txID string, walSeqStart, walSeqEnd uint64, database string, timestamp time.Time) (*Receipt, error)

NewReceipt creates a receipt and computes its hash.

func (*Receipt) UpdateHash

func (r *Receipt) UpdateHash() error

UpdateHash recomputes the receipt hash from canonical fields.

type RecoveryStreamStatus added in v1.3.1

type RecoveryStreamStatus struct {
	SnapshotStreaming bool
	SnapshotNodes     uint64
	SnapshotEdges     uint64
	WALEntries        uint64
}

RecoveryStreamStatus describes whether recovery used bounded snapshot and WAL paths. Legacy JSON snapshots require compatibility materialization.

type RelationshipConstraint

type RelationshipConstraint struct {
	Name       string
	Type       ConstraintType
	RelType    string // Relationship type (e.g., "KNOWS", "FOLLOWS")
	Properties []string
}

RelationshipConstraint represents a constraint on relationship properties.

type RelationshipCountTier

type RelationshipCountTier uint8

RelationshipCountTier selects one of the persisted relationship counter tiers.

const (
	// RelationshipCountByType counts a relationship type in one database.
	RelationshipCountByType RelationshipCountTier = iota
	// RelationshipCountByStartLabel also constrains the physical start label.
	RelationshipCountByStartLabel
	// RelationshipCountByEndLabel also constrains the physical end label.
	RelationshipCountByEndLabel
)

type RelationshipEndpointChecker

type RelationshipEndpointChecker interface {
	RelationshipEndpointVisible(id NodeID) (visible, answered bool)
}

RelationshipEndpointChecker is an optional extension interface for traversals that need a relationship's end node only to exist. For a node that a committed relationship visible to the caller points to, RelationshipEndpointVisible reports whether GetNode would return it, without reading it. answered is false when the engine can't tell without reading the node (a read-time filter such as decay can hide it); the caller then reads the node. The answer relies on a committed relationship's endpoints existing: a node with relationships can't be deleted without them.

type RelationshipPropertyEqualityLookup

type RelationshipPropertyEqualityLookup interface {
	LookupEdgesByPropertyEquality(ctx context.Context, relationshipType string, properties []string, values []interface{}) (edges []*Edge, handled bool, err error)
}

RelationshipPropertyEqualityLookup answers a fixed-hop pattern whose relationship carries equality properties a declared relationship uniqueness or relationship key constraint indexes, such as

MATCH (a)-[r:PD_RELATION {id: $id}]->(b)

from the relationship equality index the constraint's own validation maintains (badger_relationship_unique_index.go), instead of enumerating every relationship of the type. Candidates come from the index postings and each is read back and re-checked, so a value changed or a relationship deleted since its posting is never reported. handled is false when the index cannot answer this lookup (no retained or buildable index, write-behind or decay-filtered views, unkeyable values, no namespace); the caller then keeps its complete scan. Callers still evaluate the whole pattern on what a lookup returns.

type RemoteAccessMode

type RemoteAccessMode uint8

RemoteAccessMode is the caller's required routing intent for one implicit or explicit remote query. The transport never infers intent from statement text.

const (
	// RemoteAccessRead selects a read session and managed read transaction.
	RemoteAccessRead RemoteAccessMode = iota + 1
	// RemoteAccessWrite selects a write session and managed write transaction.
	RemoteAccessWrite
)

type RemoteCypherMode

type RemoteCypherMode interface{ ResolvedWriteMode() (write, known bool) }

RemoteCypherMode reports a completed query's resolved write participation. known=false requires conservative admission for a dynamic remote call.

type RemoteCypherTx

type RemoteCypherTx interface {
	QueryCypher(ctx context.Context, statement string, params map[string]interface{}) ([]string, [][]interface{}, error)
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
}

RemoteCypherTx represents an explicit remote Cypher transaction handle.

type RemoteEngine

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

RemoteEngine implements Engine by forwarding operations to a remote NornicDB instance via Bolt protocol (preferred) or HTTP tx API (fallback), auto-detected from the URI scheme.

func NewRemoteEngine

func NewRemoteEngine(cfg RemoteEngineConfig) (engine *RemoteEngine, err error)

NewRemoteEngine creates a remote engine. Transport is auto-detected from the URI scheme.

func NewStatementRemoteEngine

func NewStatementRemoteEngine(owner any, run RemoteStatementRunner) *RemoteEngine

NewStatementRemoteEngine is a remote engine of its own schema, issued to owner, whose every operation runs its statements through run (WithStatementRunner).

func (*RemoteEngine) AllEdges

func (r *RemoteEngine) AllEdges(ctx context.Context) ([]*Edge, error)

func (*RemoteEngine) AllNodes

func (r *RemoteEngine) AllNodes(ctx context.Context) ([]*Node, error)

func (*RemoteEngine) BatchGetNodes

func (r *RemoteEngine) BatchGetNodes(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

func (*RemoteEngine) BeginCypherTx

func (r *RemoteEngine) BeginCypherTx(ctx context.Context, mode RemoteAccessMode) (_ RemoteCypherTx, err error)

BeginCypherTx opens an explicit remote transaction in the required access mode. RemoteAccessRead selects a READ session; RemoteAccessWrite selects WRITE. The mode remains fixed for this handle's lifetime. ctx must be non-nil. For example:

tx, err := remote.BeginCypherTx(ctx, RemoteAccessRead) if err != nil { return err } defer tx.Rollback(ctx) _, rows, err := tx.QueryCypher(ctx, "MATCH (n) RETURN n LIMIT 10", nil)

func (*RemoteEngine) BulkCreateEdges

func (r *RemoteEngine) BulkCreateEdges(ctx context.Context, edges []*Edge) error

func (*RemoteEngine) BulkCreateNodes

func (r *RemoteEngine) BulkCreateNodes(ctx context.Context, nodes []*Node) error

func (*RemoteEngine) BulkDeleteEdges

func (r *RemoteEngine) BulkDeleteEdges(ctx context.Context, ids []EdgeID) error

func (*RemoteEngine) BulkDeleteNodes

func (r *RemoteEngine) BulkDeleteNodes(ctx context.Context, ids []NodeID) error

func (*RemoteEngine) Close

func (r *RemoteEngine) Close() error

func (*RemoteEngine) CreateEdge

func (r *RemoteEngine) CreateEdge(ctx context.Context, edge *Edge) error

func (*RemoteEngine) CreateNode

func (r *RemoteEngine) CreateNode(ctx context.Context, node *Node) (NodeID, error)

func (*RemoteEngine) DeleteByPrefix

func (r *RemoteEngine) DeleteByPrefix(prefix string) (nodesDeleted int64, edgesDeleted int64, err error)

func (*RemoteEngine) DeleteEdge

func (r *RemoteEngine) DeleteEdge(ctx context.Context, id EdgeID) error

func (*RemoteEngine) DeleteNode

func (r *RemoteEngine) DeleteNode(ctx context.Context, id NodeID) error

func (*RemoteEngine) EdgeCount

func (r *RemoteEngine) EdgeCount(ctx context.Context) (int64, error)

func (*RemoteEngine) EdgeCountByEndLabel

func (r *RemoteEngine) EdgeCountByEndLabel(ctx context.Context, label, edgeType string) (int64, error)

EdgeCountByEndLabel answers the positional (label, type) count from the remote instance's own counters: the remote server serves MATCH ()-[r:T]->(e:L) O(1).

func (*RemoteEngine) EdgeCountByStartLabel

func (r *RemoteEngine) EdgeCountByStartLabel(ctx context.Context, label, edgeType string) (int64, error)

EdgeCountByStartLabel answers the positional (label, type) count from the remote instance's own counters: the remote server serves MATCH (s:L)-[r:T]->() O(1).

func (*RemoteEngine) EdgeCountByType

func (r *RemoteEngine) EdgeCountByType(ctx context.Context, edgeType string) (int64, error)

EdgeCountByType answers the typed count from the remote instance's own per-type counter fast path (issue #638): the remote server serves this shape O(1) from its counters, so no client-side edge materialization exists on this path.

func (*RemoteEngine) GetEdge

func (r *RemoteEngine) GetEdge(ctx context.Context, id EdgeID) (*Edge, error)

func (*RemoteEngine) GetEdgeBetween

func (r *RemoteEngine) GetEdgeBetween(ctx context.Context, startID, endID NodeID, edgeType string) (*Edge, error)

func (*RemoteEngine) GetEdgesByType

func (r *RemoteEngine) GetEdgesByType(ctx context.Context, edgeType string) ([]*Edge, error)

func (*RemoteEngine) GetFirstNodeByLabel

func (r *RemoteEngine) GetFirstNodeByLabel(ctx context.Context, label string) (*Node, error)

func (*RemoteEngine) GetInDegree

func (r *RemoteEngine) GetInDegree(ctx context.Context, nodeID NodeID) (int, error)

func (*RemoteEngine) GetNode

func (r *RemoteEngine) GetNode(ctx context.Context, id NodeID) (*Node, error)

func (*RemoteEngine) GetNodesByLabel

func (r *RemoteEngine) GetNodesByLabel(ctx context.Context, label string) ([]*Node, error)

func (*RemoteEngine) GetOutDegree

func (r *RemoteEngine) GetOutDegree(ctx context.Context, nodeID NodeID) (int, error)

func (*RemoteEngine) GetSchema

func (r *RemoteEngine) GetSchema() *SchemaManager

func (*RemoteEngine) NodeCount

func (r *RemoteEngine) NodeCount(ctx context.Context) (int64, error)

func (*RemoteEngine) QueryCypher

func (r *RemoteEngine) QueryCypher(ctx context.Context, statement string, params map[string]interface{}, mode RemoteAccessMode) ([]string, [][]interface{}, error)

QueryCypher executes an arbitrary Cypher query against the remote instance and returns column names and raw rows. This is used by the fabric layer to dispatch fragment queries to remote constituents without going through the node/edge Engine abstraction.

mode is required: RemoteAccessRead selects a managed read transaction; RemoteAccessWrite selects a managed write transaction. Storage never parses source to infer mode. ctx must be non-nil. For example:

columns, rows, err := remote.QueryCypher(ctx, "RETURN 1", nil, RemoteAccessRead)

The Bolt transport returns columns from the result record keys. The HTTP transport returns columns from the tx API response.

func (*RemoteEngine) ReadAdjacentEdges

func (r *RemoteEngine) ReadAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadAdjacentEdges answers one adjacent-edge request against the remote graph. A type set becomes the statement's relationship type expression; a header request is answered from the relationships the statement returned.

func (*RemoteEngine) StatementOwner

func (r *RemoteEngine) StatementOwner() any

StatementOwner is the statement the engine was issued to (WithStatementRunner), or nil for an engine of its own.

func (*RemoteEngine) StreamNodesWithOptions

func (r *RemoteEngine) StreamNodesWithOptions(ctx context.Context, opts StreamNodesOptions, fn func(node *Node) error) error

StreamNodesWithOptions satisfies the Engine streaming contract for the remote view: nodes are materialized through the remote read path and the per-option transforms (prefix scope, projection, embedding stripping) are applied locally.

func (*RemoteEngine) UpdateEdge

func (r *RemoteEngine) UpdateEdge(ctx context.Context, updateRequest EdgeUpdateRequest) error

func (*RemoteEngine) UpdateNode

func (r *RemoteEngine) UpdateNode(ctx context.Context, updateRequest NodeUpdateRequest) error

func (*RemoteEngine) WithStatementRunner

func (r *RemoteEngine) WithStatementRunner(owner any, run RemoteStatementRunner) *RemoteEngine

WithStatementRunner is the remote engine whose every operation runs its statements through run instead of a session of its own: a composite statement's remote participant runs them in the statement's remote transaction, so nothing an operation writes is kept unless the statement commits. A transaction begun on it joins run's: it ends with whatever run belongs to, not with its own Commit or Rollback. The engine is issued to owner (StatementOwner).

type RemoteEngineConfig

type RemoteEngineConfig struct {
	// URI is the remote NornicDB endpoint (bolt:// or http:// scheme).
	URI string

	// Database is the target database name on the remote instance.
	Database string

	// AuthToken is the caller's authorization header value (e.g. "Bearer <token>"),
	// used for OIDC credential forwarding.
	AuthToken string

	// User and Password are used for explicit basic auth (user_password auth mode).
	User     string
	Password string

	// HTTPClient is an optional custom HTTP client, used only when transport is HTTP.
	HTTPClient *http.Client
}

RemoteEngineConfig configures a remote storage engine.

The URI field determines the transport protocol:

  • bolt://, bolt+s://, bolt+ssc://, neo4j://, neo4j+s://, neo4j+ssc:// → Bolt transport (preferred)
  • http://, https:// → HTTP tx API transport (fallback)

type RemoteEntityValue

type RemoteEntityValue map[string]interface{}

RemoteEntityValue is a graph entity decoded from a remote database transport. It preserves the remote element ID and nested properties without confusing an ordinary Cypher or JSON map with a node or relationship. RemoteEngine creates these values only from Bolt graph values or HTTP graph response metadata.

The map representation preserves existing JSON output. For example, a remote node marshals as {"elementId":"4:remote:n","labels":["Doc"],"properties":{}}. Consumers should preserve this type when forwarding query bindings; converting it to map[string]interface{} intentionally discards its graph provenance. This Go type is a representation marker, not an authorization boundary.

func (RemoteEntityValue) LegacyIDs

func (v RemoteEntityValue) LegacyIDs() (id, start, end int64)

LegacyIDs returns the deprecated numeric source IDs retained by the remote transport. Older hand-built markers have no numeric identity and return -1. Element IDs remain available on the value's existing elementId fields.

func (RemoteEntityValue) MarshalJSON

func (v RemoteEntityValue) MarshalJSON() ([]byte, error)

MarshalJSON preserves the public remote map shape without exposing private numeric transport identity. Entity properties are never modified.

type RemoteParameterValue

type RemoteParameterValue interface {
	RemoteParameterValue() interface{}
}

RemoteParameterValue is a value of the Cypher executor that a remote participant receives as its Cypher type. RemoteParameterValue returns it as the Neo4j Go driver sends it over Bolt: time.Time, dbtype.Date, dbtype.LocalTime, dbtype.Time, dbtype.LocalDateTime, dbtype.Duration, dbtype.Point2D, dbtype.Point3D, or a list or string.

type RemotePathValue

type RemotePathValue []RemoteEntityValue

RemotePathValue is an ordered remote path: node, relationship, node, and so on. Remote transports construct it from actual path metadata; an ordinary list never gains path identity. Preserve it when forwarding query bindings. For example, RETURN p through a remote Fabric constituent keeps its source node and relationship identities rather than becoming a generic list.

func (RemotePathValue) CypherOpaqueSlice

func (RemotePathValue) CypherOpaqueSlice()

CypherOpaqueSlice preserves path identity when a generic list reader sees this slice carrier. A remote path is a graph scalar, not a Cypher list.

func (RemotePathValue) Parts

func (p RemotePathValue) Parts() (nodes, relationships []RemoteEntityValue, ok bool)

Parts validates a remote path and returns its ordered nodes and relationships. Nil and empty carriers are not paths; a zero-hop path contains one node. For example, nodes, relationships, ok := path.Parts() preserves the remote markers for nodes(path), relationships(path), and protocol serialization.

type RemoteStatementRunner

type RemoteStatementRunner func(ctx context.Context, statement string, params map[string]interface{}, mode RemoteAccessMode) ([]string, [][]interface{}, error)

RemoteStatementRunner runs one statement of a remote engine's operations, and returns its columns and rows.

type RemoteTypedValue

type RemoteTypedValue struct {
	Type        string
	Text        string
	SRID        int
	Coordinates []float64
}

RemoteTypedValue is a temporal or spatial value a remote participant returned, in one representation for both transports. Type is Neo4j's type code. A date, time, localtime, datetime, localdatetime or duration carries its ISO 8601 Text; a point carries its SRID and Coordinates (x, y and, in three dimensions, z). Bolt delivers these values as driver values (normalizeBoltGraphValue) and HTTP as text typed by the row's metadata (decodeRemoteHTTPValue); the Cypher executor turns them into its own values.

type ReplayError

type ReplayError struct {
	Sequence  uint64
	Operation OperationType
	Error     error
}

ReplayError captures details about a failed replay entry.

type ReplayResult

type ReplayResult struct {
	Applied int           // Successfully applied entries
	Skipped int           // Expected skips (duplicates, checkpoints)
	Failed  int           // Unexpected failures
	Errors  []ReplayError // Detailed error information
}

ReplayResult tracks the outcome of WAL replay for observability.

func (ReplayResult) HasCriticalErrors

func (r ReplayResult) HasCriticalErrors() bool

HasCriticalErrors returns true if there were unexpected failures.

func (*ReplayResult) Record

func (r *ReplayResult) Record(entry WALEntry, err error)

Record accumulates the actual outcome of ReplayWALEntry. Checkpoints and duplicate creates are expected skips; every other error retains its original sequence, operation and cause. For example, a caller replaying a slice uses:

for _, entry := range entries {
	result.Record(entry, ReplayWALEntry(ctx, engine, entry))
}

func (ReplayResult) Summary

func (r ReplayResult) Summary() string

Summary returns a human-readable summary of replay results.

type ReplicationSnapshot

type ReplicationSnapshot struct {
	WALPosition uint64
	Nodes       []*Node
	Edges       []*Edge
}

ReplicationSnapshot is the full set of stored entities at a WAL position. Its MessagePack wire representation preserves dynamic property types and embedding metadata without changing the database's stored entity format.

func (*ReplicationSnapshot) DecodeMsgpack

func (snapshot *ReplicationSnapshot) DecodeMsgpack(dec *msgpack.Decoder) error

func (ReplicationSnapshot) EncodeMsgpack

func (snapshot ReplicationSnapshot) EncodeMsgpack(enc *msgpack.Encoder) error

type RetentionPolicy

type RetentionPolicy struct {
	MaxVersionsPerKey int
	TTL               time.Duration
}

RetentionPolicy controls default MVCC historical retention for a storage engine. MaxVersionsPerKey applies to closed historical versions; the current head is always preserved. When MaxVersionsPerKey <= 0 the engine skips archival entirely: updates overwrite in place and deletes remove the primary key without creating a version record. TTL optionally protects versions newer than now-TTL from pruning.

func (RetentionPolicy) RetainsHistory added in v1.1.0

func (p RetentionPolicy) RetainsHistory() bool

RetainsHistory reports whether this policy keeps any closed historical versions. Callers on the write hot path use this to short-circuit archival work when the head-only configuration is active.

type RevealScopes

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

RevealScopes is an opaque, copyable handle to the genuine query reveal leases recorded on an actual context. The zero value records no lease and cannot manufacture one; only QueryRevealScopes reads existing leases from a caller context. Holding the handle instead of that context keeps request cancellation and request values out of the borrowing owner, and it reuses the existing lease links, so capturing metadata allocates nothing.

func QueryRevealScopes

func QueryRevealScopes(ctx context.Context) RevealScopes

QueryRevealScopes captures the query reveal leases currently recorded on ctx. ctx must be the actual caller context; a context without leases yields the zero RevealScopes handle, which inherits nothing. Capture once where the owning statement is known and keep the handle; do not retain ctx for it.

func (RevealScopes) Mode

func (scopes RevealScopes) Mode(engine Engine) (reveal, owned bool)

Mode reports the reveal mode of a live lease for engine's physical store. A missing or released lease returns owned=false; a handle cannot create one. For example: reveal, owned := QueryRevealScopes(ctx).Mode(engine).

type SchemaCompositeIndexDef

type SchemaCompositeIndexDef struct {
	Name       string   `json:"name"`
	Label      string   `json:"label"`
	Properties []string `json:"properties"`
}

type SchemaDefinition

type SchemaDefinition struct {
	Version                int      `json:"version"`
	LabelTokens            []string `json:"label_tokens,omitempty"`
	RelationshipTypeTokens []string `json:"relationship_type_tokens,omitempty"`

	Constraints         []Constraint         `json:"constraints,omitempty"`
	ConstraintContracts []ConstraintContract `json:"constraint_contracts,omitempty"`

	PropertyTypeConstraints []PropertyTypeConstraint `json:"property_type_constraints,omitempty"`

	PropertyIndexes  []SchemaPropertyIndexDef  `json:"property_indexes,omitempty"`
	CompositeIndexes []SchemaCompositeIndexDef `json:"composite_indexes,omitempty"`
	FulltextIndexes  []FulltextIndex           `json:"fulltext_indexes,omitempty"`
	VectorIndexes    []VectorIndex             `json:"vector_indexes,omitempty"`
	RangeIndexes     []SchemaRangeIndexDef     `json:"range_indexes,omitempty"`
	// LookupIndexes are the token lookup indexes (schema_lookup_index.go).
	// Nil in a definition written before they were persisted, which reads
	// as the default ones.
	LookupIndexes *[]SchemaLookupIndexDef `json:"lookup_indexes,omitempty"`

	DecayProfileBundles  []knowledgepolicy.DecayProfileBundle  `json:"decay_profile_bundles,omitempty"`
	DecayProfileBindings []knowledgepolicy.DecayProfileBinding `json:"decay_profile_bindings,omitempty"`
	PromotionProfiles    []knowledgepolicy.PromotionProfileDef `json:"promotion_profiles,omitempty"`
	PromotionPolicies    []knowledgepolicy.PromotionPolicyDef  `json:"promotion_policies,omitempty"`
}

SchemaDefinition is the persisted representation of NornicDB schema rules.

It stores schema definitions and durable token positions, not derived/indexed data structures (like unique value maps), which are rebuilt from stored nodes/edges on startup.

This mirrors Neo4j’s model:

  • schema rules are durable metadata
  • index contents can be rebuilt if needed

type SchemaLookupIndexDef

type SchemaLookupIndexDef struct {
	Name       string               `json:"name"`
	EntityType ConstraintEntityType `json:"entity_type"`
}

SchemaLookupIndexDef is a persisted token lookup index.

type SchemaManager

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

SchemaManager manages database schema including constraints and indexes.

func NewSchemaManager

func NewSchemaManager() *SchemaManager

NewSchemaManager creates a new schema manager with empty constraint and index collections.

The schema manager provides thread-safe management of database schema including:

  • Unique constraints (enforce uniqueness on properties)
  • Node key constraints (composite unique keys)
  • Existence constraints (require properties to exist)
  • Property indexes (speed up lookups)
  • Vector indexes (semantic similarity search)
  • Full-text indexes (text search with scoring)

Returns:

  • *SchemaManager ready for use

Example 1 - Basic Usage:

schema := storage.NewSchemaManager()

// Add unique constraint
constraint := &storage.UniqueConstraint{
	Name:     "unique_user_email",
	Label:    "User",
	Property: "email",
}
schema.AddUniqueConstraint(constraint)

// Validate before creating node
err := schema.ValidateUnique("User", "email", "alice@example.com", "")
if err != nil {
	log.Fatal("Email already exists!")
}

Example 2 - Multiple Constraints:

schema := storage.NewSchemaManager()

// Email must be unique
schema.AddUniqueConstraint(&storage.UniqueConstraint{
	Name: "unique_email", Label: "User", Property: "email",
})

// Username must be unique
schema.AddUniqueConstraint(&storage.UniqueConstraint{
	Name: "unique_username", Label: "User", Property: "username",
})

// All users must have email property
schema.AddConstraint(storage.Constraint{
	Name: "user_must_have_email",
	Type: storage.ConstraintExists,
	Label: "User",
	Properties: []string{"email"},
})

Example 3 - With Indexes for Performance:

schema := storage.NewSchemaManager()

// Index for fast lookups
schema.AddPropertyIndex("idx_user_email", "User", []string{"email"})

// Vector index for semantic search
schema.AddVectorIndex("doc_embeddings", "Document", "embedding", 1024,
	"cosine", storage.ConstraintEntityNode)

ELI12:

Think of a SchemaManager like a rule book for your database:

  • "Every person must have a unique name" (unique constraint)
  • "You can't create a person without an age" (existence constraint)
  • "Make a quick-lookup list for emails" (index)

Before you add data, the SchemaManager checks: "Does this follow the rules?" If yes, data goes in. If no, you get an error. It keeps your database clean!

Thread Safety:

All methods are thread-safe for concurrent access.

func ReadSchema

func ReadSchema(ctx context.Context, engine Engine) (*SchemaManager, error)

ReadSchema reads an engine's schema with the caller's lifetime. A composite returns an error and no schema when any required constituent is unavailable. For example, use ReadSchema(ctx, composite) before listing merged indexes.

func (*SchemaManager) AddCompositeIndex

func (sm *SchemaManager) AddCompositeIndex(name, label string, properties []string) error

AddCompositeIndex creates a composite (equality) index on one or more properties. An arity-1 index is the single-property index; arity >= 2 adds prefix lookups.

Example usage:

sm.AddCompositeIndex("user_location_idx", "User", []string{"country", "city", "zipcode"})

This enables efficient queries like:

  • WHERE country = 'US' AND city = 'NYC' AND zipcode = '10001' (full match)
  • WHERE country = 'US' AND city = 'NYC' (prefix match)
  • WHERE country = 'US' (prefix match, uses first property only)

func (*SchemaManager) AddConstraint

func (sm *SchemaManager) AddConstraint(c Constraint, ifNotExists ...bool) error

AddConstraint adds a constraint to the schema. Stores constraint in both the constraints map and uniqueConstraints (for backward compatibility).

Conflict rules (matching Neo4j behavior):

  • Same name, already exists with identical schema+type: error, unless ifNotExists (then no-op)
  • Same name, different schema or type: error
  • Different name, same schema + same type: error (duplicate schema), unless ifNotExists
  • Uniqueness vs relationship key on same schema: error (conflicting)

Pass ifNotExists=true when the DDL includes IF NOT EXISTS; duplicate-schema is then a no-op.

func (*SchemaManager) AddConstraintContractBundle

func (sm *SchemaManager) AddConstraintContractBundle(contract ConstraintContract, compiledConstraints []Constraint, compiledTypes []PropertyTypeConstraint, ifNotExists bool) error

AddConstraintContractBundle admits the contract name and its IF NOT EXISTS no-op, then applies the primitives the contract compiles and the contract itself, persisting the definition once.

Only the families this bundle can change are staged before the first change: the contract family, the constraint/index/temporal families when it compiles constraints, and the property-type family when it compiles types. A compiled primitive whose admission fails, or a rejected persist, restores exactly those families, so every other rule keeps its live allocation, runtime value cache and filled index and the compiled binding table is not recompiled. Staging happens even without a persister, because a later compiled primitive can still reject. An IF NOT EXISTS match costs the name check alone: it exports, clones, persists and replaces nothing.

func (*SchemaManager) AddFulltextIndex

func (sm *SchemaManager) AddFulltextIndex(name string, targets, properties []string, entityType ConstraintEntityType) error

AddFulltextIndex adds a full-text index over node labels or relationship types. The entity kind selects which target list is stored; all supplied slices are owned by the schema. Existing names remain an idempotent no-op. For example, AddFulltextIndex("people", []string{"Person"}, []string{"name"}, ConstraintEntityNode) indexes node names without changing stored formats.

func (*SchemaManager) AddLookupIndex

func (sm *SchemaManager) AddLookupIndex(name string, entityType ConstraintEntityType) error

AddLookupIndex adds the lookup index for entityType named name. There is at most one per entity type; the caller reports an existing one (Neo4j's IndexAlreadyExists). An empty name is the default name. A constraint-owned name fails with ConstraintWithNameAlreadyExists before checking for an existing lookup index.

func (*SchemaManager) AddPropertyIndex

func (sm *SchemaManager) AddPropertyIndex(name, label string, properties []string) error

AddPropertyIndex adds an arity-1 equality index. It is the single-property spelling of AddCompositeIndex: the index lives in compositeIndexes and the arity-1 encoding (values) drives equality, ORDER BY, range and not-null seeks.

func (*SchemaManager) AddPropertyTypeConstraint

func (sm *SchemaManager) AddPropertyTypeConstraint(name, label, property string, expectedType PropertyType, opts PropertyTypeConstraintOptions) error

AddPropertyTypeConstraint enforces a property type (NULL values allowed), with entity scope and duplicate admission selected in opts.

Example: sm.AddPropertyTypeConstraint("age_type", "Person", "age", PropertyTypeInteger, PropertyTypeConstraintOptions{EntityType: ConstraintEntityNode}).

func (*SchemaManager) AddRangeIndex

func (sm *SchemaManager) AddRangeIndex(name, label, property string) error

AddRangeIndex adds a range index for a single property.

func (*SchemaManager) AddRangeIndexForEntity added in v1.1.6

func (sm *SchemaManager) AddRangeIndexForEntity(name, label string, properties []string, entityType ConstraintEntityType) error

AddRangeIndexForEntity adds a range index for NODE or RELATIONSHIP entities. For standalone CREATE INDEX forms, properties may contain one or more fields.

func (*SchemaManager) AddTypedIndexForEntity

func (sm *SchemaManager) AddTypedIndexForEntity(kind IndexKind, name, label string, properties []string, entityType ConstraintEntityType) error

AddTypedIndexForEntity admits a durable TEXT or POINT schema definition. Query execution retains its existing scan fallback; this method does not introduce a dedicated text-search or spatial acceleration engine.

Example:

schema.AddTypedIndexForEntity(IndexKindText, "person_name", "Person", []string{"name"}, ConstraintEntityNode)

func (*SchemaManager) AddUniqueConstraint

func (sm *SchemaManager) AddUniqueConstraint(name, label, property string, ifNotExists ...bool) error

AddUniqueConstraint adds a unique constraint. Stores in both uniqueConstraints (for value tracking) and constraints (for lookup by label). Pass ifNotExists=true for IF NOT EXISTS semantics (duplicate is no-op).

func (*SchemaManager) AddVectorIndex

func (sm *SchemaManager) AddVectorIndex(name, label, property string, dimensions int, similarityFunc string, entityType ConstraintEntityType) error

AddVectorIndex adds a vector index scoped to a node label or relationship type.

Example: sm.AddVectorIndex("doc_vector", "Doc", "embedding", 384, "cosine", ConstraintEntityNode).

func (*SchemaManager) AlterDecayProfile added in v1.1.0

func (sm *SchemaManager) AlterDecayProfile(name string, updates map[string]interface{}) error

AlterDecayProfile updates options on an existing decay profile bundle.

func (*SchemaManager) AlterDecayProfileBinding added in v1.3.1

func (sm *SchemaManager) AlterDecayProfileBinding(name string, replacement knowledgepolicy.DecayProfileBinding) error

AlterDecayProfileBinding replaces the target and APPLY definition of an existing binding.

func (*SchemaManager) AlterPromotionPolicy added in v1.1.0

func (sm *SchemaManager) AlterPromotionPolicy(name string, updates map[string]interface{}) error

AlterPromotionPolicy updates an existing promotion policy. Invalid options are rejected before changing the policy or persisting schema.

func (*SchemaManager) AlterPromotionPolicyDefinition added in v1.3.1

func (sm *SchemaManager) AlterPromotionPolicyDefinition(name string, replacement knowledgepolicy.PromotionPolicyDef) error

AlterPromotionPolicyDefinition replaces the target and APPLY definition of an existing policy.

func (*SchemaManager) AlterPromotionProfile added in v1.1.0

func (sm *SchemaManager) AlterPromotionProfile(name string, updates map[string]interface{}) error

AlterPromotionProfile updates options on an existing promotion profile.

func (*SchemaManager) ApplyUniqueValue

func (sm *SchemaManager) ApplyUniqueValue(ctx context.Context, label, property string, value any, nodeID NodeID, action UniqueValueAction) error

ApplyUniqueValue is the single owner of canonical unique-value claim publication: it resolves the (label, property) constraint and its value-key projection, then applies action to the claim under the owning constraint's mutex. It is a programming error to pass an action outside the declared UniqueValueAction constants, so that case panics instead of being treated as a publication mode.

Atomic publication retires all predecessor claims with RetiredUniqueClaim before acquiring final claims, so key transfers do not depend on mutation order. A nil or non-indexable value, or an unconstrained (label, property) pair, is a no-op. ctx owns preparation and admission; an error leaves the current claim unchanged. Accepted publication supplies its completion lifetime.

Example usage:

// Publish one current, validated claim.
err := schema.ApplyUniqueValue(ctx, "User", "email", "alice@example.com", node.ID, storage.ValidatedUniqueClaim)

// Retire the claim held by the stored node being deleted.
err = schema.ApplyUniqueValue(ctx, "User", "email", "alice@example.com", node.ID, storage.RetiredUniqueClaim)

func (*SchemaManager) BackfillCompositeIndex

func (sm *SchemaManager) BackfillCompositeIndex(ctx context.Context, name string, entries map[NodeID]map[string]interface{}) error

BackfillCompositeIndex fills a newly created composite index from the already-stored nodes, mirroring BackfillPropertyIndex. Nodes with pending writes in an attached AsyncEngine are skipped: the engine indexes them when they are flushed, and lookups see them through the pending view until then (#719). On success the index is marked filled so seeks can use it. The caller retains ctx through pending admission and every node preparation; a canceled fill never marks an unfilled index ready; the DDL owner discards a canceled staged declaration before it becomes visible.

func (*SchemaManager) BackfillPropertyIndex

func (sm *SchemaManager) BackfillPropertyIndex(label, property string, values map[NodeID]interface{}) error

BackfillPropertyIndex fills a newly created arity-1 index with values (node ID → property value). Nodes with pending writes in an attached AsyncEngine are skipped: the engine indexes them when they are flushed, and lookups see them through the pending view until then (#719).

func (*SchemaManager) BeginSchemaTransaction

func (sm *SchemaManager) BeginSchemaTransaction(ctx context.Context, begin func(context.Context, BeginRequest) (*BadgerTransaction, error)) (*BadgerTransaction, error)

BeginSchemaTransaction admits an autocommit schema statement before opening its snapshot through begin. The caller supplies the live namespace manager and its existing transaction opener, preserving wrapper admission; the opener receives AutocommitSchemaBegin, so the engine takes its exclusive lifecycle admission before that snapshot and its fill reads a population no data commit or peer schema publication can change under it. The native transaction owns this admission until publication or rollback; callers must roll back any transaction they do not commit, including rejected commits. The opener must return a new active transaction, as BeginTransaction does. Explicit transactions must use their ordinary opener to retain their snapshot and their conflict guards.

For example, tx, err := schema.BeginSchemaTransaction(ctx, engine.BeginTransaction) opens a schema statement whose peer cannot snapshot an unpublished definition.

func (*SchemaManager) CheckUniqueConstraint

func (sm *SchemaManager) CheckUniqueConstraint(ctx context.Context, label, property string, value interface{}, excludeNode NodeID) error

CheckUniqueConstraint checks if a value violates a unique constraint. ctx owns key preparation and admission; cancellation leaves claims unchanged. Returns error if constraint is violated.

func (*SchemaManager) CompositeIndexLookup

func (sm *SchemaManager) CompositeIndexLookup(ctx context.Context, idx *CompositeIndex, values []interface{}, full bool) ([]NodeID, error)

CompositeIndexLookup returns one composite-index read — all indexed properties equal (full) or the leading properties equal (prefix) — merged with the pending writes the schema is attached to (#719, NOR-375).

A composite index's postings are maintained when a write reaches the engine, so on an engine with an attached write-behind buffer they describe committed state only. An acknowledged-but-unflushed rename is already the body every read returns (GetNode, label scans, the pending property-index owner) while the index still lists the node under its previous key. A reader that resolves an indexed MATCH/MERGE candidate set through the index postings alone therefore misses the acknowledged membership, and MERGE creates a duplicate of a node that already exists. This owner is the one read that combines both populations:

  • committed candidates of nodes the pending writes superseded (created, rewritten or deleted) are dropped;
  • the pending nodes that hold the same leading values are added, read from the pending index's value populations instead of by copying every buffered node of the label.

The pending view is captured before the index lock, exactly as the scalar property-index owner (PropertyIndexLookup) captures it: the buffer's read lease stays stable while the postings are copied and merged, so a node a drain retires is counted in exactly one of the two populations — never in both, never in neither.

values are the raw pattern values; they are canonicalized exactly as IndexNode and LookupFull/LookupPrefix canonicalize them, so a pending node equals a committed entry precisely when it keys identically. A value no index entry can hold yields no pending candidate, matching the committed miss.

CompositeIndex.LookupFull and LookupPrefix remain the committed posting reads. This merged read must not be called from a caller that already holds the buffer's read view (constraint validation's captured view): the pending source's read lease is not reentrant, so re-acquiring it there would queue a second reader behind a writer that is waiting for the first, and neither would return.

func (*SchemaManager) CompositeIndexValueCount

func (sm *SchemaManager) CompositeIndexValueCount(ctx context.Context, idx *CompositeIndex, values []interface{}, full bool) (count int, indexed bool, err error)

CompositeIndexValueCount is PropertyIndexValueCount for a composite index read: the length of the committed posting list CompositeIndexLookup starts from for values (all properties when full, otherwise the leading ones), plus the most pending writes its lookup can add (compositeMatchBound), read from the same pending-write view without scanning it. indexed is false when the index cannot key values.

Both terms are read under one pending lease, the order the scalar owner uses. A write-behind flush commits a buffered node into the postings and retires it from the pending view, so reading the postings before admission lets that flush land in between: the node is then in neither term, and the estimate undercounts the population the lookup returns.

func (*SchemaManager) ConstraintCreationRequired

func (sm *SchemaManager) ConstraintCreationRequired(ctx context.Context, c Constraint, ifNotExists bool) (bool, error)

ConstraintCreationRequired checks the canonical constraint admission policy before a caller performs stored-data validation. False with no error means an IF NOT EXISTS no-op. This is a preflight, not a reservation: AddConstraint checks admission again when publishing the schema mutation.

func (*SchemaManager) ConstraintPropertyIndex

func (sm *SchemaManager) ConstraintPropertyIndex(name string) (*PropertyIndex, bool)

ConstraintPropertyIndex returns the equality index constraint name owns (#875), if it has one.

func (*SchemaManager) CreateDecayProfileBinding added in v1.1.0

func (sm *SchemaManager) CreateDecayProfileBinding(binding knowledgepolicy.DecayProfileBinding, ifNotExists ...bool) error

CreateDecayProfileBinding adds a decay profile binding to the schema.

func (*SchemaManager) CreateDecayProfileBundle added in v1.1.0

func (sm *SchemaManager) CreateDecayProfileBundle(bundle knowledgepolicy.DecayProfileBundle, ifNotExists ...bool) error

CreateDecayProfileBundle adds a decay profile bundle to the schema.

func (*SchemaManager) CreatePromotionPolicy added in v1.1.0

func (sm *SchemaManager) CreatePromotionPolicy(policy knowledgepolicy.PromotionPolicyDef, ifNotExists ...bool) error

CreatePromotionPolicy adds a promotion policy to the schema.

func (*SchemaManager) CreatePromotionProfile added in v1.1.0

func (sm *SchemaManager) CreatePromotionProfile(profile knowledgepolicy.PromotionProfileDef, ifNotExists ...bool) error

CreatePromotionProfile adds a promotion profile to the schema.

func (*SchemaManager) DropConstraint

func (sm *SchemaManager) DropConstraint(name string) error

DropConstraint removes a constraint (by name) from the schema.

The name may refer to a standard constraint, a property type constraint, or a constraint contract. Dropping a contract removes its metadata together with every primitive constraint compiled out of it (named <contract>__entry_NN), so SHOW CONSTRAINTS and SHOW CONSTRAINT CONTRACTS stay consistent. The drop is all-or-nothing: if persisting the new schema fails, everything removed is restored.

Example:

// CREATE CONSTRAINT person_contract FOR (n:Person) REQUIRE { n.id IS UNIQUE ... }
err := schema.DropConstraint("person_contract") // removes the contract and person_contract__entry_01

func (*SchemaManager) DropDecayProfile added in v1.1.0

func (sm *SchemaManager) DropDecayProfile(name string, ifExists ...bool) error

DropDecayProfile removes a decay profile bundle or binding by name.

func (*SchemaManager) DropIndex

func (sm *SchemaManager) DropIndex(name string) error

DropIndex removes an index (by name) from the schema. It searches across all index types: property, composite, fulltext, vector, and range.

func (*SchemaManager) DropPromotionPolicy added in v1.1.0

func (sm *SchemaManager) DropPromotionPolicy(name string, ifExists ...bool) error

DropPromotionPolicy removes a promotion policy by name.

func (*SchemaManager) DropPromotionProfile added in v1.1.0

func (sm *SchemaManager) DropPromotionProfile(name string, ifExists ...bool) error

DropPromotionProfile removes a promotion profile by name.

func (*SchemaManager) EdgeWriteChecked

func (sm *SchemaManager) EdgeWriteChecked(relType string) bool

EdgeWriteChecked reports whether writing a relationship of this type is checked by the schema: a relationship constraint (UNIQUE, EXISTS, KEY, TEMPORAL, DOMAIN, CARDINALITY, POLICY), a property type or a constraint contract on the type. See NodeWriteChecked for how the AsyncEngine uses it.

func (*SchemaManager) ExportDefinition

func (sm *SchemaManager) ExportDefinition(ctx context.Context) (*SchemaDefinition, error)

ExportDefinition returns a stable, persisted representation of the schema. The returned object is safe to serialize and does not include runtime caches.

ctx owns admission, contract cloning and ordering. A canceled ctx returns its own error and no partial definition; an exported definition is a detached snapshot, so later live schema changes never reach it.

func (*SchemaManager) GetAllConstraintContracts

func (sm *SchemaManager) GetAllConstraintContracts(ctx context.Context) ([]ConstraintContract, error)

GetAllConstraintContracts returns detached copies of every constraint contract ordered by name. ctx bounds metadata admission, cloning and ordering; its only errors are context cancellation/deadline errors, and an error returns no partial contracts.

func (*SchemaManager) GetAllConstraints

func (sm *SchemaManager) GetAllConstraints() []Constraint

GetAllConstraints returns all constraints in the schema, regardless of label. This is used by db.constraints() procedure to list all constraints.

func (*SchemaManager) GetAllPropertyTypeConstraints

func (sm *SchemaManager) GetAllPropertyTypeConstraints() []PropertyTypeConstraint

GetAllPropertyTypeConstraints returns all property type constraints.

func (*SchemaManager) GetBindingTable added in v1.1.0

func (sm *SchemaManager) GetBindingTable() *knowledgepolicy.BindingTable

GetBindingTable returns the current compiled binding table, or nil if not built.

func (*SchemaManager) GetCompositeIndex

func (sm *SchemaManager) GetCompositeIndex(name string) (*CompositeIndex, bool)

GetCompositeIndex returns a composite index by name.

func (*SchemaManager) GetCompositeIndexesForLabel

func (sm *SchemaManager) GetCompositeIndexesForLabel(label string) []*CompositeIndex

GetCompositeIndexForLabel returns all composite indexes for a label.

func (*SchemaManager) GetConstraintContractsForTarget

func (sm *SchemaManager) GetConstraintContractsForTarget(ctx context.Context, entityType ConstraintEntityType, labelOrType string) ([]ConstraintContract, error)

GetConstraintContractsForTarget returns detached matching contracts ordered by name. ctx bounds metadata admission, cloning and sorting. Its only errors are context cancellation/deadline errors, and an error returns no partial contracts.

func (*SchemaManager) GetConstraints

func (sm *SchemaManager) GetConstraints(ctx context.Context) ([]UniqueConstraint, error)

GetConstraints returns single-property node UNIQUE constraints. ctx bounds metadata admission and enumeration. The only errors are context cancellation/deadline errors; an error returns no partial constraints.

func (*SchemaManager) GetConstraintsForLabels

func (sm *SchemaManager) GetConstraintsForLabels(ctx context.Context, labels []string, types ...ConstraintType) ([]Constraint, error)

GetConstraintsForLabels returns all constraints for given labels, ordered by constraint name so validation reports the same violation every time an entity breaks several constraints. Returns constraints from the constraints map, preserving their original types. Optional types restrict the result before copying, so specialized consumers do not allocate unrelated rules.

ctx is the request the discovery serves: it bounds the wait for the schema lock and the scan of every declared constraint, and a discovery that observes its cancellation reports that error and no constraints rather than the partially filtered list it had already collected.

func (*SchemaManager) GetFulltextIndex

func (sm *SchemaManager) GetFulltextIndex(name string) (*FulltextIndex, bool)

GetFulltextIndex returns a fulltext index by name.

func (*SchemaManager) GetIndexStats

func (sm *SchemaManager) GetIndexStats() []IndexStats

GetIndexStats returns statistics for all indexes.

func (*SchemaManager) GetIndexes

func (sm *SchemaManager) GetIndexes() []interface{}

GetIndexes returns all indexes.

func (*SchemaManager) GetPropertyIndex

func (sm *SchemaManager) GetPropertyIndex(ctx context.Context, label, property string) (*PropertyIndex, bool, error)

GetPropertyIndex returns the filled property index the label and property combination can be seeked with. ctx is the request the lookup serves: it bounds the wait for the schema lock and the composite-index scan, and a cancelled lookup reports its error instead of an absent index.

func (*SchemaManager) GetPropertyTypeConstraintsForLabels

func (sm *SchemaManager) GetPropertyTypeConstraintsForLabels(labels []string) []PropertyTypeConstraint

GetPropertyTypeConstraintsForLabels returns type constraints for the given labels.

func (*SchemaManager) GetRangeIndex

func (sm *SchemaManager) GetRangeIndex(name string) (*RangeIndex, bool)

GetRangeIndex returns a range index by name.

func (*SchemaManager) GetVectorIndex

func (sm *SchemaManager) GetVectorIndex(name string) (*VectorIndex, bool)

GetVectorIndex returns a vector index by name.

func (*SchemaManager) HasAnyConstraintContract added in v1.1.0

func (sm *SchemaManager) HasAnyConstraintContract(ctx context.Context) (bool, error)

HasAnyConstraintContract reports whether this schema has at least one constraint contract registered. Callers use it to short-circuit work in the per-commit validator (the expensive adjacency walk is pointless when no contract exists). ctx bounds metadata admission; the only errors are context cancellation/deadline errors, and an error returns false.

func (*SchemaManager) HasAnyPropertyIndexForLabel added in v1.1.0

func (sm *SchemaManager) HasAnyPropertyIndexForLabel(label string) bool

HasAnyPropertyIndexForLabel reports whether ANY equality index (arity-1 or composite) is declared against the given label. Used by storage-side index maintenance to short-circuit per-node work when no index touches the label.

func (*SchemaManager) HasConstraintNamed

func (sm *SchemaManager) HasConstraintNamed(name string) bool

HasConstraintNamed reports whether a constraint named name is registered.

func (*SchemaManager) HasMultiPropertyIndexForLabel

func (sm *SchemaManager) HasMultiPropertyIndexForLabel(label string) bool

HasMultiPropertyIndexForLabel reports whether a composite index of two or more properties is declared against label: the only indexes a pattern read can use beyond its single-property ones.

func (*SchemaManager) HasPropertyIndex added in v1.1.0

func (sm *SchemaManager) HasPropertyIndex(ctx context.Context, label, property string) (bool, error)

HasPropertyIndex reports whether a filled arity-1 index exists for the given label+property combination. Callers can use this to choose between index-backed per-row lookups and batch preloads.

func (*SchemaManager) HasUniqueValueTracking

func (sm *SchemaManager) HasUniqueValueTracking() bool

HasUniqueValueTracking reports whether any unique constraint exists whose values are tracked in the unique-value cache. When false, callers can skip per-value ApplyUniqueValue work entirely.

func (*SchemaManager) HasWriteRules

func (sm *SchemaManager) HasWriteRules() bool

HasWriteRules reports whether the schema has any constraint, property type or constraint contract, i.e. whether any write can be checked at all.

func (*SchemaManager) KnowsGraphTokens

func (sm *SchemaManager) KnowsGraphTokens(labels, relationshipTypes []string) bool

KnowsGraphTokens reports whether the committed token catalog contains all supplied node labels and relationship types.

func (*SchemaManager) LockSchemaMutation

func (sm *SchemaManager) LockSchemaMutation() func()

LockSchemaMutation serializes admission, mutation and counters for a compound schema operation across callers sharing this manager. Individual schema APIs retain their own locks and can be called while this lock is held.

release := schema.LockSchemaMutation()
defer release()
// Validate the name, then call schema.AddLookupIndex or another schema API.

func (*SchemaManager) LookupIndexName

func (sm *SchemaManager) LookupIndexName(entityType ConstraintEntityType) (string, bool)

LookupIndexName is the name of the lookup index for entityType, if the schema has one.

func (*SchemaManager) LookupUniqueConstraintValue added in v1.0.43

func (sm *SchemaManager) LookupUniqueConstraintValue(ctx context.Context, label, property string, value interface{}) (nodeID NodeID, valueFound bool, constraintExists bool, cacheComplete bool, err error)

LookupUniqueConstraintValue returns the node currently registered for a single-property uniqueness constraint value, plus whether the values cache has been rebuilt from storage and can be trusted for misses. Planners may trust absence only when cacheComplete is true; otherwise they must retain a scan fallback because the cache may not have been rebuilt from storage yet.

func (*SchemaManager) MaintainsPropertyIndex

func (sm *SchemaManager) MaintainsPropertyIndex(label, property string) bool

MaintainsPropertyIndex reports whether writes must maintain an arity-1 index on label's property, filled or not (#875): node writes and index rebuilds use it, seeks use GetPropertyIndex.

func (*SchemaManager) MarkPropertyIndexesFilled

func (sm *SchemaManager) MarkPropertyIndexesFilled()

MarkPropertyIndexesFilled lets seeks use every equality index, once a rebuild has filled them all from the stored nodes (#875).

func (*SchemaManager) NodeWriteChecked

func (sm *SchemaManager) NodeWriteChecked(labels []string) bool

NodeWriteChecked reports whether writing a node with these labels is checked by the schema: a constraint or property type on one of the labels, a constraint contract targeting one of them, or a relationship policy that names one of them as its source or target label (relabelling a node can break a policy on its relationships).

The engine that stores the node checks all of these when it writes it. The AsyncEngine therefore writes a checked node through to that engine before acknowledging it, instead of caching it and checking only when it flushes; a write the check rejects is never acknowledged, so it can't fail the flush later (#700). A node no rule checks stays in the write cache.

func (*SchemaManager) OrderTokens

func (sm *SchemaManager) OrderTokens(names []string, relationships bool) []string

OrderTokens returns a copy of in-use names ordered by durable token position. Unknown legacy names follow known names in lexical order. Set relationships for relationship types, or leave it false for labels. Example: schema.OrderTokens([]string{"Person", "Company"}, false).

func (*SchemaManager) PropertyIndexAllNonNil

func (sm *SchemaManager) PropertyIndexAllNonNil(ctx context.Context, label, property string, descending bool) ([]NodeID, error)

PropertyIndexAllNonNil returns all node IDs from the property index in key order, excluding nil keys, merged with the pending writes. Unorderable memberships return ErrPropertyIndexValueOrderUnavailable, never a partial population. IS NOT NULL planners use PropertyIndexNonNilCandidates instead.

func (*SchemaManager) PropertyIndexDelete

func (sm *SchemaManager) PropertyIndexDelete(label, property string, nodeID NodeID, value interface{}) error

PropertyIndexDelete removes a node from an arity-1 index.

func (*SchemaManager) PropertyIndexInsert

func (sm *SchemaManager) PropertyIndexInsert(label, property string, nodeID NodeID, value interface{}) error

PropertyIndexInsert adds a node to an arity-1 index. It is the single-property spelling of IndexNode for callers that carry the value directly (imports, backfills); node-write maintenance calls IndexNode.

func (*SchemaManager) PropertyIndexLookup

func (sm *SchemaManager) PropertyIndexLookup(ctx context.Context, label, property string, value interface{}) ([]NodeID, error)

PropertyIndexLookup looks up node IDs by property value using an index, merged with an attached AsyncEngine's pending writes (#719). Returns nil if no index exists for the label/property.

func (*SchemaManager) PropertyIndexLookupAnyLabel added in v1.1.11

func (sm *SchemaManager) PropertyIndexLookupAnyLabel(ctx context.Context, property string, value interface{}) ([]NodeID, error)

PropertyIndexLookupAnyLabel looks up node IDs by property value across ALL indexes whose property name matches, regardless of the label they were declared against. Returns nil when no index covers `property`, and the union of hits across every matching index otherwise.

This is the labelless-pattern counterpart to `PropertyIndexLookup`: a query like `MATCH (n {id:$x})` carries an inline equality on `id` but no label, so any index declared as `(Label1:id) … (LabelN:id)` is a legal candidate source. Without this method the executor has to choose between (a) probing every label-prop index name it can guess at, or (b) falling back to a full node scan; (b) is what graphify's edge MERGE hits today. The union here loses no information: it never returns false positives (a node either has the value indexed or it doesn't) and the executor still applies the rest of the pattern's filter on the returned candidates.

func (*SchemaManager) PropertyIndexLookupAvailable

func (sm *SchemaManager) PropertyIndexLookupAvailable(ctx context.Context, label, property string, value interface{}) ([]NodeID, bool, error)

PropertyIndexLookupAvailable distinguishes an empty posting from a lookup whose completeness cannot be relied on. A seek must fall back if the index is dropped, rebuilding, or has a known missing posting for this value.

func (*SchemaManager) PropertyIndexNonNilCandidates

func (sm *SchemaManager) PropertyIndexNonNilCandidates(ctx context.Context, label, property string) (ids []NodeID, found bool, err error)

PropertyIndexNonNilCandidates returns complete, unordered nonnull candidates, including accepted values without equality keys (such as byte arrays), merged with current namespace pending writes. found is false if no filled index is available; an available empty population is found=true with zero IDs.

Query planners use this for IS NOT NULL, then evaluate residual predicates and ORDER BY on the actual node values. Callers needing index-provided value order use PropertyIndexAllNonNil, TopK or grouped visits; those return the explicit ErrPropertyIndexValueOrderUnavailable when the population cannot be ordered.

func (*SchemaManager) PropertyIndexRange

func (sm *SchemaManager) PropertyIndexRange(ctx context.Context, label, property string, bounds PropertyIndexBounds) (ids []NodeID, ok bool, err error)

PropertyIndexRange returns the node IDs whose indexed value lies within bounds, in value order, merged with the pending writes. ok is false when the label and property have no index or a bound is neither a number nor a string; the caller must then not rely on the index. An unbounded request that cannot value-order its population reports ErrPropertyIndexValueOrderUnavailable instead of omitting memberships.

func (*SchemaManager) PropertyIndexTopK

func (sm *SchemaManager) PropertyIndexTopK(ctx context.Context, label, property string, limit int, descending bool) ([]NodeID, error)

PropertyIndexTopK returns up to limit node IDs from a property index ordered by indexed property value, merged with the pending writes. Nil keys are skipped. ErrPropertyIndexValueOrderUnavailable reports nonnull memberships the index cannot value-order; callers must order the actual property values instead.

func (*SchemaManager) PropertyIndexValueCount

func (sm *SchemaManager) PropertyIndexValueCount(ctx context.Context, label, property string, value interface{}) (count int, indexed bool, err error)

PropertyIndexValueCount returns how many nodes label's property index lists under value: the length of the value's committed posting list plus the pending writes that hold the value, without copying either. It is the estimate a query planner compares index seeks by (NOR-414); it is not a lookup: a pending write that supersedes a committed entry is counted twice, so the count is an upper bound on PropertyIndexLookup's result.

indexed is false, with a zero count, when PropertyIndexLookup could not use the index for value: no seekable index on (label, property), or a value no index key holds.

func (*SchemaManager) PropertyTypeConstraintCreationRequired

func (sm *SchemaManager) PropertyTypeConstraintCreationRequired(ctx context.Context, c PropertyTypeConstraint, ifNotExists bool) (bool, error)

PropertyTypeConstraintCreationRequired applies the property-type admission policy before stored-data validation. AddPropertyTypeConstraint rechecks the policy while publishing; this read does not reserve a schema name.

func (*SchemaManager) RangeIndexDelete

func (sm *SchemaManager) RangeIndexDelete(name string, nodeID NodeID) error

RangeIndexDelete removes a value from a range index.

func (*SchemaManager) RangeIndexInsert

func (sm *SchemaManager) RangeIndexInsert(name string, nodeID NodeID, value interface{}) error

RangeIndexInsert adds a value to a range index.

func (*SchemaManager) RangeQuery

func (sm *SchemaManager) RangeQuery(name string, minVal, maxVal interface{}, includeMin, includeMax bool) ([]NodeID, error)

RangeQuery performs a range query on a range index. Returns node IDs where value is in range [minVal, maxVal]. Pass nil for minVal or maxVal to indicate unbounded.

func (*SchemaManager) RegisterEdgeTokens

func (sm *SchemaManager) RegisterEdgeTokens(ctx context.Context, edges []*Edge) error

RegisterEdgeTokens validates a batch and registers its relationship types in first-seen order. A batch of one type needs just one token lookup.

func (*SchemaManager) RegisterTokens

func (sm *SchemaManager) RegisterTokens(ctx context.Context, labels, relationships []string) error

RegisterTokens allocates durable label and relationship-type positions. Allocations are retained when their last entity is deleted. Example: schema.RegisterTokens(ctx, []string{"Person"}, []string{"KNOWS"}).

func (*SchemaManager) RelationshipEqualityIndexProperties

func (sm *SchemaManager) RelationshipEqualityIndexProperties(ctx context.Context, relationshipType string, boundProperties map[string]interface{}) ([]string, bool, error)

RelationshipEqualityIndexProperties selects a complete relationship RANGE key from the schema catalog. Constraint-owned keys retain priority; within each class, the shortest key wins and property-order ties are lexical. The returned names are detached from the catalog. A dropped declaration can no longer select retained derived postings; surviving declarations can.

func (*SchemaManager) ReplaceDefinitionDurable

func (sm *SchemaManager) ReplaceDefinitionDurable(ctx context.Context, engine Engine, def *SchemaDefinition) error

ReplaceDefinitionDurable replaces every schema family with def as one accepted definition replacement and persists that replacement through the manager's configured persister.

The replacement is accepted in three steps, in this order, so a definition that cannot be accepted is neither written nor published:

  1. A detached prospective manager is built from def (ReplaceFromDefinition), its derived runtime state (single-property UNIQUE values and equality index contents) is rebuilt from engine's stored entities, and every constraint family is validated against them. The detached manager's knowledge-policy bindings are compiled while it loads, so a definition referencing a missing profile is rejected here.
  2. The accepted prospective definition is persisted through the same namespace-bound persister every other schema mutation uses. A rejected write returns its error and leaves the live manager, its runtime index and UNIQUE caches, and the durable definition exactly as they were.
  3. Only then is the prospective manager published into sm: every family, the token order, the token snapshot and the compiled knowledge-policy binding table are installed through installSchemaLocked, after which the knowledge-policy changed callback runs with no schema lock held. The compiled table is the one the prospective manager validated, not a second compilation after the write.

Persisting and publishing are admitted as one schema mutation: the publication gate is held from before the accepted definition is read until publication completes, so a native commit that publishes a schema definition cannot be overtaken in that interval. The admission honors ctx, so a caller whose context is canceled before it is admitted persists and publishes nothing.

Cancellation: ctx owns detached preparation, including stored enumeration, constraint validation, and UNIQUE cache rebuilding. A canceled preparation returns before any durable write or live publication. Accepted installation completes under its schema mutation lease.

Ownership: the prospective state is derived from engine's stored entities before that admission, so this is an offline administrative replacement. It does not serialize against live entity writes, and the caller must own the destination for the duration; adminimport applies a schema document with it after importing into a namespace it has just required to be empty. A manager with no configured persister (a memory engine, or a schema with no namespace binding) publishes the replacement in memory only, as every other schema mutation does. Both ctx and engine are required; preparation is never detached from a missing caller context.

Example, after exclusive import into a namespace:

definition := &SchemaDefinition{PropertyIndexes: []SchemaPropertyIndexDef{{
	Name: "doc_id", Label: "Document", Properties: []string{"id"},
}}}
err := target.GetSchema().ReplaceDefinitionDurable(ctx, target, definition)

func (*SchemaManager) ReplaceFromDefinition

func (sm *SchemaManager) ReplaceFromDefinition(ctx context.Context, def *SchemaDefinition) error

ReplaceFromDefinition replaces the in-memory schema contents with the given definition.

This does NOT persist anything, and it intentionally discards runtime caches (unique value maps, index maps, etc.). Those must be rebuilt from data. Loading and binding compilation complete before publication; rejected definitions leave every existing family and compiled binding table intact. ctx owns detached candidate construction: loading, validation and binding compilation, including the constraint-owned index discovery it runs, and admission to the live schema. A canceled ctx installs nothing: preparation returns before the replacement waits, and a caller canceled while it waits for the schema lock returns that cancellation without installing anything. Installation starts where admission succeeds, so an admitted candidate is published atomically and leaves the previously compiled table intact.

Only an accepted installation re-tracks the pairs the attached pending-write source indexes. That completion belongs to the accepted schema change, so it runs after the schema lock is released and ctx decides nothing there: a canceled or rejected definition tracks nothing.

A nil def remains a no-op that tracks pending pairs, as before.

func (*SchemaManager) SchemaObjectCounts

func (sm *SchemaManager) SchemaObjectCounts() (indexes, constraints int)

SchemaObjectCounts returns how many indexes and constraints the schema holds, as Neo4j's schema counters count them: the index a constraint owns belongs to the constraint and is not an index of its own. Constraints are the ones SHOW CONSTRAINTS lists (constraints, property type constraints and constraint contracts).

func (*SchemaManager) SeekableCompositeIndexesForLabel

func (sm *SchemaManager) SeekableCompositeIndexesForLabel(ctx context.Context, label string) ([]*CompositeIndex, error)

SeekableCompositeIndexesForLabel returns label's composite indexes that seek paths may use: filled only. Writes and rebuilds maintain every index through GetCompositeIndexesForLabel, so a DDL-created index mid-backfill is populated but never trusted for reads (#875).

ctx is the request the discovery serves: it bounds the wait for the schema lock and the scan of every declared index, and a discovery that observes its cancellation reports that error and no candidates rather than the indexes it had already collected.

func (*SchemaManager) SetBindingTable added in v1.1.0

func (sm *SchemaManager) SetBindingTable(bt *knowledgepolicy.BindingTable)

SetBindingTable replaces the compiled binding table.

func (*SchemaManager) SetKnowledgePolicyChangedHook added in v1.1.0

func (sm *SchemaManager) SetKnowledgePolicyChangedHook(hook func())

SetKnowledgePolicyChangedHook registers a callback that runs after a knowledge-policy mutation has been persisted and the schema lock released.

func (*SchemaManager) SetPersister

func (sm *SchemaManager) SetPersister(persist func(def *SchemaDefinition) error)

SetPersister sets an optional persistence hook for schema changes. When set, schema mutations will attempt to persist the updated schema definition and will roll back the in-memory change if persistence fails.

func (*SchemaManager) ShowDecayProfiles added in v1.1.0

ShowDecayProfiles returns all stored decay profile bundles and bindings.

func (*SchemaManager) ShowPromotionPolicies added in v1.1.0

func (sm *SchemaManager) ShowPromotionPolicies() []knowledgepolicy.PromotionPolicyDef

ShowPromotionPolicies returns all stored promotion policies.

func (*SchemaManager) ShowPromotionProfiles added in v1.1.0

func (sm *SchemaManager) ShowPromotionProfiles() []knowledgepolicy.PromotionProfileDef

ShowPromotionProfiles returns all stored promotion profiles.

func (*SchemaManager) VisitPropertyIndexGroups added in v1.3.3

func (sm *SchemaManager) VisitPropertyIndexGroups(ctx context.Context, label, property string, descending bool, visit func([]NodeID) bool) (bool, error)

VisitPropertyIndexGroups visits non-null property-index entries in key order. Each callback receives the complete group of IDs whose keys compare equally, including differently typed numeric keys. Returning false stops the visit. IDs within a group are ordered by node identity. The callback runs without schema/index locks so it can read nodes or perform index operations safely. The return value reports whether the index exists, even when it is empty. Unorderable memberships return ErrPropertyIndexValueOrderUnavailable before any callback; candidate planners can then order actual values themselves.

Query planners use this to finish a primary-key tie before selecting a page by secondary ORDER BY keys. For example, a title index must visit every node with the boundary title before choosing the smallest timestamp/ID tuple.

func (*SchemaManager) VisitPropertyIndexGroupsInRange

func (sm *SchemaManager) VisitPropertyIndexGroupsInRange(ctx context.Context, label, property string, descending bool, bounds PropertyIndexBounds, visit func([]NodeID) bool) (bool, error)

VisitPropertyIndexGroupsInRange is VisitPropertyIndexGroups starting and ending at bounds: groups whose keys fall outside them are skipped without being read, found by binary search where the keys allow it (sortedKeyRangeLocked). Bounds only skip groups that can't match; the caller still tests every visited node, and gets every group when the keys can't be searched. ORDER BY … LIMIT under a range or keyset predicate (WHERE n.t > $last …) starts at the bound instead of reading the whole index before it (#939).

type SchemaPropertyIndexDef

type SchemaPropertyIndexDef struct {
	Name       string   `json:"name"`
	Label      string   `json:"label"`
	Properties []string `json:"properties"`
}

type SchemaPurpose

type SchemaPurpose uint8

SchemaPurpose identifies the edits made through an isolated transaction schema.

const (
	// KnowledgePolicyChanges reads an isolated schema without claiming a writer;
	// persisting a policy change performs admission before staging it.
	KnowledgePolicyChanges SchemaPurpose = iota
	// OrdinarySchemaChanges admits a schema writer and excludes entity writes.
	OrdinarySchemaChanges
)

type SchemaRangeIndexDef

type SchemaRangeIndexDef struct {
	Name             string               `json:"name"`
	Kind             IndexKind            `json:"kind,omitempty"`
	Label            string               `json:"label"`
	Property         string               `json:"property"`
	Properties       []string             `json:"properties,omitempty"`
	EntityType       ConstraintEntityType `json:"entity_type,omitempty"`
	OwningConstraint string               `json:"owning_constraint,omitempty"`
}

type ScopedEdgeTypeStreamer

type ScopedEdgeTypeStreamer interface {
	StreamEdgesByTypeInScope(ctx context.Context, scope, edgeType string, visit func(*Edge) error) error
}

ScopedEdgeTypeStreamer is EdgeTypeStreamer within one database. The edge type index is shared by every database on the server, so an unscoped stream decodes the type's edges of all databases; a scoped stream skips another database's index entries before reading their edge records. scope is the database's ID prefix ("db:"); "" streams every database.

Like ScopedLabelNodeReader, a wrapper that cannot pass the scope down falls back to the unscoped stream, so callers keep filtering by database.

type ScopedLabelNodeIDReader

type ScopedLabelNodeIDReader interface {
	ForEachNodeIDByLabelInScope(ctx context.Context, scope, label string, visit func(NodeID) bool) error
}

ScopedLabelNodeIDReader is the ID-only counterpart to ScopedLabelNodeReader. Its scope uses the same physical database prefix, and false stops the visit.

type ScopedLabelNodeReader

type ScopedLabelNodeReader interface {
	GetNodesByLabelInScope(ctx context.Context, scope, label string) ([]*Node, error)
	GetFirstNodeByLabelInScope(ctx context.Context, scope, label string) (*Node, error)
	StreamNodesByLabelProjectedInScope(ctx context.Context, scope, label string, properties []string, visit func(*Node) error) error
	GetNodesByLabelVisibleAtInScope(ctx context.Context, scope, label string, version MVCCVersion) ([]*Node, error)
}

ScopedLabelNodeReader is an optional extension interface for label reads within one database. The label index is shared by every database on the server. Scoped Badger reads retain an in-scope streaming prefix, then use the existing namespace dictionary at the first foreign boundary without enumerating that foreign run. scope is the database's node ID prefix ("db:"); "" reads every database, as the unscoped methods do.

Engines that wrap another engine pass the scope down when the inner engine implements this interface and fall back to the unscoped read otherwise, so a result may still hold nodes outside the scope: callers keep filtering by database.

type ScopedStoredEntityReader

type ScopedStoredEntityReader interface {
	GetStoredNodesByLabelInScope(ctx context.Context, scope, label string) ([]*Node, error)
	StreamStoredNodesByLabelProjectedInScope(ctx context.Context, scope, label string, properties []string, visit func(*Node) error) error
	StreamStoredEdgesByTypeInScope(ctx context.Context, scope, edgeType string, visit func(*Edge) error) error
}

ScopedStoredEntityReader is StoredEntityReader's scans within one database (scope is its ID prefix, "" every database), so a NamespacedEngine's stored scans skip other databases' index entries as its user scans do (#851).

type SearchNodeSnapshot

type SearchNodeSnapshot interface {
	IterateSearchNodes(ctx context.Context, fn func(*Node) bool) (skipped int, err error)
}

SearchNodeSnapshot builds a searchable population from a pinned snapshot, reporting unreadable record bodies separately from scan failures.

type SearchSizeFn added in v1.1.0

type SearchSizeFn func() int64

SearchSizeFn returns the cumulative search-index byte size across all per-database search services. Plan 04-05 wires this via search.SearchService IndexSizeBytes(); for Plan 04-04 it can be nil (returns 0).

type SerializerMigrationOptions

type SerializerMigrationOptions struct {
	BatchSize int
	DryRun    bool
}

SerializerMigrationOptions controls the in-place gob → msgpack rewrite. There is no source/target choice: the engine only emits msgpack, and the only thing this tool does is upgrade legacy gob bodies in an existing data directory so they can be read by current code without going through the legacy decode arm forever.

type SerializerMigrationStats

type SerializerMigrationStats struct {
	DataDir             string
	HasLegacyData       bool
	NodesConverted      int
	EdgesConverted      int
	EmbeddingsConverted int
	SkippedExisting     int
	TotalScanned        int
}

SerializerMigrationStats reports conversion results for the in-place gob → msgpack rewrite.

func MigrateBadgerToMsgpack added in v1.1.0

func MigrateBadgerToMsgpack(dataDir string, opts SerializerMigrationOptions) (SerializerMigrationStats, error)

MigrateBadgerToMsgpack rewrites any legacy gob-encoded node, edge, or embedding bodies in the given data directory as msgpack. The database must be offline (no running server). New writes have always been msgpack since this engine version, so on a fresh database this is a no-op.

func MigrateBadgerToMsgpackWithDB added in v1.1.0

func MigrateBadgerToMsgpackWithDB(db *badger.DB, dataDir string, opts SerializerMigrationOptions) (SerializerMigrationStats, error)

MigrateBadgerToMsgpackWithDB is MigrateBadgerToMsgpack against an already-open *badger.DB opened in Badger's default (unmanaged) mode. Used by tests and offline tooling.

type SignalType

type SignalType string

SignalType describes how an edge was detected/created.

const (
	SignalSimilarity   SignalType = "similarity" // Semantic similarity
	SignalCoAccess     SignalType = "coaccess"   // Co-access pattern
	SignalTopology     SignalType = "topology"   // Topological link prediction
	SignalLLMInference SignalType = "llm-infer"  // LLM-based inference
	SignalManual       SignalType = "manual"     // User-created
	SignalTransitive   SignalType = "transitive" // Transitive inference
	SignalTemporal     SignalType = "temporal"   // Temporal proximity
)

type Snapshot

type Snapshot struct {
	Sequence  uint64    `json:"sequence"`
	Timestamp time.Time `json:"timestamp"`
	Nodes     []*Node   `json:"nodes"`
	Edges     []*Edge   `json:"edges"`
	Version   string    `json:"version"`
}

Snapshot represents a point-in-time snapshot of the database.

func LoadSnapshot

func LoadSnapshot(ctx context.Context, path string) (*Snapshot, error)

LoadSnapshot reads legacy JSON or NDS2 v1/v2 framed snapshots from disk.

func LoadSnapshotWithKey

func LoadSnapshotWithKey(ctx context.Context, path string, key []byte) (*Snapshot, error)

LoadSnapshotWithKey reads a snapshot using the database's at-rest key. A keyless call retains the historical JSON/NDS2 compatibility contract; a keyed call requires an authenticated encrypted NDS2 stream and never falls through to plaintext JSON.

type SnapshotMetadata added in v1.3.1

type SnapshotMetadata struct {
	Sequence  uint64
	Timestamp time.Time
	NodeCount uint64
	EdgeCount uint64
}

func ReadSnapshot added in v1.3.1

func ReadSnapshot(ctx context.Context, reader io.Reader, visitor SnapshotVisitor) (SnapshotMetadata, error)

ReadSnapshot visits entities from NDS2 v1 JSON or v2 typed frames. Unsupported versions fail before visiting entities. The non-nil ctx is passed unchanged to every visitor callback. It reads records up to the limit WriteSnapshot writes with (materializedSnapshotRecordSize); a record longer than 16 MiB is read progressively (readSnapshotFrameWithLimit).

func ReadSnapshotWithKey

func ReadSnapshotWithKey(ctx context.Context, reader io.Reader, visitor SnapshotVisitor, key []byte) (SnapshotMetadata, error)

ReadSnapshotWithKey reads a framed snapshot with the snapshot-at-rest key contract. With no key it reads the plaintext NDS2 stream exactly as ReadSnapshot does. With a key it reads only an encrypted envelope and refuses a plaintext snapshot, so switching a database to encryption never silently recovers an older plaintext snapshot.

type SnapshotOptions added in v1.3.1

type SnapshotOptions struct {
	Sequence       uint64
	MaxRecordBytes int64
	// EncryptionKey is the explicit optional 32-byte AES-256 key for the
	// snapshot stream. Nil or empty writes the unchanged plaintext NDS2
	// stream. A set key writes the chunked authenticated envelope owned by
	// snapshot_encryption.go; the key itself is never stored in the snapshot.
	EncryptionKey []byte
}

type SnapshotReaderInfo

type SnapshotReaderInfo struct {
	ReaderID        string
	SnapshotVersion MVCCVersion
	StartTime       time.Time
	Namespace       string
}

SnapshotReaderInfo describes an active MVCC snapshot reader.

type SnapshotReaderRegistry

type SnapshotReaderRegistry interface {
	Register(info SnapshotReaderInfo) (string, func())
	ActiveCount() int64
	Snapshot() []SnapshotReaderInfo
}

SnapshotReaderRegistry exposes active snapshot-reader tracking.

type SnapshotVisitor added in v1.3.1

type SnapshotVisitor interface {
	VisitNode(context.Context, *Node) error
	VisitEdge(context.Context, *Edge) error
}

SnapshotVisitor consumes decoded entities on the context supplied to ReadSnapshot. A visitor may stop the read by returning an error; recovery supplies its own completion context when applying acknowledged data.

type StartupMaintenanceStateEngine

type StartupMaintenanceStateEngine interface {
	ConsumeCleanShutdownMarker(ctx context.Context) (bool, error)
	MarkCleanShutdown(ctx context.Context) error
}

StartupMaintenanceStateEngine persists and consumes the clean-shutdown boundary used to decide whether derived temporal/MVCC indexes need recovery.

type StorageEventNotifier

type StorageEventNotifier interface {
	// Node events
	OnNodeCreated(callback NodeEventCallback)
	OnNodeUpdated(callback NodeEventCallback)
	OnNodeDeleted(callback NodeDeleteCallback)

	// Edge events
	OnEdgeCreated(callback EdgeEventCallback)
	OnEdgeUpdated(callback EdgeEventCallback)
	OnEdgeDeleted(callback EdgeDeleteCallback)
}

StorageEventNotifier is an optional interface that storage engines can implement to notify listeners of storage changes. This enables automatic synchronization between storage and external services (search indexes, embeddings, caches, etc.).

Events are fired AFTER the storage operation succeeds, ensuring consistency. Each On* call adds a listener: every registered callback is invoked, so one subscriber (the GraphQL subscriptions) doesn't replace another (the search indexes).

Example:

if notifier, ok := engine.(storage.StorageEventNotifier); ok {
	notifier.OnNodeCreated(func(node *storage.Node) {
		searchService.IndexNode(node)
	})
	notifier.OnNodeDeleted(func(nodeID storage.NodeID) {
		searchService.RemoveNode(nodeID)
	})
	notifier.OnEdgeCreated(func(edge *storage.Edge) {
		graphAnalyzer.UpdateMetrics(edge)
	})
}

type StoredEntityChange

type StoredEntityChange struct {
	BeforeNode *Node
	AfterNode  *Node
	BeforeEdge *Edge
	AfterEdge  *Edge
}

StoredEntityChange is one entity's stored image before and after a logical commit. A nil image denotes absence. Exactly one entity kind is populated; repeated mutations of an ID produce one pair. Images include separately stored embeddings and metadata and belong to the commit, not its caller. Consumers must treat the images as immutable.

type StoredEntityKind

type StoredEntityKind uint8

StoredEntityKind identifies a physical entity without reading its body.

const (
	StoredEntityNodeKind StoredEntityKind = iota
	StoredEntityEdgeKind
)

type StoredEntityObserver

type StoredEntityObserver func(StoredEntityPublication) (publish func(), err error)

StoredEntityObserver applies a commit's accounting before listeners run. It must not write to storage, acquire write admission, or mutate the images.

type StoredEntityPublication

type StoredEntityPublication struct {
	Namespace string
	LogicalID string
	Changes   []StoredEntityChange
}

StoredEntityPublication is the immutable stored image delta of one logical commit. A physical replay of an acknowledged commit does not publish it again.

type StoredEntityReadBoundary

type StoredEntityReadBoundary interface {
	WithStoredEntityRead(StoredEntityReadKind, string, func() error) error
}

StoredEntityReadBoundary decorates the actual read continuation. Implementers must call read exactly once, or return their read failure without calling it. The ID is physical and namespace-qualified; scans receive the namespace.

type StoredEntityReadKind

type StoredEntityReadKind uint8

StoredEntityReadKind identifies a snapshot-bound committed-state read.

const (
	StoredEntityNodePriorRead StoredEntityReadKind = iota
	StoredEntityEdgePriorRead
	StoredEntityNodeSnapshotScan
	StoredEntityEdgeSnapshotScan
)

type StoredEntityReader

type StoredEntityReader interface {
	GetStoredNode(ctx context.Context, id NodeID) (*Node, error)
	GetStoredEdge(ctx context.Context, id EdgeID) (*Edge, error)
	// ReadStoredAdjacentEdges answers one adjacent-edge request over the
	// physically stored relationships, the ones a read-time visibility filter
	// hides included. The request's types and header detail apply as they do
	// to ReadAdjacentEdges.
	ReadStoredAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)
	GetStoredNodesByLabel(ctx context.Context, label string) ([]*Node, error)
	StreamStoredNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error
	// StreamStoredEdgesByType visits edgeType's relationships; an empty
	// edgeType visits every relationship.
	StreamStoredEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error
}

StoredEntityReader reads what storage holds: every node and relationship, those the visibility layer hides from user reads included (on-demand suppression, knowledge-policy decay and its index tombstones). The layer hides entities from users without removing them, so integrity work reads through this interface: validating a constraint over existing data, backfilling an index, snapshots, replication, backups and data-subject requests. User-facing reads keep the Engine methods.

BadgerEngine implements it (MemoryEngine by embedding); WALEngine and NamespacedEngine forward it. Callers reach it through StoredReader, which unwraps decorators that add no visibility of their own. Transaction views implement this capability themselves: stored reads bypass suppression/decay, but retain the transaction's snapshot, writes and deletes.

func StoredReader

func StoredReader(engine Engine) (reader StoredEntityReader, ok bool)

StoredReader returns the StoredEntityReader of engine, unwrapping the decorators that add no visibility of their own (size tracking, tracing, replication). ok is false for an engine that cannot read hidden entities (composite and remote databases); integrity work then reads through the Engine methods, all the engine can give.

type StoredEntitySnapshot

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

StoredEntitySnapshot visits the exact stored entities at observer installation. It is valid only synchronously inside InitializeStoredEntityObserver's callback.

func (StoredEntitySnapshot) ForEach

ForEach streams typed stored identities through the same scan fault boundary. Call entry.Read only when a complete stored image is needed.

type StoredEntitySnapshotEntry

type StoredEntitySnapshotEntry struct {
	Kind StoredEntityKind
	ID   string
	// contains filtered or unexported fields
}

StoredEntitySnapshotEntry is an identity from a pinned installation snapshot. It and Read are valid only inside the InitializeStoredEntityObserver callback. No entity body or embedding is read until Read is explicitly requested.

func (StoredEntitySnapshotEntry) Read

Read returns the complete stored final image, including separate embeddings, from the same pinned reader that produced this identity.

type StreamNodesOptions

type StreamNodesOptions struct {
	// Label is an optional index hint. Callers still check label membership.
	Label string
	// QueryNodes settles embedding metadata without loading stored vectors,
	// as QueryNodeReader does. It applies to whole-node reads without
	// WithEmbeddings; resident vectors may be shared, never copied.
	QueryNodes bool
	// Prefix limits the scan to IDs starting with this string ("" scans all).
	Prefix string
	// Projection, when non-nil, decodes only these properties.
	Projection []string
	// WithEmbeddings loads separately stored chunk vectors.
	WithEmbeddings bool
	// ApplyDecayFilter drops nodes failing decay scoring, including label scans.
	ApplyDecayFilter bool
	// StripEmbeddings removes inline/legacy embedding payloads from results.
	StripEmbeddings bool
	// PropertyFilter, with a Projection, lets the engine skip a node whose
	// projected properties it rejects before decoding the rest of the node
	// (#824). It is a hint: an engine may ignore it, and pending writes are
	// not filtered, so the caller still tests every node it receives.
	PropertyFilter func(properties map[string]interface{}) bool
	// PropertyFilterProjection names the properties PropertyFilter reads, so an
	// engine can settle the filter before it decodes the rest of a body. It
	// applies to a scan without a Projection, whose row is the whole node: a
	// Projection already names what the filter reads. Like PropertyFilter it
	// is a hint an engine may ignore, and pending writes are not filtered,
	// so the caller still tests every node it receives.
	PropertyFilterProjection []string
	// PropertyStringEquals, for projected properties, lets the engine skip a
	// node whose stored value of a property is not that string by comparing
	// the stored bytes, without decoding the node (#857). A stored string
	// equals a Cypher string exactly when its bytes do, and a value of any
	// other type never equals a string. Like PropertyFilter it is a hint.
	PropertyStringEquals map[string]string
}

StreamNodesOptions controls a streaming node scan. The five legacy stream variants (StreamNodes, StreamNodesWithoutEmbeddings, StreamNodesByPrefix, StreamNodesByPrefixProjected, StreamNodesByPrefixWithoutEmbeddings) are thin wrappers over StreamNodesWithOptions; consolidating their ~620 duplicated lines across four engines into one kernel per engine (HARD_CONVERGENCE.md item 4) means future scan fixes land in one place.

type StreamingEngine

type StreamingEngine interface {
	Engine

	// StreamNodes iterates over all nodes without loading all into memory.
	// The callback is called for each node. Return an error to stop iteration.
	// Returns nil on successful completion, context.Canceled on cancellation.
	StreamNodes(ctx context.Context, fn func(node *Node) error) error

	// StreamEdges iterates over all edges without loading all into memory.
	StreamEdges(ctx context.Context, fn func(edge *Edge) error) error

	// StreamNodeChunks iterates over nodes in chunks for batch processing.
	// More efficient than StreamNodes when processing in batches.
	StreamNodeChunks(ctx context.Context, chunkSize int, fn func(nodes []*Node) error) error
}

StreamingEngine extends Engine with streaming iteration support. This is optional - engines that don't support streaming will use the default AllNodes/AllEdges with chunked processing.

func ResolveStreamingEngine

func ResolveStreamingEngine(engine Engine) (StreamingEngine, bool)

ResolveStreamingEngine preserves streaming through transparent tracing decorators while retaining any namespace or transaction boundary. It does not claim the optional capability when the wrapped engine lacks it.

type StructuredLogger added in v1.1.0

type StructuredLogger interface {
	Logger() *slog.Logger
}

StructuredLogger is implemented by storage engines that expose their structured *slog.Logger so wrappers (NamespacedEngine, WALEngine) can derive a child logger without constructor plumbing.

type SuppressionStateChange added in v1.1.0

type SuppressionStateChange struct {
	EntityID string
	Tokens   []string
	IsEdge   bool
}

type TemporalCurrentNodeEngine

type TemporalCurrentNodeEngine interface {
	IsCurrentTemporalNode(ctx context.Context, node *Node, asOf time.Time) (bool, error)
}

TemporalCurrentNodeEngine is an optional extension interface for deciding whether a temporal node represents the current/live version for indexing and query routing.

type TemporalLookupEngine

type TemporalLookupEngine interface {
	GetTemporalNodeAsOf(ctx context.Context, label, keyProp string, keyValue interface{}, validFromProp, validToProp string, asOf time.Time) (*Node, error)
}

TemporalLookupEngine is an optional extension interface for efficient temporal lookups on a namespaced engine view.

type TemporalMaintenanceEngine

type TemporalMaintenanceEngine interface {
	RebuildTemporalIndexes(ctx context.Context) error
	PruneTemporalHistory(ctx context.Context, opts TemporalPruneOptions) (int64, error)
}

TemporalMaintenanceEngine is an optional extension interface for rebuilding and pruning temporal index state after upgrades, restores, or operator maintenance.

type TemporalPruneOptions

type TemporalPruneOptions struct {
	// MaxVersionsPerKey keeps at most this many closed historical versions per temporal key.
	// Zero means unlimited.
	MaxVersionsPerKey int

	// MinRetentionAge protects versions newer than now-MinRetentionAge from pruning.
	// Zero means no age-based protection.
	MinRetentionAge time.Duration
}

TemporalPruneOptions controls pruning of older temporal versions.

type TracedEngine added in v1.1.0

type TracedEngine struct {
	Engine
	// contains filtered or unexported fields
}

TracedEngine wraps an Engine and emits nornicdb.storage.<op> spans for each operation. The context used for span parenting is set via SetContext by the calling layer (cypher executor) which has the active span context.

func NewTracedEngine added in v1.1.0

func NewTracedEngine(inner Engine) *TracedEngine

NewTracedEngine wraps inner with tracing instrumentation.

func (*TracedEngine) AllEdges added in v1.1.0

func (t *TracedEngine) AllEdges(ctx context.Context) ([]*Edge, error)

func (*TracedEngine) AllNodes added in v1.1.0

func (t *TracedEngine) AllNodes(ctx context.Context) ([]*Node, error)

func (*TracedEngine) BatchGetNodes added in v1.1.0

func (t *TracedEngine) BatchGetNodes(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

func (*TracedEngine) BulkCreateEdges added in v1.1.0

func (t *TracedEngine) BulkCreateEdges(ctx context.Context, edges []*Edge) error

func (*TracedEngine) BulkCreateNodes added in v1.1.0

func (t *TracedEngine) BulkCreateNodes(ctx context.Context, nodes []*Node) error

func (*TracedEngine) CreateEdge added in v1.1.0

func (t *TracedEngine) CreateEdge(ctx context.Context, edge *Edge) error

func (*TracedEngine) CreateNode added in v1.1.0

func (t *TracedEngine) CreateNode(ctx context.Context, node *Node) (NodeID, error)

func (*TracedEngine) DeleteEdge added in v1.1.0

func (t *TracedEngine) DeleteEdge(ctx context.Context, id EdgeID) error

func (*TracedEngine) DeleteNode added in v1.1.0

func (t *TracedEngine) DeleteNode(ctx context.Context, id NodeID) error

func (*TracedEngine) EdgeCountByEndLabelInNamespace

func (t *TracedEngine) EdgeCountByEndLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)

EdgeCountByEndLabelInNamespace preserves the physical end-label counter.

func (*TracedEngine) EdgeCountByStartLabelInNamespace

func (t *TracedEngine) EdgeCountByStartLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)

EdgeCountByStartLabelInNamespace preserves the physical start-label counter.

func (*TracedEngine) EdgeCountByTypeInNamespace

func (t *TracedEngine) EdgeCountByTypeInNamespace(ctx context.Context, namespace, edgeType string) (int64, error)

EdgeCountByTypeInNamespace preserves the namespace relationship counter.

func (*TracedEngine) EventNotificationsSettled

func (t *TracedEngine) EventNotificationsSettled() bool

EventNotificationsSettled forwards the existing publisher's metadata.

func (*TracedEngine) ForEachNodeIDByLabel

func (t *TracedEngine) ForEachNodeIDByLabel(ctx context.Context, label string, visit func(NodeID) bool) error

ForEachNodeIDByLabel forwards ID iteration through tracing.

func (*TracedEngine) ForEachNodeIDByLabelInScope

func (t *TracedEngine) ForEachNodeIDByLabelInScope(ctx context.Context, scope, label string, visit func(NodeID) bool) error

ForEachNodeIDByLabelInScope forwards scoped ID iteration through tracing.

func (*TracedEngine) GetEdge added in v1.1.0

func (t *TracedEngine) GetEdge(ctx context.Context, id EdgeID) (*Edge, error)

func (*TracedEngine) GetEdgesByType added in v1.1.0

func (t *TracedEngine) GetEdgesByType(ctx context.Context, edgeType string) ([]*Edge, error)

func (*TracedEngine) GetFirstNodeByLabelInScope

func (t *TracedEngine) GetFirstNodeByLabelInScope(ctx context.Context, scope, label string) (*Node, error)

GetFirstNodeByLabelInScope forwards the scoped first reader through tracing.

func (*TracedEngine) GetInnerEngine

func (t *TracedEngine) GetInnerEngine() Engine

GetInnerEngine returns the underlying Engine so capability checks can peer through the tracing decorator via the canonical EngineUnwrapper accessor.

func (*TracedEngine) GetNode added in v1.1.0

func (t *TracedEngine) GetNode(ctx context.Context, id NodeID) (*Node, error)

func (*TracedEngine) GetNodesByLabel added in v1.1.0

func (t *TracedEngine) GetNodesByLabel(ctx context.Context, label string) ([]*Node, error)

func (*TracedEngine) GetNodesByLabelInScope

func (t *TracedEngine) GetNodesByLabelInScope(ctx context.Context, scope, label string) ([]*Node, error)

GetNodesByLabelInScope forwards the scoped label reader through tracing.

func (*TracedEngine) GetNodesByLabelVisibleAtInScope

func (t *TracedEngine) GetNodesByLabelVisibleAtInScope(ctx context.Context, scope, label string, version MVCCVersion) ([]*Node, error)

GetNodesByLabelVisibleAtInScope forwards the scoped snapshot read through tracing.

func (*TracedEngine) GraphMutationVersion added in v1.3.3

func (t *TracedEngine) GraphMutationVersion() (uint64, bool)

GraphMutationVersion forwards revision reporting through tracing.

func (*TracedEngine) GraphMutationVersionInNamespace added in v1.3.3

func (t *TracedEngine) GraphMutationVersionInNamespace(namespace string) (uint64, bool)

GraphMutationVersionInNamespace forwards database-scoped revision reporting.

func (*TracedEngine) IndexSourceStamp

func (t *TracedEngine) IndexSourceStamp(ctx context.Context) (string, error)

func (*TracedEngine) OpenReadSnapshot

func (t *TracedEngine) OpenReadSnapshot(ctx context.Context) (ReadSnapshotView, error)

OpenReadSnapshot forwards to the traced engine.

func (*TracedEngine) PreservesEventView

func (t *TracedEngine) PreservesEventView()

PreservesEventView declares that tracing adds no event, ID or committed-read view.

func (*TracedEngine) ReadAdjacentEdges

func (t *TracedEngine) ReadAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

func (*TracedEngine) ReadCountStore

func (t *TracedEngine) ReadCountStore(ctx context.Context, request CountStoreReadRequest) (CountStoreRead, error)

ReadCountStore preserves a single count-store observation through tracing.

func (*TracedEngine) SetContext added in v1.1.0

func (t *TracedEngine) SetContext(ctx context.Context)

SetContext updates the context used for span parenting. Called by the cypher executor at the start of Execute so storage spans nest under the cypher span.

func (*TracedEngine) StreamEdgesByType

func (t *TracedEngine) StreamEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamEdgesByType forwards the type stream to the traced engine.

func (*TracedEngine) StreamEdgesByTypeInScope

func (t *TracedEngine) StreamEdgesByTypeInScope(ctx context.Context, scope, edgeType string, visit func(*Edge) error) error

StreamEdgesByTypeInScope forwards a scoped type stream (ScopedEdgeTypeStreamer).

func (*TracedEngine) StreamNodesByLabelProjectedInScope

func (t *TracedEngine) StreamNodesByLabelProjectedInScope(ctx context.Context, scope, label string, properties []string, visit func(*Node) error) error

StreamNodesByLabelProjectedInScope forwards the scoped stream through tracing.

func (*TracedEngine) SubscribeEvents

func (t *TracedEngine) SubscribeEvents(handlers EventHandlers) error

SubscribeEvents forwards to the traced engine.

func (*TracedEngine) UpdateEdge added in v1.1.0

func (t *TracedEngine) UpdateEdge(ctx context.Context, updateRequest EdgeUpdateRequest) error

func (*TracedEngine) UpdateNode added in v1.1.0

func (t *TracedEngine) UpdateNode(ctx context.Context, updateRequest NodeUpdateRequest) error

type Transaction

type Transaction = BadgerTransaction

Transaction is the public closure-facing transaction type used by DB.Update and DB.View.

type TransactionChanges

type TransactionChanges struct {
	Namespace  string
	Nodes      map[NodeID]*Node
	Edges      map[EdgeID]*Edge
	Operations int
	// HoldsMergeKey means admission must not wait behind a writer that could
	// need this transaction's unique MERGE key lock.
	HoldsMergeKey bool
}

TransactionChanges describes the final staged entities, using physical, namespace-prefixed IDs. A nil value means deletion. Operations counts the buffered storage operations (the same count as OperationCount).

type TransactionEqualityLookup

type TransactionEqualityLookup interface {
	LookupNodesByEquality(ctx context.Context, label string, properties map[string]interface{}) ([]*Node, bool, error)
}

TransactionEqualityLookup exposes complete candidates from a transaction's pinned label population. False asks the caller to use its normal scan (for read-committed views, unkeyable values or populations outside the cache bound). Callers still apply their language's complete property/label predicate.

type TransactionRecoveryResult

type TransactionRecoveryResult struct {
	SnapshotSeq            uint64
	Transactions           map[string]*TransactionState
	CommittedTransactions  int
	RolledBackTransactions int
	AbortedTransactions    int
	FailedTransactions     []string
	UndoErrors             []string
	NonTxApplied           int
	NonTxErrors            []string
}

TransactionRecoveryResult contains detailed statistics from transaction-aware recovery.

func (*TransactionRecoveryResult) HasErrors

func (r *TransactionRecoveryResult) HasErrors() bool

HasErrors returns true if there were any errors during recovery.

func (*TransactionRecoveryResult) Summary

func (r *TransactionRecoveryResult) Summary() string

Summary returns a human-readable summary of the recovery.

type TransactionState

type TransactionState struct {
	TxID    string
	Entries []WALEntry // All entries in this transaction (in order)
	Started bool       // True if we saw TxBegin
	Done    bool       // True if we saw TxCommit or TxAbort
	Aborted bool       // True if explicitly aborted
}

TransactionState tracks the state of an in-progress transaction during recovery.

type TransactionStatus

type TransactionStatus string

TransactionStatus represents the current state of a transaction.

const (
	TxStatusActive     TransactionStatus = "active"
	TxStatusCommitted  TransactionStatus = "committed"
	TxStatusRolledBack TransactionStatus = "rolled_back"
)

type TransactionValidationSetting

type TransactionValidationSetting uint8

TransactionValidationSetting selects one independent native validation policy.

const (
	// DeferredConstraintValidation defers constraint checks until commit.
	DeferredConstraintValidation TransactionValidationSetting = iota
	// SkipCreateCommitHeadReload skips only the commit-time head reload for a
	// minted/UUID-shaped create; stored-inclusive identity checks remain required.
	SkipCreateCommitHeadReload
)

type TrustLevel

type TrustLevel int

TrustLevel defines how trustworthy a node is for edge materialization.

const (
	// TrustLevelDefault is the standard trust level
	TrustLevelDefault TrustLevel = 0
	// TrustLevelLow requires higher confidence for edges
	TrustLevelLow TrustLevel = -1
	// TrustLevelHigh allows lower confidence edges
	TrustLevelHigh TrustLevel = 1
	// TrustLevelPinned edges never decay
	TrustLevelPinned TrustLevel = 2
)

func (TrustLevel) ConfidenceAdjustment

func (t TrustLevel) ConfidenceAdjustment() float64

ConfidenceAdjustment returns the confidence threshold adjustment for this trust level. Positive values increase required confidence, negative values decrease it.

func (TrustLevel) String

func (t TrustLevel) String() string

String returns the string representation of TrustLevel.

type TypedPropertyValue

type TypedPropertyValue interface {
	PropertyValueKind() string
}

TypedPropertyValue marks a typed Cypher scalar (temporal values, points) that supplies its own durable serialization while remaining opaque to the storage layer. PropertyValueKind names the type for property type constraints: date, local-time, time, local-date-time, zoned-date-time, duration, point.

type UniqueConstraint

type UniqueConstraint struct {
	Name     string
	Label    string
	Property string
	// contains filtered or unexported fields
}

UniqueConstraint represents a unique constraint on a label and property.

type UniqueValueAction

type UniqueValueAction uint8

UniqueValueAction identifies the authority of a claim publication and the transition applied to the canonical (label, property, value) claim.

const (
	// ValidatedUniqueClaim assigns the value to nodeID unconditionally: a
	// current, validated logical mutation is the authoritative owner.
	ValidatedUniqueClaim UniqueValueAction = iota
	// RecoveredUniqueClaim assigns the value to nodeID only while no other
	// node holds it: historical WAL images can precede a later directly
	// persisted owner.
	RecoveredUniqueClaim
	// RetiredUniqueClaim deletes the value only while nodeID is its current
	// holder. Supply the stored node being retired, not a newly looked-up
	// holder: replay of an older deletion must preserve a later writer's claim
	// to the same value.
	RetiredUniqueClaim
)

type VectorIndex

type VectorIndex struct {
	Name           string
	Label          string
	Property       string
	Dimensions     int
	SimilarityFunc string // "cosine", "euclidean", "dot"
	EntityType     ConstraintEntityType
}

VectorIndex represents a vector similarity index.

type WAL

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

WAL provides write-ahead logging for durability. Thread-safe for concurrent writes.

func NewWAL

func NewWAL(dir string, cfg *WALConfig) (*WAL, error)

NewWAL creates a new write-ahead log.

func (*WAL) Append

func (w *WAL) Append(op OperationType, data interface{}) error

Append writes a new entry to the WAL using atomic write format.

The atomic format ensures partial writes are detectable:

[4 bytes: magic "WALE"]
[1 byte: format version]
[4 bytes: payload length]
[N bytes: JSON-encoded entry]
[4 bytes: CRC32 of payload]

If crash occurs mid-write:

  • Missing magic: entry doesn't exist
  • Missing/truncated payload: length mismatch detected
  • Missing checksum: CRC verification fails

func (*WAL) AppendBufferedCommit

func (w *WAL) AppendBufferedCommit(c *bufferedCommit, dictionary *propertyKeyDictionary) error

AppendBufferedCommit writes the full payload of an acknowledged write-behind commit to the WAL and pushes it to the kernel page cache (write(2)) before returning, so the ACK never outruns the record that survives kill -9. It deliberately skips fsync: power-loss durability remains the durable synchronous path's contract.

func (*WAL) AppendReturningSeq

func (w *WAL) AppendReturningSeq(op OperationType, data interface{}) (uint64, error)

AppendReturningSeq writes a new entry to the WAL and returns its sequence number.

func (*WAL) AppendWithDatabase

func (w *WAL) AppendWithDatabase(op OperationType, data interface{}, database string) error

AppendWithDatabase writes a new entry to the WAL with database/namespace information.

func (*WAL) AppendWithDatabaseReturningSeq

func (w *WAL) AppendWithDatabaseReturningSeq(op OperationType, data interface{}, database string) (uint64, error)

AppendWithDatabaseReturningSeq writes a new entry to the WAL with database/namespace information and returns the assigned sequence number.

func (*WAL) CheckRecordCapacity

func (w *WAL) CheckRecordCapacity(op OperationType, dataSize int, database string) error

CheckRecordCapacity checks an encoded body's size before ownership transfers to an asynchronous producer. It reserves the largest append-generated sequence, checksum and timestamp header, so later sequence growth cannot invalidate the admission. Near a frame boundary this requires a few bytes more headroom than an immediate append at the current sequence. It performs no I/O or reservation and does not promise that a later append will succeed against I/O failures.

For example, replication checks its JSON body's encoded size here before enrolling a command; the actual append still owns sequence assignment and I/O.

func (*WAL) Checkpoint

func (w *WAL) Checkpoint() error

Checkpoint creates a checkpoint marker for snapshot boundaries.

func (*WAL) Close

func (w *WAL) Close() error

Close closes the WAL, flushing all pending writes.

func (*WAL) Config

func (w *WAL) Config() *WALConfig

Config returns the WAL configuration (read-only access).

func (*WAL) CreateSnapshot

func (w *WAL) CreateSnapshot(engine Engine) (*Snapshot, error)

CreateSnapshot creates a point-in-time snapshot from the engine.

func (*WAL) IsDegraded

func (w *WAL) IsDegraded() bool

IsDegraded reports whether this WAL has detected corruption and performed best-effort recovery actions. When true, callers should consider the durability state degraded and surface it in health endpoints.

func (*WAL) LastCorruptionDiagnostics

func (w *WAL) LastCorruptionDiagnostics() *CorruptionDiagnostics

LastCorruptionDiagnostics returns the last corruption diagnostics captured by this WAL. Returns nil if no corruption has been observed.

func (*WAL) ManageSnapshot

func (w *WAL) ManageSnapshot(ctx context.Context, snapshotSeq uint64, mode WALSnapshotMode) error

ManageSnapshot is the single owner of post-snapshot WAL management. Call it after SaveSnapshot succeeds. Both modes take w.mu once and report ErrWALClosed on a closed WAL.

WALSnapshotTruncate validates the WAL first. It is crash-safe:

  1. Validate and read the current WAL before closing it
  2. Write and sync a new WAL with only post-snapshot entries
  3. Atomically rename the new WAL over the old file
  4. Reopen the WAL for appends

If the system crashes during truncation:

  • Old WAL remains intact (rename is atomic)
  • Recovery will replay full WAL (safe, just slower)
  • Retry truncation on next snapshot

WALSnapshotRetention deletes sealed segments a snapshot covers that retention no longer keeps. A zero snapshot sequence is a no-op.

Example:

snapshot, _ := wal.CreateSnapshot(engine)
SaveSnapshot(snapshot, "data/snapshot.json")
wal.ManageSnapshot(ctx, snapshot.Sequence, WALSnapshotTruncate)  // Reclaim disk space
wal.ManageSnapshot(ctx, snapshot.Sequence, WALSnapshotRetention) // Retention only

func (*WAL) NewBatch

func (w *WAL) NewBatch() *BatchWriter

NewBatch creates a new batch writer.

func (*WAL) NewBatchWithTxID

func (w *WAL) NewBatchWithTxID(txID string) *BatchWriter

NewBatchWithTxID creates a new batch writer that stamps each entry with a TxID. The TxID will be embedded in WAL payloads (e.g., WALNodeData.TxID).

func (*WAL) Sequence

func (w *WAL) Sequence() uint64

Sequence returns the published operation boundary, including persisted historical range floors. Refused records do not advance it. It does not itself flush or fsync the journal.

func (*WAL) Stats

func (w *WAL) Stats() WALStats

Stats returns current WAL statistics.

func (*WAL) Sync

func (w *WAL) Sync() error

Sync flushes all buffered writes to disk.

Lock discipline: we acquire w.mu ONLY to drain the bufio userspace buffer to the kernel (a short, bounded memcpy+write), then release it BEFORE the kernel fsync. The fsync is serialized instead through syncMu so concurrent Sync() callers don't issue duplicate fsyncs while still letting Append() progress against w.mu in parallel. This eliminated the dominant mutex-contention source seen during bulk seed: batchSyncLoop's 100ms ticks used to block every Append for the duration of each fsync.

func (*WAL) VisitEntriesAfter

func (w *WAL) VisitEntriesAfter(ctx context.Context, afterSeq uint64, visit func(WALEntry) error) error

VisitEntriesAfter visits retained entries through this WAL's configured frame reader, including encrypted frames, without exposing its key.

type WALBufferedCommitData

type WALBufferedCommitData struct {
	LogicalTxID string            `json:"logical_tx_id,omitempty"`
	TxID        string            `json:"tx_id"`
	Namespace   string            `json:"namespace,omitempty"`
	Ops         []Operation       `json:"ops"`
	Writes      map[string][]byte `json:"writes,omitempty"`
	Deletes     []string          `json:"deletes,omitempty"`
	Version     MVCCVersion       `json:"version"`
	NodeMax     uint64            `json:"node_max,omitempty"`
	EdgeMax     uint64            `json:"edge_max,omitempty"`
	HasCounters bool              `json:"has_counters,omitempty"`
	// NumericBindings identifies source-local node and edge IDs used by
	// physical keys and compact bodies. Foreign replay resolves their names
	// against the destination dictionary before applying those bytes.
	NumericBindings []byte `json:"numeric_bindings,omitempty"`

	// PropertyBindings binds every property token referenced by Writes,
	// including persisted names. Import remaps tokens into the destination.
	PropertyBindings     []byte `json:"property_bindings,omitempty"`
	PropertyDictionaryID string `json:"property_dictionary_id,omitempty"`
	// PhysicalPropertyImages marks a record whose Writes and Deletes are
	// authoritative physical images while the named property values in its Ops
	// are the lossy projection an older encoding wrote. The V4 upgrade sets it
	// when it repairs a legacy record into the lossless encoding: the typed
	// encoding preserves the physical keys, and this marker keeps the
	// historical named properties from becoming authority.
	PhysicalPropertyImages bool `json:"physical_property_images,omitempty"`

	// Historical writers carried only newly staged keys and source counters.
	PropKeys        []WALPropKeyEntry `json:"prop_keys,omitempty"`
	PropKeyCounters map[string]uint64 `json:"prop_key_counters,omitempty"`
	// contains filtered or unexported fields
}

WALBufferedCommitData is the durable payload of one acknowledged write-behind commit. It carries everything applyBufferedCommits needs to replay the commit into Badger after a crash loses the in-memory buffer.

The count deltas are deliberately not serialized: they are rebuilt from committed entities after replay (crash recovery is rare, so the full rebuild is acceptable).

type WALBulkDeleteEdgesData

type WALBulkDeleteEdgesData struct {
	IDs      []string `json:"ids"`
	OldEdges []*Edge  `json:"old_edges,omitempty"` // Complete edges being deleted (undo)
	TxID     string   `json:"tx_id,omitempty"`     // Transaction ID for grouping
}

WALBulkDeleteEdgesData holds bulk edge deletion data with undo support.

type WALBulkDeleteNodesData

type WALBulkDeleteNodesData struct {
	IDs      []string `json:"ids"`
	OldNodes []*Node  `json:"old_nodes,omitempty"` // Complete nodes being deleted (undo)
	TxID     string   `json:"tx_id,omitempty"`     // Transaction ID for grouping
}

WALBulkDeleteNodesData holds bulk node deletion data with undo support.

type WALBulkEdgesData

type WALBulkEdgesData struct {
	Edges []*Edge `json:"edges"`
	TxID  string  `json:"tx_id,omitempty"` // Transaction ID for grouping
}

WALBulkEdgesData holds bulk edge creation data.

type WALBulkNodesData

type WALBulkNodesData struct {
	Nodes []*Node `json:"nodes"`
	TxID  string  `json:"tx_id,omitempty"` // Transaction ID for grouping
}

WALBulkNodesData holds bulk node creation data.

type WALConfig

type WALConfig struct {
	// Directory for WAL files
	Dir string

	// SyncMode controls when writes are synced to disk
	// "immediate": fsync after each write (safest, slowest)
	// "batch": fsync periodically (faster, some risk)
	// "none": no fsync (fastest, data loss on crash)
	SyncMode string

	// DeferAppendFlush skips the per-append userspace flush in non-immediate
	// modes: records accumulate in the bufio writer and reach the kernel
	// only when the background Sync (batchSyncLoop tick) or Close drains
	// them. Per-op appends stop paying a write(2) syscall each; in exchange
	// up to BatchSyncInterval of records are lost on process crash (power
	// loss behavior is unchanged: batch mode never fsyncs per record).
	// Intended for engines that already accept a bounded loss window per
	// commit (write-behind buffering), where per-append flush syscalls
	// otherwise dominate ingest CPU.
	DeferAppendFlush bool

	// EncryptionKey is the optional 32-byte key this WAL authenticates and
	// encrypts every frame with (XChaCha20-Poly1305, frame versions 8 and 9).
	// Nil or empty keeps the journal's plaintext format. A configured key makes
	// NewWAL write and read encrypted frames only: a journal that still holds
	// plaintext frames is refused until EncryptWALDirectory converts it.
	EncryptionKey []byte

	// RecordPolicy is how this WAL writes the records it creates (NOR-412).
	// The zero value, WALRecordsStandard, keeps every record in one frame and
	// refuses a larger one. NewWAL keeps the value it is given: changing this
	// field afterwards changes nothing.
	RecordPolicy WALRecordPolicy

	// BatchSyncInterval for "batch" sync mode
	BatchSyncInterval time.Duration

	// MaxFileSize triggers rotation when exceeded
	MaxFileSize int64

	// MaxEntries triggers rotation when exceeded
	MaxEntries int64

	// SnapshotInterval for automatic snapshots
	SnapshotInterval time.Duration

	// RetentionMaxSegments keeps at most N sealed segments (0 = unlimited).
	RetentionMaxSegments int

	// RetentionMaxAge keeps segments newer than this duration (0 = unlimited).
	RetentionMaxAge time.Duration

	// SnapshotRetentionMaxCount is the maximum number of snapshot files to keep in the
	// snapshot directory (0 = keep all). Oldest snapshots are deleted after each new one.
	// Recommended 3–5 so disk space stays bounded while keeping recovery options.
	SnapshotRetentionMaxCount int

	// SnapshotRetentionMaxAge is the maximum age of snapshot files to keep (0 = unlimited).
	// Snapshots older than this are deleted even if under MaxCount.
	SnapshotRetentionMaxAge time.Duration

	// Logger receives WAL diagnostics events (optional, legacy structured
	// channel implemented by pkg/storage's WALLogger interface). If nil,
	// a default slog-backed logger is installed at ctor entry — the
	// previous stdlib-printer-backed default has been removed per LOG-01.
	Logger WALLogger

	// SlogLogger is the structured *slog.Logger used by D-07 WAL recovery
	// emissions (subsystem=wal, subsystem=wal_recovery). Optional; nil
	// falls back to a discard handler at NewWAL entry per D-01a.
	SlogLogger *slog.Logger

	// OnCorruption is called when WAL corruption diagnostics are produced (optional).
	// This allows the server layer to surface "WAL degraded" health state without
	// parsing logs. The callback MUST be fast and non-blocking.
	OnCorruption func(diag *CorruptionDiagnostics, cause error)
}

WALConfig configures WAL behavior.

func DefaultWALConfig

func DefaultWALConfig() *WALConfig

DefaultWALConfig returns sensible defaults.

type WALDeleteData

type WALDeleteData struct {
	ID      string `json:"id"`
	OldNode *Node  `json:"old_node,omitempty"` // Complete node being deleted (undo)
	OldEdge *Edge  `json:"old_edge,omitempty"` // Complete edge being deleted (undo)
	TxID    string `json:"tx_id,omitempty"`    // Transaction ID for grouping
}

WALDeleteData holds delete operation data with undo support. For proper undo, we store the complete entity being deleted.

type WALEdgeData

type WALEdgeData struct {
	Edge    *Edge  `json:"edge"`               // New state (redo)
	OldEdge *Edge  `json:"old_edge,omitempty"` // Previous state (undo) - for updates
	TxID    string `json:"tx_id,omitempty"`    // Transaction ID for grouping
}

WALEdgeData holds edge data for WAL entries with optional undo support. For update/delete operations, OldEdge contains the "before image" for rollback.

type WALEngine

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

WALEngine wraps a storage engine with write-ahead logging.

Native mutating operations are appended to the WAL before they are applied to the wrapped engine. This provides crash recovery via snapshot + replay while keeping the underlying Engine implementations simple and fast.

Design notes:

  • Issued views: statement-owned routers and remote views delegate writes to their participants. A WAL decorator on such a view does not journal its pending operations; the participant retains sole publication authority.
  • Database routing: WALEngine supports multi-database usage by recording the database/namespace in each WAL entry and by normalizing IDs when needed.
  • Embedding updates: embedding-only updates are logged using OpUpdateEmbedding, which names the node but not its new embedding. Replay leaves the node without managed embeddings, so it is embedded again.
  • Auto-compaction: optional periodic snapshots + WAL truncation to prevent unbounded WAL growth.

func NewWALEngine

func NewWALEngine(engine Engine, wal *WAL) *WALEngine

NewWALEngine creates a WAL-backed storage engine.

func (*WALEngine) AddToPendingEmbeddings

func (w *WALEngine) AddToPendingEmbeddings(nodeID NodeID)

AddToPendingEmbeddings delegates to underlying engine if it supports it.

func (*WALEngine) AllEdges

func (w *WALEngine) AllEdges(ctx context.Context) ([]*Edge, error)

AllEdges delegates to underlying engine.

func (*WALEngine) AllNodes

func (w *WALEngine) AllNodes(ctx context.Context) ([]*Node, error)

AllNodes delegates to underlying engine.

func (*WALEngine) Backup

func (w *WALEngine) Backup(path string) error

Backup holds the WAL mutation barrier while Badger creates its consistent streaming snapshot.

func (*WALEngine) BackupTo

func (w *WALEngine) BackupTo(ctx context.Context, dst io.Writer) error

BackupTo holds the same mutation barrier for a streamed native backup.

func (*WALEngine) BatchGetNodes

func (w *WALEngine) BatchGetNodes(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

BatchGetNodes delegates to underlying engine.

func (*WALEngine) BatchGetNodesWithoutEmbeddings

func (w *WALEngine) BatchGetNodesWithoutEmbeddings(ctx context.Context, ids []NodeID) (map[NodeID]*Node, error)

BatchGetNodesWithoutEmbeddings forwards a batched embedding-free read without materializing vectors in the WAL wrapper.

func (*WALEngine) BatchGetNodesWithoutEmbeddingsSupported

func (w *WALEngine) BatchGetNodesWithoutEmbeddingsSupported() bool

BatchGetNodesWithoutEmbeddingsSupported reports the wrapped engine's real capability rather than the presence of this forwarding method.

func (*WALEngine) BulkCreateEdges

func (w *WALEngine) BulkCreateEdges(ctx context.Context, edges []*Edge) error

func (*WALEngine) BulkCreateNodes

func (w *WALEngine) BulkCreateNodes(ctx context.Context, nodes []*Node) error

func (*WALEngine) BulkDeleteEdges

func (w *WALEngine) BulkDeleteEdges(ctx context.Context, ids []EdgeID) error

func (*WALEngine) BulkDeleteNodes

func (w *WALEngine) BulkDeleteNodes(ctx context.Context, ids []NodeID) error

func (*WALEngine) ClearAllEmbeddingsForPrefix

func (w *WALEngine) ClearAllEmbeddingsForPrefix(idPrefix string) (int, error)

ClearAllEmbeddingsForPrefix removes the managed embeddings of every node whose ID starts with idPrefix (all nodes when empty), as the wrapped engine's ClearAllEmbeddingsForPrefix does, and journals each node's removal with the OpUpdateEmbedding record of an embedding reset. Without that record a rebuild from an earlier snapshot would restore the removed vectors as current. The store appends the record inside that node's transaction, under the node's write authority and before its removal (BadgerEngine.clearEmbeddingsForPrefix), so the record and the removal it describes keep the order the store applied them in against ordinary writes of the node.

func (*WALEngine) Close

func (w *WALEngine) Close() error

Close closes both the WAL and underlying engine.

func (*WALEngine) CommitTransaction

func (w *WALEngine) CommitTransaction(ctx context.Context, tx *BadgerTransaction) error

CommitTransaction preserves journal ownership when an executor has staged changes on the native transaction underneath this decorator. The native publication owner journals the final entity changes, just as it does for CreateNode and UpdateNode; begin/commit markers alone cannot recover them.

func (*WALEngine) ConsumeCleanShutdownMarker

func (w *WALEngine) ConsumeCleanShutdownMarker(ctx context.Context) (bool, error)

ConsumeCleanShutdownMarker delegates startup recovery state to storage.

func (*WALEngine) CountPendingEmbeddingIDs

func (w *WALEngine) CountPendingEmbeddingIDs(ctx context.Context, accept func([]byte) bool) int

func (*WALEngine) CreateEdge

func (w *WALEngine) CreateEdge(ctx context.Context, edge *Edge) error

func (*WALEngine) CreateNode

func (w *WALEngine) CreateNode(ctx context.Context, node *Node) (NodeID, error)

func (*WALEngine) CreateRecoveryBaseline

func (w *WALEngine) CreateRecoveryBaseline(ctx context.Context, snapshotDir string) error

CreateRecoveryBaseline publishes a fresh snapshot before an upgraded store can serve traffic. Historical journals may contain transaction boundaries without enough entity images to rebuild the migrated Badger state, so this snapshot is required even when no new WAL sequence has been appended and automatic compaction is disabled.

func (*WALEngine) DeleteByPrefix

func (w *WALEngine) DeleteByPrefix(prefix string) (nodesDeleted int64, edgesDeleted int64, err error)

DeleteByPrefix delegates to the underlying engine.

func (*WALEngine) DeleteEdge

func (w *WALEngine) DeleteEdge(ctx context.Context, id EdgeID) error

func (*WALEngine) DeleteNode

func (w *WALEngine) DeleteNode(ctx context.Context, id NodeID) error

func (*WALEngine) DisableAutoCompaction

func (w *WALEngine) DisableAutoCompaction()

DisableAutoCompaction stops automatic snapshot creation and WAL truncation. Waits for the auto-compaction goroutine to finish before returning to prevent race conditions when the engine is closed.

func (*WALEngine) EdgeCount

func (w *WALEngine) EdgeCount(ctx context.Context) (int64, error)

EdgeCount delegates to underlying engine.

func (*WALEngine) EdgeCountByEndLabel

func (w *WALEngine) EdgeCountByEndLabel(ctx context.Context, label, edgeType string) (int64, error)

func (*WALEngine) EdgeCountByEndLabelInNamespace

func (w *WALEngine) EdgeCountByEndLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)

EdgeCountByEndLabelInNamespace preserves the physical end-label counter.

func (*WALEngine) EdgeCountByPrefix

func (w *WALEngine) EdgeCountByPrefix(ctx context.Context, prefix string) (int64, error)

EdgeCountByPrefix is NodeCountByPrefix for relationships.

func (*WALEngine) EdgeCountByStartLabel

func (w *WALEngine) EdgeCountByStartLabel(ctx context.Context, label, edgeType string) (int64, error)

func (*WALEngine) EdgeCountByStartLabelInNamespace

func (w *WALEngine) EdgeCountByStartLabelInNamespace(ctx context.Context, namespace, label, edgeType string) (int64, error)

EdgeCountByStartLabelInNamespace preserves the physical start-label counter.

func (*WALEngine) EdgeCountByType

func (w *WALEngine) EdgeCountByType(ctx context.Context, edgeType string) (int64, error)

EdgeCountByType delegates to the inner engine's per-type counter (issue #638). No edge materialization on this path.

func (*WALEngine) EdgeCountByTypeInNamespace

func (w *WALEngine) EdgeCountByTypeInNamespace(ctx context.Context, namespace, edgeType string) (int64, error)

EdgeCountByTypeInNamespace preserves the namespace relationship counter.

func (*WALEngine) EnableAutoCompaction

func (w *WALEngine) EnableAutoCompaction(snapshotDir string) error

EnableAutoCompaction starts automatic snapshot creation and WAL truncation. Snapshots are created at the configured SnapshotInterval, and the WAL is truncated after each successful snapshot to prevent unbounded growth.

Snapshots are saved to snapshotDir/snapshot-<timestamp>.json

This solves the "WAL grows forever" problem by automatically removing old entries that are already captured in snapshots.

Example:

walEngine.EnableAutoCompaction("data/snapshots")
// WAL will now be automatically truncated every SnapshotInterval

func (*WALEngine) EventNotificationsSettled

func (w *WALEngine) EventNotificationsSettled() bool

EventNotificationsSettled forwards the existing publisher's metadata.

func (*WALEngine) FindNodeNeedingEmbedding

func (w *WALEngine) FindNodeNeedingEmbedding(ctx context.Context) (*Node, error)

FindNodeNeedingEmbedding delegates to underlying engine if it supports it.

func (*WALEngine) ForEachNodeIDByLabel

func (w *WALEngine) ForEachNodeIDByLabel(ctx context.Context, label string, visit func(NodeID) bool) error

ForEachNodeIDByLabel delegates label-to-nodeID iteration to the underlying engine when available. This keeps LIMIT + label paths fast without forcing full node materialization.

func (*WALEngine) ForEachNodeIDByLabelInScope

func (w *WALEngine) ForEachNodeIDByLabelInScope(ctx context.Context, scope, label string, visit func(NodeID) bool) error

ForEachNodeIDByLabelInScope forwards scoped ID iteration through WAL.

func (*WALEngine) GetEdge

func (w *WALEngine) GetEdge(ctx context.Context, id EdgeID) (*Edge, error)

GetEdge delegates to underlying engine.

func (*WALEngine) GetEdgeBetween

func (w *WALEngine) GetEdgeBetween(ctx context.Context, startID, endID NodeID, edgeType string) (*Edge, error)

GetEdgeBetween delegates to underlying engine.

func (*WALEngine) GetEdgeCurrentHead

func (w *WALEngine) GetEdgeCurrentHead(ctx context.Context, id EdgeID) (MVCCHead, error)

GetEdgeCurrentHead delegates edge head lookup when supported, on the caller's context.

func (*WALEngine) GetEdgeLatestEffective

func (w *WALEngine) GetEdgeLatestEffective(ctx context.Context, id EdgeID) (*Edge, error)

GetEdgeLatestEffective delegates MVCC latest-effective edge reads to the wrapped engine when supported, on the caller's context.

func (*WALEngine) GetEdgeLatestVisible

func (w *WALEngine) GetEdgeLatestVisible(ctx context.Context, id EdgeID) (*Edge, error)

GetEdgeLatestVisible delegates latest-visible edge reads when supported.

func (*WALEngine) GetEdgeVisibleAt

func (w *WALEngine) GetEdgeVisibleAt(ctx context.Context, id EdgeID, version MVCCVersion) (*Edge, error)

GetEdgeVisibleAt delegates snapshot-visible edge reads when supported.

func (*WALEngine) GetEdgesByType

func (w *WALEngine) GetEdgesByType(ctx context.Context, edgeType string) ([]*Edge, error)

GetEdgesByType delegates to underlying engine.

func (*WALEngine) GetEdgesByTypeVisibleAt

func (w *WALEngine) GetEdgesByTypeVisibleAt(ctx context.Context, edgeType string, version MVCCVersion) ([]*Edge, error)

GetEdgesByTypeVisibleAt delegates snapshot-visible edge-type queries when supported.

func (*WALEngine) GetFirstNodeByLabel

func (w *WALEngine) GetFirstNodeByLabel(ctx context.Context, label string) (*Node, error)

GetFirstNodeByLabel delegates to underlying engine.

func (*WALEngine) GetFirstNodeByLabelInScope

func (w *WALEngine) GetFirstNodeByLabelInScope(ctx context.Context, scope, label string) (*Node, error)

GetFirstNodeByLabelInScope delegates a scoped first-node read (ScopedLabelNodeReader).

func (*WALEngine) GetInDegree

func (w *WALEngine) GetInDegree(ctx context.Context, nodeID NodeID) (int, error)

GetInDegree delegates to underlying engine.

func (*WALEngine) GetInnerEngine

func (w *WALEngine) GetInnerEngine() Engine

GetInnerEngine returns the wrapped storage engine.

func (*WALEngine) GetNode

func (w *WALEngine) GetNode(ctx context.Context, id NodeID) (*Node, error)

GetNode delegates to underlying engine.

func (*WALEngine) GetNodeCurrentHead

func (w *WALEngine) GetNodeCurrentHead(ctx context.Context, id NodeID) (MVCCHead, error)

GetNodeCurrentHead delegates node head lookup when supported, on the caller's context.

func (*WALEngine) GetNodeEmbeddingMeta

func (w *WALEngine) GetNodeEmbeddingMeta(ctx context.Context, id NodeID) (map[string]any, error)

GetNodeEmbeddingMeta delegates to the wrapped engine on the caller's context.

func (*WALEngine) GetNodeLatestEffective

func (w *WALEngine) GetNodeLatestEffective(ctx context.Context, id NodeID) (*Node, error)

GetNodeLatestEffective delegates MVCC latest-effective reads to the wrapped engine when supported. Both the capability read and the plain fallback run on the caller's context.

func (*WALEngine) GetNodeLatestVisible

func (w *WALEngine) GetNodeLatestVisible(ctx context.Context, id NodeID) (*Node, error)

GetNodeLatestVisible delegates latest-visible node reads when supported.

func (*WALEngine) GetNodeProjected

func (w *WALEngine) GetNodeProjected(ctx context.Context, id NodeID, properties []string) (*Node, error)

GetNodeProjected forwards the projected read to the underlying engine. WAL adds no overlay, so a plain forward preserves parity with GetNode.

func (*WALEngine) GetNodeVisibleAt

func (w *WALEngine) GetNodeVisibleAt(ctx context.Context, id NodeID, version MVCCVersion) (*Node, error)

GetNodeVisibleAt delegates snapshot-visible node reads when supported.

func (*WALEngine) GetNodeWithoutEmbeddings

func (w *WALEngine) GetNodeWithoutEmbeddings(ctx context.Context, id NodeID) (*Node, error)

GetNodeWithoutEmbeddings delegates an embedding-free node read when the wrapped engine supports it. The full read fallback preserves compatibility for engines that do not expose the optional projection contract.

func (*WALEngine) GetNodesByLabel

func (w *WALEngine) GetNodesByLabel(ctx context.Context, label string) ([]*Node, error)

GetNodesByLabel delegates to underlying engine.

func (*WALEngine) GetNodesByLabelInScope

func (w *WALEngine) GetNodesByLabelInScope(ctx context.Context, scope, label string) ([]*Node, error)

GetNodesByLabelInScope delegates a scoped label read (ScopedLabelNodeReader).

func (*WALEngine) GetNodesByLabelVisibleAt

func (w *WALEngine) GetNodesByLabelVisibleAt(ctx context.Context, label string, version MVCCVersion) ([]*Node, error)

GetNodesByLabelVisibleAt delegates snapshot-visible label queries when supported.

func (*WALEngine) GetNodesByLabelVisibleAtInScope

func (w *WALEngine) GetNodesByLabelVisibleAtInScope(ctx context.Context, scope, label string, version MVCCVersion) ([]*Node, error)

GetNodesByLabelVisibleAtInScope delegates a scoped snapshot label read (ScopedLabelNodeReader).

func (*WALEngine) GetOutDegree

func (w *WALEngine) GetOutDegree(ctx context.Context, nodeID NodeID) (int, error)

GetOutDegree delegates to underlying engine.

func (*WALEngine) GetQueryNode

func (w *WALEngine) GetQueryNode(ctx context.Context, id NodeID) (*Node, error)

GetQueryNode delegates the query-row node read (QueryNodeReader) when the wrapped engine supports it, else reads the full node.

func (*WALEngine) GetSchema

func (w *WALEngine) GetSchema() *SchemaManager

GetSchema delegates to underlying engine.

func (*WALEngine) GetSchemaForNamespace

func (w *WALEngine) GetSchemaForNamespace(namespace string) *SchemaManager

GetSchemaForNamespace implements NamespaceSchemaProvider when the underlying engine supports it.

func (*WALEngine) GetSnapshotStats

func (w *WALEngine) GetSnapshotStats() (totalSnapshots int64, lastSnapshotTime time.Time)

GetSnapshotStats returns statistics about automatic snapshots.

func (*WALEngine) GetStoredEdge

func (w *WALEngine) GetStoredEdge(ctx context.Context, id EdgeID) (*Edge, error)

GetStoredEdge forwards to the inner engine (StoredEntityReader).

func (*WALEngine) GetStoredNode

func (w *WALEngine) GetStoredNode(ctx context.Context, id NodeID) (*Node, error)

GetStoredNode forwards to the inner engine (StoredEntityReader).

func (*WALEngine) GetStoredNodesByLabel

func (w *WALEngine) GetStoredNodesByLabel(ctx context.Context, label string) ([]*Node, error)

GetStoredNodesByLabel forwards to the inner engine (StoredEntityReader).

func (*WALEngine) GetStoredNodesByLabelInScope

func (w *WALEngine) GetStoredNodesByLabelInScope(ctx context.Context, scope, label string) ([]*Node, error)

GetStoredNodesByLabelInScope forwards to the inner engine (ScopedStoredEntityReader).

func (*WALEngine) GetWAL

func (w *WALEngine) GetWAL() *WAL

GetWAL returns the underlying WAL for direct access.

func (*WALEngine) GraphMutationVersion added in v1.3.3

func (w *WALEngine) GraphMutationVersion() (uint64, bool)

GraphMutationVersion forwards revision reporting through the WAL wrapper.

func (*WALEngine) GraphMutationVersionInNamespace added in v1.3.3

func (w *WALEngine) GraphMutationVersionInNamespace(namespace string) (uint64, bool)

GraphMutationVersionInNamespace forwards database-scoped revision reporting.

func (*WALEngine) IndexSourceStamp

func (w *WALEngine) IndexSourceStamp(ctx context.Context) (string, error)

func (*WALEngine) IsCurrentTemporalNode

func (w *WALEngine) IsCurrentTemporalNode(ctx context.Context, node *Node, asOf time.Time) (bool, error)

IsCurrentTemporalNode delegates current-version checks to the wrapped engine when supported.

func (*WALEngine) IterateNodes

func (w *WALEngine) IterateNodes(fn func(*Node) bool) error

IterateNodes delegates to underlying engine if it supports streaming iteration.

func (*WALEngine) LastWriteTime

func (w *WALEngine) LastWriteTime() time.Time

LastWriteTime returns the last WAL entry timestamp (best-effort).

func (*WALEngine) LifecycleStatus

func (w *WALEngine) LifecycleStatus() map[string]interface{}

LifecycleStatus delegates lifecycle status when supported.

func (*WALEngine) ListNamespaces

func (w *WALEngine) ListNamespaces() []string

ListNamespaces returns known namespaces from the wrapped engine, if supported.

func (*WALEngine) MarkCleanShutdown

func (w *WALEngine) MarkCleanShutdown(ctx context.Context) error

MarkCleanShutdown delegates the durable shutdown boundary to storage.

func (*WALEngine) MarkNodeEmbedded

func (w *WALEngine) MarkNodeEmbedded(nodeID NodeID)

MarkNodeEmbedded delegates to underlying engine if it supports it.

func (*WALEngine) MatchEdgesBetween

func (w *WALEngine) MatchEdgesBetween(ctx context.Context, startID, endID NodeID, edgeType string, properties []string, match func(*Edge) bool, policy EdgeMatchReadPolicy) ([]*Edge, error)

MatchEdgesBetween delegates to the underlying engine.

func (*WALEngine) NodeCount

func (w *WALEngine) NodeCount(ctx context.Context) (int64, error)

NodeCount delegates to underlying engine.

func (*WALEngine) NodeCountByLabel added in v1.1.3

func (w *WALEngine) NodeCountByLabel(ctx context.Context, label string) (int64, error)

NodeCountByLabel preserves the caller context through counter or scan dispatch.

func (*WALEngine) NodeCountByLabelInNamespace added in v1.1.3

func (w *WALEngine) NodeCountByLabelInNamespace(ctx context.Context, namespace, label string) (int64, error)

func (*WALEngine) NodeCountByPrefix

func (w *WALEngine) NodeCountByPrefix(ctx context.Context, prefix string) (int64, error)

NodeCountByPrefix counts the nodes whose ID begins with prefix: the prefix counter, the streaming enumeration and the whole-collection read are the same three sources for nodes and edges, and countByPrefix chooses among them once.

func (*WALEngine) NotePropertyKeysInNamespace

func (w *WALEngine) NotePropertyKeysInNamespace(namespace string, properties map[string]interface{})

NotePropertyKeysInNamespace forwards to the wrapped engine (PropertyKeyRegistry); the WAL applies each write to it as it logs it.

func (*WALEngine) OnEdgeCreated

func (w *WALEngine) OnEdgeCreated(callback EdgeEventCallback)

func (*WALEngine) OnEdgeDeleted

func (w *WALEngine) OnEdgeDeleted(callback EdgeDeleteCallback)

func (*WALEngine) OnEdgeUpdated

func (w *WALEngine) OnEdgeUpdated(callback EdgeEventCallback)

func (*WALEngine) OnNodeCreated

func (w *WALEngine) OnNodeCreated(callback NodeEventCallback)

Event-callback registration forwards. WAL does not translate IDs, so the callback receives exactly what the inner engine emits.

func (*WALEngine) OnNodeDeleted

func (w *WALEngine) OnNodeDeleted(callback NodeDeleteCallback)

func (*WALEngine) OnNodeUpdated

func (w *WALEngine) OnNodeUpdated(callback NodeEventCallback)

func (*WALEngine) OpenReadSnapshot

func (w *WALEngine) OpenReadSnapshot(ctx context.Context) (ReadSnapshotView, error)

OpenReadSnapshot forwards to the engine the WAL writes through: the WAL applies every write to it before acknowledging, so it holds no other state a read could see.

func (*WALEngine) PauseLifecycle

func (w *WALEngine) PauseLifecycle()

PauseLifecycle delegates lifecycle pause when supported.

func (*WALEngine) PendingEmbeddingsCount

func (w *WALEngine) PendingEmbeddingsCount() int

PendingEmbeddingsCount delegates to underlying engine if it supports it.

func (*WALEngine) PreservesEventView

func (w *WALEngine) PreservesEventView()

PreservesEventView declares that WAL adds no event, ID or committed-read view.

func (*WALEngine) PropertyKeyKnownInNamespace

func (w *WALEngine) PropertyKeyKnownInNamespace(namespace, name string) bool

PropertyKeyKnownInNamespace forwards the property-key lookup (PropertyKeyRegistry).

func (*WALEngine) PruneMVCCVersions

func (w *WALEngine) PruneMVCCVersions(ctx context.Context, opts MVCCPruneOptions) (int64, error)

PruneMVCCVersions delegates MVCC pruning to the wrapped engine when supported.

func (*WALEngine) PruneTemporalHistory

func (w *WALEngine) PruneTemporalHistory(ctx context.Context, opts TemporalPruneOptions) (int64, error)

PruneTemporalHistory delegates temporal pruning to the wrapped engine when supported.

func (*WALEngine) ReadAdjacentEdges

func (w *WALEngine) ReadAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadAdjacentEdges delegates to the underlying engine. WAL writes are never reflected in reads (it only logs), so a forwarded request sees the same data.

func (*WALEngine) ReadAdjacentEdgesVisibleAt

func (w *WALEngine) ReadAdjacentEdgesVisibleAt(ctx context.Context, request AdjacentEdgeRead, version MVCCVersion) ([]*Edge, error)

ReadAdjacentEdgesVisibleAt delegates one snapshot-visible adjacent-edge request when the wrapped engine can answer it.

func (*WALEngine) ReadCountStore

func (w *WALEngine) ReadCountStore(ctx context.Context, request CountStoreReadRequest) (CountStoreRead, error)

ReadCountStore forwards a count-store read to the inner engine, where the counters and the visibility proof live, so the answer is one consistent read.

func (*WALEngine) ReadPendingEmbeddingCount

func (w *WALEngine) ReadPendingEmbeddingCount(ctx context.Context, accept func([]byte) bool) (int, error)

ReadPendingEmbeddingCount reads the underlying durable pending index.

func (*WALEngine) ReadStoredAdjacentEdges

func (w *WALEngine) ReadStoredAdjacentEdges(ctx context.Context, request AdjacentEdgeRead) ([]*Edge, error)

ReadStoredAdjacentEdges forwards to the inner engine (StoredEntityReader).

func (*WALEngine) RebuildMVCCHeads

func (w *WALEngine) RebuildMVCCHeads(ctx context.Context) error

RebuildMVCCHeads delegates MVCC head rebuild to the wrapped engine when supported.

func (*WALEngine) RebuildTemporalIndexes

func (w *WALEngine) RebuildTemporalIndexes(ctx context.Context) error

RebuildTemporalIndexes delegates temporal index rebuild to the wrapped engine when supported.

func (*WALEngine) RecordMaterializedAccess added in v1.1.0

func (w *WALEngine) RecordMaterializedAccess(entityID string)

RecordMaterializedAccess delegates result-materialization access recording to the underlying engine, if supported.

func (*WALEngine) RefreshPendingEmbeddingsIndex

func (w *WALEngine) RefreshPendingEmbeddingsIndex() int

RefreshPendingEmbeddingsIndex delegates to underlying engine if it supports it.

func (*WALEngine) RegisterSnapshotReader

func (w *WALEngine) RegisterSnapshotReader(info SnapshotReaderInfo) func()

RegisterSnapshotReader delegates snapshot-reader registration when supported.

func (*WALEngine) RelationshipEndpointVisible

func (w *WALEngine) RelationshipEndpointVisible(id NodeID) (visible, answered bool)

RelationshipEndpointVisible forwards to the underlying engine; WAL adds no overlay.

func (*WALEngine) Restore

func (w *WALEngine) Restore(path string) error

Restore holds the WAL mutation barrier while Badger loads the backup.

func (*WALEngine) ResumeLifecycle

func (w *WALEngine) ResumeLifecycle()

ResumeLifecycle delegates lifecycle resume when supported.

func (*WALEngine) SetLifecycleSchedule

func (w *WALEngine) SetLifecycleSchedule(interval time.Duration) error

SetLifecycleSchedule delegates lifecycle cadence updates when supported.

func (*WALEngine) SetManualSuppression

func (w *WALEngine) SetManualSuppression(ctx context.Context, kind StoredEntityKind, id string, suppressed bool) error

SetManualSuppression passes storage metadata through to the wrapped capability without adding a graph-write WAL record.

func (*WALEngine) StreamEdges

func (w *WALEngine) StreamEdges(ctx context.Context, fn func(edge *Edge) error) error

StreamEdges implements StreamingEngine.StreamEdges by delegating to the underlying engine.

func (*WALEngine) StreamEdgesByType

func (w *WALEngine) StreamEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamEdgesByType forwards the type stream to the underlying engine.

func (*WALEngine) StreamEdgesByTypeInScope

func (w *WALEngine) StreamEdgesByTypeInScope(ctx context.Context, scope, edgeType string, visit func(*Edge) error) error

StreamEdgesByTypeInScope forwards a scoped type stream (ScopedEdgeTypeStreamer).

func (*WALEngine) StreamNodeChunks

func (w *WALEngine) StreamNodeChunks(ctx context.Context, chunkSize int, fn func(nodes []*Node) error) error

StreamNodeChunks implements StreamingEngine.StreamNodeChunks by delegating to the underlying engine.

func (*WALEngine) StreamNodes

func (w *WALEngine) StreamNodes(ctx context.Context, fn func(node *Node) error) error

func (*WALEngine) StreamNodesByLabelProjected

func (w *WALEngine) StreamNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error

StreamNodesByLabelProjected delegates projected label scans to the underlying engine.

func (*WALEngine) StreamNodesByLabelProjectedInScope

func (w *WALEngine) StreamNodesByLabelProjectedInScope(ctx context.Context, scope, label string, properties []string, visit func(*Node) error) error

StreamNodesByLabelProjectedInScope delegates a scoped projected label scan (ScopedLabelNodeReader).

func (*WALEngine) StreamNodesByPrefix

func (w *WALEngine) StreamNodesByPrefix(ctx context.Context, prefix string, fn func(node *Node) error) error

StreamNodesByPrefix implements PrefixStreamingEngine by delegating prefix-scoped iteration to the wrapped engine when available. This preserves namespace-aware early termination behavior for MATCH ... LIMIT hot paths.

func (*WALEngine) StreamNodesByPrefixProjected

func (w *WALEngine) StreamNodesByPrefixProjected(ctx context.Context, prefix string, properties []string, fn func(node *Node) error) error

StreamNodesByPrefixProjected preserves embedding-free projected scans through the WAL decorator.

func (*WALEngine) StreamNodesByPrefixWithoutEmbeddings

func (w *WALEngine) StreamNodesByPrefixWithoutEmbeddings(ctx context.Context, prefix string, fn func(node *Node) error) error

StreamNodesByPrefixWithoutEmbeddings preserves lightweight scans through the WAL decorator.

func (*WALEngine) StreamNodesWithOptions

func (w *WALEngine) StreamNodesWithOptions(ctx context.Context, opts StreamNodesOptions, fn func(node *Node) error) error

StreamNodes implements StreamingEngine.StreamNodes by delegating to the underlying engine. StreamNodesWithOptions streams nodes through the options-driven kernel. The kernel is part of the Engine contract, so the delegation is direct.

func (*WALEngine) StreamNodesWithoutEmbeddings

func (w *WALEngine) StreamNodesWithoutEmbeddings(ctx context.Context, fn func(node *Node) error) error

StreamNodesWithoutEmbeddings preserves embedding-free snapshot scans through the WAL decorator.

func (*WALEngine) StreamParkedEmbeddingFailures

func (w *WALEngine) StreamParkedEmbeddingFailures(ctx context.Context, visit func(nodeID NodeID, meta map[string]any) error) (int, error)

StreamParkedEmbeddingFailures forwards the sidecar failure scan to the wrapped engine.

func (*WALEngine) StreamStoredEdgesByType

func (w *WALEngine) StreamStoredEdgesByType(ctx context.Context, edgeType string, visit func(*Edge) error) error

StreamStoredEdgesByType forwards to the inner engine (StoredEntityReader).

func (*WALEngine) StreamStoredEdgesByTypeInScope

func (w *WALEngine) StreamStoredEdgesByTypeInScope(ctx context.Context, scope, edgeType string, visit func(*Edge) error) error

StreamStoredEdgesByTypeInScope forwards to the inner engine (ScopedStoredEntityReader).

func (*WALEngine) StreamStoredNodesByLabelProjected

func (w *WALEngine) StreamStoredNodesByLabelProjected(ctx context.Context, label string, properties []string, visit func(*Node) error) error

StreamStoredNodesByLabelProjected forwards to the inner engine (StoredEntityReader).

func (*WALEngine) StreamStoredNodesByLabelProjectedInScope

func (w *WALEngine) StreamStoredNodesByLabelProjectedInScope(ctx context.Context, scope, label string, properties []string, visit func(*Node) error) error

StreamStoredNodesByLabelProjectedInScope forwards to the inner engine (ScopedStoredEntityReader).

func (*WALEngine) SubmitEntityCommit

func (w *WALEngine) SubmitEntityCommit(ctx context.Context, prepared *PreparedEntityCommit, settle func(CommitOutcome)) (*CommitReceipt, error)

SubmitEntityCommit journals the same strict semantic record peers apply. Definite rejection happens before journaling; once journal I/O begins, an uncertain error retains accepted ownership for recovery rather than rollback.

func (*WALEngine) SubscribeEvents

func (w *WALEngine) SubscribeEvents(handlers EventHandlers) error

SubscribeEvents forwards to the inner engine; WAL does not translate IDs.

func (*WALEngine) TopLifecycleDebtKeys

func (w *WALEngine) TopLifecycleDebtKeys(limit int) []MVCCLifecycleDebtKey

TopLifecycleDebtKeys delegates lifecycle debt inspection when supported.

func (*WALEngine) TriggerPruneNow

func (w *WALEngine) TriggerPruneNow(ctx context.Context) error

TriggerPruneNow delegates lifecycle prune-now when supported.

func (*WALEngine) UpdateEdge

func (w *WALEngine) UpdateEdge(ctx context.Context, request EdgeUpdateRequest) error

func (*WALEngine) UpdateNode

func (w *WALEngine) UpdateNode(ctx context.Context, request NodeUpdateRequest) error

func (*WALEngine) UpdateNodeEmbeddingSidecar

func (w *WALEngine) UpdateNodeEmbeddingSidecar(ctx context.Context, node *Node) error

UpdateNodeEmbeddingSidecar logs the OpUpdateEmbedding audit record and executes the sidecar embedding-only write (embedding key space, never the node record) on the wrapped engine. Every production inner engine implements EmbeddingSidecarUpdater (compile-time asserted); anything else is an invariant violation, reported as an error rather than silently degraded.

type WALEntry

type WALEntry struct {
	Sequence  uint64        `json:"seq"`                // Monotonically increasing sequence number
	Timestamp time.Time     `json:"ts"`                 // When the operation occurred
	Operation OperationType `json:"op"`                 // Operation type (create_node, update_node, etc.)
	Data      []byte        `json:"data"`               // JSON-serialized operation data
	Checksum  uint32        `json:"checksum"`           // CRC32 checksum for integrity
	Database  string        `json:"database,omitempty"` // Database/namespace name (for multi-database support)
	// Readers attach immutable file authority; JSON transport preserves it.
	// Native writers leave this nil and encode authority once at epoch boundaries.
	PropertyEpoch *WALPropertyEpoch `json:"property_epoch,omitempty"`
	// contains filtered or unexported fields
}

WALEntry represents a single write-ahead log entry. Each mutating operation is recorded as an entry before execution.

func FindWALEntriesByTxID

func FindWALEntriesByTxID(ctx context.Context, walDir, txID string, maxEntries int) ([]WALEntry, error)

FindWALEntriesByTxID scans entries and returns those with a matching tx_id. Use maxEntries <= 0 to return all matches.

func ReadWALEntries

func ReadWALEntries(ctx context.Context, walPath string, logger *slog.Logger) ([]WALEntry, error)

ReadWALEntries reads all entries from a WAL file. Reads the current atomic WAL format; older WAL formats are rejected. Returns error on corruption of critical entries (nodes, edges). Embedding updates are safe to skip as they can be regenerated.

A nil logger discards recovery diagnostics. ctx supplies diagnostic provenance; reading the WAL does not cancel accepted recovery work.

func ReadWALEntriesAfter

func ReadWALEntriesAfter(ctx context.Context, path string, afterSeq uint64, scope WALReadScope) ([]WALEntry, error)

ReadWALEntriesAfter reads entries after a sequence from the selected WAL scope.

func ReadWALEntriesAfterWithKey

func ReadWALEntriesAfterWithKey(ctx context.Context, path string, afterSeq uint64, scope WALReadScope, key []byte) ([]WALEntry, error)

ReadWALEntriesAfterWithKey is ReadWALEntriesAfter for a journal written with key.

func ReadWALEntriesFromDir

func ReadWALEntriesFromDir(ctx context.Context, walDir string) ([]WALEntry, error)

ReadWALEntriesFromDir reads WAL entries across all segments and the active WAL file.

func ReadWALEntriesFromDirWithKey

func ReadWALEntriesFromDirWithKey(ctx context.Context, walDir string, key []byte) ([]WALEntry, error)

ReadWALEntriesFromDirWithKey is ReadWALEntriesFromDir for retained segments and an active file written with key.

func ReadWALEntriesRangeFromDir

func ReadWALEntriesRangeFromDir(ctx context.Context, walDir string, fromSeq, toSeq uint64) ([]WALEntry, error)

ReadWALEntriesRangeFromDir reads entries in [fromSeq, toSeq] (inclusive).

func ReadWALEntriesWithKey

func ReadWALEntriesWithKey(ctx context.Context, walPath string, logger *slog.Logger, key []byte) ([]WALEntry, error)

ReadWALEntriesWithKey is ReadWALEntries for a journal written with key.

type WALFormatValidation

type WALFormatValidation uint8

WALFormatValidation selects the read-only format check at a WAL boundary.

const (
	// WALValidateCurrent admits only records readable by the running WAL.
	WALValidateCurrent WALFormatValidation = iota
	// WALValidateV4Upgrade validates historical records for the one-time V4 migration.
	WALValidateV4Upgrade
)

type WALIntegrityReport

type WALIntegrityReport struct {
	Healthy           bool                    `json:"healthy"`
	TotalEntries      int                     `json:"total_entries"`
	ValidEntries      int                     `json:"valid_entries"`
	CorruptedEntries  int                     `json:"corrupted_entries"`
	SkippedEmbeddings int                     `json:"skipped_embeddings"`
	FirstSeq          uint64                  `json:"first_seq"`
	LastSeq           uint64                  `json:"last_seq"`
	FileSize          int64                   `json:"file_size"`
	Format            string                  `json:"format"` // "atomic" or "legacy"
	Errors            []string                `json:"errors,omitempty"`
	CorruptionDetails []CorruptionDiagnostics `json:"corruption_details,omitempty"`
}

WALIntegrityReport provides detailed integrity check results

func CheckWALIntegrity

func CheckWALIntegrity(walPath string) (*WALIntegrityReport, error)

CheckWALIntegrity performs a comprehensive integrity check on a WAL file. This can be used for health checks, startup validation, or manual diagnostics. It does NOT modify the WAL - read-only operation.

func CheckWALIntegrityWithKey

func CheckWALIntegrityWithKey(walPath string, key []byte) (*WALIntegrityReport, error)

CheckWALIntegrityWithKey is CheckWALIntegrity for a journal written with key. A frame that does not authenticate under the key is reported as the error it is, never as a damaged record the check may count and continue past.

type WALLogger

type WALLogger interface {
	Log(level string, msg string, fields map[string]any)
}

WALLogger receives structured diagnostics emitted by WAL recovery / corruption handlers.

This is intentionally minimal to avoid coupling storage to a specific logging library. Implementations should treat fields as a stable machine-readable contract.

Phase 2 LOG-01 note: the legacy default implementation routed records through stdlib log printers. That implementation is gone — defaultWALLogger now wraps a *slog.Logger so all storage-package emissions flow through the production 4-layer slog handler stack (recovering → mandatory → redactor → JSON).

type WALManifest

type WALManifest struct {
	Version  int          `json:"version"`
	Segments []WALSegment `json:"segments"`
	// RetiredThrough prevents snapshot-covered segment files left behind by
	// a crash from being rediscovered and preserves sequence monotonicity.
	RetiredThrough uint64 `json:"retired_through,omitempty"`
}

WALManifest indexes all sealed WAL segments.

type WALNodeData

type WALNodeData struct {
	Node    *Node  `json:"node"`               // New state (redo)
	OldNode *Node  `json:"old_node,omitempty"` // Previous state (undo) - for updates
	TxID    string `json:"tx_id,omitempty"`    // Transaction ID for grouping
}

WALNodeData holds node data for WAL entries with optional undo support. For update/delete operations, OldNode contains the "before image" for rollback.

type WALPropKeyEntry

type WALPropKeyEntry struct {
	Namespace string `json:"namespace"`
	Name      string `json:"name"`
	ID        uint64 `json:"id"`
}

WALPropKeyEntry binds a source-store property token to its namespace and name. Replay resolves that name through the destination dictionary before applying the physical body; source numeric IDs are never installed there.

type WALPropertyEpoch

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

WALPropertyEpoch transports the explicit dictionary authority attached by a WAL reader. Its immutable state is private: JSON decoding replaces the state rather than mutating a plan already in use. Ordinary buffered record bytes contain no epoch field; file readers obtain it from the preceding header.

func (*WALPropertyEpoch) MarshalJSON

func (e *WALPropertyEpoch) MarshalJSON() ([]byte, error)

func (*WALPropertyEpoch) UnmarshalJSON

func (e *WALPropertyEpoch) UnmarshalJSON(data []byte) error

type WALReadScope

type WALReadScope uint8

WALReadScope selects whether a WAL read covers one file or its complete directory.

const (
	// WALReadFile reads only the named WAL file.
	WALReadFile WALReadScope = iota
	// WALReadDirectory reads the active WAL and retained segments in order.
	WALReadDirectory
)

type WALRecordPolicy

type WALRecordPolicy uint8

WALRecordPolicy is how a WAL frames the journal records it creates (NOR-412). NewWAL copies it from WALConfig.RecordPolicy, and no code assigns the WAL's copy afterwards.

The copy is read by encodeNewRecord, where it decides whether a record that does not fit one frame is refused or written in parts, and by journalsLargeRecords. The readers do not consult it, and maintenance that rewrites a stored record keeps the form the record was stored in. One operation, the managed vector anchor, spans frames whatever the policy (walRecordMaySpan).

const (
	// WALRecordsStandard, the zero value: a record is one frame, and a
	// record that does not fit one is refused with the frame-size error
	// (walMaxEntrySize). A WAL has this policy unless its configuration
	// asks for WALRecordsLarge, which nornicdb.Open does for a standalone
	// server only.
	WALRecordsStandard WALRecordPolicy = iota

	// WALRecordsLarge writes a record that does not fit one frame as a
	// spanned record (frame version 7): consecutive part frames that the
	// readers assemble into one record before they deliver it
	// (walRecordAssembler). A record that fits one frame is encoded to the
	// same bytes as under WALRecordsStandard (encodeWALEntryPayload).
	// nornicdb.Open selects it for a standalone server and the standard
	// policy for every other mode.
	WALRecordsLarge
)

type WALSegment

type WALSegment struct {
	FirstSeq  uint64    `json:"first_seq"`
	LastSeq   uint64    `json:"last_seq"`
	SizeBytes int64     `json:"size_bytes"`
	CreatedAt time.Time `json:"created_at"`
	Path      string    `json:"path"`
}

WALSegment describes a sealed WAL segment stored on disk.

type WALSnapshotMode

type WALSnapshotMode uint8

WALSnapshotMode selects the post-snapshot WAL work ManageSnapshot performs.

const (
	// WALSnapshotTruncate reclaims the entries a snapshot covers. With WAL
	// retention configured (RetentionMaxAge or RetentionMaxSegments, e.g.
	// NORNICDB_WAL_RETENTION_MAX_AGE) entries are not dropped: the active WAL is
	// sealed into a segment and retention removes only the sealed segments the
	// snapshot covers that are past their age or count. Those entries stay
	// readable (db.txlog.entries, replication, audit) for the retention period;
	// recovery replays only entries after the snapshot. Without retention the
	// covered entries are dropped.
	WALSnapshotTruncate WALSnapshotMode = iota
	// WALSnapshotRetention applies segment retention to sealed segments only. It
	// never rotates or rewrites the active WAL and never seals property epochs.
	WALSnapshotRetention
)

func (WALSnapshotMode) String

func (m WALSnapshotMode) String() string

String returns the stable mode name used in logs and test subtests.

type WALStats

type WALStats struct {
	Sequence      uint64
	EntryCount    int64
	BytesWritten  int64
	TotalWrites   int64
	TotalSyncs    int64
	LastSyncTime  time.Time
	LastEntryTime time.Time
	Closed        bool
}

WALStats provides observability into WAL state.

type WALTxData

type WALTxData struct {
	TxID     string            `json:"tx_id"`              // Transaction identifier
	Metadata map[string]string `json:"metadata,omitempty"` // Optional transaction metadata
	Reason   string            `json:"reason,omitempty"`   // For abort: why was it aborted
	OpCount  int               `json:"op_count,omitempty"` // For commit: number of operations
}

WALTxData holds transaction boundary data.

type WALV4UpgradeOptions

type WALV4UpgradeOptions struct {
	Transform       func(version uint8, operation OperationType, payload []byte) ([]byte, error)
	OneFrameRecords bool
	// contains filtered or unexported fields
}

WALV4UpgradeOptions selects an optional application payload conversion. Transform is invoked only for records using an older frame and must return the complete replacement payload without modifying its input.

OneFrameRecords keeps the converted journal to one-frame records: an old record whose converted form does not fit one frame is refused, in every historical format, by validation before anything changes unless it is a property-epoch control or its conversion gives other bytes the second time. The replication journal sets it, as its transport carries one-frame records only; a store journal carries such a record whole.

type WriteBehindBuffer

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

WriteBehindBuffer holds the active generation and FIFO draining generations. Apply is injected so the replay destination (Badger) stays a detail of the caller.

func NewWriteBehindBuffer

func NewWriteBehindBuffer(interval time.Duration, maxOps int, apply func(*CommitBuffer) error) *WriteBehindBuffer

NewWriteBehindBuffer builds a buffer whose rotation delay and generation size adapt to measured drain latency and throughput: after every successful drain the delay moves toward the drain duration (clamped to [minDelay, maxDelay]; the zero sentinels select the defaults) and the size threshold tracks throughput × delay. maxOps is the manual generation cap; the sentinel 0 selects auto sizing against an internal default cap. apply replays a drained generation into the underlying engine.

func (*WriteBehindBuffer) AllEdgesOverlay

func (w *WriteBehindBuffer) AllEdgesOverlay() ([]*Edge, map[EdgeID]bool)

AllEdgesOverlay is AllNodesOverlay for buffered edges.

func (*WriteBehindBuffer) AllNodesOverlay

func (w *WriteBehindBuffer) AllNodesOverlay() ([]*Node, map[NodeID]bool)

AllNodesOverlay returns the buffered node state as (nodes, touched): nodes holds the newest buffered version of every node ID the buffer wrote (deleted IDs excluded), newest generation first; touched holds every node ID the buffer created, updated or deleted. Callers merge over committed rows: drop committed rows whose ID is in touched and append the returned nodes. The returned pointers are buffer-owned; callers must copy them.

func (*WriteBehindBuffer) Append

Append appends one committed mutation to the active generation.

Append owns its input: a node or edge payload is deep-copied before the lock, so a caller may keep using, or drop, the value it passed and the buffered overlay keeps the image it acknowledged. A node or edge request derives ID from its payload. A nil node or edge payload names no read scope and leaves the overlay unchanged, but it is still one admitted operation and still counts toward the rotation threshold. A delete names its raw key and touches no entity body. The read epoch, read scopes, size accounting, rotation decision and rotation signal happen once here for every kind.

Append returns ErrInvalidData for an unknown Kind or for payload fields that do not match Kind, without changing the buffer.

func (*WriteBehindBuffer) AppendCommit

func (w *WriteBehindBuffer) AppendCommit(c bufferedCommit) commitStates

AppendCommit appends one committed statement captured at transaction commit. It folds the statement's operations into the read overlay and counts every operation toward the size threshold. It returns the selected frame for the caller's existing claim publication policy.

func (*WriteBehindBuffer) Close

func (w *WriteBehindBuffer) Close()

Close stops the background flusher and joins its actual return; every caller joins the same stop. Callers must Flush first to drain.

func (*WriteBehindBuffer) CurrentInterval

func (w *WriteBehindBuffer) CurrentInterval() time.Duration

CurrentInterval returns the adaptive rotation delay: the EWMA measured drain latency, clamped to [minDelay, maxDelay]. It equals the configured interval until the first successful apply.

func (*WriteBehindBuffer) DrainOpsPerSecond

func (w *WriteBehindBuffer) DrainOpsPerSecond() float64

DrainOpsPerSecond returns the EWMA drain throughput in operations per second; zero until the first successful apply.

func (*WriteBehindBuffer) EdgeAdjacencyOverlay

func (w *WriteBehindBuffer) EdgeAdjacencyOverlay(nodeID NodeID, outgoing bool) (live []*Edge, suppressed map[EdgeID]struct{}, nodeDeleted bool)

EdgeAdjacencyOverlay returns the buffered live edges adjacent to nodeID (outgoing or incoming) plus every buffered edge ID that committed adjacency scans must suppress, including live IDs shadowed by the buffer. nodeDeleted reports that a buffered delete hides the node itself, which hides all of its committed adjacency too. The returned edge pointers are buffer-owned; callers must copy them.

func (*WriteBehindBuffer) EdgeCountDelta

func (w *WriteBehindBuffer) EdgeCountDelta() int64

EdgeCountDelta is the buffered total edge-count delta: creates minus deletes across every generation that has not been replayed yet.

func (*WriteBehindBuffer) EdgeCountDeltaForPrefix

func (w *WriteBehindBuffer) EdgeCountDeltaForPrefix(prefix string) int64

EdgeCountDeltaForPrefix is the buffered total edge-count delta restricted to edges whose ID starts with prefix: live buffered edge IDs minus buffered deleted edge IDs. prefix may be empty for the whole graph.

func (*WriteBehindBuffer) EdgeDeleted

func (w *WriteBehindBuffer) EdgeDeleted(id EdgeID) bool

EdgeDeleted reports whether the buffer's newest state for id is a delete.

func (*WriteBehindBuffer) EdgeTypeCountDelta

func (w *WriteBehindBuffer) EdgeTypeCountDelta(edgeType string) int64

EdgeTypeCountDelta sums the derived edge-type count deltas of every buffered commit that has not been replayed yet, across all namespaces.

func (*WriteBehindBuffer) EdgeTypeCountDeltaInNamespace

func (w *WriteBehindBuffer) EdgeTypeCountDeltaInNamespace(namespace, edgeType string) int64

EdgeTypeCountDeltaInNamespace is EdgeTypeCountDelta restricted to namespace.

func (*WriteBehindBuffer) EdgesBetweenOverlay

func (w *WriteBehindBuffer) EdgesBetweenOverlay(source, target NodeID) (live []*Edge, suppressed map[EdgeID]struct{}, sourceDeleted, targetDeleted bool)

EdgesBetweenOverlay returns the buffered live edges from source to target and the deleted-edge set committed between-index results must suppress. sourceDeleted / targetDeleted report buffered deletes of the endpoints, which hide all committed between results for them.

func (*WriteBehindBuffer) Flush

func (w *WriteBehindBuffer) Flush() error

Flush rotates the active generation and drains every generation synchronously, delivering their notifications. It retries failed applies and waits for a generation another drain is applying; if no generation makes progress for ~2s after an apply failed, it returns that error.

func (*WriteBehindBuffer) GetEdge

func (w *WriteBehindBuffer) GetEdge(id EdgeID) (*Edge, bool, bool)

GetEdge resolves the latest buffered state for id across generations, newest first. Returns (value, found, deleted).

func (*WriteBehindBuffer) GetNode

func (w *WriteBehindBuffer) GetNode(id NodeID) (*Node, bool, bool)

GetNode resolves the latest buffered state for id across generations, newest first. Returns (value, found, deleted).

func (*WriteBehindBuffer) KeyCandidates

func (w *WriteBehindBuffer) KeyCandidates(label, property string, valueKey interface{}) []*Node

func (*WriteBehindBuffer) LabelCountDelta

func (w *WriteBehindBuffer) LabelCountDelta(label string) int64

LabelCountDelta sums the derived label-count deltas of every buffered commit that has not been replayed yet, across all namespaces. The replay applies the same deltas to the persisted counters when it lands the generation, so reads see committed counts + this delta.

func (*WriteBehindBuffer) LabelCountDeltaInNamespace

func (w *WriteBehindBuffer) LabelCountDeltaInNamespace(namespace, label string) int64

LabelCountDeltaInNamespace is LabelCountDelta restricted to namespace.

func (*WriteBehindBuffer) LabelNodes

func (w *WriteBehindBuffer) LabelNodes(label string) []*Node

LabelNodes returns buffered nodes carrying label, newest generation first, not yet applied. The caller merges these over committed rows.

func (*WriteBehindBuffer) LabelOverlay

func (w *WriteBehindBuffer) LabelOverlay(label string) ([]*Node, map[NodeID]bool)

LabelOverlay returns the buffered state for label as (nodes, touched): nodes holds the newest buffered version of every ID the buffer wrote for the label (IDs the buffer deleted are excluded), newest generation first; touched holds every ID the buffer created, updated or deleted for the label. Callers merge over committed rows: drop committed rows whose ID is in touched and append the returned nodes. The returned node pointers are buffer-owned; callers must copy before handing them out.

func (*WriteBehindBuffer) LastErr

func (w *WriteBehindBuffer) LastErr() error

LastErr returns the most recent apply error, if any.

func (*WriteBehindBuffer) LookupEdge

func (w *WriteBehindBuffer) LookupEdge(id EdgeID) (*Edge, bool)

LookupEdge resolves the newest buffered version of id, if the buffer has one. The returned pointer is buffer-owned; callers must copy it.

func (*WriteBehindBuffer) LookupNode

func (w *WriteBehindBuffer) LookupNode(id NodeID) (*Node, bool)

LookupNode resolves the newest buffered version of id, if the buffer has one. The returned pointer is buffer-owned; callers must copy it.

func (*WriteBehindBuffer) NodeCountDeltaForPrefix

func (w *WriteBehindBuffer) NodeCountDeltaForPrefix(prefix string) int64

NodeCountDeltaForPrefix is the buffered total node-count delta restricted to nodes whose ID starts with prefix: live buffered node IDs minus buffered deleted node IDs. prefix may be empty for the whole graph.

func (*WriteBehindBuffer) NodeDeleted

func (w *WriteBehindBuffer) NodeDeleted(id NodeID) bool

NodeDeleted reports whether the buffer's newest state for id is a delete.

func (*WriteBehindBuffer) NodeDeletedOverlay

func (w *WriteBehindBuffer) NodeDeletedOverlay(nodeID NodeID) bool

NodeDeletedOverlay reports whether a buffered delete hides nodeID from committed reads (PR #1043 read-overlay parity).

func (*WriteBehindBuffer) PendingOps

func (w *WriteBehindBuffer) PendingOps() int

PendingOps reports how many mutations are buffered but not yet applied.

func (*WriteBehindBuffer) SetDelayBounds

func (w *WriteBehindBuffer) SetDelayBounds(minDelay, maxDelay time.Duration)

SetDelayBounds overrides the adaptive delay clamp. The zero sentinel keeps the default for that bound. The configured interval always stays inside the bounds. Must be called before the first drain; safe at any time.

func (*WriteBehindBuffer) SetWarn

func (w *WriteBehindBuffer) SetWarn(warn func(string))

SetWarn installs the sizing-mismatch reporter. The engine wires it to its logger at construction; the callback runs outside the buffer lock.

func (*WriteBehindBuffer) TargetSize

func (w *WriteBehindBuffer) TargetSize() int

TargetSize returns the adaptive size threshold that rotates the active generation: measured drain throughput × interval, clamped to the configured maximum. It equals the effective cap until the first successful apply.

func (*WriteBehindBuffer) TypeEdges

func (w *WriteBehindBuffer) TypeEdges(edgeType string) []*Edge

TypeEdges returns buffered edges of edgeType, newest generation first, not yet applied.

func (*WriteBehindBuffer) TypeOverlay

func (w *WriteBehindBuffer) TypeOverlay(edgeType string) ([]*Edge, map[EdgeID]bool)

TypeOverlay is LabelOverlay for buffered edges of edgeType.

Source Files

Directories

Path Synopsis
Package writeordertest is a deterministic model-based harness for the storage write-order contract.
Package writeordertest is a deterministic model-based harness for the storage write-order contract.

Jump to

Keyboard shortcuts

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