store

package
v0.2.6 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Unlicense Imports: 109 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package store provides vector storage and indexing capabilities.

Package store provides a pooled memory allocator for Arrow operations.

Index

Constants

View Source
const (
	// DatasetFileExtension is the default file extension for exported datasets.
	DatasetFileExtension = ".parquet"
	// DatasetMagic is the magic string used to identify Longbow dataset files.
	DatasetMagic = "LONGDATASET"
	// DatasetVersion is the current version of the dataset export format.
	DatasetVersion = 1
)
View Source
const (
	// GeoIndexTypeMorton selects the linear Morton-coded spatial grid. It is
	// opt-in: inserts are ~2.3x faster and allocation-free, but its fixed
	// resolution is non-adaptive, so measured queries are 17% (selective box)
	// to 40% (global box) slower than the quadtree. Select it where the write
	// path dominates; see NewMortonGridWithResolution to tune cell size.
	GeoIndexTypeMorton = "morton"
	// GeoIndexTypeQuadtree selects the recursive quadtree, the default index
	// type, because it currently wins on query latency.
	GeoIndexTypeQuadtree = "quadtree"
)
View Source
const (
	// GPUWorkloadThreshold is the minimum number of nodes in the results set
	// to justify the GPU launch latency for graph expansion.
	GPUWorkloadThreshold = 5000

	// BeamWidth is the maximum number of frontier nodes retained after each
	// BFS hop in RankWithGraph / RankWithGraphDistributed.
	// Capping the beam collapses worst-case O(N^3) multi-hop BFS to
	// O(BeamWidth^2 * depth), providing sub-millisecond scaling at 400k+ vectors.
	BeamWidth = 100
)
View Source
const (
	// MerkleFanout is the number of children per node in the Merkle Tree.
	MerkleFanout = 16
	// MerkleDepth is the depth of the Merkle Tree.
	MerkleDepth = 4
)
View Source
const (
	VectorTypeAPIFloat32    = "float32"
	VectorTypeAPITurboQuant = "turboquant"
	VectorTypeAPIInt8       = "int8"
	VectorTypeAPIBinary     = "binary"
)

VectorTypeNative constants map the API-visible vector_type string values to internal VectorDataType constants. These are the values accepted in VectorSearchRequest metadata and CreateDataset parameters.

View Source
const (
	// MetricEuclidean is the default L2 distance (lower is closer).
	MetricEuclidean = core.MetricEuclidean
	// MetricCosine is the Cosine distance (1.0 - cosine_similarity).
	MetricCosine = core.MetricCosine
	// MetricDotProduct is the Inner Product (higher is usually better).
	MetricDotProduct = core.MetricDotProduct
)
View Source
const (
	// MaxNeighbors is the maximum number of neighbors allowed for a node in the HNSW graph.
	MaxNeighbors = types.MaxNeighbors
	// ChunkSize is the number of elements processed in a single chunk.
	ChunkSize = types.ChunkSize
	// ArrowMaxLayers is the maximum number of layers in the Arrow HNSW index.
	ArrowMaxLayers = types.ArrowMaxLayers
)
View Source
const (
	// DiskGraphMagic is a magic number used to identify DiskGraph files.
	DiskGraphMagic = hnswcore.DiskGraphMagic
	// DiskGraphVersion is the current version of the DiskGraph file format.
	DiskGraphVersion = hnswcore.DiskGraphVersion
)
View Source
const (
	// VectorTypeFloat32 represents a 32-bit floating point vector.
	VectorTypeFloat32 = types.VectorTypeFloat32
	// VectorTypeFloat64 represents a 64-bit floating point vector.
	VectorTypeFloat64 = types.VectorTypeFloat64
	// VectorTypeComplex64 represents a 64-bit complex vector.
	VectorTypeComplex64 = types.VectorTypeComplex64
	// VectorTypeComplex128 represents a 128-bit complex vector.
	VectorTypeComplex128 = types.VectorTypeComplex128
	// VectorTypeInt8 represents an 8-bit signed integer vector.
	VectorTypeInt8 = types.VectorTypeInt8
	// VectorTypeUint8 represents an 8-bit unsigned integer vector.
	VectorTypeUint8 = types.VectorTypeUint8
	// VectorTypeFloat16 represents a 16-bit floating point vector.
	VectorTypeFloat16 = types.VectorTypeFloat16
	// VectorTypeInt32 represents a 32-bit signed integer vector.
	VectorTypeInt32 = types.VectorTypeInt32
	// VectorTypeInt64 represents a 64-bit signed integer vector.
	VectorTypeInt64 = types.VectorTypeInt64
	// VectorTypeTQ represents a Tensor Quantized vector.
	VectorTypeTQ = types.VectorTypeTQ
	// VectorTypeBQ represents a Binary Quantized vector.
	VectorTypeBQ = types.VectorTypeBQ
)
View Source
const (
	// DefaultWSMaxConnections is the default maximum number of concurrent WebSocket connections allowed.
	DefaultWSMaxConnections = 1000
	// DefaultWSIdleTimeout is the duration a connection is allowed to remain idle before being disconnected.
	DefaultWSIdleTimeout = 5 * time.Minute
)
View Source
const CDCEventDelete = cluster.CDCEventDelete
View Source
const CDCEventInsert = cluster.CDCEventInsert
View Source
const CDCEventUpdate = cluster.CDCEventUpdate
View Source
const ConfluentWireMagic byte = 0x00

ConfluentWireMagic is the standard 1-byte Confluent Schema Registry framing magic byte.

View Source
const ConsistencyEventual = "eventual"

ConsistencyEventual is the default fast search mode where HNSW uses its configured parameters.

View Source
const ConsistencyStrong = "strong"

ConsistencyStrong requests exhaustive search by promoting search parameters to ensure high recall.

View Source
const IndexTypeDiskANN = index.IndexTypeDiskANN
View Source
const IndexTypeHNSW = index.IndexTypeHNSW
View Source
const IndexTypeIVFFlat = index.IndexTypeIVFFlat
View Source
const PackedRefOffShift = 32

PackedRefOffShift is the bit shift for the offset in a packed adjacency reference.

View Source
const (
	// TemporalShards is the number of shards for the temporal vector map.
	TemporalShards = 128
)

Variables

View Source
var (
	// SearchResponseSchema: [id (string), score (float32)]
	SearchResponseSchema = arrow.NewSchema([]arrow.Field{
		{Name: "id", Type: arrow.BinaryTypes.String},
		{Name: "score", Type: arrow.PrimitiveTypes.Float32},
	}, nil)

	// SearchWithVectorResponseSchema: [id (string), score (float32), vector (binary)]
	SearchWithVectorResponseSchema = arrow.NewSchema([]arrow.Field{
		{Name: "id", Type: arrow.BinaryTypes.String},
		{Name: "score", Type: arrow.PrimitiveTypes.Float32},
		{Name: "vector", Type: arrow.BinaryTypes.Binary},
	}, nil)

	SearchResponsePool           = NewRecordBuilderPool(SearchResponseSchema)
	SearchWithVectorResponsePool = NewRecordBuilderPool(SearchWithVectorResponseSchema)
)

Global Response Pools for common schemas

View Source
var (
	// MinIndexingWorkers is the minimum number of indexing workers to keep running.
	// ArrowHNSW internally parallelizes bulk inserts, so 1 worker is sufficient and avoids lock contention.
	MinIndexingWorkers = 1
	// MinIngestionWorkers is the minimum number of ingestion workers to keep running.
	MinIngestionWorkers = calculateMinWorkers(4) // 1/4th of CPU
)
View Source
var DefaultArrowHNSWConfig = types.DefaultArrowHNSWConfig

DefaultArrowHNSWConfig returns the default configuration for HNSW indices.

View Source
var DefaultHNSWSearchConfig = HNSWSearchConfig{
	EnablePrefetch:            true,
	PrefetchDistance:          3,
	EnableEarlyTermination:    true,
	EarlyTerminationThreshold: 0.95,
	ParallelSearch:            false,
	NumSearchThreads:          4,
	BatchSize:                 64,
}

DefaultHNSWSearchConfig provides recommended settings for typical search workloads.

View Source
var DefaultIndexJobQueueConfig = types.DefaultIndexJobQueueConfig

DefaultIndexJobQueueConfig returns the default configuration for the background indexing queue.

View Source
var ErrDimensionLocked = errors.New("dimension locked")

ErrDimensionLocked is returned when a vector's dimension does not match the locked dimension of the dataset.

View Source
var ErrGetNeighborsNotSupported = hnswcore.ErrGetNeighborsNotSupported

ErrGetNeighborsNotSupported is returned when the index doesn't support neighbor retrieval.

View Source
var (
	// ErrNamespaceRateLimited is returned when a namespace has exceeded its request quota.
	ErrNamespaceRateLimited = errors.New("namespace rate limit exceeded")
)
View Source
var ErrVectorNotFound = hnswcore.ErrVectorNotFound

ErrVectorNotFound is returned when a requested vector is not found in the index.

View Source
var ExtractVectorAny = hnswcore.ExtractVectorAny

ExtractVectorAny extracts a vector as an interface{} from an Arrow record batch.

View Source
var ExtractVectorF16FromArrow = hnswcore.ExtractVectorF16FromArrow

ExtractVectorF16FromArrow extracts a float16 vector from an Arrow record batch.

View Source
var ExtractVectorFromArrow = hnswcore.ExtractVectorFromArrow

ExtractVectorFromArrow extracts a vector from an Arrow record batch.

View Source
var GenerateTestVectors = hnswcore.GenerateTestVectors

GenerateTestVectors generates a set of random vectors for testing.

View Source
var GetArena = hnswcore.GetArena

GetArena returns a search arena from the global pool.

View Source
var GetArenaForNode = hnswcore.GetArenaForNode

GetArenaForNode returns a search arena from the global pool for a specific NUMA node.

View Source
var InferVectorDataType = hnswcore.InferVectorDataType

InferVectorDataType infers the vector data type from an Arrow field.

View Source
var LookupNeighbors = hnswcore.LookupNeighbors

LookupNeighbors retrieves the neighbors of a node from the graph.

View Source
var MakeBatchTestRecord = hnswcore.MakeBatchTestRecord

MakeBatchTestRecord creates an Arrow record batch for testing.

View Source
var NewArrowBitset = types.NewArrowBitset

NewArrowBitset creates a new bitset for tracking visited nodes during search.

View Source
var NewArrowHNSW = hnswcore.NewArrowHNSW

NewArrowHNSW creates a new instance of the ArrowHNSW index.

View Source
var NewArrowHNSWWithConfig = hnswcore.NewArrowHNSWWithConfig

NewArrowHNSWWithConfig creates a new HNSW index instance with a custom configuration.

View Source
var NewArrowSearchContext = hnswcore.NewArrowSearchContext

NewArrowSearchContext creates a new search context.

View Source
var NewArrowSearchContextPool = hnswcore.NewArrowSearchContextPool

NewArrowSearchContextPool creates a new pool for search contexts.

View Source
var NewChunkedLocationStore = hnswcore.NewChunkedLocationStore

NewChunkedLocationStore creates a new store for tracking vector locations.

View Source
var NewIndexJobQueueLockFree = hnswcore.NewIndexJobQueueLockFree

NewIndexJobQueueLockFree creates a new lock-free queue for background indexing jobs.

View Source
var NewLevelGenerator = hnswcore.NewLevelGenerator

NewLevelGenerator creates a new generator for HNSW node levels.

View Source
var NewLockFreeNeighborCache = hnswcore.NewLockFreeNeighborCache

NewLockFreeNeighborCache creates a new neighbor cache.

View Source
var NewLockFreeNeighborList = hnswcore.NewLockFreeNeighborList

NewLockFreeNeighborList creates a new lock-free neighbor list.

View Source
var NewNotFoundError = core.NewNotFoundError

NewNotFoundError creates a not found error.

View Source
var NewPackedAdjacency = hnswcore.NewPackedAdjacency

NewPackedAdjacency creates a new packed adjacency list for graph storage.

View Source
var NewTestHNSWIndex = hnswcore.NewTestHNSWIndex

NewTestHNSWIndex creates a small HNSW index for unit testing.

View Source
var PutArena = hnswcore.PutArena

PutArena returns a search arena to the global pool.

Functions

func AdaptivelySliceBatches

func AdaptivelySliceBatches(
	records []arrow.RecordBatch,
	tombstones map[int]*types.Bitset,
	strategy *flight.AdaptiveChunkStrategy,
) (outRecords []arrow.RecordBatch, outTombstones map[int]*types.Bitset)

AdaptivelySliceBatches slices a list of record batches into smaller chunks based on the provided AdaptiveChunkStrategy. It handles proper slicing of associated tombstones and reassigns sequential batch indices.

The returned batches are Retained and must be Released by the caller. The returned tombstones map uses the new sequential indices.

func AdviseMemory

func AdviseMemory(ptr unsafe.Pointer, size uintptr, advice MemoryAdvice) error

AdviseMemory provides hints to the kernel about the memory usage pattern.

func AdviseRecord

func AdviseRecord(rec arrow.RecordBatch, advice MemoryAdvice)

AdviseRecord provides memory hints for all buffers in an Arrow RecordBatch.

func ApplyConsistency

func ApplyConsistency(opts *SearchOptions, k int, dataset string) error

ApplyConsistency enforces the Consistency field of opts onto the option values that actually drive HNSW behaviour (ExactK, Ef). It also emits the appropriate Prometheus counter.

k is the number of results requested — used to compute the minimum Ef for strong mode.

An empty Consistency value is treated as ConsistencyEventual. An unrecognised value returns an error.

func BatchDistanceCompute

func BatchDistanceCompute(queries, candidates [][]float32, results []float32) error

BatchDistanceCompute computes distances for multiple query-candidate pairs. This enables better cache utilization and SIMD batching optimizations. Uses Prometheus metrics to track performance characteristics.

func BuildNamespacedPath

func BuildNamespacedPath(namespace, dataset string) string

BuildNamespacedPath combines namespace and dataset into a path.

func CachedRecordSize

func CachedRecordSize(rec arrow.RecordBatch) int64

CachedRecordSize uses global cache

func CalculateMinPossibleDistance

func CalculateMinPossibleDistance(query []float32, neighborCount int, avgDist float32) float32

CalculateMinPossibleDistance estimates the lower bound distance for heuristic pruning.

func CheckEvolutionCompatibility

func CheckEvolutionCompatibility(prev, next DatasetSchemaSpec, mode SchemaCompatibilityMode) error

CheckEvolutionCompatibility verifies BACKWARD, FORWARD, FULL, or NONE rules between versions.

func ComputeBatchDistancesSIMD

func ComputeBatchDistancesSIMD(queries [][]float32, vectors [][]float32, k int) [][]SearchResult

ComputeBatchDistancesSIMD computes distances for a batch of queries using SIMD instructions.

func ConvertFloat32ToUint8

func ConvertFloat32ToUint8(vec []float32) ([]uint8, error)

ConvertFloat32ToUint8 converts a slice of float32 to uint8 using min/max bounds for proper scaling to [0, 255] range.

func ConvertFloat32ToUint64

func ConvertFloat32ToUint64(vec []float32) ([]uint64, error)

ConvertFloat32ToUint64 converts a slice of float32 to uint64 codes (BQ style)

func ConvertUint8ToFloat32

func ConvertUint8ToFloat32(codes []uint8) ([]float32, error)

ConvertUint8ToFloat32 converts a slice of uint8 to float32

func ConvertUint64ToFloat32

func ConvertUint64ToFloat32(codes []uint64) ([]float32, error)

ConvertUint64ToFloat32 converts uint64 codes to float32 (BQ style)

func DecodeWirePayload

func DecodeWirePayload(raw []byte) (uint32, bool, []byte, error)

DecodeWirePayload strips an optional Confluent 5-byte wire header if present. Returns (schemaID, hasHeader, jsonPayload, err).

func DefaultBM25Config

func DefaultBM25Config() index.BM25Config

func DefaultCircuitBreakerConfig

func DefaultCircuitBreakerConfig() cluster.CircuitBreakerConfig

func DefaultReplicatorConfig

func DefaultReplicatorConfig() cluster.ReplicatorConfig

func DefaultShardedHNSWConfig

func DefaultShardedHNSWConfig() index.ShardedHNSWConfig

func DeterministicIngestEnabled

func DeterministicIngestEnabled() bool

DeterministicIngestEnabled reports whether the ingest pipeline is pinned.

func EncodeWirePayload

func EncodeWirePayload(schemaID uint32, payload []byte) []byte

EncodeWirePayload prepends the 5-byte Confluent Schema Registry wire header to payload.

func EnsureTimestampZeroCopy

func EnsureTimestampZeroCopy(mem memory.Allocator, rec arrow.RecordBatch) (arrow.RecordBatch, error)

EnsureTimestampZeroCopy ensures the record has a timestamp column, adding one if missing (zero-copy optimized)

func EstimateAlpha

func EstimateAlpha(q string) float32

EstimateAlpha calculates a heuristic alpha value based on query length.

func EstimateRecordSize

func EstimateRecordSize(rec arrow.RecordBatch) int64

EstimateRecordSize is a heuristic or fast path. For now, we alias to calculateRecordSize as it's reasonably fast (O(cols)).

func EuclideanDistanceGeo

func EuclideanDistanceGeo(p1, p2 GeoPoint) float64

EuclideanDistanceGeo calculates the planar distance between two points.

func ExtractVectorGeneric

func ExtractVectorGeneric[T any](rec arrow.RecordBatch, rowIdx, colIdx int) ([]T, error)

ExtractVectorGeneric extracts a vector of a generic type from an Arrow record batch.

func FastPathGreater

func FastPathGreater(ctx context.Context, arr arrow.Array, value string) (arrow.Array, error)

FastPathGreater applies greater-than filter directly without Arrow Compute overhead.

func FastPathGreaterEqual

func FastPathGreaterEqual(ctx context.Context, arr arrow.Array, value string) (arrow.Array, error)

FastPathGreaterEqual applies greater-than-or-equal filter directly without Arrow Compute overhead.

func FastPathLess

func FastPathLess(ctx context.Context, arr arrow.Array, value string) (arrow.Array, error)

FastPathLess applies less-than filter directly without Arrow Compute overhead.

func FastPathLessEqual

func FastPathLessEqual(ctx context.Context, arr arrow.Array, value string) (arrow.Array, error)

FastPathLessEqual applies less-than-or-equal filter directly without Arrow Compute overhead.

func GenerateSnippetHighlight

func GenerateSnippetHighlight(text string, matchedTerms []string, openTag, closeTag string, maxLen int) (string, []string)

GenerateSnippetHighlight wraps matched tokens/phrases in tags (e.g. <mark>..</mark>) and extracts a compact contextual snippet centered around the first match.

func GetByteRowBuffer

func GetByteRowBuffer(size int) []byte

GetByteRowBuffer acquires a byte slice of length size from the pool.

func GetFloat32RowBuffer

func GetFloat32RowBuffer(dim int) []float32

GetFloat32RowBuffer acquires a float32 slice of length dim from the pool.

func GetJSONEncoder

func GetJSONEncoder() (*bytes.Buffer, *json.Encoder)

GetJSONEncoder retrieves a pooled encoder and buffer.

func GetNumaNode

func GetNumaNode(ptr unsafe.Pointer) (int, error)

GetNumaNode returns the NUMA node (memory bank) where the page containing the given pointer resides.

func GetTCPNoDelayConnectionsTotal

func GetTCPNoDelayConnectionsTotal() int64

GetTCPNoDelayConnectionsTotal returns the total number of connections with TCP_NODELAY set. This is useful for testing and monitoring.

func GetVectorTypeElementSize

func GetVectorTypeElementSize(dt types.VectorDataType) float64

GetVectorTypeElementSize returns the memory size in bytes per dimension for a given vector data type.

func HashHybridQuery

func HashHybridQuery(dataset string, vector []float32, textQuery string, k int, alpha float32, rrfK int, graphAlpha float32, graphDepth int) uint64

HashHybridQuery generates a deterministic hash for a hybrid search query. It combines dataset name, vector, text query, and parameters into a uint64 key.

func HaversineDistance

func HaversineDistance(p1, p2 GeoPoint, earthRadius float64) float64

HaversineDistance calculates the great-circle distance between two points.

func IncrementRecordAccess

func IncrementRecordAccess()

IncrementRecordAccess should be called when a record is accessed (for metrics)

func LevenshteinDistance

func LevenshteinDistance(a, b string) int

LevenshteinDistance computes Optimal String Alignment (Damerau-Levenshtein) edit distance between two UTF-8 strings, counting adjacent character transpositions as distance 1.

func ListActiveGoroutines

func ListActiveGoroutines() []string

ListActiveGoroutines returns a human-readable list of known background goroutines

func LockMemory

func LockMemory(ptr unsafe.Pointer, size uintptr) error

LockMemory pins the memory region in RAM, preventing it from being swapped out.

func MatchesFilters

func MatchesFilters(rec arrow.RecordBatch, rowIdx int, filters []query.Filter) (bool, error)

MatchesFilters checks if a specific row satisfies the filters.

func NewConfigError

func NewConfigError(component, field, value, message string) error

NewConfigError creates a new ConfigError.

func NewIVFHNSWCompositeIndex

func NewIVFHNSWCompositeIndex(d int, cfg IVFHNSWConfig) (*index.IVFHNSWCompositeIndex, error)

func NewIVFOPQIndex

func NewIVFOPQIndex(d int, cfg IVFOPQConfig) (*index.IVFOPQIndex, error)

func NewIndexFactory

func NewIndexFactory() *index.IndexFactory

func NewNeighborSelectionFailedError

func NewNeighborSelectionFailedError(op string, err error) error

NewNeighborSelectionFailedError creates a new error for failed neighbor selection operations.

func NewSnapshotBackendForURI

func NewSnapshotBackendForURI(ctx context.Context, dest string) (storage.SnapshotBackend, error)

NewSnapshotBackendForURI resolves a storage.SnapshotBackend from local directory, file://, s3://, or gs:// URI (Item 4.2).

func ParseAdvancedTextQuery

func ParseAdvancedTextQuery(q string) (queryNode, error)

ParseAdvancedTextQuery parses boolean (AND/OR/NOT), parentheses, "exact phrase", and fuzzy~N syntax.

func ParseNamespacedPath

func ParseNamespacedPath(path string) (namespace, dataset string)

ParseNamespacedPath parses a path into namespace and dataset components. Format: "namespace/dataset" or "dataset" (uses "default" namespace) Examples:

  • "tenant1/mydata" -> ("tenant1", "mydata")
  • "mydata" -> ("default", "mydata")
  • "org/project/data" -> ("org", "project/data")

func ParseVectorType

func ParseVectorType(apiType string) (types.VectorDataType, error)

ParseVectorType maps an API vector_type string to the internal VectorDataType. An empty string defaults to float32.

Returns an error with a descriptive message listing valid values if the type string is unrecognised.

func PinThreadToCore

func PinThreadToCore(core int) error

PinThreadToCore pins the current goroutine's thread to a specific CPU core.

func PinThreadToNode

func PinThreadToNode(node int) error

PinThreadToNode pins the current goroutine's thread to the set of CPUs associated with the given NUMA node.

func ProjectVectorMemory

func ProjectVectorMemory(numVectors int64, dim int, dt types.VectorDataType) int64

ProjectVectorMemory estimates total memory footprint for numVectors of dimension dim and data type dt, including raw vectors, HNSW graph structures, adjacency lists, and indexing buffers.

func PutByteRowBuffer

func PutByteRowBuffer(b []byte)

PutByteRowBuffer returns a byte slice to the pool.

func PutFloat32RowBuffer

func PutFloat32RowBuffer(s []float32)

PutFloat32RowBuffer returns a float32 slice to the pool.

func PutJSONEncoder

func PutJSONEncoder(buf *bytes.Buffer, enc *json.Encoder)

PutJSONEncoder returns the encoder and buffer to the pool.

func PutSearchResultSlice

func PutSearchResultSlice(slice []SearchResult)

PutSearchResultSlice returns a slice to the pool

func RecordTurboQuantEncoding

func RecordTurboQuantEncoding(datasetName, direction string, elapsed time.Duration)

RecordTurboQuantEncoding records the cost and source of a TurboQuant encoding operation. direction should be "client_provided" or "server_encoded".

func RegisterHNSWKernels

func RegisterHNSWKernels()

RegisterHNSWKernels registers custom Arrow compute kernels for HNSW operations. Should be called during initialization.

func ResetGlobalSizeCache

func ResetGlobalSizeCache()

ResetGlobalSizeCache resets the global cache

func RetainRecordBatch

func RetainRecordBatch(rec arrow.RecordBatch) arrow.RecordBatch

RetainRecordBatch simply retains the record batch for zero-copy access. Caller must call Release() when done.

func SaveThreadAffinity

func SaveThreadAffinity() func()

SaveThreadAffinity saves the current thread's CPU affinity and returns a restore function.

func SetDeterministicIngest

func SetDeterministicIngest(on bool)

SetDeterministicIngest turns the pinning on or off. Tests use it; a running server sets it through LONGBOW_BENCH_SEED before any worker starts.

func ShouldAutoQuantize

func ShouldAutoQuantize(numVectors int64, dim int, dt types.VectorDataType, maxRAM int64, thresholdCount int64) bool

ShouldAutoQuantize determines whether a dataset should standardize on TurboQuant as its default storage mode for high-scale configurations (default 500k+ vectors) on memory-constrained infrastructure.

func ShouldSpillToDisk

func ShouldSpillToDisk(numVectors int64, dim int, dt types.VectorDataType, maxRAM int64, thresholdRatio float64) bool

ShouldSpillToDisk determines whether the projected memory footprint exceeds the threshold ratio (default 70%) of total available physical RAM or container limit.

func ShouldUsePipeline

func ShouldUsePipeline(numBatches int) bool

ShouldUsePipeline returns true if the number of batches justifies the overhead of pipelining.

func TrackVectorTypeCreation

func TrackVectorTypeCreation(datasetName, apiType string)

TrackVectorTypeCreation emits a Prometheus metric recording that a dataset was created with a specific vector type. Call this when a new dataset is first created.

func TurboQuantStorageRatio

func TurboQuantStorageRatio(tqBytes int64, vectorCount, dims int) float64

TurboQuantStorageRatio returns the compression ratio of a TurboQuant dataset relative to a float32 baseline. A ratio < 1.0 means TQ uses less storage.

ratio = tqBytes / (vectorCount * dims * 4)

func UnlockMemory

func UnlockMemory(ptr unsafe.Pointer, size uintptr) error

UnlockMemory unpins a previously locked memory region.

func UpdateTurboQuantStorageBytes

func UpdateTurboQuantStorageBytes(datasetName string, totalBytes float64)

UpdateTurboQuantStorageBytes updates the gauge tracking total TurboQuant storage bytes for a dataset (used to compare against float32 baseline).

func ValidateGeoSearchRequest

func ValidateGeoSearchRequest(req *GeoSearchRequest) error

ValidateGeoSearchRequest ensures a GeoSearchRequest is well-formed.

func ValidateStreamEvent

func ValidateStreamEvent(schema RegisteredStreamSchema, ev *StreamVectorEvent) error

ValidateEvent checks an event against the resolved schema rules.

func VectorDistance

func VectorDistance(v1, v2 []float32) float64

VectorDistance calculates the Euclidean distance between two vectors.

func ZeroCopyRecordBatch

func ZeroCopyRecordBatch(mem memory.Allocator, rec arrow.RecordBatch, deleted *types.Bitset) (arrow.RecordBatch, error)

ZeroCopyRecordBatch creates a zero-copy view of a record batch with tombstone filtering. Uses Arrow's compute kernels for efficient slicing without deep copies.

Types

type APIKey

type APIKey struct {
	KeyID          string            `json:"key_id"`
	KeyHash        string            `json:"key_hash"`
	Name           string            `json:"name"`
	Role           Role              `json:"role"`
	TenantID       string            `json:"tenant_id,omitempty"`
	Namespace      string            `json:"namespace,omitempty"`
	Datasets       []string          `json:"datasets,omitempty"`
	Permissions    []Permission      `json:"permissions"`
	RowFilters     map[string]string `json:"row_filters,omitempty"`
	CreatedAt      time.Time         `json:"created_at"`
	ExpiresAt      *time.Time        `json:"expires_at,omitempty"`
	GraceExpiresAt *time.Time        `json:"grace_expires_at,omitempty"`
	RevokedAt      *time.Time        `json:"revoked_at,omitempty"`
	RotatedFrom    string            `json:"rotated_from,omitempty"`
	LastUsed       time.Time         `json:"last_used"`
	Enabled        bool              `json:"enabled"`
}

APIKey represents a security credential for accessing the store with associated permissions.

type APIKeyOptions

type APIKeyOptions struct {
	Name       string
	Role       Role
	TenantID   string
	Namespace  string
	Datasets   []string
	RowFilters map[string]string
	TTL        time.Duration
}

APIKeyOptions configures API key creation.

type AdmissionController

type AdmissionController struct {
	Bypass bool
	// contains filtered or unexported fields
}

AdmissionController manages request admission and resource throttling.

func NewAdmissionController

func NewAdmissionController(maxMemory, currentMemory *atomic.Int64, scaler *autoscale.AutoScaler, logger zerolog.Logger) *AdmissionController

NewAdmissionController creates a new admission controller.

func (*AdmissionController) Admit

func (ac *AdmissionController) Admit(ctx context.Context, opType string) error

Admit checks if a request of the given type should be admitted.

func (*AdmissionController) AdmitMigration

func (ac *AdmissionController) AdmitMigration(ctx context.Context) error

AdmitMigration checks if a background migration/rebalancing task should proceed.

func (*AdmissionController) CanAdmitSearch

func (ac *AdmissionController) CanAdmitSearch() error

CanAdmitSearch checks if a search request would be admitted without acquiring state. Returns nil if search can proceed, or an error describing why it would be rejected.

func (*AdmissionController) IsWALReplay

func (ac *AdmissionController) IsWALReplay() bool

IsWALReplay returns true if WAL replay is active.

func (*AdmissionController) MigrationFinished

func (ac *AdmissionController) MigrationFinished()

MigrationFinished decrements the migrating count.

func (*AdmissionController) MigrationStarted

func (ac *AdmissionController) MigrationStarted()

MigrationStarted increments the migrating count.

func (*AdmissionController) Release

func (ac *AdmissionController) Release(opType string)

Release releases slots and updates request counters when operations finish.

func (*AdmissionController) SetTuner

func (ac *AdmissionController) SetTuner(tuner *lbmem.GCTuner)

SetTuner associates a GCTuner with the admission controller.

func (*AdmissionController) SetWALReplay

func (ac *AdmissionController) SetWALReplay(active bool)

SetWALReplay flags whether WAL replay is in progress.

type AdvancedRerankManager

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

AdvancedRerankManager integrates strategies, caching, query rewriting, and metering.

func NewAdvancedRerankManager

func NewAdvancedRerankManager(s *VectorStore) *AdvancedRerankManager

NewAdvancedRerankManager constructs the central reranking & query rewriting service.

func (*AdvancedRerankManager) Rerank

func (m *AdvancedRerankManager) Rerank(ctx context.Context, strategy, query string, candidates []SearchResult, tenant string) ([]SearchResult, bool, error)

Rerank runs the chosen strategy ("hybrid", "heuristic", "llm", "cohere", "cross_encoder") with cache.

func (*AdvancedRerankManager) Rewrite

func (m *AdvancedRerankManager) Rewrite(query string, mode QueryRewriteMode) []string

Rewrite rewrites/expands a query.

type AdvancedTextQueryRequest

type AdvancedTextQueryRequest struct {
	Dataset      string            `json:"dataset"`
	Query        string            `json:"query"`
	K            int               `json:"k"`
	FuzzyMaxDist int               `json:"fuzzy_max_dist,omitempty"` // optional global Levenshtein distance (default allows term~N)
	HighlightTag string            `json:"highlight_tag,omitempty"`  // default "<mark>" / "</mark>"
	SnippetChars int               `json:"snippet_chars,omitempty"`  // default 160
	FacetFields  []string          `json:"facet_fields,omitempty"`
	BM25         *BM25TuningParams `json:"bm25,omitempty"`
}

AdvancedTextQueryRequest supports boolean, phrase, fuzzy matching, highlighting, and facets.

type AdvancedTextSearchManager

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

AdvancedTextSearchManager provides full-text boolean/phrase/fuzzy search, highlighting, faceted counts, dynamic BM25 k1/b tuning, and search analytics tracking.

func NewAdvancedTextSearchManager

func NewAdvancedTextSearchManager(s *VectorStore) *AdvancedTextSearchManager

NewAdvancedTextSearchManager creates an advanced text search & analytics engine.

func (*AdvancedTextSearchManager) Analytics

Analytics returns search volume, top queries, and zero-result queries.

func (*AdvancedTextSearchManager) GetBM25Params

func (m *AdvancedTextSearchManager) GetBM25Params(dataset string) BM25TuningParams

GetBM25Params returns effective BM25 tuning for dataset.

func (*AdvancedTextSearchManager) Search

Search executes full-text boolean/phrase/fuzzy evaluation with tunable BM25 scoring, highlighted snippets, faceted counts, and analytics recording.

func (*AdvancedTextSearchManager) SetBM25Params

func (m *AdvancedTextSearchManager) SetBM25Params(dataset string, params BM25TuningParams) error

SetBM25Params tunes k1 and b parameters dynamically for a dataset.

type AdvancedTextSearchResponse

type AdvancedTextSearchResponse struct {
	Query     string                  `json:"query"`
	TotalHits int                     `json:"total_hits"`
	TookMs    float64                 `json:"took_ms"`
	Hits      []HighlightedTextHit    `json:"hits"`
	Facets    map[string][]FacetCount `json:"facets,omitempty"`
	BM25Used  BM25TuningParams        `json:"bm25_used"`
}

AdvancedTextSearchResponse bundles hits, facet counts, and tuned BM25 settings.

type AggOp

type AggOp string

AggOp enumerates supported columnar & metadata aggregation functions.

const (
	AggCount AggOp = "count"
	AggSum   AggOp = "sum"
	AggAvg   AggOp = "avg"
	AggMin   AggOp = "min"
	AggMax   AggOp = "max"
)

type AggSpec

type AggSpec struct {
	Alias string `json:"alias"`
	Field string `json:"field,omitempty"`
	Op    AggOp  `json:"op"`
}

AggSpec defines one computed metric column inside a materialized view.

type AggregationBucket

type AggregationBucket struct {
	Timestamp int64    `json:"timestamp"`
	Count     int      `json:"count"`
	Min       *float32 `json:"min,omitempty"`
	Max       *float32 `json:"max,omitempty"`
	Mean      *float32 `json:"mean,omitempty"`
	Sum       *float32 `json:"sum,omitempty"`
}

AggregationBucket represents a single time-based bucket in an aggregation result.

type AggregationType

type AggregationType string

AggregationType defines the type of streaming aggregation to perform.

const (
	// AggregationTypeMovingAverage calculates the simple moving average.
	AggregationTypeMovingAverage AggregationType = "moving_average"
	// AggregationTypeExponential calculates the exponential moving average.
	AggregationTypeExponential AggregationType = "exponential"
	// AggregationTypeCumulative calculates the cumulative sum.
	AggregationTypeCumulative AggregationType = "cumulative"
	// AggregationTypeWeighted calculates a weighted average.
	AggregationTypeWeighted AggregationType = "weighted"
)

type AlignedShard

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

AlignedShard wraps RWMutex with cache-line padding and contention metrics.

type AlignedShardedMutex

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

AlignedShardedMutex provides cache-aligned sharding with contention tracking.

Key improvements over standard ShardedRWMutex: 1. Cache-line alignment prevents false sharing 2. Lock-free fast path for uncontended cases 3. Contention metrics for monitoring and adaptive scaling 4. Optional adaptive shard count adjustment

func NewAlignedShardedMutex

func NewAlignedShardedMutex(cfg AlignedShardedMutexConfig) *AlignedShardedMutex

NewAlignedShardedMutex creates a cache-aligned sharded mutex.

func NewAlignedShardedMutexDefault

func NewAlignedShardedMutexDefault() *AlignedShardedMutex

NewAlignedShardedMutexDefault creates a mutex with default configuration.

func (*AlignedShardedMutex) AdaptShardCount

func (sm *AlignedShardedMutex) AdaptShardCount()

AdaptShardCount adjusts the shard count based on measured contention. Only effective if EnableAdaptive is true in config.

func (*AlignedShardedMutex) Lock

func (sm *AlignedShardedMutex) Lock(key uint64)

Lock acquires a write lock for the shard associated with the given key. Uses fast path (TryLock) first, falls back to blocking lock with contention tracking.

func (*AlignedShardedMutex) LockShard

func (sm *AlignedShardedMutex) LockShard(shard int)

LockShard acquires a write lock on a specific shard directly.

func (*AlignedShardedMutex) NumShards

func (sm *AlignedShardedMutex) NumShards() int

NumShards returns the current number of shards.

func (*AlignedShardedMutex) RLock

func (sm *AlignedShardedMutex) RLock(key uint64)

RLock acquires a read lock for the shard associated with the given key.

func (*AlignedShardedMutex) RLockShard

func (sm *AlignedShardedMutex) RLockShard(shard int)

RLockShard acquires a read lock on a specific shard directly.

func (*AlignedShardedMutex) RUnlock

func (sm *AlignedShardedMutex) RUnlock(key uint64)

RUnlock releases the read lock for the shard associated with the given key.

func (*AlignedShardedMutex) RUnlockShard

func (sm *AlignedShardedMutex) RUnlockShard(shard int)

RUnlockShard releases a read lock on a specific shard directly.

func (*AlignedShardedMutex) ResetStats

func (sm *AlignedShardedMutex) ResetStats()

ResetStats resets all contention metrics.

func (*AlignedShardedMutex) ShardFor

func (sm *AlignedShardedMutex) ShardFor(key uint64) int

ShardFor returns the shard index for a given key using FNV-1a hash.

func (*AlignedShardedMutex) Stats

Stats returns current statistics.

func (*AlignedShardedMutex) TryLock

func (sm *AlignedShardedMutex) TryLock(key uint64) bool

TryLock attempts to acquire a write lock without blocking. Returns true if lock was acquired, false if already held. This is the lock-free fast path for uncontended cases.

func (*AlignedShardedMutex) Unlock

func (sm *AlignedShardedMutex) Unlock(key uint64)

Unlock releases the write lock for the shard associated with the given key.

func (*AlignedShardedMutex) UnlockShard

func (sm *AlignedShardedMutex) UnlockShard(shard int)

UnlockShard releases a write lock on a specific shard directly.

type AlignedShardedMutexConfig

type AlignedShardedMutexConfig struct {
	NumShards        int     // Number of shards (default: runtime.NumCPU())
	TargetContention float64 // Target avg contention per shard (default: 100.0)
	EnableAdaptive   bool    // Enable adaptive shard scaling (default: false)
}

AlignedShardedMutexConfig configures the cache-aligned sharded mutex.

func DefaultAlignedShardedMutexConfig

func DefaultAlignedShardedMutexConfig() AlignedShardedMutexConfig

DefaultAlignedShardedMutexConfig returns sensible defaults.

type AlignedShardedMutexStats

type AlignedShardedMutexStats struct {
	TotalContentions int64   // Total number of contentions across all shards
	TotalWaitNs      int64   // Total nanoseconds spent waiting
	FastPathHits     int64   // Total successful TryLock calls
	FastPathMisses   int64   // Total failed TryLock calls
	AvgContention    float64 // Average contention per shard
	FastPathRate     float64 // Percentage of fast path hits
}

AlignedShardedMutexStats holds statistics for the mutex.

type AllocatorAwareCache

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

AllocatorAwareCache provides cached access to Arrow RecordBatches with zero-copy buffer retrieval

func NewAllocatorAwareCache

func NewAllocatorAwareCache(alloc memory.Allocator, maxSize int) *AllocatorAwareCache

NewAllocatorAwareCache creates a new cache with zero-copy support

func (*AllocatorAwareCache) Get

Get retrieves a RecordBatch from cache Returns a retained reference - caller must Release()

func (*AllocatorAwareCache) GetBufferDirect

func (c *AllocatorAwareCache) GetBufferDirect(key string, colIdx, bufIdx int) []byte

GetBufferDirect retrieves underlying buffer bytes without copying colIdx: column index, bufIdx: buffer index (0=validity, 1=data)

func (*AllocatorAwareCache) Put

func (c *AllocatorAwareCache) Put(key string, rec arrow.RecordBatch)

Put stores a RecordBatch in the cache with proper reference counting

type AndExpr

type AndExpr = types.AndExpr

AndExpr represents a logical AND operation between multiple filter expressions.

type ArrowBitset

type ArrowBitset = types.ArrowBitset

ArrowBitset provides a fast bitset implementation for visited nodes.

type ArrowHNSW

type ArrowHNSW = hnswcore.ArrowHNSW

ArrowHNSW is the core HNSW implementation using Arrow memory.

type ArrowHNSWConfig

type ArrowHNSWConfig = types.ArrowHNSWConfig

ArrowHNSWConfig defines the configuration for ArrowHNSW.

type ArrowHNSWPredicate

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

ArrowHNSWPredicate implements HNSWPredicate for Arrow-backed indices using memory-mapped data.

func NewArrowHNSWPredicate

func NewArrowHNSWPredicate(hnsw *ArrowHNSW, indexedFields []string) *ArrowHNSWPredicate

NewArrowHNSWPredicate creates a new predicate evaluator for a set of indexed fields.

func (*ArrowHNSWPredicate) ApplyFilter

func (hp *ArrowHNSWPredicate) ApplyFilter(filter query.Filter) ([]uint32, error)

ApplyFilter returns the set of node IDs that satisfy the filter criteria.

func (*ArrowHNSWPredicate) CanAcceptFilter

func (hp *ArrowHNSWPredicate) CanAcceptFilter(filter query.Filter) bool

CanAcceptFilter returns true if the predicate can evaluate the given filter.

func (*ArrowHNSWPredicate) GetIndexedFields

func (hp *ArrowHNSWPredicate) GetIndexedFields() []string

GetIndexedFields returns the list of fields that this predicate can evaluate.

type ArrowSearchContext

type ArrowSearchContext = hnswcore.ArrowSearchContext

ArrowSearchContext holds state for a single HNSW search.

type ArrowSearchContextPool

type ArrowSearchContextPool = hnswcore.ArrowSearchContextPool

ArrowSearchContextPool provides a pool for reusing search contexts.

type AutoScaleConfig

type AutoScaleConfig struct {
	Enabled            bool    `json:"enabled"`
	MinWorkers         int     `json:"min_workers"`
	MaxWorkers         int     `json:"max_workers"`
	TargetQPSPerWorker float64 `json:"target_qps_per_worker"`
	ScaleUpThreshold   float64 `json:"scale_up_threshold"`
	ScaleDownThreshold float64 `json:"scale_down_threshold"`
}

AutoScaleConfig defines the parameters for automatic scaling of workers.

type AutoShardingConfig

type AutoShardingConfig struct {
	// Enabled determines if auto-sharding is active.
	Enabled bool
	// ShardThreshold is the number of vectors at which to trigger sharding.
	ShardThreshold int
	// ShardCount is the target number of shards to create (defaults to NumCPU).
	ShardCount int
	// ShardSplitThreshold is the size of each shard (defaults to 65536).
	ShardSplitThreshold int
	// UseRingSharding determines if consistent hashing sharding is used.
	UseRingSharding bool

	// IndexConfig holds the configuration for the underlying HNSW index (optional).
	// If set, NewAutoShardingIndex will generic ArrowHNSW with this config.
	IndexConfig *ArrowHNSWConfig
}

AutoShardingConfig configures the auto-sharding behavior.

func DefaultAutoShardingConfig

func DefaultAutoShardingConfig() AutoShardingConfig

DefaultAutoShardingConfig returns a standard configuration.

type AutoShardingIndex

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

AutoShardingIndex wraps a VectorIndex and transparently upgrades it to a ShardedHNSW when the dataset grows beyond a threshold.

func (*AutoShardingIndex) AddBatch

func (idx *AutoShardingIndex) AddBatch(ctx context.Context, recs []arrow.RecordBatch, rowIdxs, batchIdxs []int) ([]uint32, error)

AddBatch adds multiple vectors from Arrow record batches efficiently.

func (*AutoShardingIndex) AddByLocation

func (idx *AutoShardingIndex) AddByLocation(ctx context.Context, batchIdx, rowIdx int) (uint32, error)

AddByLocation adds a vector to the index using its storage location.

func (*AutoShardingIndex) AddByRecord

func (idx *AutoShardingIndex) AddByRecord(ctx context.Context, rec arrow.RecordBatch, rowIdx, batchIdx int) (uint32, error)

AddByRecord adds a vector from an Arrow record batch.

func (*AutoShardingIndex) ApplyDelta

func (idx *AutoShardingIndex) ApplyDelta(delta *types.DeltaSync) error

ApplyDelta applies a delta sync object to the index.

func (*AutoShardingIndex) Close

func (idx *AutoShardingIndex) Close() error

Close releases all resources held by the index.

func (*AutoShardingIndex) DeleteBatch

func (idx *AutoShardingIndex) DeleteBatch(ctx context.Context, ids []uint32) error

DeleteBatch removes a batch of vectors from the index.

func (*AutoShardingIndex) EstimateMemory

func (idx *AutoShardingIndex) EstimateMemory() int64

EstimateMemory implements VectorIndex.

func (*AutoShardingIndex) ExportDelta

func (idx *AutoShardingIndex) ExportDelta(fromVersion uint64) (*types.DeltaSync, error)

ExportDelta returns a delta sync object since the given version.

func (*AutoShardingIndex) ExportGraph

func (idx *AutoShardingIndex) ExportGraph(w io.Writer) error

ExportGraph serializes the graph structure to a writer.

func (*AutoShardingIndex) ExportState

func (idx *AutoShardingIndex) ExportState() ([]byte, error)

ExportState serializes the current index state.

func (*AutoShardingIndex) GetData

func (idx *AutoShardingIndex) GetData() *types.GraphData

GetData returns graph data from the current index.

func (*AutoShardingIndex) GetDimension

func (idx *AutoShardingIndex) GetDimension() uint32

GetDimension implements VectorIndex.

func (*AutoShardingIndex) GetEntryPoint

func (idx *AutoShardingIndex) GetEntryPoint() uint32

GetEntryPoint returns the entry point node ID for HNSW traversal.

func (*AutoShardingIndex) GetGPUIndex

func (idx *AutoShardingIndex) GetGPUIndex() any

GetGPUIndex returns the GPU-accelerated index if active.

func (*AutoShardingIndex) GetIndexType

func (idx *AutoShardingIndex) GetIndexType() string

GetIndexType returns the index type identifier for the active index.

func (*AutoShardingIndex) GetLocation

func (idx *AutoShardingIndex) GetLocation(id uint32) (any, bool)

GetLocation retrieves the storage location for a given vector ID.

func (*AutoShardingIndex) GetNeighbors

func (idx *AutoShardingIndex) GetNeighbors(ctx context.Context, id uint32, k int) ([]types.SearchResult, error)

GetNeighbors returns the k nearest neighbors for a given vector ID as SearchResults.

func (*AutoShardingIndex) GetPQEncoder

func (idx *AutoShardingIndex) GetPQEncoder() *pq.PQEncoder

GetPQEncoder returns the Product Quantizer encoder for the index.

func (*AutoShardingIndex) GetParallelSearchConfig

func (idx *AutoShardingIndex) GetParallelSearchConfig() types.ParallelSearchConfig

GetParallelSearchConfig returns the current parallel search configuration.

func (*AutoShardingIndex) GetRawNeighbors

func (idx *AutoShardingIndex) GetRawNeighbors(id uint32) ([]uint32, error)

GetRawNeighbors returns the diagnostic neighbor IDs for a given vector ID.

func (*AutoShardingIndex) GetShardedIndex

func (idx *AutoShardingIndex) GetShardedIndex() *ShardedHNSW

GetShardedIndex returns the underlying sharded index if it exists.

func (*AutoShardingIndex) GetVectorID

func (idx *AutoShardingIndex) GetVectorID(loc any) (uint32, bool)

GetVectorID retrieves the vector ID for a given storage location.

func (*AutoShardingIndex) ImportGraph

func (idx *AutoShardingIndex) ImportGraph(r io.Reader) error

ImportGraph restores the graph structure from a reader.

func (*AutoShardingIndex) ImportState

func (idx *AutoShardingIndex) ImportState(data []byte) error

ImportState restores the index state from a byte slice.

func (*AutoShardingIndex) InitGPU

func (idx *AutoShardingIndex) InitGPU(deviceID int32, logger zerolog.Logger) error

InitGPU initializes GPU acceleration on the underlying HNSW index.

func (*AutoShardingIndex) IsSharded

func (idx *AutoShardingIndex) IsSharded() bool

IsSharded returns true if the index has been upgraded to a sharded implementation.

func (*AutoShardingIndex) Len

func (idx *AutoShardingIndex) Len() int

Len returns the total number of vectors across all shards.

func (*AutoShardingIndex) PreWarm

func (idx *AutoShardingIndex) PreWarm(targetSize int)

PreWarm explicitly warms up the underlying index to a target size.

func (*AutoShardingIndex) ReleaseMonolithicChunk

func (idx *AutoShardingIndex) ReleaseMonolithicChunk(cID int) error

ReleaseMonolithicChunk releases a monolithic chunk from memory.

func (*AutoShardingIndex) RelocateToOffHeap

func (idx *AutoShardingIndex) RelocateToOffHeap() error

RelocateToOffHeap relocates the index to off-heap memory.

func (*AutoShardingIndex) RemapLocations

func (idx *AutoShardingIndex) RemapLocations(ctx context.Context, mapping map[uint32]any) error

RemapLocations updates storage locations for physical movement (compaction).

func (*AutoShardingIndex) Search

func (idx *AutoShardingIndex) Search(ctx context.Context, q any, k int, options any) ([]types.Candidate, error)

Search implements VectorIndexer.

func (*AutoShardingIndex) SearchVectors

func (idx *AutoShardingIndex) SearchVectors(ctx context.Context, q any, k int, filters []query.Filter, options any) ([]SearchResult, error)

SearchVectors returns the k nearest neighbors for a query vector.

func (*AutoShardingIndex) SearchVectorsInRange

func (idx *AutoShardingIndex) SearchVectorsInRange(ctx context.Context, q any, threshold float32, filters []query.Filter, options any) ([]SearchResult, error)

SearchVectorsInRange returns nearest neighbors within a distance threshold.

func (*AutoShardingIndex) SearchVectorsWithBitmap

func (idx *AutoShardingIndex) SearchVectorsWithBitmap(ctx context.Context, q any, k int, filter *roaring.Bitmap, options any) ([]SearchResult, error)

SearchVectorsWithBitmap returns k nearest neighbors filtered by a bitset.

func (*AutoShardingIndex) SetEfConstruction

func (idx *AutoShardingIndex) SetEfConstruction(ef int)

SetEfConstruction updates the efConstruction parameter dynamically.

func (*AutoShardingIndex) SetGPUIndex

func (idx *AutoShardingIndex) SetGPUIndex(gIdx any)

SetGPUIndex assigns a GPU index to the underlying HNSW index.

func (*AutoShardingIndex) SetIndexedColumns

func (idx *AutoShardingIndex) SetIndexedColumns(cols []string)

SetIndexedColumns configures which columns are indexed for fast equality lookups.

func (*AutoShardingIndex) SetInitialDimension

func (idx *AutoShardingIndex) SetInitialDimension(dim int)

SetInitialDimension sets the dimension for the underlying index if not yet set.

func (*AutoShardingIndex) SetParallelSearchConfig

func (idx *AutoShardingIndex) SetParallelSearchConfig(cfg types.ParallelSearchConfig)

SetParallelSearchConfig updates the parallel search configuration

func (*AutoShardingIndex) Size

func (idx *AutoShardingIndex) Size() int

Size returns the total number of nodes in the index.

func (*AutoShardingIndex) TrainPQ

func (idx *AutoShardingIndex) TrainPQ(vectors [][]float32) error

TrainPQ trains a Product Quantizer for the index.

func (*AutoShardingIndex) Warmup

func (idx *AutoShardingIndex) Warmup() int

Warmup delegates to the current index.

type BM25ArenaDocument

type BM25ArenaDocument = index.BM25ArenaDocument

type BM25ArenaIndex

type BM25ArenaIndex = index.BM25ArenaIndex

func NewBM25ArenaIndex

func NewBM25ArenaIndex(arena *memory.SlabArena, offset int) *BM25ArenaIndex

type BM25Config

type BM25Config = index.BM25Config

type BM25Document

type BM25Document = index.BM25Document

type BM25InvertedIndex

type BM25InvertedIndex = index.BM25InvertedIndex

func NewBM25InvertedIndex

func NewBM25InvertedIndex(cfg index.BM25Config) *BM25InvertedIndex

type BM25TuningParams

type BM25TuningParams struct {
	K1 float64 `json:"k1"`
	B  float64 `json:"b"`
}

BM25TuningParams configures dynamic per-dataset or per-query BM25 k1 and b parameters.

func DefaultBM25Tuning

func DefaultBM25Tuning() BM25TuningParams

DefaultBM25Tuning returns standard Okapi BM25 parameters (k1=1.2, b=0.75).

type BQEncoder

type BQEncoder = types.BQEncoder

BQEncoder implements Binary Quantization.

type BackpressureConfig

type BackpressureConfig struct {
	SoftLimitBytes    uint64
	HardLimitBytes    uint64
	CheckInterval     time.Duration
	SoftPressureDelay time.Duration
}

BackpressureConfig configures memory backpressure behavior thresholds and delays.

type BackupConfig

type BackupConfig struct {
	BackupDir      string
	Interval       time.Duration
	RetentionDays  int
	RetentionCount int
	Incremental    bool
	Compression    bool
	Destination    string
}

BackupConfig defines the configuration for dataset backups.

type BackupDelta

type BackupDelta struct {
	Seq       int64
	Timestamp time.Time
	SizeBytes int64
	Checksum  string
}

BackupDelta represents a specific change in an incremental backup.

type BackupManager

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

BackupManager handles the creation and management of dataset backups.

func NewBackupManager

func NewBackupManager(config BackupConfig) (*BackupManager, error)

NewBackupManager creates a new backup manager with the given configuration.

func (*BackupManager) ApplyRetentionPolicy

func (bm *BackupManager) ApplyRetentionPolicy() (int, error)

ApplyRetentionPolicy removes backups that are older than the retention period.

func (*BackupManager) CreateBackup

func (bm *BackupManager) CreateBackup(datasetName string, data []byte, parentBackupID string) (BackupMetadata, error)

CreateBackup creates a new full or incremental backup for a dataset.

func (*BackupManager) CreateIncrementalBackup

func (bm *BackupManager) CreateIncrementalBackup(datasetName string, deltas []BackupDelta) (BackupMetadata, error)

CreateIncrementalBackup creates an incremental backup from a series of deltas.

func (*BackupManager) DeleteBackup

func (bm *BackupManager) DeleteBackup(backupID string) error

DeleteBackup removes a backup and its metadata.

func (*BackupManager) GetBackup

func (bm *BackupManager) GetBackup(backupID string) (BackupMetadata, bool)

GetBackup retrieves metadata for a specific backup ID.

func (*BackupManager) ListBackups

func (bm *BackupManager) ListBackups(datasetName string) []BackupMetadata

ListBackups returns all backups for a given dataset.

func (*BackupManager) Restore

func (bm *BackupManager) Restore(config RestoreConfig) ([]byte, error)

Restore performs a restoration of a dataset from backup. It verifies the backup exists, validates the checksum against data, and returns the backup data for re-insertion by the caller.

func (*BackupManager) VerifyBackup

func (bm *BackupManager) VerifyBackup(backupID string, data []byte) (bool, error)

VerifyBackup checks the integrity of a backup using its checksum.

type BackupMetadata

type BackupMetadata struct {
	BackupID     string
	DatasetName  string
	Timestamp    time.Time
	SizeBytes    int64
	Type         string
	Checksum     string
	ParentBackup string
	Version      int
	WALSequence  uint64
	RowCount     int64
	Destination  string
}

BackupMetadata stores information about a specific backup.

type BatchDistanceComputer

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

BatchDistanceComputer uses Apache Arrow compute kernels for vectorized distance calculations. This provides significant performance improvements for large candidate sets (>32 vectors).

func NewBatchDistanceComputer

func NewBatchDistanceComputer(mem memory.Allocator, dim int) *BatchDistanceComputer

NewBatchDistanceComputer creates a new batch distance computer.

func (*BatchDistanceComputer) ComputeL2Distances

func (b *BatchDistanceComputer) ComputeL2Distances(
	query []float32,
	candidateVectors [][]float32,
) ([]float32, error)

ComputeL2Distances computes L2 (Euclidean) distances between a query vector and multiple candidate vectors. This uses Arrow compute kernels for vectorized operations, providing 3-5x speedup for large batches.

Parameters:

  • query: The query vector (length must equal dim)
  • candidateVectors: Slice of candidate vectors to compare against

Returns:

  • distances: L2 distances for each candidate
  • error: Any error during computation

func (*BatchDistanceComputer) ComputeL2DistancesInto

func (b *BatchDistanceComputer) ComputeL2DistancesInto(
	query []float32,
	candidateVectors [][]float32,
	out []float32,
) ([]float32, error)

ComputeL2DistancesInto computes L2 distances into a provided buffer. If out is nil or too small, a new slice is allocated.

func (*BatchDistanceComputer) ComputeL2DistancesKernel

func (b *BatchDistanceComputer) ComputeL2DistancesKernel(
	query []float32,
	candidateVectors [][]float32,
) ([]float32, error)

ComputeL2DistancesKernel computes L2 distances using the registered "l2_distance" Arrow compute kernel. This fulfills the "True Arrow Compute" requirement by invoking the runtime kernel registry.

func (*BatchDistanceComputer) ComputeL2DistancesSIMDFallback

func (b *BatchDistanceComputer) ComputeL2DistancesSIMDFallback(
	query []float32,
	candidateVectors [][]float32,
) ([]float32, error)

ComputeL2DistancesSIMDFallback is a fallback using the existing SIMD implementation. Used for small batches where Arrow compute overhead isn't justified.

func (*BatchDistanceComputer) SelectTopKNeighbors

func (b *BatchDistanceComputer) SelectTopKNeighbors(
	distances []float32,
	ids []uint32,
	k int,
) (indices []uint32, dists []float32, err error)

SelectTopKNeighbors selects the k nearest neighbors based on distances using Arrow compute kernels. It uses the custom "select_k_neighbors" kernel.

func (*BatchDistanceComputer) ShouldUseBatchCompute

func (b *BatchDistanceComputer) ShouldUseBatchCompute(candidateCount int) bool

ShouldUseBatchCompute determines whether to use Arrow compute or SIMD fallback. Arrow compute has overhead, so it's only beneficial for larger batches.

type BatchDistanceFunc

type BatchDistanceFunc func(query []float32, vectors [][]float32, results []float32) error

BatchDistanceFunc is the function signature for calculating distances between one query and multiple vectors.

type BatchDistanceSQ8Func

type BatchDistanceSQ8Func func(query []byte, vectors [][]byte, results []float32) error

BatchDistanceSQ8Func is the function signature for SQ8 batch distance.

type BatchLayoutDetail

type BatchLayoutDetail struct {
	BatchIdx int
	Rows     int
	Deleted  int
	Density  float64
	ReadAmp  float64
	Hits     int64
}

BatchLayoutDetail provides fine-grained information about a single record batch's disk layout.

type BatchNeighborUpdate

type BatchNeighborUpdate struct {
	NodeID    uint32
	Layer     int
	Neighbors []uint32
}

BatchNeighborUpdate represents a deferred update to a node's neighbor list.

type BatchNeighborUpdater

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

BatchNeighborUpdater accumulates neighbor updates and applies them in batches. This reduces the overhead of lock acquisition and release in hot paths.

func NewBatchNeighborUpdater

func NewBatchNeighborUpdater(cfg BatchNeighborUpdaterConfig) *BatchNeighborUpdater

NewBatchNeighborUpdater creates a new batch updater.

func (*BatchNeighborUpdater) Add

func (bu *BatchNeighborUpdater) Add(update BatchNeighborUpdate)

Add adds a neighbor update to the batch.

func (*BatchNeighborUpdater) Flush

func (bu *BatchNeighborUpdater) Flush() error

Flush immediately flushes all pending updates.

func (*BatchNeighborUpdater) PendingCount

func (bu *BatchNeighborUpdater) PendingCount() int

PendingCount returns the number of pending updates.

func (*BatchNeighborUpdater) Stop

func (bu *BatchNeighborUpdater) Stop() error

Stop stops the background worker and flushes any pending updates.

type BatchNeighborUpdaterConfig

type BatchNeighborUpdaterConfig struct {
	MaxBatchSize  int
	FlushInterval time.Duration
	OnFlush       func(updates []BatchNeighborUpdate) error
}

BatchNeighborUpdaterConfig configures the batch updater.

type BatchSearchBatcher

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

BatchSearchBatcher collects search requests and processes them in batches.

func NewBatchSearchBatcher

func NewBatchSearchBatcher(batchSize int, interval int) *BatchSearchBatcher

NewBatchSearchBatcher creates a new batcher with specified size and interval.

func (*BatchSearchBatcher) AddRequest

func (bb *BatchSearchBatcher) AddRequest(req BatchSearchRequest)

AddRequest adds a search request to the batcher.

func (*BatchSearchBatcher) GetResults

func (bb *BatchSearchBatcher) GetResults() <-chan BatchSearchResult

GetResults returns a channel for receiving batch search results.

type BatchSearchProcessor

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

BatchSearchProcessor handles concurrent processing of search requests.

func NewBatchSearchProcessor

func NewBatchSearchProcessor(workers int, queueSize int) *BatchSearchProcessor

NewBatchSearchProcessor creates a new processor with the specified number of workers.

func (*BatchSearchProcessor) Close

func (bp *BatchSearchProcessor) Close()

Close stops the processor and waits for all workers to finish.

func (*BatchSearchProcessor) Search

func (bp *BatchSearchProcessor) Search(ctx context.Context, query []float32, k int, filters []query.Filter, options SearchOptions) ([]SearchResult, error)

Search submits a search request to the processor and waits for the results.

func (*BatchSearchProcessor) Start

func (bp *BatchSearchProcessor) Start(ctx context.Context, searchFn func(ctx context.Context, q any, k int, filters []query.Filter, options SearchOptions) ([]SearchResult, error))

Start begins processing search requests with the provided search function.

type BatchSearchRequest

type BatchSearchRequest struct {
	Query    []float32
	K        int
	Filters  []query.Filter
	Options  SearchOptions
	ResultCh chan []SearchResult
	ErrorCh  chan error
}

BatchSearchRequest represents a single search request within a batch.

type BatchSearchResult

type BatchSearchResult struct {
	Results []SearchResult
	Err     error
}

BatchSearchResult contains the results or error for a batch search.

type BeamSearchCandidate

type BeamSearchCandidate struct {
	ID    uint32
	Dist  float32
	Layer int
}

BeamSearchCandidate represents a potential match during graph traversal.

func BeamSearchOptimized

func BeamSearchOptimized(
	query []float32,
	vectors [][]float32,
	ef int,
	config HNSWSearchConfig,
) []BeamSearchCandidate

BeamSearchOptimized executes a high-performance beam search traversal on the graph.

func ParallelBeamSearch

func ParallelBeamSearch(
	query []float32,
	vectors [][]float32,
	ef int,
	numThreads int,
	config HNSWSearchConfig,
) []BeamSearchCandidate

ParallelBeamSearch distributes a beam search operation across multiple CPU cores.

type BeamSearchHeap

type BeamSearchHeap []BeamSearchCandidate

BeamSearchHeap is a min-priority queue of search candidates, ordered by distance.

func (BeamSearchHeap) Len

func (h BeamSearchHeap) Len() int

func (BeamSearchHeap) Less

func (h BeamSearchHeap) Less(i, j int) bool

func (*BeamSearchHeap) Pop

func (h *BeamSearchHeap) Pop() any

Pop removes the best candidate from the heap.

func (*BeamSearchHeap) Push

func (h *BeamSearchHeap) Push(x any)

Push adds a candidate to the heap.

func (BeamSearchHeap) Swap

func (h BeamSearchHeap) Swap(i, j int)

type BenchmarkResult

type BenchmarkResult struct {
	Collection         string  `json:"collection"`
	QueryCount         int     `json:"query_count"`
	AvgLatencyMs       float64 `json:"avg_latency_ms"`
	AvgResultsPerQuery float64 `json:"avg_results_per_query"`
	P50LatencyMs       float64 `json:"p50_latency_ms"`
	P99LatencyMs       float64 `json:"p99_latency_ms"`
	ThroughputQPS      float64 `json:"throughput_qps"`
}

BenchmarkResult holds the performance metrics for a search benchmark.

type BillingExporter

type BillingExporter interface {
	ExportBilling(ctx context.Context, reports []TenantUsageReport) error
}

BillingExporter receives billing usage snapshots for downstream accounting systems.

type BlockEntry

type BlockEntry struct {
	Offset     int64
	CompSize   uint32
	RawSize    uint32
	NumVectors int
	StartIdx   int
	CompType   byte
	Tier       storage.StorageTier
	RemoteKey  string
	HotKey     string
	CreatedAt  time.Time
}

BlockEntry tracks a compressed block in the disk store.

type BranchConfig

type BranchConfig struct {
	Name         string
	BaseVersion  int64
	CreatedAt    time.Time
	LastCommitID string
}

BranchConfig defines the configuration for a dataset branch.

type BufferRetainerStats

type BufferRetainerStats struct {
	ActiveBuffers      int
	TotalBytesRetained int64
	TotalRetained      int64
	TotalReleased      int64
}

BufferRetainerStats holds statistics about retained buffers

type ByteType

type ByteType interface{}

ByteType identifies byte code type (used by PQ)

type CDCEvent

type CDCEvent = cluster.CDCEvent

type CDCEventType

type CDCEventType = cluster.CDCEventType

type CDCFilter

type CDCFilter = cluster.CDCFilter

type CDCSubscribeRequest

type CDCSubscribeRequest struct {
	Dataset    string   `json:"dataset"`
	EventTypes []string `json:"event_types,omitempty"`
	Columns    []string `json:"columns,omitempty"`
	BufferSize int      `json:"buffer_size,omitempty"`
}

CDCSubscribeRequest defines the request body for CDC subscription actions.

type CDCSubscription

type CDCSubscription = cluster.CDCSubscription

type COWMetadataMap

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

COWMetadataMap provides a Copy-On-Write map for dataset metadata. Reads are lock-free via atomic pointer; writes copy the entire map. This eliminates lock contention in ListFlights.

func NewCOWMetadataMap

func NewCOWMetadataMap() *COWMetadataMap

NewCOWMetadataMap creates a new Copy-On-Write metadata map.

func (*COWMetadataMap) Delete

func (c *COWMetadataMap) Delete(name string)

Delete removes metadata for a dataset (copy-on-write).

func (*COWMetadataMap) Get

func (c *COWMetadataMap) Get(name string) (DatasetMetadata, bool)

Get returns metadata for a dataset (lock-free read).

func (*COWMetadataMap) IncrementStats

func (c *COWMetadataMap) IncrementStats(name string, rows int64, batches int)

IncrementStats atomically increments row and batch counts.

func (*COWMetadataMap) Len

func (c *COWMetadataMap) Len() int

Len returns the number of datasets in the map.

func (*COWMetadataMap) Set

func (c *COWMetadataMap) Set(name string, meta DatasetMetadata)

Set adds or updates metadata for a dataset (copy-on-write).

func (*COWMetadataMap) Snapshot

func (c *COWMetadataMap) Snapshot() map[string]DatasetMetadata

Snapshot returns the current map for iteration. The returned map is immutable and safe to iterate without locks.

func (*COWMetadataMap) UpdateFromRecords

func (c *COWMetadataMap) UpdateFromRecords(name string, batches []arrow.RecordBatch)

UpdateFromRecords updates metadata from a slice of record batches.

type CacheLinePadding

type CacheLinePadding [64]byte

CacheLinePadding ensures each shard is on a separate cache line (64 bytes). This prevents false sharing where multiple CPU cores invalidate each other's caches when accessing different shards.

type Candidate

type Candidate = types.Candidate

Candidate represents a potential search result during HNSW traversal.

type CapacityPlan

type CapacityPlan struct {
	CurrentVectors   int64     `json:"current_vectors"`
	MaxVectors       int64     `json:"max_vectors"`
	StorageBytes     int64     `json:"storage_bytes"`
	SearchQPS        float64   `json:"search_qps"`
	IngestQPS        float64   `json:"ingest_qps"`
	AvgLatencyMs     float64   `json:"avg_latency_ms"`
	RecommendedScale string    `json:"recommended_scale"`
	Timestamp        time.Time `json:"timestamp"`
}

CapacityPlan represents the current and projected capacity of the vector store.

type CentralityResult

type CentralityResult struct {
	Scores map[uint32]float32
}

CentralityResult holds centrality scores for top nodes.

type ChangeDataCapture

type ChangeDataCapture = cluster.ChangeDataCapture

func NewChangeDataCapture

func NewChangeDataCapture(s cluster.CDCStore, l zerolog.Logger) *ChangeDataCapture

type ChunkAllocator

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

ChunkAllocator manages allocation of large byte slices (chunks). It uses a sync.Pool to recycle chunks and reduce GC pressure.

func NewChunkAllocator

func NewChunkAllocator(numItems, itemSizeBytes int) *ChunkAllocator

NewChunkAllocator creates a new allocator for chunks of dimensions: numItems * itemSizeBytes. NewChunkAllocator creates a new allocator for chunks of dimensions: numItems * itemSizeBytes.

func (*ChunkAllocator) Alloc

func (a *ChunkAllocator) Alloc() []byte

Alloc returns a slice of bytes of the configured size. The slice contents are not guaranteed to be zeroed (dirty).

func (*ChunkAllocator) Free

func (a *ChunkAllocator) Free(b []byte)

Free returns a slice to the pool. The caller must assume the slice is invalid after calling Free.

type ChunkHandler

type ChunkHandler func(ctx context.Context, chunk *FlightDataChunk) error

ChunkHandler is the callback for processing a chunk.

type ChunkWorkerPool

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

ChunkWorkerPool processes chunks from a queue using multiple workers.

func NewChunkWorkerPool

func NewChunkWorkerPool(config ChunkWorkerPoolConfig, queue *FlightDataQueue, handler ChunkHandler) *ChunkWorkerPool

NewChunkWorkerPool creates a new worker pool.

func (*ChunkWorkerPool) IsRunning

func (p *ChunkWorkerPool) IsRunning() bool

IsRunning returns whether pool is running.

func (*ChunkWorkerPool) Start

func (p *ChunkWorkerPool) Start()

Start launches worker goroutines.

func (*ChunkWorkerPool) Stats

Stats returns current statistics.

func (*ChunkWorkerPool) Stop

func (p *ChunkWorkerPool) Stop()

Stop signals workers to stop and waits for completion.

type ChunkWorkerPoolConfig

type ChunkWorkerPoolConfig struct {
	NumWorkers     int           // number of worker goroutines
	ProcessTimeout time.Duration // timeout for processing each chunk
}

ChunkWorkerPoolConfig configures the worker pool.

func DefaultChunkWorkerPoolConfig

func DefaultChunkWorkerPoolConfig() ChunkWorkerPoolConfig

DefaultChunkWorkerPoolConfig returns sensible defaults.

func (ChunkWorkerPoolConfig) Validate

func (c ChunkWorkerPoolConfig) Validate() error

Validate checks config validity.

type ChunkWorkerPoolStats

type ChunkWorkerPoolStats struct {
	Processed int64
	Errors    int64
}

ChunkWorkerPoolStats tracks worker pool operations.

type ChunkedLocationStore

type ChunkedLocationStore = hnswcore.ChunkedLocationStore

ChunkedLocationStore manages vector location mappings in memory-efficient chunks.

type CircuitBreakerRegistry

type CircuitBreakerRegistry = cluster.CircuitBreakerRegistry

type ClockComparison

type ClockComparison int

ClockComparison represents the result of comparing two vector clocks

const (
	// ClockEqual indicates that the two vector clocks are identical.
	ClockEqual ClockComparison = iota
	// ClockBefore indicates that the first clock happened before the second.
	ClockBefore
	// ClockAfter indicates that the first clock happened after the second.
	ClockAfter
	// ClockConcurrent indicates that the clocks are concurrent (conflict).
	ClockConcurrent
)

type CloudCluster

type CloudCluster struct {
	ID               string                    `json:"id"`
	Name             string                    `json:"name"`
	TenantID         string                    `json:"tenant_id"`
	Tier             CloudTier                 `json:"tier"`
	Status           CloudClusterStatus        `json:"status"`
	PrimaryRegion    string                    `json:"primary_region"`
	Nodes            int                       `json:"nodes"`
	ReplicationMode  ReplicationMode           `json:"replication_mode"`
	ReplicationLSN   uint64                    `json:"replication_lsn"`
	SLAPolicy        SLAPolicy                 `json:"sla_policy"`
	Regions          map[string]*RegionReplica `json:"regions"`
	History          []ReplicationEvent        `json:"history,omitempty"`
	UptimeSamples    int64                     `json:"uptime_samples"`
	CompliantSamples int64                     `json:"compliant_samples"`
	LastFailoverAt   *time.Time                `json:"last_failover_at,omitempty"`
	CreatedAt        time.Time                 `json:"created_at"`
	UpdatedAt        time.Time                 `json:"updated_at"`
}

CloudCluster describes a provisioned managed cloud cluster and its regional replicas.

type CloudClusterStatus

type CloudClusterStatus string

CloudClusterStatus represents the lifecycle state of a managed cloud cluster.

const (
	ClusterStatusProvisioning CloudClusterStatus = "provisioning"
	ClusterStatusActive       CloudClusterStatus = "active"
	ClusterStatusScaling      CloudClusterStatus = "scaling"
	ClusterStatusDegraded     CloudClusterStatus = "degraded"
	ClusterStatusFailover     CloudClusterStatus = "failover"
	ClusterStatusDeleting     CloudClusterStatus = "deleting"
)

type CloudControlPlane

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

CloudControlPlane manages provisioned SaaS clusters, multi-region replication, regional failover promotion, and continuous SLA monitoring.

func NewCloudControlPlane

func NewCloudControlPlane(s *VectorStore) *CloudControlPlane

NewCloudControlPlane creates a managed cloud control plane attached to store s.

func (*CloudControlPlane) AddReplicaRegion

func (c *CloudControlPlane) AddReplicaRegion(id, region, endpoint string) (*CloudCluster, error)

AddReplicaRegion attaches a new geographic replica region to a managed cluster.

func (*CloudControlPlane) ApplyIncomingReplication

func (c *CloudControlPlane) ApplyIncomingReplication(ctx context.Context, ev ReplicationEvent) error

ApplyIncomingReplication verifies the SHA-256 event checksum and applies the mutation to the local VectorStore.

func (*CloudControlPlane) CreateCluster

CreateCluster provisions a managed multi-region cloud cluster with tier SLA defaults.

func (*CloudControlPlane) DeleteCluster

func (c *CloudControlPlane) DeleteCluster(id string) error

DeleteCluster decommissions a managed cloud cluster by ID.

func (*CloudControlPlane) EvaluateSLA

func (c *CloudControlPlane) EvaluateSLA(clusterID string, observedP99Ms float64) (*SLAReport, error)

EvaluateSLA evaluates regional health, replication RPO lag, failover RTO, and latency against SLAPolicy.

func (*CloudControlPlane) GetCluster

func (c *CloudControlPlane) GetCluster(id string) (*CloudCluster, bool)

GetCluster returns a deep copy of a cluster by ID.

func (*CloudControlPlane) ListClusters

func (c *CloudControlPlane) ListClusters(tenantID string) []*CloudCluster

ListClusters returns all managed clusters, optionally filtered by tenantID.

func (*CloudControlPlane) MarkRegionHealth

func (c *CloudControlPlane) MarkRegionHealth(id, region string, healthy bool, lagMs int64) error

MarkRegionHealth updates regional health and observed replication lag.

func (*CloudControlPlane) PromoteRegion

func (c *CloudControlPlane) PromoteRegion(_ context.Context, clusterID, targetRegion, _ string) (*CloudCluster, error)

PromoteRegion executes a regional failover promotion to targetRegion (or auto-selects healthiest replica).

func (*CloudControlPlane) ReplicateMutation

func (c *CloudControlPlane) ReplicateMutation(ctx context.Context, clusterID string, ev ReplicationEvent) (int, error)

ReplicateMutation assigns a monotonic LSN, checksums the mutation event, applies it locally if appropriate, and dispatches replication across replica regions respecting sync policy.

func (*CloudControlPlane) ScaleCluster

func (c *CloudControlPlane) ScaleCluster(id string, nodes int, tier CloudTier) (*CloudCluster, error)

ScaleCluster adjusts node count and/or tier on an existing managed cluster.

func (*CloudControlPlane) SelectReadRegion

func (c *CloudControlPlane) SelectReadRegion(clusterID, preferredRegion string) (string, string, error)

SelectReadRegion routes read requests to preferredRegion if healthy, otherwise lowest-lag healthy region.

func (*CloudControlPlane) SetTransport

func (c *CloudControlPlane) SetTransport(t ReplicationTransport)

SetTransport overrides the replication transport (used for custom RPCs or tests).

type CloudTier

type CloudTier string

CloudTier identifies the managed service tier and SLA guarantees for a cloud cluster.

const (
	CloudTierServerless CloudTier = "serverless"
	CloudTierDedicated  CloudTier = "dedicated"
	CloudTierEnterprise CloudTier = "enterprise"
)

type ClusterNodeHealth

type ClusterNodeHealth struct {
	NodeID        string            `json:"node_id"`
	Addr          string            `json:"addr"`
	Zone          string            `json:"zone,omitempty"`
	Healthy       bool              `json:"healthy"`
	LastHeartbeat time.Time         `json:"last_heartbeat"`
	LoadScore     float64           `json:"load_score"` // 0.0 - 1.0+
	Tags          map[string]string `json:"tags,omitempty"`
}

ClusterNodeHealth represents discovery & heartbeat status for a storage node.

type CohereReranker

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

CohereReranker implements a reranking logic using Cohere's API.

func NewCohereReranker

func NewCohereReranker(apiKey, model string) *CohereReranker

NewCohereReranker creates a new CohereReranker with the specified API key and model.

func (*CohereReranker) Close

func (c *CohereReranker) Close() error

Close releases resources associated with the reranker.

func (*CohereReranker) Dimension

func (c *CohereReranker) Dimension() int

Dimension reports zero for the Cohere reranker backend.

func (*CohereReranker) Embed

func (c *CohereReranker) Embed(ctx context.Context, texts []string) ([][]float32, error)

Embed is not supported by the Cohere reranker backend.

func (*CohereReranker) Score

func (c *CohereReranker) Score(ctx context.Context, query string, documents []string) ([]float32, error)

Score returns relevance scores for a query and a list of documents.

type CollectionInfo

type CollectionInfo struct {
	Name        string            `json:"name"`
	Description string            `json:"description"`
	Tags        []string          `json:"tags"`
	Dimension   int               `json:"dimension"`
	VectorCount int               `json:"vector_count"`
	Metadata    map[string]string `json:"metadata"`
	Shards      []string          `json:"shards"`
	CreatedAt   int64             `json:"created_at"`
	UpdatedAt   int64             `json:"updated_at"`
}

CollectionInfo contains metadata and statistics for a search collection.

type CollectionRegistry

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

CollectionRegistry manages the registration and lookup of search collections and routing rules.

func NewCollectionRegistry

func NewCollectionRegistry() *CollectionRegistry

NewCollectionRegistry creates a new empty collection registry.

func (*CollectionRegistry) DeleteCollection

func (cr *CollectionRegistry) DeleteCollection(name string) error

DeleteCollection removes a collection from the registry.

func (*CollectionRegistry) GetCollection

func (cr *CollectionRegistry) GetCollection(name string) (*CollectionInfo, bool)

GetCollection retrieves collection information by name.

func (*CollectionRegistry) GetRoutingRule

func (cr *CollectionRegistry) GetRoutingRule(tag string) (*RoutingRule, bool)

GetRoutingRule retrieves a routing rule by its tag.

func (*CollectionRegistry) ListCollections

func (cr *CollectionRegistry) ListCollections() []*CollectionInfo

ListCollections returns a slice of all registered collections.

func (*CollectionRegistry) ListRoutingRules

func (cr *CollectionRegistry) ListRoutingRules() []*RoutingRule

ListRoutingRules returns all registered routing rules sorted by priority.

func (*CollectionRegistry) RegisterCollection

func (cr *CollectionRegistry) RegisterCollection(info *CollectionInfo) error

RegisterCollection adds a new collection to the registry.

func (*CollectionRegistry) RegisterRoutingRule

func (cr *CollectionRegistry) RegisterRoutingRule(rule *RoutingRule) error

RegisterRoutingRule adds a new routing rule to the registry.

func (*CollectionRegistry) UpdateCollection

func (cr *CollectionRegistry) UpdateCollection(name string, info *CollectionInfo) error

UpdateCollection updates the metadata for an existing collection.

type ColumnInvertedIndex

type ColumnInvertedIndex = index.ColumnInvertedIndex

func NewColumnInvertedIndex

func NewColumnInvertedIndex() *ColumnInvertedIndex

type ColumnMetadata

type ColumnMetadata struct {
	Name      string
	Type      arrow.DataType
	Nullable  bool
	Metadata  arrow.Metadata
	AddedAt   uint64 // version when added
	DroppedAt uint64 // version when dropped (0 = not dropped)
}

ColumnMetadata tracks column lifecycle

type CommunityResult

type CommunityResult struct {
	CommunityCount int
	Labels         map[uint32]uint32 // NodeID -> CommunityID
}

CommunityResult holds the detected communities.

type CompactionConfig

type CompactionConfig struct {
	// Enabled controls whether the background compaction process is active.
	Enabled bool

	// CheckInterval is how often to check for compaction needs.
	CheckInterval time.Duration

	// TargetBatchSize is the desired size of a batch after compaction.
	TargetBatchSize int
	// MinBatchesToCompact is the minimum number of fragmented batches required to trigger compaction.
	MinBatchesToCompact int

	// MinFragmentationRatio is the ratio of deleted nodes to trigger compaction.
	MinFragmentationRatio float64
	// MinDeletedNodes is the minimum number of deleted nodes to trigger compaction.
	MinDeletedNodes int

	// MaxCompactionTime is the maximum allowed duration for a single compaction run.
	MaxCompactionTime time.Duration
	// ParallelWorkers is the number of goroutines to use for compaction.
	ParallelWorkers int

	// MaxMemoryUsageMB is the memory limit for the compaction process.
	MaxMemoryUsageMB int
	// MaxCPUUsage is the CPU limit for the compaction process (0.0 to 1.0).
	MaxCPUUsage float64

	// TriggerThresholds holds named thresholds for triggering compaction.
	TriggerThresholds map[string]int64
	// CompactionStrategy defines the compaction algorithm to use.
	CompactionStrategy string

	// RateLimitBytesPerSec limits the I/O rate of compaction.
	RateLimitBytesPerSec int64
}

CompactionConfig holds configuration for background compaction processes.

func DefaultCompactionConfig

func DefaultCompactionConfig() *CompactionConfig

DefaultCompactionConfig returns a default compaction configuration.

type CompactionWorker

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

CompactionWorker handles background compaction of vector indices.

func NewCompactionWorker

func NewCompactionWorker(store *VectorStore, config *CompactionConfig) *CompactionWorker

NewCompactionWorker creates a new compaction worker.

func (*CompactionWorker) GetStats

func (w *CompactionWorker) GetStats() (total, failed int64, lastTime time.Time, isRunning bool)

GetStats returns compaction worker statistics.

func (*CompactionWorker) IsRunning

func (w *CompactionWorker) IsRunning() bool

IsRunning returns true if the compaction worker is active.

func (*CompactionWorker) Start

func (w *CompactionWorker) Start()

Start begins the compaction worker background process.

func (*CompactionWorker) Stop

func (w *CompactionWorker) Stop()

Stop stops the compaction worker.

func (*CompactionWorker) Trigger

func (w *CompactionWorker) Trigger(dataset string)

Trigger manually triggers a compaction for the specified dataset.

func (*CompactionWorker) TriggerCompaction

func (w *CompactionWorker) TriggerCompaction()

TriggerCompaction signals the worker to start a compaction cycle.

type CompareOp

type CompareOp int

CompareOp represents a comparison operation type

const (
	// CompareOpLess represents the < operator
	CompareOpLess CompareOp = iota
	// CompareOpGreater represents the > operator
	CompareOpGreater
	// CompareOpLessEqual represents the <= operator
	CompareOpLessEqual
	// CompareOpGreaterEqual represents the >= operator
	CompareOpGreaterEqual
)

type ConfigError

type ConfigError struct {
	Component string
	Field     string
	Value     string
	Message   string
	Timestamp time.Time
}

ConfigError represents an error in configuration.

func (*ConfigError) Error

func (e *ConfigError) Error() string

type ConsistencyLevel

type ConsistencyLevel = cluster.ConsistencyLevel

func ParseConsistencyLevel

func ParseConsistencyLevel(s string) (ConsistencyLevel, error)

type ContainsExpr

type ContainsExpr = types.ContainsExpr

ContainsExpr represents a containment comparison filter (e.g., for sets or strings).

type CreateCloudClusterRequest

type CreateCloudClusterRequest struct {
	ID              string            `json:"id,omitempty"`
	Name            string            `json:"name"`
	TenantID        string            `json:"tenant_id,omitempty"`
	Tier            CloudTier         `json:"tier,omitempty"`
	PrimaryRegion   string            `json:"primary_region"`
	ReplicaRegions  map[string]string `json:"replica_regions,omitempty"` // region -> endpoint
	PrimaryEndpoint string            `json:"primary_endpoint,omitempty"`
	Nodes           int               `json:"nodes,omitempty"`
	ReplicationMode ReplicationMode   `json:"replication_mode,omitempty"`
	SLAPolicy       *SLAPolicy        `json:"sla_policy,omitempty"`
}

CreateCloudClusterRequest configures provisioning a managed multi-region cluster.

type CrossEncoderConfig

type CrossEncoderConfig struct {
	ModelPath string  `json:"model_path"`
	BatchSize int     `json:"batch_size"`
	MLWeight  float32 `json:"ml_weight"`
}

CrossEncoderConfig configures batched cross-encoder reranking.

type CrossEncoderReranker

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

CrossEncoderReranker scores (query, candidate document) pairs using an MLBackend (WASM/ONNX) or injectable scoring callback, calibrating logits via sigmoid.

func NewCallbackCrossEncoderReranker

func NewCallbackCrossEncoderReranker(fn func(ctx context.Context, query string, docs []string) ([]float32, error), mlWeight float32) *CrossEncoderReranker

NewCallbackCrossEncoderReranker wraps an explicit pair scoring function (useful for tests/custom models).

func NewCrossEncoderReranker

func NewCrossEncoderReranker(backend MLBackend, cfg CrossEncoderConfig) *CrossEncoderReranker

NewCrossEncoderReranker creates a cross-encoder reranker over a WASM/ONNX MLBackend.

func (*CrossEncoderReranker) Rerank

func (c *CrossEncoderReranker) Rerank(ctx context.Context, query string, results []SearchResult) ([]SearchResult, error)

Rerank scores candidate documents in batches and returns sorted results.

type DLQEntry

type DLQEntry struct {
	Connector string    `json:"connector"`
	Topic     string    `json:"topic"`
	Partition int32     `json:"partition"`
	Offset    int64     `json:"offset"`
	Reason    string    `json:"reason"`
	Payload   string    `json:"payload"`
	Timestamp time.Time `json:"timestamp"`
}

DLQEntry stores a rejected streaming message and reason for inspection or replay.

type DataServer

type DataServer = cluster.DataServer

func NewDataServer

func NewDataServer(store cluster.FlightBackend) *DataServer

type Dataset

type Dataset struct {
	Records *LockFreeSlice[arrow.RecordBatch]

	Version int64
	Index   VectorIndex // Use common interface (Item 3)

	Name   string
	Schema *arrow.Schema
	Topo   *memory.NUMATopology

	PreferredVectorType types.VectorDataType

	// Schema Evolution
	SchemaManager *SchemaEvolutionManager

	// Tombstones map BatchIdx -> Bitset of deleted RowIdxs
	Tombstones map[int]*types.Bitset

	// BatchNodes tracks which NUMA node each RecordBatch is allocated on
	BatchNodes *LockFreeSlice[int]

	// TotalIngestedRows is the running sum of NumRows over Records. It is
	// maintained by appendRecordLocked/replaceRecords and exists so that the
	// global row offset of a newly arriving batch - the base ID hybrid search
	// and text indexing derive from it - can be read without walking every
	// historical batch on every ingest.
	TotalIngestedRows atomic.Int64

	// PrimaryIndex maps ID -> Physical Location (O(1) lookup)
	PrimaryIndex        map[string]RowLocation
	NumericPrimaryIndex map[int64]RowLocation
	Uint64PrimaryIndex  map[uint64]RowLocation

	// Memory tracking
	SizeBytes        atomic.Int64
	IndexMemoryBytes atomic.Int64

	// In-flight Indexing Tracking (Compaction Safety)
	PendingIndexJobs        atomic.Int64
	PendingIngestion        atomic.Int64
	LastIngestionCompletion atomic.Int64 // Unix timestamp of last successful ingestion job completion (for stale-PendingIngestion watchdog)
	ActiveIngestStreams     atomic.Int64 // Number of active DoPut streams for this dataset
	IsReady                 atomic.Bool  // Set to true after first successful ingestion (v0.2.0)
	RegistryPublished       atomic.Bool  // Set to true when advertised to the cluster

	// LWW State
	LWW *TimestampMap

	// Anti-Entropy
	Merkle *MerkleTree

	// Hybrid Search
	InvertedIndexes map[string]*InvertedIndex
	BM25Index       *BM25InvertedIndex
	BM25ArenaIndex  *BM25ArenaIndex // Arena-based BM25 index (optimization)

	// GraphRAG Store
	Graph *GraphStore

	// Product Quantization (Persisted Codebooks)
	PQEncoder *pq.PQEncoder

	// Disk Storage (Phase 6)
	DiskStore *DiskVectorStore

	// Geospatial Index (Quadtree)
	GeoIndex *GeoIndex

	// Metric defines the distance metric for this dataset
	HNSWConfig HNSWSettings
	Metric     DistanceMetric

	ColumnIndex *ColumnInvertedIndex

	StringDicts      map[string]*qry.StringDictionary
	BatchStringCodes map[string]map[int][]uint16

	TemporalIndex *TemporalIndex

	Admission *AdmissionController

	EvictionManager *index.GraphLayerEvictionManager

	Logger zerolog.Logger
	// contains filtered or unexported fields
}

Dataset wraps records with metadata for eviction and tombstones.

func NewDataset

func NewDataset(name string, schema *arrow.Schema) *Dataset

NewDataset creates a new Dataset with the specified name and schema.

func (*Dataset) AddToIndex

func (d *Dataset) AddToIndex(batchIdx, rowIdx int) error

AddToIndex adds a vector to the index AddToIndex adds a vector to the index.

func (*Dataset) Close

func (d *Dataset) Close()

Close releases resources associated with the dataset Close releases resources associated with the dataset.

func (*Dataset) Compact

func (d *Dataset) Compact(fragmentedIdxs, hotIdxs []int) error

Compact performs fragmentation-aware compaction on the dataset. It prioritizes hot batches and squashes fragmented ones. This implementation is asynchronous and non-blocking for the majority of its execution.

func (*Dataset) EvictExpiredRecords

func (d *Dataset) EvictExpiredRecords() []arrow.RecordBatch

EvictExpiredRecords removes TTL-expired records from the dataset using tombstones Returns the number of records evicted

func (*Dataset) ExtractIDs

func (d *Dataset) ExtractIDs(rec arrow.RecordBatch) *IDMap

ExtractIDs extracts primary IDs from a record batch into an IDMap. This can be called outside of dataMu lock to prepare for a bulk update.

func (*Dataset) GenerateFilterBitset

func (d *Dataset) GenerateFilterBitset(filters []qry.Filter, filterExpr FilterExpr) (*types.Bitset, error)

GenerateFilterBitset pre-calculates a bitset of VectorIDs that match the filters.

func (*Dataset) GenerateFilterBitsetLocked

func (d *Dataset) GenerateFilterBitsetLocked(filters []qry.Filter, filterExpr FilterExpr, hash string) (*types.Bitset, error)

GenerateFilterBitsetLocked is the variant that assumes d.dataMu is already held.

func (*Dataset) GetDiskLayoutInfo

func (d *Dataset) GetDiskLayoutInfo() DiskLayoutInfo

GetDiskLayoutInfo returns diagnostic information about batch fragmentation.

func (*Dataset) GetDiskStore

func (d *Dataset) GetDiskStore() any

func (*Dataset) GetEvictionManager

func (d *Dataset) GetEvictionManager() any

func (*Dataset) GetExistingSchema

func (ds *Dataset) GetExistingSchema() *arrow.Schema

GetExistingSchema returns the schema of the first record in the dataset. Uses dataMu RLock for read-only access to Records. Returns nil if dataset has no records.

func (*Dataset) GetFragmentedBatches

func (d *Dataset) GetFragmentedBatches(threshold float64) []int

GetFragmentedBatches returns indices of batches exceeding the fragmentation threshold.

func (*Dataset) GetIndex

func (d *Dataset) GetIndex() any

GetIndex returns the underlying vector index GetIndex returns the underlying vector index.

func (*Dataset) GetLogger

func (d *Dataset) GetLogger() zerolog.Logger

func (*Dataset) GetMetric

func (d *Dataset) GetMetric() DistanceMetric

func (*Dataset) GetName

func (d *Dataset) GetName() string

GetName returns the name of the dataset.

func (*Dataset) GetPQEncoder

func (d *Dataset) GetPQEncoder() *pq.PQEncoder

GetPQEncoder returns the PQ encoder for the dataset GetPQEncoder returns the PQ encoder for the dataset.

func (*Dataset) GetPreferredVectorType

func (d *Dataset) GetPreferredVectorType() types.VectorDataType

GetPreferredVectorType returns the preferred vector data type in a thread-safe manner.

func (*Dataset) GetRecord

func (d *Dataset) GetRecord(idx int) (arrow.RecordBatch, bool)

GetRecord returns the record batch at the given index in a thread-safe manner.

func (*Dataset) GetRecordMetadata

func (d *Dataset) GetRecordMetadata(rec arrow.RecordBatch) *RecordMetadata

GetRecordMetadata retrieves eviction metadata for a record

func (*Dataset) GetRecords

func (d *Dataset) GetRecords() []arrow.RecordBatch

GetRecords returns the records in the dataset GetRecords returns the records in the dataset.

func (*Dataset) GetRecordsCount

func (ds *Dataset) GetRecordsCount() int

GetRecordsCount returns the number of records in the dataset. Uses dataMu RLock for read-only access.

func (*Dataset) GetRowCount

func (d *Dataset) GetRowCount() int64

GetRowCount returns the total number of rows across all record batches in the dataset.

func (*Dataset) GetSchema

func (d *Dataset) GetSchema() *arrow.Schema

GetSchema returns the schema of the dataset GetSchema returns the schema of the dataset.

func (*Dataset) GetShardedIndex

func (d *Dataset) GetShardedIndex() *ShardedHNSW

GetShardedIndex returns the index as a *ShardedHNSW if it is one.

func (*Dataset) GetStringCodes

func (d *Dataset) GetStringCodes(colName string, batchIdx int) ([]uint16, *qry.StringDictionary)

GetStringCodes returns precomputed 16-bit dictionary codes for a string column in a batch.

func (*Dataset) GetTombstones

func (d *Dataset) GetTombstones() map[int]*types.Bitset

GetTombstones returns a copy of the tombstones for the dataset.

func (*Dataset) GetTopo

func (d *Dataset) GetTopo() *memory.NUMATopology

func (*Dataset) GetVectorIndex

func (d *Dataset) GetVectorIndex() VectorIndex

GetVectorIndex returns the current index safely GetVectorIndex returns the current index safely.

func (*Dataset) GetVersion

func (ds *Dataset) GetVersion() int64

GetVersion returns the current schema version. Uses RLock for read-only access.

func (*Dataset) IndexLen

func (d *Dataset) IndexLen() int

IndexLen returns the total number of vectors currently in the dataset's index.

func (*Dataset) IndexStringColumn

func (d *Dataset) IndexStringColumn(colName string, batchIdx int, col *array.String)

IndexStringColumn maps categorical strings to 16-bit integer IDs at ingest for vectorized SIMD filter evaluation.

func (*Dataset) IngestBatch

func (d *Dataset) IngestBatch(batch []DatasetParquetRecord) error

IngestBatch appends a batch of Parquet records to the dataset

func (*Dataset) InitRecordEviction

func (d *Dataset) InitRecordEviction()

InitRecordEviction initializes the per-record eviction manager for a dataset

func (*Dataset) IsSharded

func (d *Dataset) IsSharded() bool

IsSharded returns true if the dataset's vector index is sharded.

func (*Dataset) LastAccess

func (d *Dataset) LastAccess() time.Time

LastAccess returns the time of the last access to the dataset.

func (*Dataset) MigrateToShardedIndex

func (d *Dataset) MigrateToShardedIndex(cfg AutoShardingConfig) error

MigrateToShardedIndex migrates the current index to a sharded index.

func (*Dataset) RLockData

func (d *Dataset) RLockData()

RLockData acquires a read lock on the dataset data RLockData acquires a read lock on the dataset data.

func (*Dataset) RUnlockData

func (d *Dataset) RUnlockData()

RUnlockData releases a read lock on the dataset data RUnlockData releases a read lock on the dataset data.

func (*Dataset) RecordBatchDeletion

func (d *Dataset) RecordBatchDeletion(batchIdx int)

RecordBatchDeletion records a deletion in the specified batch.

func (*Dataset) RegisterRecordWithTTL

func (d *Dataset) RegisterRecordWithTTL(rec arrow.RecordBatch, ttl time.Duration)

RegisterRecordWithTTL registers a record for per-record TTL eviction

func (*Dataset) ResetBatchFragmentation

func (d *Dataset) ResetBatchFragmentation(batchIdx int)

ResetBatchFragmentation resets the tracking for a batch.

func (*Dataset) ResetTombstones

func (d *Dataset) ResetTombstones()

ResetTombstones clears all tombstones in the dataset

func (*Dataset) SearchDataset

func (d *Dataset) SearchDataset(ctx context.Context, queryVec []float32, k int) ([]SearchResult, error)

SearchDataset delegates to the vector index if available SearchDataset delegates to the vector index if available.

func (*Dataset) SearchGraphRAG

func (d *Dataset) SearchGraphRAG(ctx context.Context, queryVec []float32, k int, alpha float32, depth int) ([]SearchResult, error)

SearchGraphRAG performs graph-based RAG search with GPU acceleration fallback.

func (*Dataset) SetAdmission

func (d *Dataset) SetAdmission(admission *AdmissionController)

SetAdmission associates an AdmissionController with the dataset.

func (*Dataset) SetLastAccess

func (d *Dataset) SetLastAccess(t time.Time)

SetLastAccess updates the time of the last access to the dataset.

func (*Dataset) SetPreferredVectorType

func (d *Dataset) SetPreferredVectorType(t types.VectorDataType)

SetPreferredVectorType updates the preferred vector data type in a thread-safe manner.

func (*Dataset) SetTurboQuantBits

func (d *Dataset) SetTurboQuantBits(bits int)

func (*Dataset) TriggerRequantization

func (d *Dataset) TriggerRequantization(targetType types.VectorDataType)

TriggerRequantization starts a background job to change the quantization level of the dataset.

func (*Dataset) TurboQuantBits

func (d *Dataset) TurboQuantBits() int

func (*Dataset) UpdateBatchSize

func (d *Dataset) UpdateBatchSize(batchIdx, size int)

UpdateBatchSize sets the total size of a batch in the fragmentation tracker.

func (*Dataset) UpdatePrimaryIndex

func (d *Dataset) UpdatePrimaryIndex(batchIdx int, idMap *IDMap)

UpdatePrimaryIndex updates the ID mapping for a given batch using a pre-extracted ID map. The caller must hold dataMu lock.

func (*Dataset) UpdatePrimaryIndexAsync

func (d *Dataset) UpdatePrimaryIndexAsync(batchIdx int, idMap *IDMap)

UpdatePrimaryIndexAsync updates the primary index without holding dataMu. Uses a dedicated mutex for serialization.

func (*Dataset) UpgradeSchemaVersion

func (ds *Dataset) UpgradeSchemaVersion()

UpgradeSchemaVersion increments the dataset version. Uses Lock for exclusive write access.

func (*Dataset) VisualizeLayout

func (d *Dataset) VisualizeLayout() string

VisualizeLayout returns a string representation of the fragmentation.

func (*Dataset) WaitForIndexing

func (d *Dataset) WaitForIndexing()

WaitForIndexing blocks until all pending indexing jobs for this dataset are complete.

type DatasetHeader

type DatasetHeader struct {
	Magic      string    `json:"magic"`
	Version    int       `json:"version"`
	Name       string    `json:"name"`
	NumRecords int       `json:"num_records"`
	NumVectors int64     `json:"num_vectors"`
	SchemaJSON string    `json:"schema_json"`
	CreatedAt  time.Time `json:"created_at"`
	ExportedAt time.Time `json:"exported_at"`
	VectorDim  int       `json:"vector_dim"`
	VectorType string    `json:"vector_type"`
}

DatasetHeader contains metadata for an exported dataset.

func (*DatasetHeader) Validate

func (d *DatasetHeader) Validate() error

Validate checks if the header magic and version are supported.

type DatasetIO

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

DatasetIO handles importing and exporting datasets in various formats.

func NewDatasetIO

func NewDatasetIO(vs *VectorStore) *DatasetIO

NewDatasetIO creates a new DatasetIO instance.

func (*DatasetIO) ExportToArrowIPC

func (d *DatasetIO) ExportToArrowIPC(ctx context.Context, name string, backend storage.SnapshotBackend) (int64, error)

ExportToArrowIPC exports a dataset to Arrow IPC format.

func (*DatasetIO) ExportToParquet

func (d *DatasetIO) ExportToParquet(ctx context.Context, name string, backend storage.SnapshotBackend) (int64, error)

ExportToParquet exports a dataset to Parquet format using the provided backend.

func (*DatasetIO) ImportFromArrowIPC

func (d *DatasetIO) ImportFromArrowIPC(ctx context.Context, name string, backend storage.SnapshotBackend, schema *arrow.Schema) (int64, error)

ImportFromArrowIPC imports a dataset from Arrow IPC format.

func (*DatasetIO) ImportFromParquet

func (d *DatasetIO) ImportFromParquet(ctx context.Context, snapshotName, datasetName string, backend storage.SnapshotBackend, schema *arrow.Schema) (int64, error)

ImportFromParquet imports a dataset from Parquet format.

type DatasetInfo

type DatasetInfo struct {
	Name       string   `json:"name"`
	RowCount   int64    `json:"row_count"`
	IndexCount int      `json:"index_count"`
	VectorDim  int      `json:"vector_dim"`
	Tombstones int      `json:"tombstones"`
	Fields     []string `json:"fields,omitempty"`
}

DatasetInfo summarizes dataset dimensions, row counts, and fields for REST/GraphQL inspection.

type DatasetMetadata

type DatasetMetadata struct {
	Name       string
	Schema     *arrow.Schema
	TotalRows  int64
	BatchCount int
}

DatasetMetadata holds lightweight metadata for ListFlights without requiring locks on the main Dataset struct.

type DatasetParquetRecord

type DatasetParquetRecord struct {
	ID        int64  `parquet:"id,optional"`
	Vector    []byte `parquet:"vector,optional"`
	Metadata  []byte `parquet:"metadata,optional"`
	CreatedAt int64  `parquet:"created_at,optional"`
}

DatasetParquetRecord defines the structure of a single record when exporting to Parquet.

type DatasetSchemaSpec

type DatasetSchemaSpec struct {
	Dataset        string                  `json:"dataset"`
	Version        int                     `json:"version"`
	Compatibility  SchemaCompatibilityMode `json:"compatibility"`
	Constraints    []FieldConstraint       `json:"constraints"`
	MetadataTypes  map[string]string       `json:"metadata_types,omitempty"`
	StrictMetadata bool                    `json:"strict_metadata,omitempty"`
	UpdatedAt      time.Time               `json:"updated_at"`
}

DatasetSchemaSpec declares versioned field constraints, metadata typing, and evolution compatibility.

type DeltaSync

type DeltaSync = types.DeltaSync

DeltaSync represents a delta update for index synchronization.

type DimensionError

type DimensionError struct {
	DatasetName  string
	Expected     int
	Got          int
	AutoDetected bool
}

DimensionError is the rich error type returned by DimensionGuard.CheckOrSet on a dimension mismatch. It wraps ErrDimensionLocked so callers can use errors.Is.

func (*DimensionError) Error

func (e *DimensionError) Error() string

func (*DimensionError) Unwrap

func (e *DimensionError) Unwrap() error

Unwrap returns ErrDimensionLocked so errors.Is works correctly.

type DimensionGuard

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

DimensionGuard provides thread-safe auto-detection and locking of a dataset's vector dimension from the first insert.

When created with dim=0 (sentinel), the first call to CheckOrSet will record the dimension from the incoming vector. All subsequent vectors must match.

When created with dim>0 the dimension is locked immediately and CheckOrSet acts as a pure validator.

func NewDimensionGuard

func NewDimensionGuard(datasetName string, explicitDim int) *DimensionGuard

NewDimensionGuard creates a guard for datasetName. If explicitDim > 0 the dimension is pre-locked; pass 0 to enable auto-detection from the first vector.

func (*DimensionGuard) CheckOrSet

func (g *DimensionGuard) CheckOrSet(vec []float32) error

CheckOrSet validates vec against the locked dimension, or, if no dimension is locked yet, sets the dimension from len(vec) and returns nil.

Returns a descriptive *DimensionError (wrapping ErrDimensionLocked) on mismatch. Returns nil on success.

Set LONGBOW_AUTO_EVOLVE=1 to automatically recreate index on dimension change.

func (*DimensionGuard) Dim

func (g *DimensionGuard) Dim() int

Dim returns the currently locked dimension (0 if not yet set).

func (*DimensionGuard) IsAutoDetected

func (g *DimensionGuard) IsAutoDetected() bool

IsAutoDetected returns true if the dimension was inferred from the first vector rather than supplied explicitly at dataset creation.

type DirectBufferReader

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

DirectBufferReader provides zero-copy access to Arrow buffers

func NewDirectBufferReader

func NewDirectBufferReader(alloc memory.Allocator) *DirectBufferReader

NewDirectBufferReader creates a new direct buffer reader

func (*DirectBufferReader) Allocator

func (r *DirectBufferReader) Allocator() memory.Allocator

Allocator returns the underlying allocator

func (*DirectBufferReader) CreateArrayDataFromBuffer

func (r *DirectBufferReader) CreateArrayDataFromBuffer(
	dt arrow.DataType,
	length int,
	dataBuf []byte,
	nullBitmap []byte,
) arrow.ArrayData

CreateArrayDataFromBuffer creates arrow.ArrayData directly from a byte buffer without copying the data. The buffer must remain valid for the lifetime of the returned ArrayData.

func (*DirectBufferReader) GetBufferReference

func (r *DirectBufferReader) GetBufferReference(data []byte) []byte

GetBufferReference returns a reference to the buffer without copying The returned slice points to the same underlying array as the input

type Direction

type Direction int

Direction defines the traversal direction in the graph.

const (
	// DirectionOutgoing traverses from subject to object.
	DirectionOutgoing Direction = iota
	// DirectionIncoming traverses from object to subject.
	DirectionIncoming
	// DirectionBoth traverses in both directions.
	DirectionBoth
)

type DiskIORequest

type DiskIORequest struct {
	Offset    int64
	Size      int
	Priority  int
	BlockID   uint64
	Data      []byte
	Done      chan error
	Timestamp time.Time
}

DiskIORequest represents a single I/O operation request.

type DiskIOScheduler

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

DiskIOScheduler manages background I/O requests with concurrency control and prefetching.

func NewDiskIOScheduler

func NewDiskIOScheduler(maxConcurrent int) *DiskIOScheduler

NewDiskIOScheduler creates a new DiskIOScheduler with the specified concurrency limit.

func (*DiskIOScheduler) ClearPrefetched

func (s *DiskIOScheduler) ClearPrefetched()

ClearPrefetched resets the prefetch tracking state.

func (*DiskIOScheduler) ConfigurePrefetch

func (s *DiskIOScheduler) ConfigurePrefetch(readAheadBlocks, maxPrefetch int)

ConfigurePrefetch updates the prefetching parameters.

func (*DiskIOScheduler) GetPrefetchChannel

func (s *DiskIOScheduler) GetPrefetchChannel() <-chan uint64

GetPrefetchChannel returns the channel for receiving prefetch block IDs.

func (*DiskIOScheduler) GetStats

func (s *DiskIOScheduler) GetStats() DiskIOStats

GetStats returns current I/O performance metrics.

func (*DiskIOScheduler) IsPrefetched

func (s *DiskIOScheduler) IsPrefetched(blockID uint64) bool

IsPrefetched returns true if the block is currently in the prefetch cache.

func (*DiskIOScheduler) MarkPrefetchComplete

func (s *DiskIOScheduler) MarkPrefetchComplete(blockID uint64)

MarkPrefetchComplete flags a block as successfully prefetched.

func (*DiskIOScheduler) RecordAccess

func (s *DiskIOScheduler) RecordAccess(blockID uint64)

RecordAccess logs a block access to update prefetching state.

func (*DiskIOScheduler) Submit

func (s *DiskIOScheduler) Submit(req DiskIORequest) error

Submit adds a request to the scheduler.

func (*DiskIOScheduler) Wait

func (s *DiskIOScheduler) Wait(ctx context.Context) error

Wait blocks until all pending requests are complete or the context is cancelled.

type DiskIOStats

type DiskIOStats struct {
	TotalRequests   int64
	TotalBytes      int64
	AvgLatencyUs    int64
	QueueDepth      int
	ActiveReads     int
	PrefetchHits    int64
	PrefetchMisses  int64
	ReadAheadHits   int64
	SequentialReads int64
	RandomReads     int64
}

DiskIOStats contains performance metrics for the I/O scheduler.

type DiskLayoutInfo

type DiskLayoutInfo struct {
	TotalBatches   int
	TotalRows      int
	TotalDeleted   int
	BatchDetails   []BatchLayoutDetail
	ReadAmpAverage float64
}

DiskLayoutInfo represents the fragmentation status of a dataset's batches.

type DiskVectorStore

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

DiskVectorStore provides append-only persistent storage for vectors with block-level compression.

func NewDiskVectorStore

func NewDiskVectorStore(path string, dim int) (*DiskVectorStore, error)

NewDiskVectorStore creates a new DiskVectorStore with default settings.

func NewDiskVectorStoreWithConfig

func NewDiskVectorStoreWithConfig(path string, dim int, useUring, useDirect bool) (*DiskVectorStore, error)

NewDiskVectorStoreWithConfig creates a new DiskVectorStore with specific I/O settings.

func (*DiskVectorStore) BatchAppend

func (dvs *DiskVectorStore) BatchAppend(vectors [][]float32) (int, error)

BatchAppend appends a list of raw vectors to the disk store.

func (*DiskVectorStore) BatchAppendAny

func (dvs *DiskVectorStore) BatchAppendAny(vectors any) (int, error)

BatchAppendAny appends a slice of typed vector slices to the disk store.

func (*DiskVectorStore) BatchAppendArrow

func (dvs *DiskVectorStore) BatchAppendArrow(rec arrow.RecordBatch, colIdx int) (int, error)

BatchAppendArrow appends vectors directly from an Arrow RecordBatch. This is significantly faster than BatchAppend as it avoids row-by-row extraction.

func (*DiskVectorStore) Close

func (dvs *DiskVectorStore) Close() error

Close releases resources and closes the underlying storage backend.

func (*DiskVectorStore) Compact

func (dvs *DiskVectorStore) Compact() (int, error)

Compact removes deleted markers (currently a simplified implementation).

func (*DiskVectorStore) Delete

func (dvs *DiskVectorStore) Delete(idx int) bool

Delete marks a vector as deleted in the store's tombstone map.

func (*DiskVectorStore) DeleteBatch

func (dvs *DiskVectorStore) DeleteBatch(indices []int) int

DeleteBatch marks multiple vectors as deleted.

func (*DiskVectorStore) EnforcePolicy

func (dvs *DiskVectorStore) EnforcePolicy(ctx context.Context, maxAge time.Duration) (int, error)

EnforcePolicy checks for blocks that exceed the maxAge and offloads them to warm tier.

func (*DiskVectorStore) FetchBlockData

func (dvs *DiskVectorStore) FetchBlockData(bIdx int) ([]byte, error)

FetchBlockData retrieves the decompressed data for the block at bIdx.

func (*DiskVectorStore) GetBatch

func (dvs *DiskVectorStore) GetBatch(indices []int) ([][]float32, error)

GetBatch retrieves multiple vectors by their absolute indices.

func (*DiskVectorStore) GetBatchAny

func (dvs *DiskVectorStore) GetBatchAny(indices []int) (any, error)

GetBatchAny retrieves multiple vectors of any supported type by their absolute indices.

func (*DiskVectorStore) GetBatchInto

func (dvs *DiskVectorStore) GetBatchInto(indices []int, dst [][]float32) error

GetBatchInto retrieves multiple vectors into caller-provided/pooled row buffers dst with zero heap allocations.

func (*DiskVectorStore) GetVector

func (dvs *DiskVectorStore) GetVector(idx int, dst []float32) error

GetVector decodes a single vector directly into dst with zero heap allocations.

func (*DiskVectorStore) GetVectorAnyInto

func (dvs *DiskVectorStore) GetVectorAnyInto(idx int, dst any) error

GetVectorAnyInto decodes a single vector of any supported dtype directly into dst.

func (*DiskVectorStore) GetVectorInto

func (dvs *DiskVectorStore) GetVectorInto(idx int, dst []float32) error

GetVectorInto decodes a single float32 vector directly into dst with zero heap allocations.

func (*DiskVectorStore) IsDeleted

func (dvs *DiskVectorStore) IsDeleted(idx int) bool

IsDeleted checks if a vector has been marked as deleted.

func (*DiskVectorStore) OffloadBlock

func (dvs *DiskVectorStore) OffloadBlock(ctx context.Context, bIdx int) error

OffloadBlock uploads a local block to remote storage and transitions it to TierWarm.

func (*DiskVectorStore) PrefetchBatch

func (dvs *DiskVectorStore) PrefetchBatch(indices []int) error

PrefetchBatch informs the underlying storage backend to prefetch data for blocks containing the specified vector indices.

func (*DiskVectorStore) ScanRows

func (dvs *DiskVectorStore) ScanRows(indices []int, fn func(idx int, row []float32) bool) error

ScanRows traverses the specified indices with zero heap allocations, invoking fn for each decoded vector using a pooled row buffer.

func (*DiskVectorStore) ScanRowsAny

func (dvs *DiskVectorStore) ScanRowsAny(indices []int, fn func(idx int, row any) bool) error

ScanRowsAny traverses the specified indices with zero heap allocations for any vector type.

func (*DiskVectorStore) SetCompression

func (dvs *DiskVectorStore) SetCompression(c string)

SetCompression updates the compression algorithm used for new blocks.

func (*DiskVectorStore) SetTieredConfig

func (dvs *DiskVectorStore) SetTieredConfig(remote storage.RemoteStorage, cacheMB int)

SetTieredConfig configures the remote storage backend and cache size for tiered storage. The same LRU also caches hot (local) blocks under synthetic "hot:" keys.

func (*DiskVectorStore) SetTurboQuant

func (dvs *DiskVectorStore) SetTurboQuant(bits int)

SetTurboQuant configures the store to use TurboQuant encoding.

type DiskWriterUring

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

DiskWriterUring utilizes io_uring for high-performance, asynchronous snapshots.

func NewDiskWriterUring

func NewDiskWriterUring(path string, bufferSize int, maxBuffers int) (*DiskWriterUring, error)

NewDiskWriterUring creates a new DiskWriterUring instance with io_uring support.

func (*DiskWriterUring) Close

func (d *DiskWriterUring) Close() error

Close closes the underlying file and deactivates the writer.

func (*DiskWriterUring) Flush

func (d *DiskWriterUring) Flush()

Flush waits for all pending writes to complete.

func (*DiskWriterUring) SubmitWrite

func (d *DiskWriterUring) SubmitWrite(data []byte, offset int64) (chan error, error)

SubmitWrite handles an asynchronous write using io_uring SQE. It returns a channel that will receive the error (or nil) when the write completes.

type DistanceFunc

type DistanceFunc func(a, b []float32) (float32, error)

DistanceFunc is the function signature for calculating distance between two vectors.

type DistanceMetric

type DistanceMetric = core.DistanceMetric

DistanceMetric defines the distance metric used for vector comparison.

type DoGetPipeline

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

DoGetPipeline implements pipelined processing for DoGet operations. Workers filter batches in parallel while the main thread writes, hiding compute latency behind network I/O.

func NewDoGetPipeline

func NewDoGetPipeline(workers, bufferSize int) *DoGetPipeline

NewDoGetPipeline creates a new pipeline with the specified number of workers. If workers is 0, defaults to runtime.NumCPU(). If bufferSize is 0, defaults to workers * 2.

func (*DoGetPipeline) NumWorkers

func (p *DoGetPipeline) NumWorkers() int

NumWorkers returns the number of worker goroutines

func (*DoGetPipeline) Process

func (p *DoGetPipeline) Process(
	ctx context.Context,
	batches []arrow.RecordBatch,
	filterFn FilterFunc,
) (results <-chan PipelineResult, errs <-chan error)

Process starts pipelined processing of batches. Returns a channel of ordered results and an error channel. Results are guaranteed to arrive in the same order as input batches.

func (*DoGetPipeline) ProcessRecords

func (p *DoGetPipeline) ProcessRecords(
	ctx context.Context,
	records []arrow.RecordBatch,
	tombstones map[int]*types.Bitset,
	filters []query.Filter,
	evaluator any,
) <-chan PipelineStage

ProcessRecords is the compatibility method for store.go

func (*DoGetPipeline) Stats

func (p *DoGetPipeline) Stats() PipelineStats

Stats returns current pipeline statistics

func (*DoGetPipeline) Stop

func (p *DoGetPipeline) Stop()

Stop terminates the pipeline and stops all active processing.

type DoGetPipelineConfig

type DoGetPipelineConfig struct {
	Workers    int // Number of parallel workers
	BufferSize int // Channel buffer size
	Threshold  int // Minimum batches to trigger pipeline (vs serial)
}

DoGetPipelineConfig holds configuration for DoGet pipeline processing

func DefaultDoGetPipelineConfig

func DefaultDoGetPipelineConfig() DoGetPipelineConfig

DefaultDoGetPipelineConfig returns sensible defaults

type DoGetPipelinePool

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

DoGetPipelinePool manages a pool of reusable pipelines

func NewDoGetPipelinePool

func NewDoGetPipelinePool(workers, bufferSize int) *DoGetPipelinePool

NewDoGetPipelinePool creates a pool of pipelines

func (*DoGetPipelinePool) Get

func (pp *DoGetPipelinePool) Get() *DoGetPipeline

Get retrieves a pipeline from the pool

func (*DoGetPipelinePool) Put

func (pp *DoGetPipelinePool) Put(p *DoGetPipeline)

Put returns a pipeline to the pool

type Edge

type Edge struct {
	Subject   VectorID
	Predicate string
	Object    VectorID
	Weight    float32
}

Edge represents a weighted relationship between a subject and an object.

type ElasticScalingPolicy

type ElasticScalingPolicy struct {
	Enabled              bool    `json:"enabled"`
	MinShards            int     `json:"min_shards"`
	MaxShards            int     `json:"max_shards"`
	SplitVectorThreshold int64   `json:"split_vector_threshold"`
	SplitQPSThreshold    float64 `json:"split_qps_threshold"`
	MergeVectorThreshold int64   `json:"merge_vector_threshold"`
	HeartbeatTimeoutSec  int     `json:"heartbeat_timeout_sec"`
	CooldownSec          int     `json:"cooldown_sec"`
}

ElasticScalingPolicy controls automatic shard splits, merges, and cluster rebalancing.

type ElasticShardingController

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

ElasticShardingController implements dynamic shard split/merge, live key-range data migration, node discovery/health checks, automatic replica failover, and auto-scaling.

func NewElasticShardingController

func NewElasticShardingController(s *VectorStore) *ElasticShardingController

NewElasticShardingController creates an elastic sharding controller with production defaults.

func (*ElasticShardingController) CheckHealthAndFailover

func (c *ElasticShardingController) CheckHealthAndFailover(now time.Time) []ScaleDecision

CheckHealthAndFailover marks timed-out nodes unhealthy and promotes replicas for orphaned shards.

func (*ElasticShardingController) EnsureDatasetShards

func (c *ElasticShardingController) EnsureDatasetShards(dataset, primaryNode string, replicas []string) []*ShardDescriptor

EnsureDatasetShards initializes a single full-ring shard for dataset if none exist.

func (*ElasticShardingController) MergeShards

func (c *ElasticShardingController) MergeShards(dataset, leftID, rightID string) (ShardDescriptor, int, error)

MergeShards merges two adjacent shards back into one contiguous range cleanly.

func (*ElasticShardingController) Policy

Policy returns the active scaling policy.

func (*ElasticShardingController) RebalanceShards

func (c *ElasticShardingController) RebalanceShards(dataset string) ([]MigrationTask, error)

RebalanceShards balances shard primary owners evenly across healthy nodes.

func (*ElasticShardingController) ReconcileAutoScale

func (c *ElasticShardingController) ReconcileAutoScale(dataset string, bypassCooldown bool) ([]ScaleDecision, error)

ReconcileAutoScale inspects per-shard QPS & vector volume and applies split/merge decisions.

func (*ElasticShardingController) RecordKeyPlacement

func (c *ElasticShardingController) RecordKeyPlacement(dataset, key string, bytes int64) (ShardDescriptor, error)

AssignVectorCount increments vector & QPS stats on the owning shard of a key.

func (*ElasticShardingController) RegisterNode

func (c *ElasticShardingController) RegisterNode(node ClusterNodeHealth)

RegisterNode records or refreshes node membership and heartbeat.

func (*ElasticShardingController) RouteKey

func (c *ElasticShardingController) RouteKey(dataset, key string) (ShardDescriptor, bool)

RouteKey maps a vector key cleanly onto its owning ShardDescriptor using FNV-1a token hashing.

func (*ElasticShardingController) SetPolicy

SetPolicy updates the scaling policy.

func (*ElasticShardingController) SplitShard

func (c *ElasticShardingController) SplitShard(dataset, shardID string) (ShardDescriptor, ShardDescriptor, int, error)

SplitShard online splits one shard's [StartToken, EndToken] range into two adjacent shards, redistributing tracked keys proportionally and selecting a replica/target node for the right half.

func (*ElasticShardingController) TopologySnapshot

func (c *ElasticShardingController) TopologySnapshot() map[string]any

TopologySnapshot returns nodes, dataset shard maps, and recent migrations.

type EmbeddingCache

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

EmbeddingCache provides a simple LRU-like cache for embeddings.

func NewEmbeddingCache

func NewEmbeddingCache(ttl time.Duration, maxEntries int) *EmbeddingCache

NewEmbeddingCache creates a new EmbeddingCache with the given TTL and capacity.

func (*EmbeddingCache) Get

func (c *EmbeddingCache) Get(key string) ([]float32, bool)

Get retrieves an embedding from the cache if it exists and is not expired.

func (*EmbeddingCache) Set

func (c *EmbeddingCache) Set(key string, value []float32)

Set adds or updates an embedding in the cache.

func (*EmbeddingCache) Stats

func (c *EmbeddingCache) Stats() (hits, misses int64, size int)

Stats returns the cache hit/miss statistics and current size.

type EmbeddingConfig

type EmbeddingConfig struct {
	ModelPath    string
	ModelType    string
	Dimension    int
	BatchSize    int
	Device       string
	APIKey       string
	Provider     string
	ModelName    string
	ModelVersion string
	MaxRetries   int
	CacheEnabled bool
	CacheTTL     time.Duration
}

EmbeddingConfig holds configuration for an embedding generator.

type EmbeddingGenerator

type EmbeddingGenerator interface {
	Generate(ctx context.Context, texts []string) ([][]float32, error)
	GenerateSingle(ctx context.Context, text string) ([]float32, error)
	Dimension() int
	Close() error
}

EmbeddingGenerator defines the interface for generating vector embeddings from text.

func NewCohereEmbedding

func NewCohereEmbedding(config EmbeddingConfig) (EmbeddingGenerator, error)

NewCohereEmbedding creates a Cohere embedding generator.

func NewEmbeddingGenerator

func NewEmbeddingGenerator(config EmbeddingConfig) (EmbeddingGenerator, error)

NewEmbeddingGenerator creates an embedding generator based on the provided configuration.

func NewHuggingFaceEmbedding

func NewHuggingFaceEmbedding(config EmbeddingConfig) (EmbeddingGenerator, error)

NewHuggingFaceEmbedding creates a HuggingFace embedding generator.

func NewLocalEmbeddingGenerator

func NewLocalEmbeddingGenerator(config EmbeddingConfig) (EmbeddingGenerator, error)

NewLocalEmbeddingGenerator creates a local embedding generator using ONNX or WASM.

func NewOpenAIEmbedding

func NewOpenAIEmbedding(config EmbeddingConfig) (EmbeddingGenerator, error)

NewOpenAIEmbedding creates an OpenAI embedding generator.

type EmbeddingLogger

type EmbeddingLogger interface {
	Debug(msg string, keysAndValues ...interface{})
	Info(msg string, keysAndValues ...interface{})
	Error(msg string, keysAndValues ...interface{})
}

EmbeddingLogger defines the logging interface used by embedding generators.

type EmbeddingModel

type EmbeddingModel interface {
	Inference(input []string) ([][]float32, error)
	Close() error
}

EmbeddingModel defines the interface for local model inference.

type EmbeddingModelRegistry

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

EmbeddingModelRegistry manages available embedding models and their generators.

func NewEmbeddingModelRegistry

func NewEmbeddingModelRegistry(cacheTTL time.Duration, maxCacheEntries int) *EmbeddingModelRegistry

NewEmbeddingModelRegistry creates a new model registry.

func (*EmbeddingModelRegistry) GetCache

func (r *EmbeddingModelRegistry) GetCache() *EmbeddingCache

GetCache returns the shared embedding cache.

func (*EmbeddingModelRegistry) GetDefaultModel

func (r *EmbeddingModelRegistry) GetDefaultModel(provider string) (ModelVersion, bool)

GetDefaultModel returns the default model version for a provider.

func (*EmbeddingModelRegistry) GetGenerator

func (r *EmbeddingModelRegistry) GetGenerator(key string) (EmbeddingGenerator, bool)

GetGenerator retrieves an active generator for a model key.

func (*EmbeddingModelRegistry) GetModel

func (r *EmbeddingModelRegistry) GetModel(provider, modelName string) (ModelVersion, bool)

GetModel retrieves a model version from the registry.

func (*EmbeddingModelRegistry) ListAllModels

func (r *EmbeddingModelRegistry) ListAllModels() map[string][]ModelVersion

ListAllModels returns all registered model versions grouped by provider.

func (*EmbeddingModelRegistry) ListModels

func (r *EmbeddingModelRegistry) ListModels(provider string) []ModelVersion

ListModels returns all model versions for a given provider.

func (*EmbeddingModelRegistry) RegisterModel

func (r *EmbeddingModelRegistry) RegisterModel(provider, modelName string, version ModelVersion) error

RegisterModel adds a model version to the registry.

func (*EmbeddingModelRegistry) SetDefaultModel

func (r *EmbeddingModelRegistry) SetDefaultModel(provider, modelName string) error

SetDefaultModel marks a specific model as the default for its provider.

func (*EmbeddingModelRegistry) SetGenerator

func (r *EmbeddingModelRegistry) SetGenerator(key string, gen EmbeddingGenerator)

SetGenerator registers an active generator for a model key.

func (*EmbeddingModelRegistry) UpdateModelVersion

func (r *EmbeddingModelRegistry) UpdateModelVersion(provider, modelName string, version ModelVersion) error

UpdateModelVersion updates an existing model version's metadata.

type EqExpr

type EqExpr = types.EqExpr

EqExpr represents an equality comparison filter.

type ErrNeighborSelectionLengthMismatch

type ErrNeighborSelectionLengthMismatch struct {
	DistancesLen int
	IDsLen       int
}

ErrNeighborSelectionLengthMismatch is the error type for mismatched input lengths.

func (*ErrNeighborSelectionLengthMismatch) Error

type ErrNotFound

type ErrNotFound = core.ErrNotFound

ErrNotFound indicates a requested resource does not exist.

type ErrUnsupportedCodeType

type ErrUnsupportedCodeType struct {
	CodeType      string
	ExpectedTypes []string
}

ErrUnsupportedCodeType is returned when a code type is not supported

func (*ErrUnsupportedCodeType) Error

func (e *ErrUnsupportedCodeType) Error() string

type ErrUnsupportedVectorType

type ErrUnsupportedVectorType struct {
	InputType     string
	ExpectedTypes []string
}

ErrUnsupportedVectorType is returned when a vector type is not supported

func (*ErrUnsupportedVectorType) Error

func (e *ErrUnsupportedVectorType) Error() string

type EvalQueryCase

type EvalQueryCase struct {
	Query      string
	Candidates []SearchResult
	Relevant   map[core.VectorID]float64 // graded relevance e.g. 1.0, 2.0
}

EvalQueryCase represents a labeled evaluation query for reranker quality testing.

type ExplainSearchRequest

type ExplainSearchRequest struct {
	Dataset    string    `json:"dataset"`
	Vector     []float32 `json:"vector"`
	TextQuery  string    `json:"text_query,omitempty"`
	K          int       `json:"k"`
	Alpha      float64   `json:"alpha"`
	GraphAlpha float64   `json:"graph_alpha,omitempty"`
	MaxHops    int       `json:"max_hops,omitempty"`
}

ExplainSearchRequest configures ExplainSearch and DebugSearchPath Flight actions.

type ExplainedCandidate

type ExplainedCandidate struct {
	ID         core.VectorID     `json:"id"`
	UserID     string            `json:"user_id,omitempty"`
	Distance   float32           `json:"distance"`
	Breakdown  ScoreBreakdown    `json:"breakdown"`
	Provenance *VectorProvenance `json:"provenance,omitempty"`
}

ExplainedCandidate augments a ranked result with score components and tracked provenance.

type FacetCount

type FacetCount struct {
	Value string `json:"value"`
	Count int    `json:"count"`
}

FacetCount holds one category bucket frequency.

type FeatureSuite

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

FeatureSuite holds lazily-initialized enterprise and extended feature managers attached to a VectorStore instance.

type FederatedBenchmark

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

FederatedBenchmark provides tools for benchmarking federated search performance.

func NewFederatedBenchmark

func NewFederatedBenchmark(router *FederatedQueryRouter) *FederatedBenchmark

NewFederatedBenchmark creates a new benchmark tool for the given router.

func (*FederatedBenchmark) CompareSingleVsFederated

func (fb *FederatedBenchmark) CompareSingleVsFederated(ctx context.Context, collections []string, queries [][]float32, k int) (map[string]*BenchmarkResult, error)

CompareSingleVsFederated runs benchmarks for both single and federated search for comparison.

func (*FederatedBenchmark) RunFederated

func (fb *FederatedBenchmark) RunFederated(ctx context.Context, collections []string, queries [][]float32, k int) (*BenchmarkResult, error)

RunFederated benchmarks search performance across multiple collections.

func (*FederatedBenchmark) RunSingleCollection

func (fb *FederatedBenchmark) RunSingleCollection(ctx context.Context, collection string, queries [][]float32, k int) (*BenchmarkResult, error)

RunSingleCollection benchmarks search performance for a single collection.

type FederatedQueryRouter

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

FederatedQueryRouter routes search queries to multiple collections and merges results.

func NewFederatedQueryRouter

func NewFederatedQueryRouter() *FederatedQueryRouter

NewFederatedQueryRouter creates a new federated query router with default settings.

func (*FederatedQueryRouter) GetCollectionCount

func (fqr *FederatedQueryRouter) GetCollectionCount() int

GetCollectionCount returns the number of registered collections.

func (*FederatedQueryRouter) GetRRFFactor

func (fqr *FederatedQueryRouter) GetRRFFactor() float64

GetRRFFactor returns the current Reciprocal Rank Fusion factor.

func (*FederatedQueryRouter) ListCollections

func (fqr *FederatedQueryRouter) ListCollections() []*CollectionInfo

ListCollections returns metadata for all registered federated collections.

func (*FederatedQueryRouter) RegisterCollection

func (fqr *FederatedQueryRouter) RegisterCollection(name string, searcher VectorSearcher, info *CollectionInfo) error

RegisterCollection registers a searcher and its metadata with the router.

func (*FederatedQueryRouter) RegisterRoutingRule

func (fqr *FederatedQueryRouter) RegisterRoutingRule(rule *RoutingRule) error

RegisterRoutingRule registers a tag-to-collection routing rule with the router.

func (*FederatedQueryRouter) Search

func (fqr *FederatedQueryRouter) Search(ctx context.Context, query []float32, collections []string, k int) ([]lbtypes.SearchResult, error)

Search performs a parallel search across specified collections and merges results using the default RRF k.

func (*FederatedQueryRouter) SearchByTags

func (fqr *FederatedQueryRouter) SearchByTags(ctx context.Context, query []float32, tags []string, k int) ([]lbtypes.SearchResult, error)

SearchByTags routes a search query to collections matching the specified tags.

func (*FederatedQueryRouter) SearchWithRRFK

func (fqr *FederatedQueryRouter) SearchWithRRFK(ctx context.Context, query []float32, collections []string, k, rrfK int) ([]lbtypes.SearchResult, error)

SearchWithRRFK performs a parallel search across specified collections and merges results using RRF with rrfK.

func (*FederatedQueryRouter) SetRRFFactor

func (fqr *FederatedQueryRouter) SetRRFFactor(rraf float64)

SetRRFFactor updates the Reciprocal Rank Fusion factor.

func (*FederatedQueryRouter) UpsertCollection

func (fqr *FederatedQueryRouter) UpsertCollection(name string, searcher VectorSearcher, info *CollectionInfo)

UpsertCollection registers or refreshes a collection searcher and metadata idempotently.

type FederatedSearchRequest

type FederatedSearchRequest = core.FederatedSearchRequest

FederatedSearchRequest defines a request for cross-collection federated search.

type FieldConstraint

type FieldConstraint struct {
	Field     string   `json:"field"`
	Type      string   `json:"type,omitempty"` // "string", "number", "int", "bool", "vector"
	NotNull   bool     `json:"not_null,omitempty"`
	Unique    bool     `json:"unique,omitempty"`
	Min       *float64 `json:"min,omitempty"`
	Max       *float64 `json:"max,omitempty"`
	Regex     string   `json:"regex,omitempty"`
	Enum      []string `json:"enum,omitempty"`
	VectorDim int      `json:"vector_dim,omitempty"`
}

FieldConstraint defines validation & constraint rules for an Arrow column or metadata key.

type FilterExpr

type FilterExpr = types.FilterExpr

FilterExpr is the AST node interface for evaluating complex boolean nesting conditions.

func ParseFilter

func ParseFilter(node map[string]interface{}) FilterExpr

ParseFilter converts a generic JSON map structural AST into a typed FilterExpr recursively. Ex: {"$and": [{"$eq": {"status": "active"}}, {"$contains": {"role": "admin"}}]}

type FilterFunc

type FilterFunc func(ctx context.Context, rec arrow.RecordBatch) (arrow.RecordBatch, error)

FilterFunc is the signature for batch filtering functions

type FixedHeap

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

FixedHeap is a fixed-capacity min-heap for managing search candidates. It avoids allocations by using a pre-allocated array.

func NewFixedHeap

func NewFixedHeap(capacity int) *FixedHeap

NewFixedHeap creates a new fixed-capacity heap.

func (*FixedHeap) Clear

func (h *FixedHeap) Clear()

Clear resets the heap to empty.

func (*FixedHeap) Grow

func (h *FixedHeap) Grow(newCap int)

Grow ensures the heap has at least newCap capacity.

func (*FixedHeap) Items

func (h *FixedHeap) Items() []Candidate

Items returns a slice of all items in the heap (not sorted).

func (*FixedHeap) Len

func (h *FixedHeap) Len() int

Len returns the current number of elements in the heap.

func (*FixedHeap) Peek

func (h *FixedHeap) Peek() (Candidate, bool)

Peek returns the minimum element without removing it.

func (*FixedHeap) Pop

func (h *FixedHeap) Pop() (Candidate, bool)

Pop removes and returns the minimum element (smallest distance).

func (*FixedHeap) Push

func (h *FixedHeap) Push(c Candidate) bool

Push adds a candidate to the heap. Returns false if heap is full.

type FlightClientPool

type FlightClientPool = cluster.FlightClientPool

func NewFlightClientPool

func NewFlightClientPool(cfg FlightClientPoolConfig) *FlightClientPool

type FlightClientPoolConfig

type FlightClientPoolConfig = cluster.FlightClientPoolConfig

func DefaultFlightClientPoolConfig

func DefaultFlightClientPoolConfig() FlightClientPoolConfig

type FlightCompatibilityLayer

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

FlightCompatibilityLayer provides compatibility between current implementation and future v23 APIs.

func NewFlightCompatibilityLayer

func NewFlightCompatibilityLayer() *FlightCompatibilityLayer

NewFlightCompatibilityLayer creates a new compatibility layer

func (*FlightCompatibilityLayer) Close

func (fcl *FlightCompatibilityLayer) Close() error

Close closes the compatibility layer and underlying client

func (*FlightCompatibilityLayer) EnhancedDoAction

EnhancedDoAction provides DoAction with proper error handling for v23 migration

func (*FlightCompatibilityLayer) EnhancedDoGet

EnhancedDoGet provides DoGet with proper error handling for v23 migration

func (*FlightCompatibilityLayer) EnhancedDoPut

EnhancedDoPut provides DoPut with proper error handling for v23 migration

func (*FlightCompatibilityLayer) EnhancedGetFlightInfo

func (fcl *FlightCompatibilityLayer) EnhancedGetFlightInfo(ctx context.Context, desc *flight.FlightDescriptor) (*flight.FlightInfo, error)

EnhancedGetFlightInfo provides enhanced flight info retrieval

func (*FlightCompatibilityLayer) EnhancedGetSchema

func (fcl *FlightCompatibilityLayer) EnhancedGetSchema(ctx context.Context, desc *flight.FlightDescriptor) (*arrow.Schema, error)

EnhancedGetSchema provides enhanced schema retrieval

func (*FlightCompatibilityLayer) EnhancedListActions

EnhancedListActions provides enhanced action listing

func (*FlightCompatibilityLayer) EnhancedListFlights

EnhancedListFlights provides enhanced flight listing

func (*FlightCompatibilityLayer) GetAPIVersion

func (fcl *FlightCompatibilityLayer) GetAPIVersion() string

GetAPIVersion returns current API version

func (*FlightCompatibilityLayer) IsV23Compatible

func (fcl *FlightCompatibilityLayer) IsV23Compatible() bool

IsV23Compatible checks if the current implementation is v23-ready

func (*FlightCompatibilityLayer) NewClient

func (fcl *FlightCompatibilityLayer) NewClient(endpoint string, opts ...interface{}) (flight.Client, error)

NewClient creates a new flight client with proper options

func (*FlightCompatibilityLayer) PrepareForV23

func (fcl *FlightCompatibilityLayer) PrepareForV23() error

PrepareForV23 prepares the compatibility layer for v23 migration

func (*FlightCompatibilityLayer) SetClient

func (fcl *FlightCompatibilityLayer) SetClient(client flight.Client)

SetClient sets the underlying flight client

type FlightDataChunk

type FlightDataChunk struct {
	DatasetName string
	Record      arrow.RecordBatch
	ReceivedAt  time.Time
}

FlightDataChunk represents a received Arrow RecordBatch with metadata.

type FlightDataQueue

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

FlightDataQueue is a buffered channel wrapper for decoupling receive from processing.

func NewFlightDataQueue

func NewFlightDataQueue(config FlightDataQueueConfig) *FlightDataQueue

NewFlightDataQueue creates a new queue.

func (*FlightDataQueue) Close

func (q *FlightDataQueue) Close()

Close closes the queue, preventing new enqueues.

func (*FlightDataQueue) Dequeue

func (q *FlightDataQueue) Dequeue(ctx context.Context) (*FlightDataChunk, bool)

Dequeue retrieves the next chunk, respecting context cancellation. Returns (nil, false) if queue is closed and empty, or if the context is cancelled/timed out. Blocks until a chunk is available, the context expires, or the queue is closed.

func (*FlightDataQueue) IsClosed

func (q *FlightDataQueue) IsClosed() bool

IsClosed returns whether queue is closed.

func (*FlightDataQueue) Len

func (q *FlightDataQueue) Len() int

Len returns current queue length.

func (*FlightDataQueue) Stats

Stats returns current statistics.

func (*FlightDataQueue) TryEnqueue

func (q *FlightDataQueue) TryEnqueue(chunk *FlightDataChunk) bool

TryEnqueue attempts to enqueue a chunk without blocking indefinitely. Returns false if queue is full or closed.

type FlightDataQueueConfig

type FlightDataQueueConfig struct {
	QueueSize      int           // buffered channel capacity
	EnqueueTimeout time.Duration // timeout for TryEnqueue
	DrainTimeout   time.Duration // timeout for draining on close
}

FlightDataQueueConfig configures the flight data queue.

func DefaultFlightDataQueueConfig

func DefaultFlightDataQueueConfig() FlightDataQueueConfig

DefaultFlightDataQueueConfig returns sensible defaults.

func (FlightDataQueueConfig) Validate

func (c FlightDataQueueConfig) Validate() error

Validate checks config validity.

type FlightDataQueueStats

type FlightDataQueueStats struct {
	Enqueued int64
	Dequeued int64
	Dropped  int64
}

FlightDataQueueStats tracks queue operations.

type FlightReaderBufferRetainer

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

FlightReaderBufferRetainer manages buffer lifecycles for zero-copy operations

func NewFlightReaderBufferRetainer

func NewFlightReaderBufferRetainer(maxBuffers int) *FlightReaderBufferRetainer

NewFlightReaderBufferRetainer creates a new buffer retainer

func (*FlightReaderBufferRetainer) GetBuffer

func (r *FlightReaderBufferRetainer) GetBuffer(handle uint64) []byte

GetBuffer retrieves a retained buffer by handle

func (*FlightReaderBufferRetainer) MaxBuffers

func (r *FlightReaderBufferRetainer) MaxBuffers() int

MaxBuffers returns the maximum number of retained buffers

func (*FlightReaderBufferRetainer) ReleaseBuffer

func (r *FlightReaderBufferRetainer) ReleaseBuffer(handle uint64) bool

ReleaseBuffer releases a retained buffer

func (*FlightReaderBufferRetainer) RetainBuffer

func (r *FlightReaderBufferRetainer) RetainBuffer(buf []byte) uint64

RetainBuffer retains a buffer and returns a handle for later retrieval

func (*FlightReaderBufferRetainer) Stats

Stats returns current buffer retainer statistics

type Float16Type

type Float16Type interface{}

Float16Type identifies float16 vector type

type Float32Type

type Float32Type interface{}

Float32Type identifies float32 vector type

type FlowControlPolicy

type FlowControlPolicy int

FlowControlPolicy defines the strategy for HTTP/2 flow control window management.

const (
	// PolicyDefault uses 4MB window sizes.
	PolicyDefault FlowControlPolicy = iota // 4MB windows
	// PolicyHighBandwidth uses 16MB window sizes (recommended for 10GbE+ networks).
	PolicyHighBandwidth
	// PolicyAuto is reserved for future auto-tuning functionality.
	PolicyAuto
)

type FragmentationTracker

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

FragmentationTracker tracks tombstone density per batch for fragmentation-aware compaction

func NewFragmentationTracker

func NewFragmentationTracker() *FragmentationTracker

NewFragmentationTracker creates a new fragmentation tracker

func (*FragmentationTracker) GetDensity

func (f *FragmentationTracker) GetDensity(batchIdx int) float64

GetDensity returns the tombstone density for a batch (0.0 to 1.0)

func (*FragmentationTracker) GetFragmentedBatches

func (f *FragmentationTracker) GetFragmentedBatches(threshold float64) []int

GetFragmentedBatches returns batch indices where density >= threshold or read amplification is high

func (*FragmentationTracker) GetHotBatches

func (f *FragmentationTracker) GetHotBatches(minHits int64) []int

GetHotBatches returns batch indices that are frequently accessed

func (*FragmentationTracker) RecordAccess

func (f *FragmentationTracker) RecordAccess(batchIdx int)

RecordAccess records an access (hit) for vectors in this batch

func (*FragmentationTracker) RecordDeletion

func (f *FragmentationTracker) RecordDeletion(batchIdx int)

RecordDeletion records a deletion in the specified batch

func (*FragmentationTracker) Reset

func (f *FragmentationTracker) Reset(batchIdx int)

Reset resets the fragmentation tracking for a batch (e.g., after compaction)

func (*FragmentationTracker) ResetAll

func (f *FragmentationTracker) ResetAll()

ResetAll resets tracking for all batches

func (*FragmentationTracker) SetBatchSize

func (f *FragmentationTracker) SetBatchSize(batchIdx, size int)

SetBatchSize sets the total size of a batch

func (*FragmentationTracker) SetDatasetName

func (f *FragmentationTracker) SetDatasetName(name string)

SetDatasetName sets the dataset name for metrics

type FusionMode

type FusionMode int

FusionMode defines how to combine dense and sparse results

const (
	// FusionModeRRF uses Reciprocal Rank Fusion to combine results.
	FusionModeRRF FusionMode = iota
	// FusionModeLinear uses a linear weighted combination of scores.
	FusionModeLinear
	// FusionModeCascade uses cascade-style filtering (exact -> keyword -> vector).
	FusionModeCascade
)

type GRPCConfig

type GRPCConfig struct {
	// Keepalive parameters
	KeepAliveTime                time.Duration // Time between keepalive pings (server sends to client)
	KeepAliveTimeout             time.Duration // Timeout for keepalive ping acknowledgement
	KeepAliveMinTime             time.Duration // Minimum time client should wait between pings
	KeepAlivePermitWithoutStream bool          // Allow keepalive pings when no active streams

	// Concurrent streams limit
	MaxConcurrentStreams uint32 // Maximum concurrent streams per connection

	// HTTP/2 flow control window sizes
	InitialWindowSize     int32 // Initial window size for a stream
	InitialConnWindowSize int32 // Initial window size for a connection

	// Policy selection for flow control
	Policy FlowControlPolicy

	// Message size limits
	MaxRecvMsgSize int // Maximum message size the server can receive
	MaxSendMsgSize int // Maximum message size the server can send

	// Compression settings - enables gzip compression for 50-70% bandwidth reduction
	CompressionEnabled bool // Enable gzip compression for streaming data

	// Socket-level buffer sizes
	WriteBufferSize int // Size of the socket write buffer
	ReadBufferSize  int // Size of the socket read buffer
}

GRPCConfig holds all gRPC server/client tuning parameters for optimal throughput. Configuring these parameters can yield 5-10% improvement in sustained throughput.

func DefaultGRPCConfig

func DefaultGRPCConfig() GRPCConfig

DefaultGRPCConfig returns a GRPCConfig with sensible defaults optimized for throughput. These defaults are tuned for vector database workloads with large message payloads.

func (*GRPCConfig) ApplyPolicy

func (c *GRPCConfig) ApplyPolicy()

ApplyPolicy updates window sizes based on the selected FlowControlPolicy.

func (GRPCConfig) BuildClientOptions

func (c GRPCConfig) BuildClientOptions() []grpc.DialOption

BuildClientOptions returns a slice of grpc.DialOption configured from this GRPCConfig. These options optimize gRPC client performance to match server settings. When CompressionEnabled is true, all calls will use gzip compression for 50-70% bandwidth reduction on vector data.

func (GRPCConfig) BuildServerOptions

func (c GRPCConfig) BuildServerOptions() []grpc.ServerOption

BuildServerOptions returns a slice of grpc.ServerOption configured from this GRPCConfig. These options optimize gRPC server performance for sustained throughput. Note: Server-side compression is automatically available when the gzip encoding package is imported - no explicit server option needed. The server will respond with compressed data when clients request it via UseCompressor.

func (GRPCConfig) ClientKeepaliveParams

func (c GRPCConfig) ClientKeepaliveParams() keepalive.ClientParameters

ClientKeepaliveParams returns keepalive.ClientParameters for client configuration.

func (GRPCConfig) ServerEnforcementPolicy

func (c GRPCConfig) ServerEnforcementPolicy() keepalive.EnforcementPolicy

ServerEnforcementPolicy returns keepalive.EnforcementPolicy for server configuration.

func (GRPCConfig) ServerKeepaliveParams

func (c GRPCConfig) ServerKeepaliveParams() keepalive.ServerParameters

ServerKeepaliveParams returns keepalive.ServerParameters for server configuration.

func (GRPCConfig) String

func (c GRPCConfig) String() string

String returns a human-readable representation of the config for logging.

func (GRPCConfig) Validate

func (c GRPCConfig) Validate() error

Validate checks if the configuration is valid.

type GenericBQQuantizer

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

GenericBQQuantizer wraps BQEncoder to implement Quantizer interface

func NewGenericBQQuantizer

func NewGenericBQQuantizer(encoder *BQEncoder) *GenericBQQuantizer

NewGenericBQQuantizer creates a generic BQ quantizer wrapper

func (*GenericBQQuantizer) Decode

func (g *GenericBQQuantizer) Decode(codes []uint64) ([]float32, error)

Decode implements Quantizer interface

func (*GenericBQQuantizer) Dims

func (g *GenericBQQuantizer) Dims() int

Dims implements Quantizer interface

func (*GenericBQQuantizer) Encode

func (g *GenericBQQuantizer) Encode(vectors any) ([]uint64, error)

Encode implements Quantizer interface

type GenericPQQuantizer

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

GenericPQQuantizer wraps PQEncoder to implement Quantizer interface

func NewGenericPQQuantizer

func NewGenericPQQuantizer(encoder *pq.PQEncoder) *GenericPQQuantizer

NewGenericPQQuantizer creates a generic PQ quantizer wrapper

func (*GenericPQQuantizer) Decode

func (g *GenericPQQuantizer) Decode(codes []byte) ([]float32, error)

Decode implements Quantizer interface

func (*GenericPQQuantizer) Dims

func (g *GenericPQQuantizer) Dims() int

Dims implements Quantizer interface

func (*GenericPQQuantizer) Encode

func (g *GenericPQQuantizer) Encode(vectors any) ([]byte, error)

Encode implements Quantizer interface

type GenericSQ8Quantizer

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

GenericSQ8Quantizer wraps SQ8Encoder to implement Quantizer interface

func NewGenericSQ8Quantizer

func NewGenericSQ8Quantizer(encoder *SQ8Encoder) *GenericSQ8Quantizer

NewGenericSQ8Quantizer creates a generic SQ8 quantizer wrapper

func (*GenericSQ8Quantizer) Decode

func (g *GenericSQ8Quantizer) Decode(codes []uint8) ([]float32, error)

Decode implements Quantizer interface

func (*GenericSQ8Quantizer) Dims

func (g *GenericSQ8Quantizer) Dims() int

Dims implements Quantizer interface

func (*GenericSQ8Quantizer) Encode

func (g *GenericSQ8Quantizer) Encode(vectors any) ([]uint8, error)

Encode implements Quantizer interface

type GeoBoundingBox

type GeoBoundingBox = lbtypes.GeoBoundingBox

GeoBoundingBox defines a rectangular geographic area.

func BoundingBox

func BoundingBox(p GeoPoint, radiusKm float64) GeoBoundingBox

BoundingBox calculates a bounding box around a point with the given radius.

type GeoDistanceType

type GeoDistanceType string

GeoDistanceType defines the method used for distance calculations.

const (
	// GeoDistanceHaversine uses the spherical law of cosines for great-circle distance.
	GeoDistanceHaversine GeoDistanceType = "haversine"
	// GeoDistanceEuclidean uses planar distance (suitable for small areas).
	GeoDistanceEuclidean GeoDistanceType = "euclidean"
	// GeoDistanceApproximate uses a faster, less accurate distance calculation.
	GeoDistanceApproximate GeoDistanceType = "approximate"
)

type GeoIndex

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

GeoIndex provides efficient spatial indexing for vectors.

func NewGeoIndex

func NewGeoIndex(datasetName string, dimension int, config *GeoSearchConfig) *GeoIndex

NewGeoIndex creates a new GeoIndex with the specified configuration.

func (*GeoIndex) Add

func (gi *GeoIndex) Add(id uint64, vector []float32, point GeoPoint, metadata []byte) error

Add inserts a vector and its location into the index.

func (*GeoIndex) AddBatch

func (gi *GeoIndex) AddBatch(ids []uint64, vectors [][]float32, points []GeoPoint, metadata [][]byte) error

AddBatch inserts multiple vectors into the GeoIndex.

func (*GeoIndex) Delete

func (gi *GeoIndex) Delete(id uint64)

Delete removes a vector from the geo index by its ID.

func (*GeoIndex) Get

func (gi *GeoIndex) Get(id uint64) (*GeoIndexedVector, bool)

Get retrieves a vector by its ID.

func (*GeoIndex) GetBounds

func (gi *GeoIndex) GetBounds() (GeoPoint, float64)

GetBounds computes and returns the centroid and max radius (in km) covering the index vectors.

func (*GeoIndex) GetVectorIndex

func (gi *GeoIndex) GetVectorIndex() VectorIndex

func (*GeoIndex) HybridSearch

func (gi *GeoIndex) HybridSearch(ctx context.Context, queryVector []float32, center GeoPoint, radiusKm float64, k int) ([]lbtypes.SearchResult, error)

HybridSearch combines vector similarity and geographic proximity.

func (*GeoIndex) PrecomputeGeoCandidateBitmap

func (gi *GeoIndex) PrecomputeGeoCandidateBitmap(center GeoPoint, radiusKm float64) *roaring.Bitmap

PrecomputeGeoCandidateBitmap pre-computes a Roaring Bitmap of valid candidates via Quadtree bounding boxes.

func (*GeoIndex) SearchBox

func (gi *GeoIndex) SearchBox(ctx context.Context, box GeoBoundingBox, k int) ([]lbtypes.SearchResult, error)

SearchBox finds all vectors within a rectangular area.

func (*GeoIndex) SearchRadius

func (gi *GeoIndex) SearchRadius(ctx context.Context, center GeoPoint, radiusKm float64, k int) ([]lbtypes.SearchResult, error)

func (*GeoIndex) SetGPUIndex

func (gi *GeoIndex) SetGPUIndex(idx gputypes.Index)

SetGPUIndex sets the GPU acceleration index for this GeoIndex.

func (*GeoIndex) Size

func (gi *GeoIndex) Size() int

Size returns the total number of vectors in the geo index.

type GeoIndexedVector

type GeoIndexedVector struct {
	ID        uint64
	Vector    []float32
	GeoPoint  GeoPoint
	Timestamp int64
	Metadata  []byte
}

GeoIndexedVector pairs a vector with its geographic location.

type GeoPoint

type GeoPoint = lbcore.GeoPoint

GeoPoint represents a geographic location with latitude and longitude.

type GeoPointIndex

type GeoPointIndex interface {
	Insert(vec *GeoIndexedVector) bool
	Contains(point GeoPoint) bool
	QueryBox(box GeoBoundingBox) []*GeoIndexedVector
	QueryBoxAppend(box GeoBoundingBox, results *[]*GeoIndexedVector)
	QueryBoxBitmap(box GeoBoundingBox, bm *roaring.Bitmap)
	QueryRadius(center GeoPoint, radiusKm float64, results *[]*GeoIndexedVector)
	QueryRadiusPruned(center GeoPoint, radiusKm float64, results *[]*GeoIndexedVector)
}

GeoPointIndex is the spatial index contract shared by Quadtree and MortonGrid.

type GeoPolygon

type GeoPolygon []GeoPoint

GeoPolygon represents a sequence of GeoPoints forming a closed area.

type GeoPredicate

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

GeoPredicate implements types.HNSWPredicate for geospatial filtering.

func (*GeoPredicate) IsMatch

func (gp *GeoPredicate) IsMatch(id uint32) bool

func (*GeoPredicate) MatchBatch

func (gp *GeoPredicate) MatchBatch(ids []uint32, dst []byte)

type GeoSearchConfig

type GeoSearchConfig struct {
	DistanceType GeoDistanceType
	EarthRadius  float64
	IndexType    string
}

GeoSearchConfig holds configuration for geospatial indexing and search.

type GeoSearchRequest

type GeoSearchRequest = lbtypes.GeoSearchRequest

GeoSearchRequest encapsulates parameters for various geographic search types.

type GlobalSearchCoordinator

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

GlobalSearchCoordinator handles scatter-gather logic

func NewGlobalSearchCoordinator

func NewGlobalSearchCoordinator(logger zerolog.Logger, pool *FlightClientPool) *GlobalSearchCoordinator

NewGlobalSearchCoordinator creates a new GlobalSearchCoordinator with the provided logger and client pool.

func (*GlobalSearchCoordinator) Close

func (c *GlobalSearchCoordinator) Close() error

Close releases any resources held by the coordinator.

func (*GlobalSearchCoordinator) GlobalGeoSearch

func (c *GlobalSearchCoordinator) GlobalGeoSearch(ctx context.Context, localResults []SearchResult, req *core.GeoSearchRequest, peers []mesh.Member) ([]SearchResult, error)

GlobalGeoSearch performs scatter-gather geospatial search across the cluster

func (*GlobalSearchCoordinator) GlobalSearch

func (c *GlobalSearchCoordinator) GlobalSearch(ctx context.Context, localResults []SearchResult, req *query.VectorSearchRequest, peers []mesh.Member) ([]SearchResult, error)

GlobalSearch performs scatter-gather search across the cluster

func (*GlobalSearchCoordinator) GlobalTemporalSearch

func (c *GlobalSearchCoordinator) GlobalTemporalSearch(ctx context.Context, localResults []SearchResult, req *core.TemporalSearchRequest, peers []mesh.Member) ([]SearchResult, error)

GlobalTemporalSearch performs scatter-gather temporal search across the cluster

type GoroutineAudit

type GoroutineAudit struct {
	// Core store goroutines
	CompactionWorker  bool // Runs compaction tasks
	LifecycleManager  bool // Manages dataset lifecycle
	EvictionTicker    bool // Handles periodic eviction
	RepairWorker      bool // Repairs HNSW consistency
	IndexingWorker    bool // Handles batch indexing
	ReplicationWorker bool // Handles data replication

	// Index-specific goroutines
	HNSWRepairWorker bool // HNSW background repair
	BM25IndexWorker  bool // BM25 background indexing
	BM25EvictWorker  bool // BM25 background eviction

	// Network goroutines
	GossipListener bool // Gossip protocol listener
	GRPCServer     bool // gRPC server main loop
	HTTPServer     bool // HTTP API server
	FlightServer   bool // Arrow Flight server

	// Utility goroutines
	MetricsCollector bool // Prometheus metrics scraping
	PprofServer      bool // pprof HTTP server
}

GoroutineAudit documents all background goroutines with their lifecycle ownership

func AuditGoroutines

func AuditGoroutines() GoroutineAudit

AuditGoroutines inspects the current goroutine landscape

type GraphAnalytics

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

GraphAnalytics provides analysis algorithms for the graph structure.

func NewGraphAnalytics

func NewGraphAnalytics(graphProvider func() *types.GraphData) *GraphAnalytics

NewGraphAnalytics creates a new GraphAnalytics instance with the provided graph provider.

func (*GraphAnalytics) AnalyzeProperties

func (ga *GraphAnalytics) AnalyzeProperties(ctx context.Context) (*GraphProperties, error)

AnalyzeProperties calculates basic graph statistics.

func (*GraphAnalytics) CalculatePageRank

func (ga *GraphAnalytics) CalculatePageRank(ctx context.Context, config PageRankConfig) (*CentralityResult, error)

CalculatePageRank computes the PageRank for all nodes in the graph (Layer 0). Note: This builds a reverse adjacency list in memory, which can be expensive.

func (*GraphAnalytics) DetectCommunities

func (ga *GraphAnalytics) DetectCommunities(ctx context.Context, maxIter int) (*CommunityResult, error)

DetectCommunities runs Label Propagation Algorithm (LPA).

type GraphBackend

type GraphBackend interface {
	// GetNeighbors returns the neighbors of the given node at the specified layer.
	// usage of 'buf' allows reducing allocations. If buf is large enough, it is used.
	// Returns a slice containing the neighbors (safe/stable copy).
	GetNeighbors(layer int, nodeID uint32, buf []uint32) []uint32

	// GetLevel returns the maximum level of the node.
	// Returns -1 if the node does not exist.
	GetLevel(nodeID uint32) int

	// Size returns the total number of nodes in the graph.
	Size() int

	// GetCapacity returns the current capacity of the backend.
	GetCapacity() int

	// GetVectorSQ8 returns the SQ8 encoded vector for the given node.
	// Returns nil if not present.
	GetVectorSQ8(nodeID uint32) []byte

	// GetVectorPQ returns the PQ encoded vector for the given node.
	// Returns nil if not present.
	GetVectorPQ(nodeID uint32) []byte

	// Close cleans up any resources associated with the backend (e.g., file handles).
	Close() error
}

GraphBackend abstracts the storage of the HNSW graph structure (adjacency list). Implementations can be in-memory (GraphData) or on-disk (DiskGraph).

type GraphData

type GraphData = types.GraphData

GraphData represents the graph structure for HNSW.

type GraphProperties

type GraphProperties struct {
	NodeCount int
	EdgeCount int
	AvgDegree float32
	Density   float32
}

GraphProperties contains basic statistics about the graph structure.

type GraphSearchContext

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

GraphSearchContext provides pooled buffers for GraphRAG search operations to eliminate GC pressure during high-frequency graph expansions.

func (*GraphSearchContext) AddScore

func (ctx *GraphSearchContext) AddScore(id uint32, delta float32)

AddScore safely adds to the score of a node.

func (*GraphSearchContext) EnsureCapacity

func (ctx *GraphSearchContext) EnsureCapacity(id uint32)

EnsureCapacity ensures the scores and visited buffers can accommodate the given ID.

func (*GraphSearchContext) GetScore

func (ctx *GraphSearchContext) GetScore(id uint32) float32

GetScore safely gets the score for a node.

func (*GraphSearchContext) IsVisited

func (ctx *GraphSearchContext) IsVisited(id uint32) bool

IsVisited safely checks if a node was visited.

func (*GraphSearchContext) Reset

func (ctx *GraphSearchContext) Reset(maxID int, initialCount int)

Reset clears the context for reuse.

func (*GraphSearchContext) SetScore

func (ctx *GraphSearchContext) SetScore(id uint32, score float32)

SetScore safely sets the score for a node, growing the buffer if needed.

func (*GraphSearchContext) SetVisited

func (ctx *GraphSearchContext) SetVisited(id uint32)

SetVisited safely marks a node as visited.

type GraphStore

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

GraphStore manages an in-memory graph representation for GraphRAG operations.

func NewGraphStore

func NewGraphStore() *GraphStore

NewGraphStore creates an empty GraphStore.

func (*GraphStore) AddEdge

func (gs *GraphStore) AddEdge(edge Edge) error

AddEdge adds a new edge to the graph store.

func (*GraphStore) Close

func (gs *GraphStore) Close() error

Close releases all resources associated with the graph store.

func (*GraphStore) CommunityCount

func (gs *GraphStore) CommunityCount() int

CommunityCount returns the number of nodes that have outgoing edges.

func (*GraphStore) EdgeCount

func (gs *GraphStore) EdgeCount() int

EdgeCount returns the total number of edges in the graph.

func (*GraphStore) FromArrowBatch

func (gs *GraphStore) FromArrowBatch(record arrow.RecordBatch, _ []string) error

FromArrowBatch loads edges from an Arrow Record into the GraphStore. The record must have the schema: subject (uint32), predicate (dictionary), object (uint32), weight (float32). This method automatically recovers the predicate vocabulary from the Arrow Dictionary. The optional predicates parameter is kept for backward compatibility but is ignored if the record contains a dictionary.

func (*GraphStore) FromArrowRecord

func (gs *GraphStore) FromArrowRecord(record arrow.RecordBatch, predicates []string) error

FromArrowRecord is an alias for FromArrowBatch for API consistency.

func (*GraphStore) GetCSR

func (gs *GraphStore) GetCSR() (offsets []uint32, neighbors []uint32, weights []float32)

GetCSR converts the graph to a Compressed Sparse Row (CSR) format.

func (*GraphStore) GetEdgesByObject

func (gs *GraphStore) GetEdgesByObject(object uint32) []Edge

GetEdgesByObject returns all incoming edges for a given object.

func (*GraphStore) GetEdgesByPredicate

func (gs *GraphStore) GetEdgesByPredicate(predicate string) []Edge

GetEdgesByPredicate returns all edges with a specific predicate.

func (*GraphStore) GetEdgesBySubject

func (gs *GraphStore) GetEdgesBySubject(subject uint32) []Edge

GetEdgesBySubject returns all outgoing edges for a given subject.

func (*GraphStore) PredicateVocabulary

func (gs *GraphStore) PredicateVocabulary() []string

PredicateVocabulary returns the list of all predicates in the graph.

func (*GraphStore) RankWithGraph

func (gs *GraphStore) RankWithGraph(dataset string, queryVec []float32, results []SearchResult, alpha float32, depth int) []SearchResult

RankWithGraph performs graph-based reranking using CPU execution. It uses the pre-materialized adjList under a single adjMu.RLock() to avoid per-edge LockFreeMap contention, and applies Beam Search pruning after each BFS hop to bound complexity to O(BeamWidth^2 * depth).

func (*GraphStore) RankWithGraphDistributed

func (gs *GraphStore) RankWithGraphDistributed(ctx context.Context, dataset string, queryVec []float32, results []SearchResult, alpha float32, depth int, provider NeighborProvider) []SearchResult

RankWithGraphDistributed performs graph-based reranking across a distributed mesh. Uses the pre-materialized adjList (local) under adjMu.RLock(), and falls back to remote NeighborProvider only for IDs not present locally. Beam Search pruning is applied after each hop to bound frontier size to BeamWidth.

func (*GraphStore) RankWithGraphGPU

func (gs *GraphStore) RankWithGraphGPU(dataset string, queryVec []float32, results []SearchResult, alpha float32, depth int, gpuIdx gputypes.Index) ([]SearchResult, error)

RankWithGraphGPU performs graph-based reranking using GPU acceleration.

func (*GraphStore) ToArrowBatch

func (gs *GraphStore) ToArrowBatch() (arrow.RecordBatch, error)

ToArrowBatch exports the GraphStore's edges to an Arrow Record. It uses Dictionary Encoding for the 'predicate' column to ensure the predicate vocabulary is self-contained within the record.

func (*GraphStore) ToArrowRecord

func (gs *GraphStore) ToArrowRecord() (arrow.RecordBatch, error)

ToArrowRecord is an alias for ToArrowBatch for API consistency.

func (*GraphStore) Traverse

func (gs *GraphStore) Traverse(start VectorID, opts TraverseOptions) []Path

Traverse performs a graph traversal starting from a specific node. Uses the pre-materialized adjList / bwdAdjList under a single adjMu.RLock() to avoid per-edge LockFreeMap acquisitions during BFS path enumeration.

type HNSWPredicate

type HNSWPredicate interface {
	// CanAcceptFilter returns true if the predicate can evaluate the given filter.
	CanAcceptFilter(filter query.Filter) bool
	// ApplyFilter returns the set of node IDs that satisfy the filter criteria.
	ApplyFilter(filter query.Filter) ([]uint32, error)
	// GetIndexedFields returns the list of fields that this predicate can evaluate.
	GetIndexedFields() []string
}

HNSWPredicate defines an interface for evaluating filtering conditions on HNSW nodes to support metadata filtering.

type HNSWSearchConfig

type HNSWSearchConfig struct {
	EnablePrefetch            bool
	PrefetchDistance          int
	EnableEarlyTermination    bool
	EarlyTerminationThreshold float32
	ParallelSearch            bool
	NumSearchThreads          int
	BatchSize                 int
}

HNSWSearchConfig defines tunable parameters for the optimized HNSW search path.

type HNSWSettings

type HNSWSettings struct {
	// M is the number of bi-directional links created for every new element during construction.
	M int
	// EfConstruction is the size of the dynamic list for the nearest neighbors (used during construction).
	EfConstruction int
}

HNSWSettings holds configuration parameters for the HNSW index construction.

type HeuristicReranker

type HeuristicReranker struct {
	ModelName string
}

HeuristicReranker implements a second-stage reranker using text-matching heuristics.

func (*HeuristicReranker) Rerank

func (r *HeuristicReranker) Rerank(ctx context.Context, query string, results []SearchResult) ([]SearchResult, error)

Rerank re-orders the search results based on a cross-encoder model or heuristic.

type HighlightedTextHit

type HighlightedTextHit struct {
	ID         string         `json:"id"`
	VectorID   uint32         `json:"vector_id"`
	Score      float64        `json:"score"`
	Snippet    string         `json:"snippet"`
	Highlights []string       `json:"highlights,omitempty"`
	Metadata   map[string]any `json:"metadata,omitempty"`
}

HighlightedTextHit represents one full-text match with snippet highlights and metadata.

type HybridPipelineConfig

type HybridPipelineConfig struct {
	Alpha          float32    // 0.0=pure keyword, 1.0=pure vector, 0.5=balanced
	RRFk           int        // RRF parameter k (typically 60)
	FusionMode     FusionMode // How to combine results
	UseColumnIndex bool       // Use column index for exact filters
}

HybridPipelineConfig configures the hybrid search pipeline

func DefaultHybridPipelineConfig

func DefaultHybridPipelineConfig() HybridPipelineConfig

DefaultHybridPipelineConfig returns sensible defaults

func (*HybridPipelineConfig) Validate

func (c *HybridPipelineConfig) Validate() error

Validate checks if the hybrid pipeline configuration is within valid ranges.

type HybridQuery

type HybridQuery struct {
	Enabled   bool    // Whether hybrid search is enabled for this query
	TextQuery string  // The text query for BM25/keyword search
	Alpha     float64 // Weighting: 1.0 = pure vector, 0.0 = pure keyword
	K         int     // Number of results to return
}

HybridQuery represents a hybrid search query combining vector and BM25 search

func DefaultHybridQuery

func DefaultHybridQuery() HybridQuery

DefaultHybridQuery returns a HybridQuery with sensible defaults

func (*HybridQuery) IsPureKeyword

func (q *HybridQuery) IsPureKeyword() bool

IsPureKeyword returns true if this is a pure keyword/BM25 search (alpha=0.0)

func (*HybridQuery) IsPureVector

func (q *HybridQuery) IsPureVector() bool

IsPureVector returns true if this is a pure vector search (alpha=1.0)

func (*HybridQuery) Validate

func (q *HybridQuery) Validate() error

Validate checks if the HybridQuery is valid

type HybridReranker

type HybridReranker struct {
	Secondary     Reranker
	MLWeight      float32
	DenseWeight   float32
	LexicalWeight float32
	FieldBoosts   map[string]float32
}

HybridReranker combines dense vector similarity, full-length lexical term & exact-phrase matching, metadata field weights, and an optional ML/CrossEncoder/LLM second-stage reranker.

func NewHybridReranker

func NewHybridReranker(secondary Reranker) *HybridReranker

NewHybridReranker builds a balanced ML + lexical + dense heuristic reranker.

func (*HybridReranker) Rerank

func (h *HybridReranker) Rerank(ctx context.Context, query string, results []SearchResult) ([]SearchResult, error)

Rerank scores every candidate across all signals and sorts descending.

type HybridSearchConfig

type HybridSearchConfig struct {
	// Alpha controls the weighting between vector and keyword search
	// Alpha = 1.0 means pure vector search (dense)
	// Alpha = 0.0 means pure keyword search (sparse/BM25)
	// Alpha = 0.5 means balanced hybrid
	Alpha float32

	// TextColumns specifies which columns should be indexed for BM25 search
	TextColumns []string

	// RRFk is the k parameter for Reciprocal Rank Fusion
	// Higher values give more weight to lower-ranked results
	// Typical values: 60 (default), range 1-1000
	RRFk int

	// BM25 contains the BM25 algorithm parameters
	BM25 BM25Config

	// Enabled determines if hybrid search is active
	Enabled bool
}

HybridSearchConfig configures hybrid search behavior combining BM25 and vector search

func DefaultHybridSearchConfig

func DefaultHybridSearchConfig() HybridSearchConfig

DefaultHybridSearchConfig returns a HybridSearchConfig with sensible defaults

func (*HybridSearchConfig) IsPureKeyword

func (c *HybridSearchConfig) IsPureKeyword() bool

IsPureKeyword returns true if Alpha is 0.0 (pure keyword search)

func (*HybridSearchConfig) IsPureVector

func (c *HybridSearchConfig) IsPureVector() bool

IsPureVector returns true if Alpha is 1.0 (pure vector search)

func (*HybridSearchConfig) Validate

func (c *HybridSearchConfig) Validate() error

Validate checks if the configuration is valid

type HybridSearchPipeline

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

HybridSearchPipeline combines column index, BM25, and HNSW search

func NewHybridSearchPipeline

func NewHybridSearchPipeline(cfg HybridPipelineConfig) *HybridSearchPipeline

NewHybridSearchPipeline creates a new hybrid search pipeline

func (*HybridSearchPipeline) Search

Search performs hybrid search combining all configured indexes

func (*HybridSearchPipeline) SetBM25Index

func (p *HybridSearchPipeline) SetBM25Index(idx *BM25InvertedIndex)

SetBM25Index sets the BM25 inverted index for keyword search

func (*HybridSearchPipeline) SetColumnIndex

func (p *HybridSearchPipeline) SetColumnIndex(idx *ColumnInvertedIndex)

SetColumnIndex sets the column inverted index for exact filters

func (*HybridSearchPipeline) SetDataset

func (p *HybridSearchPipeline) SetDataset(ds *Dataset)

SetDataset sets the dataset for content lookups

func (*HybridSearchPipeline) SetHNSWIndex

func (p *HybridSearchPipeline) SetHNSWIndex(idx VectorIndex)

SetHNSWIndex sets the HNSW index for vector search

func (*HybridSearchPipeline) SetReranker

func (p *HybridSearchPipeline) SetReranker(r Reranker)

SetReranker sets the second-stage reranker

type HybridSearchQuery

type HybridSearchQuery struct {
	Vector        []float32      // Query vector for dense search
	KeywordQuery  string         // Text query for BM25 search
	K             int            // Number of results
	AlphaOverride *float32       // Override pipeline alpha if set
	ExactFilters  []query.Filter // Exact match filters (for column index)
}

HybridSearchQuery extends search with vector, keyword, and filter options

func DefaultHybridSearchQuery

func DefaultHybridSearchQuery() HybridSearchQuery

DefaultHybridSearchQuery returns a HybridSearchQuery with default limit.

func (*HybridSearchQuery) Validate

func (q *HybridSearchQuery) Validate() error

Validate ensures the hybrid search query has all required fields and valid parameters.

type HybridSearchRequest

type HybridSearchRequest struct {
	Dataset     string
	QueryVector []float32
	QueryText   string
	K           int
	Alpha       float32 // Weight for vector score (0-1)
	Filters     []query.Filter
	Bitset      *types.Bitset
}

HybridSearchRequest encapsulates parameters for hybrid search.

type IDMap

type IDMap struct {
	StringMap map[string]int
	IntMap    map[int64]int
	UintMap   map[uint64]int
	IsNumeric bool
}

IDMap is a pooled container for ID to row index mappings. Supports string, int64, and uint64 IDs to avoid allocation/conversion.

func (*IDMap) Release

func (m *IDMap) Release()

Release returns the IDMap to the pool.

type IOScheduleItem

type IOScheduleItem struct {
	BlockID    uint64
	Priority   int
	IsRead     bool
	Callback   func([]byte, error)
	SubmitTime time.Time
}

IOScheduleItem is an internal item used for scheduling I/O operations.

type IPCBufferPool

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

IPCBufferPool manages reusable bytes.Buffer instances for IPC serialization. Uses sync.Pool internally for thread-safe, lock-free buffer management.

func NewIPCBufferPool

func NewIPCBufferPool(cfg RecordWriterPoolConfig) *IPCBufferPool

NewIPCBufferPool creates a new buffer pool with the given configuration.

func (*IPCBufferPool) Get

func (p *IPCBufferPool) Get() *bytes.Buffer

Get retrieves a buffer from the pool or allocates a new one. The returned buffer is reset and ready for use.

func (*IPCBufferPool) GetSized

func (p *IPCBufferPool) GetSized(size int) *bytes.Buffer

GetSized returns a reset buffer with capacity for at least size bytes, growing a pooled buffer only when the requested size does not already fit. size is clamped to MaxBufferSize so an oversized estimate cannot pin an unbounded buffer in the pool.

func (*IPCBufferPool) Put

func (p *IPCBufferPool) Put(buf *bytes.Buffer)

Put returns a buffer to the pool for reuse. Oversized buffers (> MaxBufferSize) are discarded to prevent memory bloat.

func (*IPCBufferPool) Reset

func (p *IPCBufferPool) Reset()

Reset clears all statistics.

func (*IPCBufferPool) Stats

func (p *IPCBufferPool) Stats() IPCBufferPoolStats

Stats returns current pool statistics.

type IPCBufferPoolStats

type IPCBufferPoolStats struct {
	Gets      int64 // Total Get() calls
	Puts      int64 // Total Put() calls
	Hits      int64 // Buffer reused from pool
	Misses    int64 // New buffer allocated
	Discarded int64 // Oversized buffers discarded
}

IPCBufferPoolStats tracks pool usage metrics.

type IVFHNSWConfig

type IVFHNSWConfig = index.IVFHNSWConfig

type IVFOPQConfig

type IVFOPQConfig = index.IVFOPQConfig

type IncrementalBackup

type IncrementalBackup struct {
	Metadata BackupMetadata
	Deltas   []BackupDelta
}

IncrementalBackup represents a backup containing only changes since a parent backup.

type IndexAdaptationConfig

type IndexAdaptationConfig = index.IndexAdaptationConfig

type IndexConfig

type IndexConfig = index.IndexConfig

type IndexJob

type IndexJob = types.IndexJob

IndexJob represents a background indexing task.

type IndexJobQueueConfig

type IndexJobQueueConfig = types.IndexJobQueueConfig

IndexJobQueueConfig defines configuration for the index job queue.

type IndexJobQueueLockFree

type IndexJobQueueLockFree = hnswcore.IndexJobQueueLockFree

IndexJobQueueLockFree is a high-performance index job queue.

type IndexJobQueueStats

type IndexJobQueueStats = types.IndexJobQueueStats

IndexJobQueueStats provides metrics for the index job queue.

type IndexPrediction

type IndexPrediction = index.IndexPrediction

type IndexType

type IndexType = index.IndexType

type IngestionJob

type IngestionJob struct {
	DS    *Dataset
	Batch arrow.RecordBatch
	TS    int64
}

IngestionJob represents a unit of work for the ingestion pipeline, containing a record batch and timestamp.

type IngestionRingBuffer

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

IngestionRingBuffer is a lock-free Multi-Producer Multi-Consumer (MPMC) queue optimized for high-throughput ingestion.

func NewIngestionRingBuffer

func NewIngestionRingBuffer(size uint64) *IngestionRingBuffer

NewIngestionRingBuffer creates a new ring buffer with the specified size. Size must be a power of 2.

func (*IngestionRingBuffer) Capacity

func (rb *IngestionRingBuffer) Capacity() int

Capacity returns the total size of the ring buffer

func (*IngestionRingBuffer) Len

func (rb *IngestionRingBuffer) Len() int

Len returns approximate length

func (*IngestionRingBuffer) Notify

func (rb *IngestionRingBuffer) Notify() <-chan struct{}

Notify returns a channel that receives a token whenever a job is published.

Consumers block on it instead of polling with a timer. An idle worker pool used to wake every millisecond per goroutine - at 16 workers that is 16,000 runtime timer operations per second for a queue with nothing in it, and profiling attributed 1,498 s (24.93%) of cumulative block delay in runtime.selectgo to exactly that churn.

func (*IngestionRingBuffer) Pop

func (rb *IngestionRingBuffer) Pop() (IngestionJob, bool)

Pop removes an item from the queue. Returns false if the queue is empty.

func (*IngestionRingBuffer) Push

func (rb *IngestionRingBuffer) Push(job IngestionJob) bool

Push adds an item to the queue. Returns false if the queue is full.

func (*IngestionRingBuffer) PushBlocking

func (rb *IngestionRingBuffer) PushBlocking(job IngestionJob, timeout time.Duration) bool

PushBlocking adds an item, blocking/yielding if full until space is available or timeout.

type Int8Type

type Int8Type interface{}

Int8Type identifies int8 vector type

type InvertedIndex

type InvertedIndex = index.InvertedIndex

func NewInvertedIndex

func NewInvertedIndex() *InvertedIndex

type JointMultiModalEmbedder

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

JointMultiModalEmbedder supports HTTP CLIP/CLAP/Whisper inference, local WASM/ONNX MLBackend, and an integrated deterministic pixel+spectral+semantic feature extractor for zero-external-dep execution.

func NewJointMultiModalEmbedder

func NewJointMultiModalEmbedder(cfg MultiModalConfig) (*JointMultiModalEmbedder, error)

NewJointMultiModalEmbedder constructs a multi-modal embedder with sensible defaults.

func (*JointMultiModalEmbedder) Dimension

func (e *JointMultiModalEmbedder) Dimension() int

Dimension returns the shared joint embedding dimensionality.

func (*JointMultiModalEmbedder) EmbedAudio

func (e *JointMultiModalEmbedder) EmbedAudio(ctx context.Context, raw []byte, mimeType, transcript string) ([]float32, error)

EmbedAudio extracts spectral/temporal + transcript features for WAV/PCM or compressed audio payloads.

func (*JointMultiModalEmbedder) EmbedImage

func (e *JointMultiModalEmbedder) EmbedImage(ctx context.Context, raw []byte, mimeType, caption string) ([]float32, error)

EmbedImage extracts normalized visual + semantic features for image payloads (CLIP-compatible).

func (*JointMultiModalEmbedder) EmbedText

func (e *JointMultiModalEmbedder) EmbedText(ctx context.Context, text string) ([]float32, error)

EmbedText embeds text into the joint multi-modal embedding space.

type LLMRerankConfig

type LLMRerankConfig struct {
	Provider   string `json:"provider"` // "openai", "local", "cohere"
	Endpoint   string `json:"endpoint"` // e.g. "https://api.openai.com/v1/chat/completions" or "http://localhost:11434/api/chat"
	APIKey     string `json:"api_key,omitempty"`
	Model      string `json:"model"`
	TimeoutMs  int    `json:"timeout_ms,omitempty"`
	MaxDocChar int    `json:"max_doc_char,omitempty"`
}

LLMRerankConfig configures OpenAI or local (Ollama/vLLM) LLM reranking.

type LLMReranker

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

LLMReranker uses OpenAI-compatible or local Ollama/vLLM JSON relevance scoring endpoints.

func NewLLMReranker

func NewLLMReranker(cfg LLMRerankConfig) (*LLMReranker, error)

NewLLMReranker constructs an LLM-based listwise reranker.

func (*LLMReranker) Rerank

func (l *LLMReranker) Rerank(ctx context.Context, query string, results []SearchResult) ([]SearchResult, error)

Rerank prompts the configured LLM to score candidate passages and returns sorted results.

type LearnedIndexConfig

type LearnedIndexConfig = index.LearnedIndexConfig

type Location

type Location = types.Location

Location maps a VectorID to a physical location in a Dataset (Batch + Row).

type LockFreeMap

type LockFreeMap[K comparable, V any] = types.LockFreeMap[K, V]

func NewLockFreeMap

func NewLockFreeMap[K comparable, V any]() *LockFreeMap[K, V]

type LockFreeNeighborCache

type LockFreeNeighborCache = hnswcore.LockFreeNeighborCache

LockFreeNeighborCache provides a cache of lock-free neighbor lists.

type LockFreeNeighborList

type LockFreeNeighborList = hnswcore.LockFreeNeighborList

LockFreeNeighborList provides lock-free reads with copy-on-write updates.

type LockFreeRingBuffer

type LockFreeRingBuffer[T any] = hnswcore.LockFreeRingBuffer[T]

LockFreeRingBuffer is a high-performance concurrent ring buffer.

type LockFreeSlice

type LockFreeSlice[T any] = types.LockFreeSlice[T]

func NewLockFreeSlice

func NewLockFreeSlice[T any]() *LockFreeSlice[T]

func NewLockFreeSliceFrom

func NewLockFreeSliceFrom[T any](items []T) *LockFreeSlice[T]

type MLBackend

type MLBackend interface {
	Embed(ctx context.Context, texts []string) ([][]float32, error)
	Score(ctx context.Context, query string, docs []string) ([]float32, error)
	Dimension() int
	Close() error
}

MLBackend is the unified interface for local ML inference used across the vector engine (embeddings, reranking, and sparse generation).

type MLModel

type MLModel interface {
	// Score calculates relevance scores for a query and a set of documents.
	Score(query string, documents []string) ([]float32, error)
	// Close releases resources associated with the model.
	Close() error
}

MLModel defines the interface for ML model inference.

type MQConfig

type MQConfig struct {
	Type           MQType `json:"type"`
	Brokers        string `json:"brokers"`
	Topic          string `json:"topic"`
	ProducerMode   string `json:"producer_mode"`
	BatchSize      int    `json:"batch_size"`
	BatchTimeoutMs int    `json:"batch_timeout_ms"`
	Acks           int    `json:"acks"`
	Compression    string `json:"compression"`
}

MQConfig holds configuration for the message queue exporter.

type MQMetrics

type MQMetrics struct {
	MessagesProduced atomic.Int64
	MessagesFailed   atomic.Int64
	BytesProduced    atomic.Int64
	BatchesProduced  atomic.Int64
}

MQMetrics tracks performance and throughput for the MQ exporter.

type MQType

type MQType string

MQType defines the supported message queue types.

const (
	// MQTypeKafka represents a Kafka message queue.
	MQTypeKafka MQType = "kafka"
	// MQTypePulsar represents a Pulsar message queue.
	MQTypePulsar MQType = "pulsar"
)

type MaterializedViewManager

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

MaterializedViewManager manages view definitions, count/sum/avg/min/max aggregation, refresh policies (manual/scheduled/streaming), and query planner integration.

func NewMaterializedViewManager

func NewMaterializedViewManager(s *VectorStore) *MaterializedViewManager

NewMaterializedViewManager initializes a materialized view manager.

func (*MaterializedViewManager) CreateView

CreateView registers a materialized view, computes its initial snapshot, and starts scheduled background refresh loops if configured.

func (*MaterializedViewManager) ListViews

ListViews returns snapshots for all registered materialized views.

func (*MaterializedViewManager) OnDatasetIngest

func (m *MaterializedViewManager) OnDatasetIngest(ctx context.Context, dataset string)

OnDatasetIngest refreshes all streaming materialized views dependent on dataset.

func (*MaterializedViewManager) QueryView

func (m *MaterializedViewManager) QueryView(name string, groupFilter map[string]string) (*MaterializedViewSnapshot, error)

QueryView returns the materialized snapshot, optionally filtered by exact group field equality.

func (*MaterializedViewManager) RefreshView

RefreshView recomputes a materialized view consistently over the source dataset's active Arrow batches while respecting tombstones.

func (*MaterializedViewManager) TryPlanQuery

func (m *MaterializedViewManager) TryPlanQuery(dataset string, groupBy []string, aggs []AggSpec) (*MaterializedViewSnapshot, bool)

TryPlanQuery implements query-planner integration: if a matching materialized view covers dataset + groupBy + aggs, serves the precomputed rows directly.

type MaterializedViewRow

type MaterializedViewRow struct {
	GroupKey string             `json:"group_key"`
	Group    map[string]string  `json:"group"`
	Metrics  map[string]float64 `json:"metrics"`
}

MaterializedViewRow holds one aggregated group bucket and computed metrics.

func AggregateBatches

func AggregateBatches(batches []arrow.RecordBatch, tombstones map[int]*types.Bitset, spec MaterializedViewSpec) ([]MaterializedViewRow, int64)

AggregateBatches computes exact grouped count/sum/avg/min/max over Arrow RecordBatches + JSON metadata.

type MaterializedViewSnapshot

type MaterializedViewSnapshot struct {
	Spec        MaterializedViewSpec  `json:"spec"`
	Version     uint64                `json:"version"`
	RefreshedAt time.Time             `json:"refreshed_at"`
	SourceRows  int64                 `json:"source_rows"`
	Rows        []MaterializedViewRow `json:"rows"`
}

MaterializedViewSnapshot stores a point-in-time consistent materialized view state.

type MaterializedViewSpec

type MaterializedViewSpec struct {
	Name              string            `json:"name"`
	SourceDataset     string            `json:"source_dataset"`
	GroupBy           []string          `json:"group_by"`
	Aggregations      []AggSpec         `json:"aggregations"`
	FilterEquals      map[string]string `json:"filter_equals,omitempty"`
	RefreshPolicy     ViewRefreshPolicy `json:"refresh_policy"`
	RefreshMode       ViewRefreshPolicy `json:"refresh_mode,omitempty"`
	RefreshIntervalMs int               `json:"refresh_interval_ms,omitempty"`
}

MaterializedViewSpec declares a materialized aggregation view over a dataset.

type MaxHeap

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

MaxHeap is a fixed-capacity max-heap. It keeps the LARGEST elements at the top.

func NewMaxHeap

func NewMaxHeap(capacity int) *MaxHeap

NewMaxHeap creates a new fixed-capacity max-heap.

func (*MaxHeap) Len

func (h *MaxHeap) Len() int

Len returns the current number of elements in the heap.

func (*MaxHeap) Peek

func (h *MaxHeap) Peek() (Candidate, bool)

Peek returns the maximum element without removing it.

func (*MaxHeap) Pop

func (h *MaxHeap) Pop() (Candidate, bool)

Pop removes and returns the maximum element (largest distance).

func (*MaxHeap) Push

func (h *MaxHeap) Push(c Candidate)

Push adds a candidate to the heap. If full, it replaces the largest element if the new candidate is smaller.

type MeasuredMutex

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

MeasuredMutex wraps sync.Mutex to record wait duration.

func NewMeasuredMutex

func NewMeasuredMutex(label string) MeasuredMutex

NewMeasuredMutex creates a new measured mutex. Ideally usage implies struct embedding or direct replacement, but since we can't easily init array of structs with args, we might need to rely on a lazy init or a factory. For shardedLocks, we might just set the label when using. But sync.Mutex zero value is valid. MeasuredMutex zero value has empty label. We should allow empty label or use a SetLabel method, or just hardcode "shard" if widely used there. Better: Store the label in the wrapper.

func (*MeasuredMutex) Lock

func (m *MeasuredMutex) Lock()

Lock records the duration spent waiting for the lock.

func (*MeasuredMutex) Unlock

func (m *MeasuredMutex) Unlock()

Unlock unlocks the mutex.

type MeasuredRWMutex

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

MeasuredRWMutex wraps sync.RWMutex.

func NewMeasuredRWMutex

func NewMeasuredRWMutex(label string) MeasuredRWMutex

NewMeasuredRWMutex creates a new measured read-write mutex.

func (*MeasuredRWMutex) Lock

func (m *MeasuredRWMutex) Lock()

Lock records the duration spent waiting for the write lock.

func (*MeasuredRWMutex) RLock

func (m *MeasuredRWMutex) RLock()

RLock records the duration spent waiting for the read lock.

func (*MeasuredRWMutex) RUnlock

func (m *MeasuredRWMutex) RUnlock()

RUnlock unlocks the read lock.

func (*MeasuredRWMutex) Unlock

func (m *MeasuredRWMutex) Unlock()

Unlock unlocks the write lock.

type MediaModality

type MediaModality string

MediaModality enumerates supported multi-modal asset modalities.

const (
	ModalityImage MediaModality = "image"
	ModalityAudio MediaModality = "audio"
	ModalityText  MediaModality = "text"
)

type MemStoreOptions

type MemStoreOptions struct {
	UseArena   bool
	UseOffHeap bool
	Dim        int
}

MemStoreOptions defines configuration options for the MemVectorStore.

type MemVectorStore

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

MemVectorStore is an in-memory vector storage engine. It supports both legacy [][]float32 and optimized SlabArena storage.

func NewMemVectorStore

func NewMemVectorStore(opts MemStoreOptions) (*MemVectorStore, error)

NewMemVectorStore creates a new in-memory vector store with the provided options.

func (*MemVectorStore) Close

func (ms *MemVectorStore) Close() error

Close releases all resources associated with the memory store.

func (*MemVectorStore) Delete

func (ms *MemVectorStore) Delete(key string) bool

Delete marks a vector as deleted via tombstone (consistent with ArrowHNSW). Returns true if the key existed and was marked deleted, false otherwise.

func (*MemVectorStore) DeleteBatch

func (ms *MemVectorStore) DeleteBatch(keys []string) int

DeleteBatch marks multiple vectors as deleted via tombstone. Returns the count of successfully deleted vectors.

func (*MemVectorStore) Get

func (ms *MemVectorStore) Get(key string) ([]float32, bool)

Get retrieves a vector from the memory store by its key.

func (*MemVectorStore) IsDeleted

func (ms *MemVectorStore) IsDeleted(key string) bool

IsDeleted checks if a key is marked as deleted.

func (*MemVectorStore) Set

func (ms *MemVectorStore) Set(key string, vec []float32) error

Set stores a vector in the memory store under the given key.

type MemoryAdvice

type MemoryAdvice int

MemoryAdvice identifies the type of access pattern for a memory region.

const (
	// AdviceNormal indicates the default memory access pattern.
	AdviceNormal MemoryAdvice = iota
	// AdviceRandom indicates that memory access is expected to be random.
	AdviceRandom
	// AdviceSequential indicates that memory access is expected to be sequential.
	AdviceSequential
	// AdviceWillNeed indicates that the memory will be needed in the near future.
	AdviceWillNeed
	// AdviceDontNeed indicates that the memory will not be needed in the near future.
	AdviceDontNeed
	// AdviceHugePage indicates that the memory should use huge pages if available.
	AdviceHugePage
)

type MemoryBackpressureController

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

MemoryBackpressureController manages memory backpressure for the store.

func NewMemoryBackpressureController

func NewMemoryBackpressureController(cfg BackpressureConfig) *MemoryBackpressureController

NewMemoryBackpressureController creates a new backpressure controller.

func (*MemoryBackpressureController) Acquire

Acquire blocks until memory pressure allows proceeding.

func (*MemoryBackpressureController) CheckPressure

func (c *MemoryBackpressureController) CheckPressure() PressureLevel

CheckPressure evaluates current memory usage and returns pressure level. This is expensive (runtime.ReadMemStats) and should usually be called by the background ticker.

func (*MemoryBackpressureController) GetAcquireCount

func (c *MemoryBackpressureController) GetAcquireCount() uint64

GetAcquireCount returns the total number of successful acquires.

func (*MemoryBackpressureController) GetHardLimit

func (c *MemoryBackpressureController) GetHardLimit() uint64

GetHardLimit returns the configured hard limit.

func (*MemoryBackpressureController) GetPressureLevel

func (c *MemoryBackpressureController) GetPressureLevel() PressureLevel

GetPressureLevel returns the current pressure level without re-checking.

func (*MemoryBackpressureController) GetRejectCount

func (c *MemoryBackpressureController) GetRejectCount() uint64

GetRejectCount returns the total number of rejected acquires.

func (*MemoryBackpressureController) GetSoftLimit

func (c *MemoryBackpressureController) GetSoftLimit() uint64

GetSoftLimit returns the configured soft limit.

func (*MemoryBackpressureController) Release

func (c *MemoryBackpressureController) Release()

Release signals completion of a memory-intensive operation.

func (*MemoryBackpressureController) SetPressureLevel

func (c *MemoryBackpressureController) SetPressureLevel(level PressureLevel)

SetPressureLevel manually sets the pressure level (for testing).

func (*MemoryBackpressureController) Start

Start begins the background memory monitoring.

func (*MemoryBackpressureController) Stop

func (c *MemoryBackpressureController) Stop()

Stop halts the background monitoring.

type MemoryConfig

type MemoryConfig struct {
	MaxMemory        int64   // Maximum memory in bytes
	EvictionHeadroom float64 // Percentage headroom before eviction (0.10 = 10%)
	EvictionPolicy   string  // "lru", "oldest", "largest"
	RejectWrites     bool    // Reject writes when limit hit (vs attempt eviction)
}

MemoryConfig defines memory management behavior

func DefaultMemoryConfig

func DefaultMemoryConfig() MemoryConfig

DefaultMemoryConfig returns sensible defaults

func (MemoryConfig) EvictionThreshold

func (c MemoryConfig) EvictionThreshold() int64

EvictionThreshold returns the memory threshold at which eviction should trigger

type MerkleNode

type MerkleNode struct {
	Hash     [32]byte
	Children [MerkleFanout]*MerkleNode
}

MerkleNode represents a node in the Merkle Tree

type MerkleTree

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

MerkleTree manages consistency hashes for a Dataset

func NewMerkleTree

func NewMerkleTree() *MerkleTree

NewMerkleTree creates a new Merkle Tree for dataset consistency tracking.

func (*MerkleTree) GetNode

func (t *MerkleTree) GetNode(path []int) (hash [32]byte, children [][32]byte, found bool)

GetNode retrieves the hash and child hashes for a node at the specified path.

func (*MerkleTree) RootHash

func (t *MerkleTree) RootHash() [32]byte

RootHash returns the current root hash of the Merkle Tree.

func (*MerkleTree) Update

func (t *MerkleTree) Update(id VectorID, ts int64)

Update updates the hash for a given VectorID with its latest timestamp

type MeshStatusCache

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

MeshStatusCache caches the serialized mesh status to avoid repeated allocations.

func NewMeshStatusCache

func NewMeshStatusCache(ttl time.Duration) *MeshStatusCache

NewMeshStatusCache creates a new mesh status cache with the specified TTL.

func (*MeshStatusCache) Get

func (c *MeshStatusCache) Get(currentMemberCount int) []byte

Get returns the cached JSON if valid, otherwise returns nil.

func (*MeshStatusCache) Invalidate

func (c *MeshStatusCache) Invalidate()

Invalidate clears the cache.

func (*MeshStatusCache) Set

func (c *MeshStatusCache) Set(data []byte, memberCount int)

Set updates the cache with new JSON data.

type MessageQueueExporter

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

MessageQueueExporter handles exporting CDC events to external message queues.

func NewMessageQueueExporter

func NewMessageQueueExporter(logger zerolog.Logger, cdc *ChangeDataCapture, config MQConfig) (*MessageQueueExporter, error)

NewMessageQueueExporter creates a new instance of MessageQueueExporter.

func (*MessageQueueExporter) GetConfig

func (m *MessageQueueExporter) GetConfig() MQConfig

GetConfig returns the current configuration.

func (*MessageQueueExporter) GetMetrics

func (m *MessageQueueExporter) GetMetrics() (produced, failed, bytes, batches int64)

GetMetrics returns the current production statistics.

func (*MessageQueueExporter) IsRunning

func (m *MessageQueueExporter) IsRunning() bool

IsRunning checks if the exporter is currently active.

func (*MessageQueueExporter) SetConfig

func (m *MessageQueueExporter) SetConfig(config MQConfig) error

SetConfig updates the exporter configuration.

func (*MessageQueueExporter) Start

func (m *MessageQueueExporter) Start() error

Start begins the background export loop.

func (*MessageQueueExporter) Stop

func (m *MessageQueueExporter) Stop() error

Stop terminates the background export loop and closes producers.

type MetaServer

type MetaServer = cluster.MetaServer

func NewMetaServer

func NewMetaServer(store cluster.FlightBackend) *MetaServer

type MigrationHelper

type MigrationHelper struct{}

MigrationHelper provides utility functions for v23 migration

func NewMigrationHelper

func NewMigrationHelper() *MigrationHelper

NewMigrationHelper creates a new migration helper

func (*MigrationHelper) ValidateAction

func (mh *MigrationHelper) ValidateAction(action *genflight.Action) error

ValidateAction validates action for v23 compatibility

func (*MigrationHelper) ValidateFlightDescriptor

func (mh *MigrationHelper) ValidateFlightDescriptor(desc *flight.FlightDescriptor) error

ValidateFlightDescriptor validates flight descriptor for v23 compatibility

func (*MigrationHelper) ValidateFlightInfo

func (mh *MigrationHelper) ValidateFlightInfo(info *flight.FlightInfo) error

ValidateFlightInfo validates flight info for v23 compatibility

type MigrationTask

type MigrationTask struct {
	ShardID    string    `json:"shard_id"`
	FromNode   string    `json:"from_node"`
	ToNode     string    `json:"to_node"`
	Vectors    int64     `json:"vectors"`
	Reason     string    `json:"reason"`
	Status     string    `json:"status"`
	StartedAt  time.Time `json:"started_at"`
	FinishedAt time.Time `json:"finished_at,omitempty"`
}

MigrationTask represents a live shard data migration between source and destination nodes.

type ModelHealthStatus

type ModelHealthStatus struct {
	ModelName   string    `json:"model_name"`
	Provider    string    `json:"provider"`
	Status      string    `json:"status"` // "healthy", "degraded", "unhealthy"
	LastChecked time.Time `json:"last_checked"`
	LatencyMs   int64     `json:"latency_ms"`
	ErrorCount  int       `json:"error_count"`
}

ModelHealthStatus tracks the availability and performance of an embedding model.

type ModelVersion

type ModelVersion struct {
	Version   string    `json:"version"`
	ModelName string    `json:"model_name"`
	Provider  string    `json:"provider"`
	CreatedAt time.Time `json:"created_at"`
	IsDefault bool      `json:"is_default"`
	Dimension int       `json:"dimension"`
	Checksum  string    `json:"checksum,omitempty"`
}

ModelVersion tracks metadata for a specific version of an embedding model.

type MortonGrid

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

MortonGrid is a linear spatial index: a uniform grid of Z-order (Morton) coded cells backed by contiguous slices, used instead of the recursive Quadtree. The covered bounds are cut into 2^bits x 2^bits cells, a cell is identified by the 64-bit Morton code of its corner, and indexed points are appended to a single contiguous arena. The cell directory is an open-addressed table of uint32 chain heads, so an insert only grows flat slices and never allocates a child node the way Quadtree.subdivide does.

QueryBox converts a query into a cell rectangle, walks the Z-order code interval of that rectangle and filters every candidate with the same inclusive lat/lon comparison the Quadtree applies, so both indexes return the same point set for the same inputs. MortonGrid is safe for concurrent use.

func NewMortonGrid

func NewMortonGrid(bounds GeoBoundingBox, expectedPoints int, datasetName string) *MortonGrid

NewMortonGrid creates a Morton-coded spatial grid over bounds using the default cell resolution. expectedPoints pre-sizes the entry arena and the cell directory; values <= 0 fall back to a modest default.

func NewMortonGridWithResolution

func NewMortonGridWithResolution(bounds GeoBoundingBox, bits, expectedPoints int, datasetName string) *MortonGrid

NewMortonGridWithResolution creates a Morton-coded spatial grid with an explicit per-axis cell resolution of 2^bits cells per axis (1 <= bits <= 32). expectedPoints pre-sizes the entry arena and the cell directory.

func (*MortonGrid) Bits

func (g *MortonGrid) Bits() int

Bits returns the per-axis cell resolution of the grid.

func (*MortonGrid) CellCount

func (g *MortonGrid) CellCount() int

CellCount returns the number of occupied cells.

func (*MortonGrid) Contains

func (g *MortonGrid) Contains(point GeoPoint) bool

Contains checks if a GeoPoint is within the grid bounds.

func (*MortonGrid) Insert

func (g *MortonGrid) Insert(vec *GeoIndexedVector) bool

Insert adds a geographic vector to the grid. It reports whether the point fell inside the grid bounds; points outside the bounds are rejected, exactly like Quadtree.Insert.

func (*MortonGrid) Len

func (g *MortonGrid) Len() int

Len returns the number of indexed points.

func (*MortonGrid) QueryBox

func (g *MortonGrid) QueryBox(box GeoBoundingBox) []*GeoIndexedVector

QueryBox returns all vectors within a bounding box.

func (*MortonGrid) QueryBoxAppend

func (g *MortonGrid) QueryBoxAppend(box GeoBoundingBox, results *[]*GeoIndexedVector)

QueryBoxAppend appends all vectors within box to the target results slice without extra allocations.

func (*MortonGrid) QueryBoxBitmap

func (g *MortonGrid) QueryBoxBitmap(box GeoBoundingBox, bm *roaring.Bitmap)

QueryBoxBitmap populates bm with matching VectorIDs within box.

func (*MortonGrid) QueryRadius

func (g *MortonGrid) QueryRadius(center GeoPoint, radiusKm float64, results *[]*GeoIndexedVector)

QueryRadius returns all vectors within a given radius from a point.

func (*MortonGrid) QueryRadiusPruned

func (g *MortonGrid) QueryRadiusPruned(center GeoPoint, radiusKm float64, results *[]*GeoIndexedVector)

QueryRadiusPruned returns vectors within radiusKm, filtering points by Haversine distance (MortonGrid has no tree to prune, so this is a leaf filter).

type MultiModalConfig

type MultiModalConfig struct {
	Dimension          int    `json:"dimension"`
	ImageModel         string `json:"image_model"`          // e.g. "openclip-vit-b32"
	AudioModel         string `json:"audio_model"`          // e.g. "whisper-clap-v1"
	InferenceEndpoint  string `json:"inference_endpoint"`   // optional Triton / ONNX / OpenCLIP HTTP server
	WASMModelPath      string `json:"wasm_model_path"`      // optional local .wasm/.onnx embedding backend
	InferenceTimeoutMs int    `json:"inference_timeout_ms"` // HTTP inference timeout
}

MultiModalConfig configures CLIP/OpenCLIP and Whisper/CLAP inference endpoints or local backends.

type MultiModalEmbedder

type MultiModalEmbedder interface {
	Dimension() int
	EmbedText(ctx context.Context, text string) ([]float32, error)
	EmbedImage(ctx context.Context, raw []byte, mimeType, caption string) ([]float32, error)
	EmbedAudio(ctx context.Context, raw []byte, mimeType, transcript string) ([]float32, error)
}

MultiModalEmbedder projects text, image, and audio inputs into a shared normalized embedding space.

type MultiModalItem

type MultiModalItem struct {
	ID        string         `json:"id"`
	Modality  MediaModality  `json:"modality"`
	MimeType  string         `json:"mime_type,omitempty"`
	SourceURI string         `json:"source_uri,omitempty"`
	Caption   string         `json:"caption,omitempty"`
	Blob      []byte         `json:"blob,omitempty"`
	BlobB64   string         `json:"blob_base64,omitempty"`
	Vector    []float32      `json:"vector,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

MultiModalItem represents one multi-modal record for embedding and Arrow storage.

type MultiModalPipeline

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

MultiModalPipeline manages embedding generation, S3/Parquet ingestion, and cross-modal search.

func NewMultiModalPipeline

func NewMultiModalPipeline(s *VectorStore, cfg MultiModalConfig) (*MultiModalPipeline, error)

NewMultiModalPipeline creates a multi-modal pipeline attached to VectorStore.

func (*MultiModalPipeline) IngestItems

func (p *MultiModalPipeline) IngestItems(ctx context.Context, dataset string, items []MultiModalItem) (int, error)

IngestItems embeds missing vectors and stores multi-modal Arrow batches (`blob + modality + vector`).

func (*MultiModalPipeline) IngestParquetFile

func (p *MultiModalPipeline) IngestParquetFile(ctx context.Context, dataset, parquetPath string) (int, error)

IngestParquetFile reads Parquet multi-modal media rows and ingests them via IngestItems.

func (*MultiModalPipeline) Search

Search performs cross-modal text-to-image, image-to-text, or audio-to-text search.

func (*MultiModalPipeline) SetEmbedder

func (p *MultiModalPipeline) SetEmbedder(emb MultiModalEmbedder)

SetEmbedder injects a custom/ONNX/mock MultiModalEmbedder.

type MultiModalSearchRequest

type MultiModalSearchRequest struct {
	Dataset     string        `json:"dataset"`
	Modality    MediaModality `json:"modality,omitempty"` // optional filter: "image", "audio", "text"
	TextQuery   string        `json:"text_query,omitempty"`
	ImageBase64 string        `json:"image_base64,omitempty"`
	AudioBase64 string        `json:"audio_base64,omitempty"`
	MediaURI    string        `json:"media_uri,omitempty"`
	MimeType    string        `json:"mime_type,omitempty"`
	K           int           `json:"k"`
}

MultiModalSearchRequest defines text or media-based cross-modal search options.

type MutableGraphBackend

type MutableGraphBackend interface {
	GraphBackend

	// SetNeighbors updates the neighbors of the given node at the specified layer.
	SetNeighbors(layer int, nodeID uint32, neighbors []uint32)

	// SetLevel sets the level of a node.
	SetLevel(nodeID uint32, level int)

	// Grow ensures the backend has capacity for at least minCap nodes.
	// returns true if growth happened.
	Grow(minCap int) bool
}

MutableGraphBackend extends GraphBackend with write operations. In-memory implementations usually support this.

type Namespace

type Namespace struct {
	Name      string
	CreatedAt time.Time
	Metadata  map[string]string

	MaxVectors          int64
	MaxDimensions       int
	MaxStorageBytes     int64
	CurrentVectors      int64
	CurrentStorageBytes int64
	// contains filtered or unexported fields
}

Namespace represents a tenant isolation unit containing related datasets. Namespaces provide multi-tenancy support with dataset isolation.

func NewNamespace

func NewNamespace(name string) *Namespace

NewNamespace creates a new namespace with the given name.

func (*Namespace) AddDataset

func (n *Namespace) AddDataset(name string)

AddDataset registers a dataset in this namespace.

func (*Namespace) AddUsage

func (n *Namespace) AddUsage(vectors int64, storageBytes int64)

AddUsage increments the current resource usage counters for the namespace.

func (*Namespace) CheckQuota

func (n *Namespace) CheckQuota(vectors int64, dimensions int, storageBytes int64) error

CheckQuota verifies if the requested resources fit within the namespace's allocated quota.

func (*Namespace) DatasetCount

func (n *Namespace) DatasetCount() int

DatasetCount returns the number of datasets in this namespace.

func (*Namespace) GetUsage

func (n *Namespace) GetUsage() (vectors int64, storageBytes int64)

GetUsage returns the current vector count and storage bytes used by the namespace.

func (*Namespace) HasDataset

func (n *Namespace) HasDataset(name string) bool

HasDataset checks if a dataset exists in this namespace.

func (*Namespace) ListDatasets

func (n *Namespace) ListDatasets() []string

ListDatasets returns a list of all dataset names registered in this namespace.

func (*Namespace) RemoveDataset

func (n *Namespace) RemoveDataset(name string)

RemoveDataset removes a dataset from this namespace.

func (*Namespace) RemoveUsage

func (n *Namespace) RemoveUsage(vectors int64, storageBytes int64)

RemoveUsage decrements the current resource usage counters for the namespace.

func (*Namespace) SetQuota

func (n *Namespace) SetQuota(maxVectors int64, maxDimensions int, maxStorageBytes int64)

SetQuota configures resource limits for the namespace, including max vectors, dimensions, and storage.

type NamespaceMigrationConfig

type NamespaceMigrationConfig struct {
	SourceNamespace string
	TargetNamespace string
	TargetNode      string
	Datasets        []string
	CopyMode        bool
}

NamespaceMigrationConfig defines the parameters for migrating a namespace.

type NamespaceMigrationResult

type NamespaceMigrationResult struct {
	Success          bool
	MigratedDatasets int
	FailedDatasets   []string
	Duration         time.Duration
}

NamespaceMigrationResult contains the outcome of a namespace migration.

type NamespaceRateLimiter

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

NamespaceRateLimiter implements rate limiting for a specific namespace.

func (*NamespaceRateLimiter) Allow

func (r *NamespaceRateLimiter) Allow() bool

Allow returns true if a request is allowed under the current rate limit.

func (*NamespaceRateLimiter) GetConfig

func (r *NamespaceRateLimiter) GetConfig() RateLimitConfig

GetConfig returns the current rate limit configuration for the namespace.

func (*NamespaceRateLimiter) SetConfig

func (r *NamespaceRateLimiter) SetConfig(config RateLimitConfig)

SetConfig updates the rate limit configuration for the namespace.

type NeighborProvider

type NeighborProvider interface {
	GetNeighborsBulk(ctx context.Context, dataset string, nodeIDs []uint32) (map[uint32][]uint32, error)
}

NeighborProvider defines an interface for bulk neighbor lookups.

type NodeMonitor

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

NodeMonitor tracks local resource usage to provide load balancing hints.

func NewNodeMonitor

func NewNodeMonitor() *NodeMonitor

NewNodeMonitor creates and starts a new NodeMonitor.

func (*NodeMonitor) DecrementQueue

func (nm *NodeMonitor) DecrementQueue()

DecrementQueue decreases the queue depth by one.

func (*NodeMonitor) GetLoadHints

func (nm *NodeMonitor) GetLoadHints() loadbalancing.LoadHints

GetLoadHints returns current load balancing hints.

func (*NodeMonitor) IncrementQueue

func (nm *NodeMonitor) IncrementQueue()

IncrementQueue increases the queue depth by one.

func (*NodeMonitor) Stop

func (nm *NodeMonitor) Stop()

Stop terminates the background monitoring loop.

type NotExpr

type NotExpr = types.NotExpr

NotExpr represents a logical NOT operation on a filter expression.

type ONNXReranker

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

ONNXReranker uses ONNX Runtime or WASM for cross-encoder reranking.

func NewONNXReranker

func NewONNXReranker(modelPath string, logger zerolog.Logger) (*ONNXReranker, error)

NewONNXReranker creates a new ONNX-based reranker.

func (*ONNXReranker) Close

func (r *ONNXReranker) Close() error

Close releases the underlying ML model resources.

func (*ONNXReranker) Rerank

func (r *ONNXReranker) Rerank(ctx context.Context, query string, results []SearchResult) ([]SearchResult, error)

Rerank performs second-stage reranking on search results using an ML model.

type OllamaConfig

type OllamaConfig = index.OllamaConfig

type OptimisticConcurrentConfig

type OptimisticConcurrentConfig struct {
	MaxRetries       int    `json:"max_retries"`
	RetryDelayMs     int    `json:"retry_delay_ms"`
	VersionCacheSize int    `json:"version_cache_size"`
	EnableVersioning bool   `json:"enable_versioning"`
	ConflictStrategy string `json:"conflict_strategy"` // abort, overwrite, merge
}

OptimisticConcurrentConfig defines the configuration for optimistic concurrency control.

type OptimisticConcurrentUpdates

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

OptimisticConcurrentUpdates manages optimistic concurrency for vector updates.

func NewOptimisticConcurrentUpdates

func NewOptimisticConcurrentUpdates(logger zerolog.Logger, config OptimisticConcurrentConfig) *OptimisticConcurrentUpdates

NewOptimisticConcurrentUpdates creates a new OptimisticConcurrentUpdates manager.

func (*OptimisticConcurrentUpdates) BatchUpdate

func (o *OptimisticConcurrentUpdates) BatchUpdate(updates []OptimisticUpdate, modifiedBy string) []UpdateResult

BatchUpdate performs multiple vector updates concurrently.

func (*OptimisticConcurrentUpdates) ClearCache

func (o *OptimisticConcurrentUpdates) ClearCache()

ClearCache removes all version information from the cache.

func (*OptimisticConcurrentUpdates) DeleteVector

func (o *OptimisticConcurrentUpdates) DeleteVector(vectorID string)

DeleteVector removes the version information for a vector.

func (*OptimisticConcurrentUpdates) GetCacheSize

func (o *OptimisticConcurrentUpdates) GetCacheSize() int

GetCacheSize returns the number of vectors currently in the version cache.

func (*OptimisticConcurrentUpdates) GetConfig

GetConfig returns the current configuration for optimistic concurrency control.

func (*OptimisticConcurrentUpdates) GetStats

func (o *OptimisticConcurrentUpdates) GetStats() (attempted, succeeded, conflicted, retried, aborted int64)

GetStats returns the current operational statistics for optimistic updates.

func (*OptimisticConcurrentUpdates) GetVectorInfo

func (o *OptimisticConcurrentUpdates) GetVectorInfo(vectorID string) (*VectorVersion, bool)

GetVectorInfo retrieves the full version information for a specific vector.

func (*OptimisticConcurrentUpdates) GetVersion

func (o *OptimisticConcurrentUpdates) GetVersion(vectorID string) (uint64, bool)

GetVersion retrieves the current version of a vector.

func (*OptimisticConcurrentUpdates) SetConfig

SetConfig updates the configuration for optimistic concurrency control.

func (*OptimisticConcurrentUpdates) SetVersion

func (o *OptimisticConcurrentUpdates) SetVersion(vectorID string, version uint64, vector []float32)

SetVersion explicitly sets the version and data for a vector.

func (*OptimisticConcurrentUpdates) UpdateVector

func (o *OptimisticConcurrentUpdates) UpdateVector(vectorID string, newVector []float32, expectedVersion uint64, modifiedBy string) UpdateResult

UpdateVector attempts to update a vector, failing if the expected version does not match.

func (*OptimisticConcurrentUpdates) UpdateVectorWithRetry

func (o *OptimisticConcurrentUpdates) UpdateVectorWithRetry(vectorID string, newVector []float32, expectedVersion uint64, modifiedBy string) UpdateResult

UpdateVectorWithRetry attempts to update a vector, retrying on conflicts according to the configuration.

type OptimisticStats

type OptimisticStats struct {
	UpdatesAttempted  atomic.Int64
	UpdatesSucceeded  atomic.Int64
	UpdatesConflicted atomic.Int64
	UpdatesRetried    atomic.Int64
	UpdatesAborted    atomic.Int64
}

OptimisticStats tracks operational statistics for optimistic updates.

type OptimisticUpdate

type OptimisticUpdate struct {
	VectorID   string
	Vector     []float32
	Version    uint64
	Timestamp  time.Time
	RetryCount int
}

OptimisticUpdate represents a request to update a vector with optimistic concurrency control.

type OptimizedSearchContext

type OptimizedSearchContext struct {
	PrefetchEnabled bool
	PrefetchDist    int
}

OptimizedSearchContext maintains state for an individual search operation, enabling optimizations like prefetching.

func (*OptimizedSearchContext) PrefetchNode

func (ctx *OptimizedSearchContext) PrefetchNode(nodeID uint32)

PrefetchNode hints to the memory subsystem to load a node's data.

type OrExpr

type OrExpr = types.OrExpr

OrExpr represents a logical OR operation between multiple filter expressions.

type PITRConfig

type PITRConfig struct {
	BackupID     string
	DatasetName  string
	WALDir       string
	TargetTime   time.Time // Replay entries up to TargetTime (inclusive); zero means unlimited
	TargetMaxSeq uint64    // Replay entries up to TargetMaxSeq (inclusive); 0 means unlimited
	VerifyOnly   bool
}

PITRConfig configures Point-in-Time Recovery using a baseline snapshot + WAL replay (Item 4.4).

type PackedAdjacency

type PackedAdjacency = hnswcore.PackedAdjacency

PackedAdjacency stores graph neighbors in a compact, cache-friendly format.

type PageRankConfig

type PageRankConfig struct {
	DampingFactor float32
	MaxIterations int
	Tolerance     float32
}

PageRankConfig controls the PageRank execution.

func DefaultPageRankConfig

func DefaultPageRankConfig() PageRankConfig

DefaultPageRankConfig returns standard defaults.

type ParallelRecordReader

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

ParallelRecordReader handles gRPC-to-Arrow decoding in parallel

func NewParallelRecordReader

func NewParallelRecordReader(stream flight.FlightService_DoPutServer, alloc memory.Allocator, logger zerolog.Logger) (*ParallelRecordReader, error)

NewParallelRecordReader creates a new ParallelRecordReader that decodes Flight data in parallel.

func (*ParallelRecordReader) Err

func (pr *ParallelRecordReader) Err() error

Err returns the first error encountered during reading.

func (*ParallelRecordReader) LatestFlightDescriptor

func (pr *ParallelRecordReader) LatestFlightDescriptor() *flight.FlightDescriptor

LatestFlightDescriptor returns the flight descriptor from the most recent message.

func (*ParallelRecordReader) Next

func (pr *ParallelRecordReader) Next() bool

Next advances to the next record batch. It returns false if there are no more batches or an error occurred.

func (*ParallelRecordReader) RecordBatch

func (pr *ParallelRecordReader) RecordBatch() arrow.RecordBatch

RecordBatch returns the most recently read record batch.

func (*ParallelRecordReader) Release

func (pr *ParallelRecordReader) Release()

Release shuts down the reader and releases all resources.

func (*ParallelRecordReader) Schema

func (pr *ParallelRecordReader) Schema() *arrow.Schema

Schema returns the Arrow schema for the records being read.

type ParallelSearchConfig

type ParallelSearchConfig = types.ParallelSearchConfig

ParallelSearchConfig defines configuration for parallel search operations.

type ParallelSearchResult

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

ParallelSearchResult aggregates search results from multiple threads in a thread-safe manner.

func NewParallelSearchResult

func NewParallelSearchResult(k int, total uint32) *ParallelSearchResult

NewParallelSearchResult creates a new aggregator for k results.

func (*ParallelSearchResult) Add

func (r *ParallelSearchResult) Add(candidate BeamSearchCandidate)

Add incorporates a candidate into the shared result set.

func (*ParallelSearchResult) Get

Get returns the final sorted search results.

type ParquetIngester

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

ParquetIngester handles high-performance ingestion from Parquet files

func NewParquetIngester

func NewParquetIngester(ds *Dataset, batchSize int) *ParquetIngester

NewParquetIngester creates a new Parquet ingester for the given dataset and batch size.

func (*ParquetIngester) Ingest

func (pi *ParquetIngester) Ingest(ctx context.Context, path string) (int64, error)

Ingest performs high-throughput ingestion from a Parquet file. It uses io_uring for zero-copy reads on Linux if available.

type ParquetMediaRow

type ParquetMediaRow struct {
	ID        string    `parquet:"id"`
	Modality  string    `parquet:"modality"`
	MimeType  string    `parquet:"mime_type,optional"`
	SourceURI string    `parquet:"source_uri,optional"`
	Caption   string    `parquet:"caption,optional"`
	Blob      []byte    `parquet:"blob,optional"`
	Vector    []float32 `parquet:"vector,list,optional"`
}

ParquetMediaRow matches Parquet multi-modal export/ingest row layouts.

type ParquetRow

type ParquetRow struct {
	ID     int64     `parquet:"id"`
	Vector []float32 `parquet:"vector"`
}

ParquetRow represents a single vectorized record in Parquet

type PartitionedRecords

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

PartitionedRecords provides partitioned storage for Arrow RecordBatches. Each partition has its own lock, enabling concurrent access to different partitions.

func NewPartitionedRecords

func NewPartitionedRecords(cfg PartitionedRecordsConfig) *PartitionedRecords

NewPartitionedRecords creates new partitioned records with given config.

func NewPartitionedRecordsDefault

func NewPartitionedRecordsDefault() *PartitionedRecords

NewPartitionedRecordsDefault creates partitioned records with default config.

func (*PartitionedRecords) Append

func (pr *PartitionedRecords) Append(batch arrow.RecordBatch, routingKey uint64)

Append adds a batch to a partition based on the provided routing key. The batch is retained (ref count incremented).

func (*PartitionedRecords) AppendToPartition

func (pr *PartitionedRecords) AppendToPartition(batch arrow.RecordBatch, partIdx int)

AppendToPartition adds a batch directly to a specific partition.

func (*PartitionedRecords) AppendWithKey

func (pr *PartitionedRecords) AppendWithKey(batch arrow.RecordBatch, key uint64) int

AppendWithKey adds a batch using hash-based routing, returns partition index.

func (*PartitionedRecords) Clear

func (pr *PartitionedRecords) Clear()

Clear removes all batches from all partitions.

func (*PartitionedRecords) ForEach

func (pr *PartitionedRecords) ForEach(fn func(batch arrow.RecordBatch, partition int) bool)

ForEach iterates over all batches, calling fn for each. If fn returns false, iteration stops early.

func (*PartitionedRecords) ForEachInPartition

func (pr *PartitionedRecords) ForEachInPartition(partIdx int, fn func(batch arrow.RecordBatch) bool)

ForEachInPartition iterates over batches in a specific partition.

func (*PartitionedRecords) GetAll

func (pr *PartitionedRecords) GetAll() []arrow.RecordBatch

GetAll returns all batches across all partitions. Caller should NOT release returned batches - they are still owned by PartitionedRecords.

func (*PartitionedRecords) GetPartition

func (pr *PartitionedRecords) GetPartition(partIdx int) []arrow.RecordBatch

GetPartition returns all batches from a specific partition.

func (*PartitionedRecords) NumPartitions

func (pr *PartitionedRecords) NumPartitions() int

NumPartitions returns the number of partitions.

func (*PartitionedRecords) PartitionBatches

func (pr *PartitionedRecords) PartitionBatches(partitionIdx int) int

PartitionBatches returns the number of batches in a specific partition.

func (*PartitionedRecords) ReplaceAll

func (pr *PartitionedRecords) ReplaceAll(partIdx int, batches []arrow.RecordBatch)

ReplaceAll atomically replaces all batches in a partition.

func (*PartitionedRecords) Stats

Stats returns current statistics.

func (*PartitionedRecords) TotalBatches

func (pr *PartitionedRecords) TotalBatches() int

TotalBatches returns the total number of batches across all partitions.

type PartitionedRecordsConfig

type PartitionedRecordsConfig struct {
	NumPartitions int // Number of partitions (default: runtime.NumCPU())
}

PartitionedRecordsConfig configures partitioned records storage.

func DefaultPartitionedRecordsConfig

func DefaultPartitionedRecordsConfig() PartitionedRecordsConfig

DefaultPartitionedRecordsConfig returns sensible defaults.

func (PartitionedRecordsConfig) Validate

func (c PartitionedRecordsConfig) Validate() error

Validate checks configuration validity.

type PartitionedRecordsStats

type PartitionedRecordsStats struct {
	TotalBatches   int
	NumPartitions  int
	BatchesPerPart []int
}

PartitionedRecordsStats holds statistics for partitioned records.

type Path

type Path struct {
	Nodes []VectorID
	Edges []Edge
	Score float32
}

Path represents a sequence of nodes and edges found during traversal.

type PathPriorityQueue

type PathPriorityQueue []Path

PathPriorityQueue for weighted traversal

func (PathPriorityQueue) Len

func (pq PathPriorityQueue) Len() int

Len returns the number of paths in the queue.

func (PathPriorityQueue) Less

func (pq PathPriorityQueue) Less(i, j int) bool

func (*PathPriorityQueue) Pop

func (pq *PathPriorityQueue) Pop() any

Pop removes the highest-scoring path from the priority queue.

func (*PathPriorityQueue) Push

func (pq *PathPriorityQueue) Push(x any)

Push adds a path to the priority queue.

func (PathPriorityQueue) Swap

func (pq PathPriorityQueue) Swap(i, j int)

type PeekedStream

type PeekedStream struct {
	flight.FlightService_DoExchangeServer
	// contains filtered or unexported fields
}

PeekedStream wraps DoExchangeServer to inject a pre-read message

func (*PeekedStream) Recv

func (p *PeekedStream) Recv() (*flight.FlightData, error)

Recv reads the next message from the stream, returning the peeked message first if available.

type PeerReplicator

type PeerReplicator = cluster.PeerReplicator

func NewPeerReplicator

func NewPeerReplicator(cfg cluster.ReplicatorConfig) *PeerReplicator

type Permission

type Permission string

Permission defines a specific action that can be performed in the system.

const (
	// PermRead allows reading vector data and metadata.
	PermRead Permission = "read"
	// PermWrite allows updating existing vectors and metadata.
	PermWrite Permission = "write"
	// PermDelete allows deleting vectors and datasets.
	PermDelete Permission = "delete"
	// PermIngest allows adding new vectors to datasets.
	PermIngest Permission = "ingest"
	// PermAdmin allows performing administrative tasks like backup and sync.
	PermAdmin Permission = "admin"
	// PermBackup allows performing dataset backups.
	PermBackup Permission = "backup"
	// PermManageKeys allows creating, rotating, and revoking API keys.
	PermManageKeys Permission = "manage-keys"
	// PermManageTenant allows managing tenant namespaces, RLS policies, and quotas.
	PermManageTenant Permission = "manage-tenant"
)

type PipelineResult

type PipelineResult struct {
	Record arrow.RecordBatch
	Index  int
}

PipelineResult holds a filtered record with its original index for ordering

type PipelineStage

type PipelineStage struct {
	Record    arrow.RecordBatch
	BatchIdx  int
	Tombstone *types.Bitset // Legacy field
	Err       error
}

PipelineStage is the legacy result type expected by store.go

type PipelineStats

type PipelineStats struct {
	BatchesProcessed int64
	BatchesFiltered  int64
	ErrorCount       int64
}

PipelineStats tracks pipeline processing statistics

type PooledAllocator

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

PooledAllocator implements memory.Allocator with buffer pooling to reduce GC pressure during high-throughput ingestion. It uses size-bucketed sync.Pools for efficient buffer reuse.

func NewPooledAllocator

func NewPooledAllocator() *PooledAllocator

NewPooledAllocator creates a new pooled allocator. The underlying allocator is used for allocations larger than 32MB.

func (*PooledAllocator) Allocate

func (p *PooledAllocator) Allocate(size int) []byte

Allocate returns a buffer of at least the requested size. Buffers may be larger than requested due to bucketing.

func (*PooledAllocator) Free

func (p *PooledAllocator) Free(b []byte)

Free returns a buffer to the appropriate pool.

func (*PooledAllocator) Reallocate

func (p *PooledAllocator) Reallocate(size int, b []byte) []byte

Reallocate resizes a buffer, potentially reusing pooled memory.

func (*PooledAllocator) Stats

Stats returns current allocator statistics.

type PooledAllocatorStats

type PooledAllocatorStats struct {
	AllocatedBytes int64
	ReusedBuffers  int64
}

PooledAllocatorStats returns allocator statistics.

type PredicatePushdownOptimizer

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

PredicatePushdownOptimizer manages filter pushdown optimizations for multiple indices to accelerate filtered search.

func NewPredicatePushdownOptimizer

func NewPredicatePushdownOptimizer() *PredicatePushdownOptimizer

NewPredicatePushdownOptimizer creates a new optimizer instance.

func (*PredicatePushdownOptimizer) ApplyPushdown

func (ppo *PredicatePushdownOptimizer) ApplyPushdown(filters []query.Filter) (map[string][]uint32, error)

ApplyPushdown executes the pushdown optimization and returns the resulting node ID sets.

func (*PredicatePushdownOptimizer) GetStats

func (ppo *PredicatePushdownOptimizer) GetStats() map[string]interface{}

GetStats returns usage statistics for the optimizer.

func (*PredicatePushdownOptimizer) Optimize

func (ppo *PredicatePushdownOptimizer) Optimize(filters []query.Filter) (pushable []query.Filter, nonPushable []query.Filter)

Optimize separates filters into those that can be pushed down and those that cannot.

func (*PredicatePushdownOptimizer) RegisterHNSW

func (ppo *PredicatePushdownOptimizer) RegisterHNSW(name string, hnsw *ArrowHNSW, fields []string)

RegisterHNSW associates an HNSW index with the optimizer.

type PressureLevel

type PressureLevel int32

PressureLevel indicates the current memory pressure state.

const (
	// PressureNone indicates no memory pressure.
	PressureNone PressureLevel = iota
	// PressureSoft indicates memory usage is above the soft limit; operations are delayed.
	PressureSoft
	// PressureHard indicates memory usage is above the hard limit; operations are blocked.
	PressureHard
)

type PricingModel

type PricingModel struct {
	CostPer1KQueries      float64 `json:"cost_per_1k_queries"`
	CostPer1MVectors      float64 `json:"cost_per_1m_vectors"`
	CostPerGBMonthStorage float64 `json:"cost_per_gb_month_storage"`
	CostPerGBEgress       float64 `json:"cost_per_gb_egress"`
	CostPer1KReranks      float64 `json:"cost_per_1k_reranks"`
	Currency              string  `json:"currency"`
}

PricingModel defines unit billing prices used to compute estimated tenant charges.

func DefaultPricingModel

func DefaultPricingModel() PricingModel

DefaultPricingModel returns baseline SaaS unit pricing in USD.

type PriorityQueue

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

PriorityQueue implements a simple priority queue for I/O tasks.

func NewPriorityQueue

func NewPriorityQueue(maxSize int) *PriorityQueue

NewPriorityQueue creates a new PriorityQueue with a maximum size.

func (*PriorityQueue) Len

func (pq *PriorityQueue) Len() int

Len returns the number of items in the queue.

func (*PriorityQueue) Pop

func (pq *PriorityQueue) Pop() (IOScheduleItem, bool)

Pop removes and returns the highest priority item from the queue.

func (*PriorityQueue) Push

func (pq *PriorityQueue) Push(item IOScheduleItem) bool

Push adds an item to the priority queue. Returns false if full.

type ProvenanceManager

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

ProvenanceManager maintains vector lineage records and produces search explanations.

func NewProvenanceManager

func NewProvenanceManager(s *VectorStore) *ProvenanceManager

NewProvenanceManager creates a vector provenance & search explainability manager.

func (*ProvenanceManager) ExplainSearch

ExplainSearch runs dense + optional sparse/BM25 search alongside an HNSW graph traversal trace and returns per-candidate score breakdowns + provenance.

func (*ProvenanceManager) Get

func (pm *ProvenanceManager) Get(dataset, vectorID string) (VectorProvenance, bool)

Get retrieves provenance metadata for one vector.

func (*ProvenanceManager) ListByDataset

func (pm *ProvenanceManager) ListByDataset(dataset string, limit int) []VectorProvenance

ListByDataset returns tracked provenance entries for a dataset sorted by vector_id.

func (*ProvenanceManager) Record

func (pm *ProvenanceManager) Record(prov VectorProvenance) error

Record stores or updates provenance metadata for a vector, computing a content hash if absent.

type Quadtree

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

Quadtree implements a spatial partitioning structure using iterative stack traversal.

func NewQuadtree

func NewQuadtree(bounds GeoBoundingBox, capacity int, datasetName string) *Quadtree

NewQuadtree creates a new Quadtree instance with the given bounds and capacity.

func (*Quadtree) Contains

func (q *Quadtree) Contains(point GeoPoint) bool

Contains checks if a GeoPoint is within the quadtree bounds.

func (*Quadtree) Insert

func (q *Quadtree) Insert(vec *GeoIndexedVector) bool

Insert adds a geographic vector to the quadtree.

func (*Quadtree) QueryBox

func (q *Quadtree) QueryBox(box GeoBoundingBox) []*GeoIndexedVector

QueryBox returns all vectors within a bounding box.

func (*Quadtree) QueryBoxAppend

func (q *Quadtree) QueryBoxAppend(box GeoBoundingBox, results *[]*GeoIndexedVector)

QueryBoxAppend appends all vectors within box to the target results slice without extra allocations.

func (*Quadtree) QueryBoxBitmap

func (q *Quadtree) QueryBoxBitmap(box GeoBoundingBox, bm *roaring.Bitmap)

QueryBoxBitmap pre-computes a Roaring Bitmap of valid geospatial candidates via Quadtree bounding boxes.

func (*Quadtree) QueryRadius

func (q *Quadtree) QueryRadius(center GeoPoint, radiusKm float64, results *[]*GeoIndexedVector)

QueryRadius returns all vectors within a given radius from a point.

func (*Quadtree) QueryRadiusPruned

func (q *Quadtree) QueryRadiusPruned(center GeoPoint, radiusKm float64, results *[]*GeoIndexedVector)

QueryRadiusPruned returns vectors within radiusKm, pruning subtrees whose bounding box does not intersect the search circle and filtering points at leaves by Haversine distance.

type QuantizationTuner

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

QuantizationTuner handles automatic selection of quantization levels.

func NewQuantizationTuner

func NewQuantizationTuner(logger zerolog.Logger, store *VectorStore) *QuantizationTuner

NewQuantizationTuner creates a new tuner instance.

func (*QuantizationTuner) Start

func (t *QuantizationTuner) Start(ctx context.Context)

Start runs the periodic tuning loop.

func (*QuantizationTuner) TuneAll

func (t *QuantizationTuner) TuneAll()

TuneAll iterates through all datasets and performs tuning.

func (*QuantizationTuner) TuneDataset

func (t *QuantizationTuner) TuneDataset(name string, ds *Dataset)

TuneDataset evaluates and potentially adjusts quantization for a single dataset.

type QuantizationType

type QuantizationType string

QuantizationType represents the supported quantization levels.

const (
	// QuantizationFloat32 uses 32-bit floating point numbers (full precision).
	QuantizationFloat32 QuantizationType = "float32"
	// QuantizationFloat16 uses 16-bit floating point numbers.
	QuantizationFloat16 QuantizationType = "float16"
	// QuantizationInt8 uses 8-bit integers.
	QuantizationInt8 QuantizationType = "int8"
	// QuantizationPQ uses Product Quantization.
	QuantizationPQ QuantizationType = "pq"
	// QuantizationTurboQuant uses the high-performance TurboQuant compression.
	QuantizationTurboQuant QuantizationType = "turboquant"
)

type Quantizer

type Quantizer[T VectorType, U any] interface {
	// Encode converts a batch of vectors to quantized codes
	Encode([]T) []U
	// Decode converts quantized codes back to vectors
	Decode([]U) []T
	// Dims returns the number of dimensions
	Dims() int
}

Quantizer defines a generic quantizer interface. T is the input vector type, U is the output code type

This interface allows quantizers to work with different vector types while maintaining type safety through generic parameters.

Supported combinations: - float32 vectors -> uint8 codes (SQ8) - float32 vectors -> uint64 codes (BQ) - float32 vectors -> byte codes (PQ) - Future: float16 vectors, int8 vectors

type QuantizerType

type QuantizerType interface{}

QuantizerType identifies all quantizer types

type QueryAnalyticsEntry

type QueryAnalyticsEntry struct {
	Query        string    `json:"query"`
	Count        int64     `json:"count"`
	ZeroResults  int64     `json:"zero_results"`
	AvgLatencyMs float64   `json:"avg_latency_ms"`
	LastSeen     time.Time `json:"last_seen"`
}

QueryAnalyticsEntry summarizes query popularity and zero-result diagnostics.

type QueryFeatures

type QueryFeatures = index.QueryFeatures

type QueryRewriteMode

type QueryRewriteMode string

QueryRewriteMode specifies query expansion strategy.

const (
	RewriteSynonyms   QueryRewriteMode = "synonyms"
	RewriteMultiQuery QueryRewriteMode = "multi_query"
	RewriteHyDE       QueryRewriteMode = "hyde"
)

type QueryRewriter

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

QueryRewriter expands, decomposes, or HyDE-augments queries prior to retrieval/reranking.

func NewQueryRewriter

func NewQueryRewriter() *QueryRewriter

NewQueryRewriter initializes a rewriter with technical & domain synonyms.

func (*QueryRewriter) AddSynonyms

func (qr *QueryRewriter) AddSynonyms(term string, expansions []string)

AddSynonyms registers custom domain synonyms.

func (*QueryRewriter) Rewrite

func (qr *QueryRewriter) Rewrite(query string, mode QueryRewriteMode) []string

Rewrite returns rewritten/expanded query variants.

type QueryStats

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

QueryStats tracks performance metrics for searches on a dataset.

func (*QueryStats) GetMetrics

func (s *QueryStats) GetMetrics() (p50, p99, avg float64, recall float64, qps float64)

GetMetrics returns the calculated performance metrics.

func (*QueryStats) Record

func (s *QueryStats) Record(latency time.Duration, recall float64)

Record adds a new sample to the query statistics.

type QuorumManager

type QuorumManager = cluster.QuorumManager

type QuotaDecision

type QuotaDecision struct {
	Allowed     bool    `json:"allowed"`
	SoftWarning bool    `json:"soft_warning"`
	Resource    string  `json:"resource,omitempty"`
	Reason      string  `json:"reason,omitempty"`
	Utilization float64 `json:"utilization,omitempty"`
}

QuotaDecision describes whether an operation is permitted and whether a soft warning fired.

type RBACManager

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

RBACManager handles Role-Based Access Control for the vector store.

func NewRBACManager

func NewRBACManager() *RBACManager

NewRBACManager creates a new instance of RBACManager.

func (*RBACManager) AuthorizeToken

func (r *RBACManager) AuthorizeToken(ctx context.Context, rawToken, permission, namespace, dataset string) (*security.TenantContext, error)

AuthorizeToken implements security.AccessValidator, validating key, permission, and tenant/dataset scope.

func (*RBACManager) CheckPermission

func (r *RBACManager) CheckPermission(keyStr string, perm Permission, namespace, dataset string) (bool, error)

CheckPermission verifies if the provided API key has permission for a specific action in a namespace/dataset.

func (*RBACManager) CreateAPIKey

func (r *RBACManager) CreateAPIKey(name string, role Role, namespace string, datasets []string) (*APIKey, error)

CreateAPIKey generates and registers a new API key with the specified role and scope.

func (*RBACManager) CreateAPIKeyWithOptions

func (r *RBACManager) CreateAPIKeyWithOptions(opts APIKeyOptions) (*APIKey, string, error)

CreateAPIKeyWithOptions issues a new API key and returns both the key record and the raw secret string.

func (*RBACManager) DeleteAPIKey

func (r *RBACManager) DeleteAPIKey(keyStr string) error

DeleteAPIKey removes an API key from the registry.

func (*RBACManager) GetAPIKey

func (r *RBACManager) GetAPIKey(keyStr string) (*APIKey, bool)

GetAPIKey retrieves an API key by its raw string value or SHA-256 hash.

func (*RBACManager) ListAPIKeys

func (r *RBACManager) ListAPIKeys() []*APIKey

ListAPIKeys returns a list of all registered API keys (metadata without exposing raw secrets).

func (*RBACManager) RLSEvaluator

func (r *RBACManager) RLSEvaluator() *security.RLSEvaluator

RLSEvaluator returns the active RLS evaluator.

func (*RBACManager) RevokeAPIKey

func (r *RBACManager) RevokeAPIKey(keyStr string) error

RevokeAPIKey disables an existing API key by raw secret, KeyID, or hash.

func (*RBACManager) RotateAPIKey

func (r *RBACManager) RotateAPIKey(oldRawKey string, gracePeriod time.Duration) (*APIKey, string, error)

RotateAPIKey issues a replacement key with the same role/tenant scope and places a grace period on the old key.

func (*RBACManager) SetAuditLogger

func (r *RBACManager) SetAuditLogger(a *security.AuditLogger)

SetAuditLogger attaches an external AuditLogger.

func (*RBACManager) SetRLSEvaluator

func (r *RBACManager) SetRLSEvaluator(e *security.RLSEvaluator)

SetRLSEvaluator attaches a row-level security evaluator.

func (*RBACManager) UpdateAPIKey

func (r *RBACManager) UpdateAPIKey(keyStr string, role Role, namespace string, datasets []string) error

UpdateAPIKey updates the properties of an existing API key.

func (*RBACManager) ValidateAPIKey

func (r *RBACManager) ValidateAPIKey(keyStr string) (bool, error)

ValidateAPIKey checks if an API key exists, is enabled, and has not expired.

type RangeSearchRequest

type RangeSearchRequest = core.RangeSearchRequest

RangeSearchRequest defines a request for distance-threshold range search.

type RateLimitConfig

type RateLimitConfig struct {
	// RequestsPerSecond is the maximum number of requests allowed per second.
	RequestsPerSecond float64
	// Burst is the maximum number of requests that can be handled at once.
	Burst int
	// Enabled indicates whether rate limiting is active.
	Enabled bool
}

RateLimitConfig defines the configuration for namespace-level rate limiting.

type RateLimiter

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

RateLimiter wraps a token bucket limiter to provide easy integration with bandwidth-heavy background operations like compaction and snapshotting.

func NewRateLimiter

func NewRateLimiter(limitBytes int64) *RateLimiter

NewRateLimiter creates a new limiter with the specified bytes per second limit. If limitBytes is <= 0, it returns a no-op limiter (infinite rate).

func (*RateLimiter) Limit

func (rl *RateLimiter) Limit() float64

Limit returns the current limit in bytes per second.

func (*RateLimiter) SetLimit

func (rl *RateLimiter) SetLimit(limitBytes int64)

SetLimit updates the rate limit.

func (*RateLimiter) Wait

func (rl *RateLimiter) Wait(ctx context.Context, n int) error

Wait blocks until enough tokens are available for N bytes. If the limiter is disabled (nil), it returns immediately.

type RateLimiterManager

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

RateLimiterManager coordinates rate limiters across multiple namespaces.

func NewRateLimiterManager

func NewRateLimiterManager(defaultCfg RateLimitConfig) *RateLimiterManager

NewRateLimiterManager creates a new RateLimiterManager with the given default configuration.

func (*RateLimiterManager) Allow

func (m *RateLimiterManager) Allow(namespace string) bool

Allow checks if a request should be allowed for the given namespace.

func (*RateLimiterManager) GetLimiter

func (m *RateLimiterManager) GetLimiter(namespace string) *NamespaceRateLimiter

GetLimiter returns the rate limiter for the specified namespace, creating one if it doesn't exist.

func (*RateLimiterManager) RemoveLimit

func (m *RateLimiterManager) RemoveLimit(namespace string)

RemoveLimit deletes the rate limiter for a specific namespace.

func (*RateLimiterManager) SetLimit

func (m *RateLimiterManager) SetLimit(namespace string, config RateLimitConfig)

SetLimit configures the rate limit for a specific namespace.

type ReadRequest

type ReadRequest struct {
	ID     uint64
	Result chan ReadResult
}

ReadRequest tracks an asynchronous read operation.

type ReadResult

type ReadResult struct {
	N   int
	Err error
}

type RecordBuilderPool

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

RecordBuilderPool manages reusable array.RecordBuilder instances for specific schemas. This significantly reduces GC pressure on search hot paths by recycling builder buffers.

func NewRecordBuilderPool

func NewRecordBuilderPool(schema *arrow.Schema) *RecordBuilderPool

NewRecordBuilderPool creates a new pool for the given schema.

func (*RecordBuilderPool) Get

Get retrieves a builder from the pool.

func (*RecordBuilderPool) Put

Put returns a builder to the pool after resetting it. Important: All arrays created from this builder must be released BEFORE putting the builder back, OR the builder must be reset which releases internal references.

type RecordEvictionManager

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

RecordEvictionManager tracks eviction metadata for individual records Uses unsafe.Pointer as keys for zero-copy pointer-identity lookups

func NewRecordEvictionManager

func NewRecordEvictionManager() *RecordEvictionManager

NewRecordEvictionManager creates a new per-record eviction manager

func (*RecordEvictionManager) Count

func (m *RecordEvictionManager) Count() int

Count returns the number of tracked records

func (*RecordEvictionManager) EvictExpired

func (m *RecordEvictionManager) EvictExpired() []uintptr

EvictExpired removes all expired records and returns their pointers

func (*RecordEvictionManager) Get

Get retrieves metadata for a record by pointer identity

func (*RecordEvictionManager) GetEvictionCount

func (m *RecordEvictionManager) GetEvictionCount() int64

GetEvictionCount returns total number of records evicted

func (*RecordEvictionManager) Register

func (m *RecordEvictionManager) Register(rec arrow.RecordBatch, ttl time.Duration)

Register adds a record to the eviction manager with optional TTL

func (*RecordEvictionManager) SelectLFUVictims

func (m *RecordEvictionManager) SelectLFUVictims(count int) []uintptr

SelectLFUVictims returns pointers to the N least frequently accessed records

func (*RecordEvictionManager) SelectLRUVictims

func (m *RecordEvictionManager) SelectLRUVictims(count int) []uintptr

SelectLRUVictims returns pointers to the N least recently accessed records

func (*RecordEvictionManager) Unregister

func (m *RecordEvictionManager) Unregister(rec arrow.RecordBatch)

Unregister removes a record from the eviction manager

func (*RecordEvictionManager) UpdateRecordMetadataGauge

func (m *RecordEvictionManager) UpdateRecordMetadataGauge()

UpdateRecordMetadataGauge updates the gauge with current tracked record count

type RecordMetadata

type RecordMetadata struct {
	CreatedAt   int64         // Unix nanos - immutable after creation
	LastAccess  atomic.Int64  // Unix nanos - updated atomically on access
	AccessCount atomic.Int64  // Frequency counter - incremented atomically
	TTL         time.Duration // 0 = no expiration
}

RecordMetadata tracks per-record eviction information using atomics for zero-lock reads

func NewRecordMetadata

func NewRecordMetadata(ttl time.Duration) *RecordMetadata

NewRecordMetadata creates metadata for a record with optional TTL

func (*RecordMetadata) GetAccessCount

func (m *RecordMetadata) GetAccessCount() int64

GetAccessCount returns the total access count

func (*RecordMetadata) GetLastAccess

func (m *RecordMetadata) GetLastAccess() time.Time

GetLastAccess returns the last access time

func (*RecordMetadata) IsExpired

func (m *RecordMetadata) IsExpired() bool

IsExpired returns true if TTL has elapsed since creation

func (*RecordMetadata) RecordAccess

func (m *RecordMetadata) RecordAccess()

RecordAccess updates last access time and increments access count atomically

type RecordSizeCache

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

RecordSizeCache caches the size of Arrow record batches to avoid repeated calculations

func NewRecordSizeCache

func NewRecordSizeCache() *RecordSizeCache

NewRecordSizeCache creates a new cache

func (*RecordSizeCache) Clear

func (c *RecordSizeCache) Clear()

Clear empties the cache

func (*RecordSizeCache) GetOrCompute

func (c *RecordSizeCache) GetOrCompute(rec arrow.RecordBatch) int64

GetOrCompute returns the cached size or computes it

func (*RecordSizeCache) Hits

func (c *RecordSizeCache) Hits() int64

Hits returns hit count

func (*RecordSizeCache) Invalidate

func (c *RecordSizeCache) Invalidate(rec arrow.RecordBatch)

Invalidate removes a record from cache

func (*RecordSizeCache) Len

func (c *RecordSizeCache) Len() int

Len returns cache size

func (*RecordSizeCache) Misses

func (c *RecordSizeCache) Misses() int64

Misses returns miss count

type RecordVersion

type RecordVersion struct {
	VersionID   int64
	Timestamp   time.Time
	CommitID    string
	ParentID    int64
	IsTombstone bool
}

RecordVersion represents a specific version of a record or dataset.

type RecordWriterPoolConfig

type RecordWriterPoolConfig struct {
	// InitialBufferSize is the starting capacity for pooled buffers (default: 64KB)
	InitialBufferSize int
	// MaxBufferSize is the maximum buffer size to keep in pool (default: 4MB)
	// Buffers larger than this are discarded to prevent memory bloat
	MaxBufferSize int
	// UseLZ4 enables LZ4 compression for IPC messages
	UseLZ4 bool
}

RecordWriterPoolConfig configures the IPC buffer pool.

func DefaultRecordWriterPoolConfig

func DefaultRecordWriterPoolConfig() RecordWriterPoolConfig

DefaultRecordWriterPoolConfig returns sensible defaults for high-throughput DoGet.

func (RecordWriterPoolConfig) Validate

func (c RecordWriterPoolConfig) Validate() error

Validate checks configuration validity.

type RegionReplica

type RegionReplica struct {
	Region             string    `json:"region"`
	Endpoint           string    `json:"endpoint"`
	Role               string    `json:"role"` // "primary" or "replica"
	Healthy            bool      `json:"healthy"`
	LastAppliedLSN     uint64    `json:"last_applied_lsn"`
	LagMs              int64     `json:"lag_ms"`
	LastHeartbeat      time.Time `json:"last_heartbeat"`
	AppliedMutations   int64     `json:"applied_mutations"`
	FailedReplications int64     `json:"failed_replications"`
	LastError          string    `json:"last_error,omitempty"`
}

RegionReplica tracks a regional deployment participating in multi-region replication.

type RegisteredStreamSchema

type RegisteredStreamSchema struct {
	ID              uint32            `json:"id"`
	Subject         string            `json:"subject"`
	Version         int               `json:"version"`
	ExpectedDim     int               `json:"expected_dim"`
	RequiredFields  []string          `json:"required_fields"`
	FieldTypes      map[string]string `json:"field_types,omitempty"`
	AllowExtraField bool              `json:"allow_extra_fields"`
}

RegisteredStreamSchema describes expected structure and dimensions for streaming payloads.

type RepairAgentConfig

type RepairAgentConfig = hnswcore.RepairAgentConfig

RepairAgentConfig defines the configuration for the HNSW repair agent.

type ReplicationEvent

type ReplicationEvent struct {
	ClusterID     string         `json:"cluster_id"`
	SourceRegion  string         `json:"source_region"`
	LSN           uint64         `json:"lsn,omitempty"`
	Dataset       string         `json:"dataset"`
	Op            string         `json:"op"` // "upsert" or "delete"
	ID            string         `json:"id"`
	Vector        []float32      `json:"vector,omitempty"`
	Text          string         `json:"text,omitempty"`
	Metadata      map[string]any `json:"metadata,omitempty"`
	TimestampUnix int64          `json:"timestamp_unix,omitempty"`
	Checksum      string         `json:"checksum,omitempty"`
}

ReplicationEvent captures a single replicated dataset mutation across regions.

type ReplicationMode

type ReplicationMode string

ReplicationMode configures cross-region write acknowledgment policy.

const (
	ReplicationAsync    ReplicationMode = "async"
	ReplicationSemiSync ReplicationMode = "semi_sync"
	ReplicationSync     ReplicationMode = "sync"
)

type ReplicationTransport

type ReplicationTransport interface {
	Replicate(ctx context.Context, replica *RegionReplica, ev ReplicationEvent) error
}

ReplicationTransport delivers a ReplicationEvent to a target regional replica.

type ReplicatorConfig

type ReplicatorConfig = cluster.ReplicatorConfig

type RequestSemaphore

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

RequestSemaphore limits concurrent DoGet/DoPut operations using a weighted semaphore.

func NewRequestSemaphore

func NewRequestSemaphore(cfg RequestSemaphoreConfig) *RequestSemaphore

NewRequestSemaphore creates a new request semaphore with the given configuration.

func (*RequestSemaphore) Acquire

func (rs *RequestSemaphore) Acquire(ctx context.Context) error

Acquire blocks until a slot is available or timeout/context cancellation occurs.

func (*RequestSemaphore) Available

func (rs *RequestSemaphore) Available() int

Available returns the number of available slots.

func (*RequestSemaphore) MaxConcurrent

func (rs *RequestSemaphore) MaxConcurrent() int

MaxConcurrent returns the maximum concurrent requests allowed.

func (*RequestSemaphore) Release

func (rs *RequestSemaphore) Release()

Release releases a slot back to the semaphore.

func (*RequestSemaphore) Stats

func (rs *RequestSemaphore) Stats() SemaphoreStats

Stats returns current statistics about semaphore usage.

func (*RequestSemaphore) TryAcquire

func (rs *RequestSemaphore) TryAcquire() bool

TryAcquire attempts to acquire a slot without blocking. Returns true if successful, false if no slots available.

type RequestSemaphoreConfig

type RequestSemaphoreConfig struct {
	// MaxConcurrent is the maximum number of concurrent requests.
	// Default: runtime.GOMAXPROCS(0) (number of CPU cores)
	MaxConcurrent int

	// AcquireTimeout is how long to wait before timing out on acquire.
	// Default: 30 seconds
	AcquireTimeout time.Duration

	// Enabled controls whether the semaphore is active.
	// When disabled, Acquire always succeeds immediately.
	Enabled bool
}

RequestSemaphoreConfig configures the request semaphore for limiting concurrent DoGet/DoPut operations to prevent thread-thrashing.

func DefaultRequestSemaphoreConfig

func DefaultRequestSemaphoreConfig() RequestSemaphoreConfig

DefaultRequestSemaphoreConfig returns a configuration with sensible defaults.

func (RequestSemaphoreConfig) Validate

func (c RequestSemaphoreConfig) Validate() error

Validate checks if the configuration is valid.

type RerankCache

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

RerankCache caches reranked search results by strategy + query + candidate set hash with TTL.

func NewRerankCache

func NewRerankCache(maxEntries int, ttl time.Duration) *RerankCache

NewRerankCache initializes an LRU + TTL rerank cache.

func (*RerankCache) Get

func (rc *RerankCache) Get(strategy, query string, candidates []SearchResult) ([]SearchResult, bool)

Get retrieves cached reranked results when valid and unexpired.

func (*RerankCache) Put

func (rc *RerankCache) Put(strategy, query string, candidates, ranked []SearchResult)

Put stores reranked results into cache.

type RerankEvalMetrics

type RerankEvalMetrics struct {
	Cases      int     `json:"cases"`
	K          int     `json:"k"`
	MeanNDCG   float64 `json:"mean_ndcg"`
	MeanMRR    float64 `json:"mean_mrr"`
	MeanRecall float64 `json:"mean_recall"`
}

RerankEvalMetrics reports standard IR effectiveness metrics (NDCG@K, MRR, Recall@K).

func EvaluateReranker

func EvaluateReranker(ctx context.Context, r Reranker, cases []EvalQueryCase, k int) (RerankEvalMetrics, error)

EvaluateReranker benchmarks reranking quality on labeled relevance judgments.

type Reranker

type Reranker interface {
	Rerank(ctx context.Context, query string, results []SearchResult) ([]SearchResult, error)
}

Reranker defines the interface for the second-stage re-ranking

func AutoSelectReranker

func AutoSelectReranker() Reranker

AutoSelectReranker returns a default reranker suitable for general use.

type RerankerFactory

type RerankerFactory struct{}

RerankerFactory creates reranker instances based on configuration.

func NewDefaultRerankerFactory

func NewDefaultRerankerFactory() *RerankerFactory

NewDefaultRerankerFactory creates a new RerankerFactory instance.

func (*RerankerFactory) CreateReranker

func (f *RerankerFactory) CreateReranker(config map[string]interface{}) (Reranker, error)

CreateReranker builds a reranker from a configuration map.

type RestoreConfig

type RestoreConfig struct {
	BackupID    string
	DatasetName string
	TargetPath  string
	Timestamp   time.Time
}

RestoreConfig defines the parameters for restoring a dataset from backup.

type RestoreVerificationReport

type RestoreVerificationReport struct {
	BackupID          string `json:"backup_id"`
	DatasetName       string `json:"dataset_name"`
	ChecksumsVerified bool   `json:"checksums_verified"`
	RestoredRows      int64  `json:"restored_rows"`
	WALEntriesApplied int    `json:"wal_entries_applied"`
	FinalWALSequence  uint64 `json:"final_wal_sequence"`
}

RestoreVerificationReport summarizes integrity and consistency checks performed during restore.

type ResultHeap

type ResultHeap []StreamItem

ResultHeap implements heap.Interface for a stream of SearchResults

func (ResultHeap) Len

func (h ResultHeap) Len() int

func (ResultHeap) Less

func (h ResultHeap) Less(i, j int) bool

func (*ResultHeap) Pop

func (h *ResultHeap) Pop() any

Pop removes and returns the smallest StreamItem from the heap.

func (*ResultHeap) Push

func (h *ResultHeap) Push(x any)

Push adds a StreamItem to the heap.

func (ResultHeap) Swap

func (h ResultHeap) Swap(i, j int)

type Role

type Role string

Role defines the access level for a user or service.

const (
	// RoleAdmin has full access to all system operations.
	RoleAdmin Role = "admin"
	// RoleTenantAdmin has administrative access scoped to a single tenant/namespace.
	RoleTenantAdmin Role = "tenant-admin"
	// RoleWriter / RoleReadWrite has access to read and modify data.
	RoleWriter    Role = "writer"
	RoleReadWrite Role = "read-write"
	// RoleReader / RoleReadOnly has access to read data only.
	RoleReader   Role = "reader"
	RoleReadOnly Role = "read-only"
	// RoleIngest has access to read data and ingest new vectors.
	RoleIngest Role = "ingest-only"
)

func (Role) HasPermission

func (r Role) HasPermission(perm Permission) bool

HasPermission checks if a role has the specified permission.

type RoutingRule

type RoutingRule struct {
	Tag        string   `json:"tag"`
	Collection string   `json:"collection"`
	Priority   int      `json:"priority"`
	Conditions []string `json:"conditions"`
}

RoutingRule defines how queries should be routed to collections based on tags.

type RowLocation

type RowLocation = types.RowLocation

RowLocation maps a row to its physical storage.

type RowPosition

type RowPosition = index.RowPosition

type SLAPolicy

type SLAPolicy struct {
	AvailabilityTarget  float64 `json:"availability_target"`
	MaxReplicationLagMs int64   `json:"max_replication_lag_ms"`
	RPOSeconds          int64   `json:"rpo_seconds"`
	RTOSeconds          int64   `json:"rto_seconds"`
	MaxP99LatencyMs     float64 `json:"max_p99_latency_ms"`
}

SLAPolicy defines uptime, replication RPO/lag, failover RTO, and latency targets.

func DefaultSLAPolicy

func DefaultSLAPolicy(tier CloudTier) SLAPolicy

DefaultSLAPolicy returns tier-appropriate SLA targets for a managed cloud cluster.

type SLAReport

type SLAReport struct {
	ClusterID            string    `json:"cluster_id"`
	Tier                 CloudTier `json:"tier"`
	TargetAvailability   float64   `json:"target_availability"`
	ObservedAvailability float64   `json:"observed_availability"`
	Compliant            bool      `json:"compliant"`
	MaxObservedLagMs     int64     `json:"max_observed_lag_ms"`
	ObservedP99Ms        float64   `json:"observed_p99_ms"`
	RPOMet               bool      `json:"rpo_met"`
	RTOMet               bool      `json:"rto_met"`
	UnhealthyRegions     []string  `json:"unhealthy_regions,omitempty"`
	BreachReasons        []string  `json:"breach_reasons,omitempty"`
	EvaluatedAt          time.Time `json:"evaluated_at"`
}

SLAReport summarizes live compliance against the cluster's SLA policy.

type SQ8Encoder

type SQ8Encoder = hnswcore.SQ8Encoder

SQ8Encoder implements 8-bit Scalar Quantization.

type ScaleDecision

type ScaleDecision struct {
	Action string `json:"action"` // "split", "merge", "rebalance", "failover", "noop"
	Target string `json:"target"`
	Detail string `json:"detail"`
}

ScaleDecision describes an auto-scaling or failover action taken during reconciliation.

type SchemaCompatibility

type SchemaCompatibility int

SchemaCompatibility represents the result of schema comparison

const (
	// SchemaExactMatch indicates schemas are identical
	SchemaExactMatch SchemaCompatibility = iota
	// SchemaEvolution indicates new schema is a compatible superset
	SchemaEvolution
	// SchemaIncompatible indicates schemas are not compatible
	SchemaIncompatible
)

func CheckSchemaCompatibility

func CheckSchemaCompatibility(existing, incoming *arrow.Schema) SchemaCompatibility

CheckSchemaCompatibility compares existing and incoming schemas. Returns SchemaExactMatch if identical, SchemaEvolution if incoming is a compatible superset (prefix matches), or SchemaIncompatible otherwise.

type SchemaCompatibilityMode

type SchemaCompatibilityMode string

SchemaCompatibilityMode mirrors Confluent-style evolution guarantees.

const (
	CompatNone     SchemaCompatibilityMode = "NONE"
	CompatBackward SchemaCompatibilityMode = "BACKWARD"
	CompatForward  SchemaCompatibilityMode = "FORWARD"
	CompatFull     SchemaCompatibilityMode = "FULL"
)

type SchemaConstraintRegistry

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

SchemaConstraintRegistry enforces field constraints, unique keys, metadata typing, evolution compatibility, and dataset migration.

func NewSchemaConstraintRegistry

func NewSchemaConstraintRegistry(s *VectorStore) *SchemaConstraintRegistry

NewSchemaConstraintRegistry creates a schema validation & constraint registry.

func (*SchemaConstraintRegistry) LatestSchema

func (r *SchemaConstraintRegistry) LatestSchema(dataset string) (DatasetSchemaSpec, bool)

LatestSchema returns the current active schema spec for a dataset, if registered.

func (*SchemaConstraintRegistry) MigrateDatasetSchema

func (r *SchemaConstraintRegistry) MigrateDatasetSchema(ds *Dataset, target DatasetSchemaSpec, addStringCols map[string]string) (int, error)

MigrateDatasetSchema registers the new schema version and backfills default values for newly added columns across existing Arrow batches in the Dataset.

func (*SchemaConstraintRegistry) RegisterSchema

func (r *SchemaConstraintRegistry) RegisterSchema(spec DatasetSchemaSpec) (int, error)

RegisterSchema checks evolution compatibility against prior versions, pre-compiles regexes, and stores the new schema version.

func (*SchemaConstraintRegistry) ValidateBatch

func (r *SchemaConstraintRegistry) ValidateBatch(ctx context.Context, dataset string, rec arrow.RecordBatch) error

ValidateBatch enforces registered schema constraints, metadata types, NOT NULL, UNIQUE, and CHECK rules against an Arrow RecordBatch before ingestion.

type SchemaEvolutionManager

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

SchemaEvolutionManager handles dynamic schema changes without dataset locks

func NewSchemaEvolutionManager

func NewSchemaEvolutionManager(initialSchema *arrow.Schema, datasetName string) *SchemaEvolutionManager

NewSchemaEvolutionManager creates a new manager with initial schema

func (*SchemaEvolutionManager) AddColumn

func (m *SchemaEvolutionManager) AddColumn(name string, dtype arrow.DataType) error

AddColumn adds a new column without requiring dataset lock or rewrite

func (*SchemaEvolutionManager) DropColumn

func (m *SchemaEvolutionManager) DropColumn(name string) error

DropColumn marks a column as dropped without rewriting data

func (*SchemaEvolutionManager) Evolve

func (m *SchemaEvolutionManager) Evolve(newSchema *arrow.Schema) error

Evolve upgrades the schema based on the input schema. It applies additive changes found in newSchema.

func (*SchemaEvolutionManager) GetColumnCount

func (m *SchemaEvolutionManager) GetColumnCount() int

GetColumnCount returns the number of active (non-dropped) columns

func (*SchemaEvolutionManager) GetCurrentSchema

func (m *SchemaEvolutionManager) GetCurrentSchema() *arrow.Schema

GetCurrentSchema returns the current schema (excluding dropped columns). The result is cached and invalidated on any schema mutation.

func (*SchemaEvolutionManager) GetCurrentVersion

func (m *SchemaEvolutionManager) GetCurrentVersion() uint64

GetCurrentVersion returns the current schema version

func (*SchemaEvolutionManager) GetSchemaAtVersion

func (m *SchemaEvolutionManager) GetSchemaAtVersion(version uint64) *arrow.Schema

GetSchemaAtVersion returns the schema at a specific version

func (*SchemaEvolutionManager) GetVersionCount

func (m *SchemaEvolutionManager) GetVersionCount() int

GetVersionCount returns the number of schema versions

func (*SchemaEvolutionManager) IsColumnAvailable

func (m *SchemaEvolutionManager) IsColumnAvailable(name string, version uint64) bool

IsColumnAvailable checks if a column is available at a specific version

func (*SchemaEvolutionManager) IsColumnDropped

func (m *SchemaEvolutionManager) IsColumnDropped(name string) bool

IsColumnDropped checks if a column has been dropped

func (*SchemaEvolutionManager) ValidateCompatibility

func (m *SchemaEvolutionManager) ValidateCompatibility(newSchema *arrow.Schema) error

ValidateCompatibility checks if the new schema is compatible with the current schema. Compatible means: 1. All existing columns must exist in new schema with same type (unless dropped). 2. New columns are allowed (additive). 3. Dropped columns in new schema are allowed if they are also dropped in current schema (or we allow implicit drops? No, we require explicit drop).

Actually, for DoPut, we often allow partial updates (subset of columns). But for "Evolution", we usually mean the schema of the *Batch* implies the new desired schema. If the batch has NEW columns -> Add them. If the batch MISSES columns -> That's fine, they will be null/default in storage. If the batch has CHANGED types -> Error.

type SchemaRegistryClient

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

SchemaRegistryClient integrates Confluent-style Schema Registry HTTP endpoints and local schema caching with wire-frame decoding and payload validation.

func NewSchemaRegistryClient

func NewSchemaRegistryClient(baseURL string) *SchemaRegistryClient

NewSchemaRegistryClient creates a schema registry client. baseURL may be empty for offline/local-only mode.

func (*SchemaRegistryClient) RegisterLocal

func (r *SchemaRegistryClient) RegisterLocal(subject string, schema RegisteredStreamSchema) uint32

RegisterLocal registers or updates a schema locally for deterministic validation and tests.

func (*SchemaRegistryClient) ResolveSchema

func (r *SchemaRegistryClient) ResolveSchema(ctx context.Context, schemaID uint32, subject string) (RegisteredStreamSchema, bool, error)

ResolveSchema looks up a schema by ID or subject, querying the HTTP registry when configured.

type SchemaVersion

type SchemaVersion struct {
	Version   uint64
	Fields    []arrow.Field
	CreatedAt time.Time
}

SchemaVersion tracks a specific schema state

type ScoreBreakdown

type ScoreBreakdown struct {
	DenseScore  float64            `json:"dense_score"`
	SparseScore float64            `json:"sparse_score"`
	GraphScore  float64            `json:"graph_score"`
	RRFScore    float64            `json:"rrf_score"`
	RerankScore float64            `json:"rerank_score"`
	FinalScore  float64            `json:"final_score"`
	Weights     map[string]float64 `json:"weights,omitempty"`
}

ScoreBreakdown decomposes dense, sparse/BM25, graph expansion, RRF, and rerank score contributions.

type SearchAnalyticsSnapshot

type SearchAnalyticsSnapshot struct {
	TotalQueries      int64                 `json:"total_queries"`
	ZeroResultQueries int64                 `json:"zero_result_queries"`
	TopQueries        []QueryAnalyticsEntry `json:"top_queries"`
	ZeroResultTop     []QueryAnalyticsEntry `json:"zero_result_top"`
}

SearchAnalyticsSnapshot exposes top queries and zero-result queries.

type SearchArena

type SearchArena = hnswcore.SearchArena

SearchArena provides pre-allocated memory for search operations to reduce heap churn.

type SearchEfConfig

type SearchEfConfig struct {
	BaseEf int

	DimensionEf128  int
	DimensionEf384  int
	DimensionEf768  int
	DimensionEf1536 int

	GPUefMultiplier float32
	// contains filtered or unexported fields
}

SearchEfConfig defines the configuration for search ef tuning.

func NewSearchEfConfig

func NewSearchEfConfig() SearchEfConfig

NewSearchEfConfig creates a new SearchEfConfig with default values.

func (*SearchEfConfig) GetEf

func (cfg *SearchEfConfig) GetEf(isGPU bool, dimension int) int

GetEf calculates the final ef value based on hardware and dimension.

func (*SearchEfConfig) GetEfForDimension

func (cfg *SearchEfConfig) GetEfForDimension(dim int) int

GetEfForDimension returns the base ef value for a given dimension.

type SearchExplanation

type SearchExplanation struct {
	Dataset    string               `json:"dataset"`
	QueryK     int                  `json:"query_k"`
	Alpha      float64              `json:"alpha"`
	GraphAlpha float64              `json:"graph_alpha"`
	IndexType  string               `json:"index_type"`
	EntryPoint uint32               `json:"entry_point"`
	TotalHops  int                  `json:"total_hops"`
	ElapsedMs  float64              `json:"elapsed_ms"`
	Hops       []TraversalHop       `json:"hops"`
	Candidates []ExplainedCandidate `json:"candidates"`
}

SearchExplanation describes full ranking transparency, graph traversal trace, and provenance.

type SearchMetrics

type SearchMetrics struct {
	NodesVisited   int32
	Computations   int32
	EarlyTermCount int32
	PrefetchHits   int32
	PrefetchMisses int32
}

SearchMetrics tracks performance and quality counters during search operations for diagnostics.

func (*SearchMetrics) Get

func (m *SearchMetrics) Get() (visited, computations, earlyTerm int32)

Get returns the current metric values.

func (*SearchMetrics) RecordComputation

func (m *SearchMetrics) RecordComputation()

RecordComputation increments the counter for distance calculations.

func (*SearchMetrics) RecordEarlyTermination

func (m *SearchMetrics) RecordEarlyTermination()

RecordEarlyTermination increments the counter for early termination events.

func (*SearchMetrics) RecordVisit

func (m *SearchMetrics) RecordVisit()

RecordVisit increments the counter for visited nodes.

func (*SearchMetrics) Reset

func (m *SearchMetrics) Reset()

Reset clears all search metrics.

type SearchOptions

type SearchOptions = types.SearchOptions

SearchOptions defines tunable parameters for vector search operations.

type SearchResult

type SearchResult = types.SearchResult

SearchResult is an alias for types.SearchResult.

func CombineHybridResults

func CombineHybridResults(vectorResults, bm25Results []SearchResult, alpha float32, k int) []SearchResult

CombineHybridResults combines vector and BM25 results using alpha weighting vector scores are distances (lower is better), BM25 scores are relevance (higher is better)

func CombineHybridResultsRRF

func CombineHybridResultsRRF(vectorResults, bm25Results []SearchResult, rrfK, limit int) []SearchResult

CombineHybridResultsRRF combines results using Reciprocal Rank Fusion (legacy alignment)

func FuseCascade

func FuseCascade(filter *roaring.Bitmap, keyword, vector []SearchResult, limit int) []SearchResult

FuseCascade implements cascade-style filtering: exact -> keyword -> vector

func FuseLinear

func FuseLinear(dense, sparse []SearchResult, alpha float32, limit int) []SearchResult

FuseLinear combines results using linear weighted combination

func FuseRRF

func FuseRRF(dataset string, dense, sparse []SearchResult, k, limit int) []SearchResult

FuseRRF is an alias for ReciprocalRankFusion (legacy alignment)

func GetSearchResultSlice

func GetSearchResultSlice(capacity int) []SearchResult

GetSearchResultSlice retrieves a pre-allocated slice from the pool

func MergeSortedStreams

func MergeSortedStreams(channels []<-chan []SearchResult, k int) []SearchResult

MergeSortedStreams merges multiple sortedResult channels into a single sorted stream. It assumes input channels produce results sorted by Score (ascending).

func ReciprocalRankFusion

func ReciprocalRankFusion(dataset string, list1, list2 []SearchResult, args ...interface{}) []SearchResult

ReciprocalRankFusion performs Reciprocal Rank Fusion.

func ReciprocalRankFusionLegacy

func ReciprocalRankFusionLegacy(dataset string, dense, sparse []SearchResult, k, limit int) []SearchResult

ReciprocalRankFusionLegacy combines results from multiple search systems using their ranks. Formula: score = sum(1 / (k + rank)) Reference: https://dl.acm.org/doi/10.1145/1571941.1572114

type SearchResultPool

type SearchResultPool = types.SearchResultPool

func NewSearchResultPool

func NewSearchResultPool() *SearchResultPool

type SegmentNode

type SegmentNode struct {
	Left  *SegmentNode
	Right *SegmentNode
	IDs   *roaring.Bitmap
}

SegmentNode represents a node in the dynamic segment tree.

type SegmentTree

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

SegmentTree is a high-performance dynamic segment tree for storing intervals and querying overlaps, returning roaring bitmaps of vector IDs.

func NewSegmentTree

func NewSegmentTree(min, max int64) *SegmentTree

NewSegmentTree creates a new dynamic segment tree capable of storing intervals within the [min, max] range.

func (*SegmentTree) Insert

func (st *SegmentTree) Insert(start, end int64, id uint32)

Insert adds a vector ID to the interval [start, end].

func (*SegmentTree) InsertBatch

func (st *SegmentTree) InsertBatch(starts, ends []int64, ids []uint32)

InsertBatch adds multiple vector IDs to their intervals, locking once for the batch.

func (*SegmentTree) Query

func (st *SegmentTree) Query(point int64) *roaring.Bitmap

Query returns a bitmap of all vector IDs whose intervals overlap with the given point.

func (*SegmentTree) QueryRange

func (st *SegmentTree) QueryRange(start, end int64) *roaring.Bitmap

QueryRange returns a bitmap of all vector IDs whose intervals overlap with [start, end].

func (*SegmentTree) Remove

func (st *SegmentTree) Remove(start, end int64, id uint32)

Remove deletes a vector ID from the interval [start, end].

type SelectKOptions

type SelectKOptions struct {
	K int
}

SelectKOptions provides parameters for the select_k_neighbors kernel.

func (*SelectKOptions) TypeName

func (s *SelectKOptions) TypeName() string

TypeName returns the unique identifier for the SelectKOptions type.

type SemaphoreStats

type SemaphoreStats struct {
	TotalAcquires int64
	TotalReleases int64
	TotalTimeouts int64
	CurrentActive int64
	MaxConcurrent int
}

SemaphoreStats holds statistics about semaphore usage.

type SequenceDeduplicator

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

SequenceDeduplicator provides bounded exactly-once / idempotent message deduplication using explicit idempotency keys and monotonic per-partition offset watermarks.

func NewSequenceDeduplicator

func NewSequenceDeduplicator(maxKeys int) *SequenceDeduplicator

NewSequenceDeduplicator creates a bounded deduplicator holding maxKeys recent keys.

func (*SequenceDeduplicator) CheckAndMark

func (d *SequenceDeduplicator) CheckAndMark(partition int32, offset int64, idempotencyKey string) bool

CheckAndMark returns true if the message is fresh (not a duplicate) and records it after commit.

type ShardDescriptor

type ShardDescriptor struct {
	ShardID     string     `json:"shard_id"`
	Dataset     string     `json:"dataset"`
	StartToken  uint64     `json:"start_token"` // inclusive
	EndToken    uint64     `json:"end_token"`   // inclusive (math.MaxUint64 for last shard)
	OwnerNode   string     `json:"owner_node"`
	Replicas    []string   `json:"replicas,omitempty"`
	VectorCount int64      `json:"vector_count"`
	MemoryBytes int64      `json:"memory_bytes"`
	QPS         float64    `json:"qps"`
	State       ShardState `json:"state"`
}

ShardDescriptor describes a contiguous hash-token range partition and its replicas.

type ShardState

type ShardState string

ShardState tracks lifecycle transitions during online split, merge, and drain.

const (
	ShardStateActive    ShardState = "active"
	ShardStateSplitting ShardState = "splitting"
	ShardStateMerging   ShardState = "merging"
	ShardStateDraining  ShardState = "draining"
)

type ShardedDataset

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

ShardedDataset provides a dataset with sharded record storage. Enables concurrent access to different shards without lock contention.

func NewShardedDataset

func NewShardedDataset(name string, cfg ShardedDatasetConfig) *ShardedDataset

NewShardedDataset creates a new sharded dataset with given config.

func NewShardedDatasetDefault

func NewShardedDatasetDefault(name string) *ShardedDataset

NewShardedDatasetDefault creates a sharded dataset with default config.

func (*ShardedDataset) Append

func (sd *ShardedDataset) Append(batch arrow.RecordBatch, routingKey uint64)

Append adds a record batch using hash-based routing.

func (*ShardedDataset) AppendToShard

func (sd *ShardedDataset) AppendToShard(batch arrow.RecordBatch, shardIdx int)

AppendToShard adds a record batch directly to a specific shard.

func (*ShardedDataset) Clear

func (sd *ShardedDataset) Clear()

Clear removes all records from all shards.

func (*ShardedDataset) ForEach

func (sd *ShardedDataset) ForEach(fn func(batch arrow.RecordBatch, shard int) bool)

ForEach iterates over all record batches. If fn returns false, iteration stops early.

func (*ShardedDataset) ForEachInShard

func (sd *ShardedDataset) ForEachInShard(shardIdx int, fn func(batch arrow.RecordBatch) bool)

ForEachInShard iterates over records in a specific shard.

func (*ShardedDataset) GetAllRecords

func (sd *ShardedDataset) GetAllRecords() []arrow.RecordBatch

GetAllRecords returns all record batches across all shards. Order is not guaranteed to be consistent.

func (*ShardedDataset) GetShardRecords

func (sd *ShardedDataset) GetShardRecords(shardIdx int) []arrow.RecordBatch

GetShardRecords returns all records from a specific shard.

func (*ShardedDataset) IncrementVersion

func (sd *ShardedDataset) IncrementVersion() int64

IncrementVersion atomically increments and returns the new version.

func (*ShardedDataset) Index

func (sd *ShardedDataset) Index() VectorIndex

Index returns the HNSW index (may be nil).

func (*ShardedDataset) LastAccess

func (sd *ShardedDataset) LastAccess() time.Time

LastAccess returns the last access time.

func (*ShardedDataset) Name

func (sd *ShardedDataset) Name() string

Name returns the dataset name.

func (*ShardedDataset) NumShards

func (sd *ShardedDataset) NumShards() int

NumShards returns the number of shards.

func (*ShardedDataset) ReplaceShardRecords

func (sd *ShardedDataset) ReplaceShardRecords(shardIdx int, batches []arrow.RecordBatch)

ReplaceShardRecords atomically replaces all records in a shard.

func (*ShardedDataset) SetIndex

func (sd *ShardedDataset) SetIndex(idx VectorIndex)

SetIndex sets the HNSW index.

func (*ShardedDataset) SetLastAccess

func (sd *ShardedDataset) SetLastAccess(t time.Time)

SetLastAccess sets the last access time.

func (*ShardedDataset) ShardRecordCount

func (sd *ShardedDataset) ShardRecordCount(shardIdx int) int

ShardRecordCount returns the number of records in a specific shard.

func (*ShardedDataset) Stats

func (sd *ShardedDataset) Stats() ShardedDatasetStats

Stats returns current statistics.

func (*ShardedDataset) ToLegacyRecords

func (sd *ShardedDataset) ToLegacyRecords() []arrow.RecordBatch

ToLegacyRecords returns all records as a flat slice for backward compatibility.

func (*ShardedDataset) TotalRecords

func (sd *ShardedDataset) TotalRecords() int

TotalRecords returns total number of record batches across all shards.

func (*ShardedDataset) Version

func (sd *ShardedDataset) Version() int64

Version returns the current version.

type ShardedDatasetConfig

type ShardedDatasetConfig struct {
	NumShards int // Number of shards (default: runtime.NumCPU())
}

ShardedDatasetConfig configures a sharded dataset.

func DefaultShardedDatasetConfig

func DefaultShardedDatasetConfig() ShardedDatasetConfig

DefaultShardedDatasetConfig returns sensible defaults.

func (ShardedDatasetConfig) Validate

func (c ShardedDatasetConfig) Validate() error

Validate checks configuration validity.

type ShardedDatasetStats

type ShardedDatasetStats struct {
	TotalRecords    int
	NumShards       int
	RecordsPerShard []int
}

ShardedDatasetStats holds statistics for a sharded dataset.

type ShardedHNSW

type ShardedHNSW = index.ShardedHNSW

type ShardedInvertedIndex

type ShardedInvertedIndex = index.ShardedInvertedIndex

type ShardedMap

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

ShardedMap provides concurrent access to datasets via sharding

func NewShardedMap

func NewShardedMap() *ShardedMap

NewShardedMap creates a new sharded map

func (*ShardedMap) Delete

func (sm *ShardedMap) Delete(name string)

Delete removes a dataset (write lock on single shard)

func (*ShardedMap) Get

func (sm *ShardedMap) Get(name string) (*Dataset, bool)

Get retrieves a dataset by name (read lock on single shard)

func (*ShardedMap) GetOrCreate

func (sm *ShardedMap) GetOrCreate(name string, create func() *Dataset) *Dataset

GetOrCreate atomically gets or creates a dataset

func (*ShardedMap) Keys

func (sm *ShardedMap) Keys() []string

Keys returns all dataset names

func (*ShardedMap) Len

func (sm *ShardedMap) Len() int

Len returns total count across all shards (acquires all read locks)

func (*ShardedMap) Range

func (sm *ShardedMap) Range(fn func(name string, ds *Dataset) bool)

Range iterates over all datasets (acquires read locks per shard) The callback should not hold references to the dataset after returning

func (*ShardedMap) RangeWithLock

func (sm *ShardedMap) RangeWithLock(fn func(name string, ds *Dataset, deleteFn func()))

RangeWithLock iterates with write lock (for modifications)

func (*ShardedMap) Set

func (sm *ShardedMap) Set(name string, ds *Dataset)

Set stores a dataset (write lock on single shard)

func (*ShardedMap) WithLock

func (sm *ShardedMap) WithLock(name string, fn func(data map[string]*Dataset))

WithLock executes fn with write lock on the shard containing name

func (*ShardedMap) WithRLock

func (sm *ShardedMap) WithRLock(name string, fn func(data map[string]*Dataset))

WithRLock executes fn with read lock on the shard containing name

type ShardedRWMutex

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

ShardedRWMutex provides a sharded read-write mutex for reduced contention. Different keys may hash to different shards, allowing concurrent access.

func NewShardedRWMutex

func NewShardedRWMutex(cfg ShardedRWMutexConfig) *ShardedRWMutex

NewShardedRWMutex creates a new sharded mutex with the given configuration.

func NewShardedRWMutexDefault

func NewShardedRWMutexDefault() *ShardedRWMutex

NewShardedRWMutexDefault creates a sharded mutex with default configuration.

func (*ShardedRWMutex) Lock

func (sm *ShardedRWMutex) Lock(key uint64)

Lock acquires a write lock for the shard associated with the given key.

func (*ShardedRWMutex) LockAll

func (sm *ShardedRWMutex) LockAll()

LockAll acquires write locks on all shards (use sparingly).

func (*ShardedRWMutex) LockShard

func (sm *ShardedRWMutex) LockShard(shard int)

LockShard acquires a write lock on a specific shard directly.

func (*ShardedRWMutex) NumShards

func (sm *ShardedRWMutex) NumShards() int

NumShards returns the number of shards.

func (*ShardedRWMutex) RLock

func (sm *ShardedRWMutex) RLock(key uint64)

RLock acquires a read lock for the shard associated with the given key.

func (*ShardedRWMutex) RLockAll

func (sm *ShardedRWMutex) RLockAll()

RLockAll acquires read locks on all shards.

func (*ShardedRWMutex) RLockShard

func (sm *ShardedRWMutex) RLockShard(shard int)

RLockShard acquires a read lock on a specific shard directly.

func (*ShardedRWMutex) RUnlock

func (sm *ShardedRWMutex) RUnlock(key uint64)

RUnlock releases the read lock for the shard associated with the given key.

func (*ShardedRWMutex) RUnlockAll

func (sm *ShardedRWMutex) RUnlockAll()

RUnlockAll releases read locks on all shards.

func (*ShardedRWMutex) RUnlockShard

func (sm *ShardedRWMutex) RUnlockShard(shard int)

RUnlockShard releases a read lock on a specific shard directly.

func (*ShardedRWMutex) ShardFor

func (sm *ShardedRWMutex) ShardFor(key uint64) int

ShardFor returns the shard index for a given key using an inline FNV-1a hash.

func (*ShardedRWMutex) Stats

func (sm *ShardedRWMutex) Stats() ShardedRWMutexStats

Stats returns current statistics.

func (*ShardedRWMutex) Unlock

func (sm *ShardedRWMutex) Unlock(key uint64)

Unlock releases the write lock for the shard associated with the given key.

func (*ShardedRWMutex) UnlockAll

func (sm *ShardedRWMutex) UnlockAll()

UnlockAll releases write locks on all shards.

func (*ShardedRWMutex) UnlockShard

func (sm *ShardedRWMutex) UnlockShard(shard int)

UnlockShard releases a write lock on a specific shard directly.

type ShardedRWMutexConfig

type ShardedRWMutexConfig struct {
	NumShards int // Number of shards (default: runtime.NumCPU())
}

ShardedRWMutexConfig configures the sharded mutex.

func DefaultShardedRWMutexConfig

func DefaultShardedRWMutexConfig() ShardedRWMutexConfig

DefaultShardedRWMutexConfig returns sensible defaults.

func (ShardedRWMutexConfig) Validate

func (c ShardedRWMutexConfig) Validate() error

Validate checks configuration validity.

type ShardedRWMutexStats

type ShardedRWMutexStats struct {
	TotalLocks  int64
	TotalRLocks int64
}

ShardedRWMutexStats holds statistics for the sharded mutex.

type ShardedResultAggregator

type ShardedResultAggregator struct{}

ShardedResultAggregator handles efficient merging of results from multiple shards.

func NewShardedResultAggregator

func NewShardedResultAggregator() *ShardedResultAggregator

NewShardedResultAggregator creates a new result aggregator.

func (*ShardedResultAggregator) MergeKWay

func (a *ShardedResultAggregator) MergeKWay(shardResults [][]SearchResult, k int) []SearchResult

MergeKWay performs a k-way merge on sorted results from multiple shards. It assumes each slice in shardResults is already sorted by Score ascending.

type SlidingWindowPredicate

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

SlidingWindowPredicate implements types.HNSWPredicate for sliding window filtering.

func (*SlidingWindowPredicate) IsMatch

func (sp *SlidingWindowPredicate) IsMatch(id uint32) bool

func (*SlidingWindowPredicate) MatchBatch

func (sp *SlidingWindowPredicate) MatchBatch(ids []uint32, dst []byte)

type SnapshotDatasetMetadata

type SnapshotDatasetMetadata struct {
	Name          string   `json:"name"`
	Version       int64    `json:"version"`
	IndexedCols   []string `json:"indexed_columns,omitempty"`
	TombstoneRows [][2]int `json:"tombstone_rows,omitempty"` // [batchIdx, rowIdx]
	IndexType     string   `json:"index_type"`
}

SnapshotDatasetMetadata holds dataset-level state persisted alongside Arrow batches.

type SnapshotManifest

type SnapshotManifest struct {
	FormatVersion int               `json:"format_version"`
	BackupID      string            `json:"backup_id"`
	DatasetName   string            `json:"dataset_name"`
	CreatedAt     time.Time         `json:"created_at"`
	WALSequence   uint64            `json:"wal_sequence"`
	RowCount      int64             `json:"row_count"`
	Dimension     uint32            `json:"dimension"`
	Metric        string            `json:"metric"`
	FileChecksums map[string]string `json:"file_checksums"`
}

SnapshotManifest describes the components and integrity checksums of an archive snapshot (Item 4.1).

func BuildSnapshotArchive

func BuildSnapshotArchive(ds *Dataset, backupID string, walSeq uint64) ([]byte, SnapshotManifest, error)

BuildSnapshotArchive serializes dataset records, index metadata, and dataset metadata into a checksummed tar.gz archive.

func ParseAndVerifySnapshotArchive

func ParseAndVerifySnapshotArchive(archiveBytes []byte) (SnapshotManifest, map[string][]byte, error)

ParseAndVerifySnapshotArchive extracts a tar.gz snapshot archive and verifies every component SHA-256 checksum.

type SparseLayerIndex

type SparseLayerIndex = hnswcore.SparseLayerIndex

SparseLayerIndex manages sparse index layers.

type SplitBrainDetector

type SplitBrainDetector = cluster.SplitBrainDetector

func NewSplitBrainDetector

func NewSplitBrainDetector(cfg cluster.SplitBrainConfig) *SplitBrainDetector

type StorageConfig

type StorageConfig = storage.StorageConfig

StorageConfig defines the configuration for the persistence layer.

type StreamAggregate

type StreamAggregate struct {
	VectorID  string
	Vector    []float32
	Timestamp time.Time
	Weight    float64
	Sequence  uint64
}

StreamAggregate represents a single data point in a stream.

type StreamConnector

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

StreamConnector manages a single streaming ingestion connector (and optional CDC exporter).

func (*StreamConnector) DLQEntries

func (c *StreamConnector) DLQEntries() []DLQEntry

DLQEntries returns recorded dead-letter queue entries.

func (*StreamConnector) ProcessEnvelopes

func (c *StreamConnector) ProcessEnvelopes(ctx context.Context, envs []StreamEnvelope) (int, int, error)

ProcessEnvelopes validates, deduplicates, applies backpressure, and ingests a batch of envelopes. Returns (committedCount, deduplicatedCount, error).

func (*StreamConnector) Start

func (c *StreamConnector) Start() error

Start begins external Kafka/Pulsar consumer loops (or marks memory connector running).

func (*StreamConnector) Stats

Stats returns a point-in-time snapshot of connector metrics.

func (*StreamConnector) Stop

func (c *StreamConnector) Stop() error

Stop shuts down consumer loops and bidirectional exporter.

type StreamConnectorConfig

type StreamConnectorConfig struct {
	Name                string           `json:"name"`
	Dataset             string           `json:"dataset"`
	SourceType          StreamSourceType `json:"source_type"`
	Brokers             string           `json:"brokers"`
	Topic               string           `json:"topic"`
	GroupID             string           `json:"group_id,omitempty"`
	SchemaRegistryURL   string           `json:"schema_registry_url,omitempty"`
	SchemaSubject       string           `json:"schema_subject,omitempty"`
	ExpectedDim         int              `json:"expected_dim,omitempty"`
	BatchSize           int              `json:"batch_size,omitempty"`
	FlushIntervalMs     int              `json:"flush_interval_ms,omitempty"`
	MaxInFlightBatches  int              `json:"max_in_flight_batches,omitempty"`
	BackpressurePauseMs int              `json:"backpressure_pause_ms,omitempty"`
	ExactlyOnce         bool             `json:"exactly_once"`
	ExportCDC           bool             `json:"export_cdc,omitempty"`
	ExportTopic         string           `json:"export_topic,omitempty"`
}

StreamConnectorConfig configures a bidirectional streaming ingestion + optional CDC export pipeline.

type StreamConnectorStats

type StreamConnectorStats struct {
	Name               string  `json:"name"`
	Dataset            string  `json:"dataset"`
	SourceType         string  `json:"source_type"`
	Topic              string  `json:"topic"`
	Running            bool    `json:"running"`
	Consumed           int64   `json:"consumed"`
	Committed          int64   `json:"committed"`
	Deduplicated       int64   `json:"deduplicated"`
	Failed             int64   `json:"failed"`
	DLQCount           int64   `json:"dlq_count"`
	BackpressurePauses int64   `json:"backpressure_pauses"`
	InFlight           int64   `json:"in_flight"`
	CommittedOffset    int64   `json:"committed_offset"`
	LatestOffset       int64   `json:"latest_offset"`
	ConsumerLag        int64   `json:"consumer_lag"`
	ThroughputEPS      float64 `json:"throughput_eps"`
}

StreamConnectorStats exposes live lag, deduplication, backpressure, and throughput metrics.

type StreamEnvelope

type StreamEnvelope struct {
	Topic     string            `json:"topic"`
	Partition int32             `json:"partition"`
	Offset    int64             `json:"offset"`
	Key       string            `json:"key,omitempty"`
	Headers   map[string]string `json:"headers,omitempty"`
	Payload   []byte            `json:"payload"`
	Timestamp time.Time         `json:"timestamp,omitempty"`
}

StreamEnvelope wraps raw bytes with broker partition/offset/key metadata.

type StreamIngestionManager

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

StreamIngestionManager orchestrates active streaming connectors and schema registry integration.

func NewStreamIngestionManager

func NewStreamIngestionManager(s *VectorStore) *StreamIngestionManager

NewStreamIngestionManager initializes a streaming ingestion manager attached to VectorStore.

func (*StreamIngestionManager) CreateConnector

func (m *StreamIngestionManager) CreateConnector(cfg StreamConnectorConfig, startNow bool) (*StreamConnector, error)

CreateConnector registers (and optionally starts for external Kafka/Pulsar brokers) a streaming connector.

func (*StreamIngestionManager) GetConnector

func (m *StreamIngestionManager) GetConnector(name string) (*StreamConnector, bool)

GetConnector returns a named connector.

func (*StreamIngestionManager) ListStats

ListStats lists stats for all connectors.

func (*StreamIngestionManager) Registry

Registry returns the shared SchemaRegistryClient.

func (*StreamIngestionManager) StopConnector

func (m *StreamIngestionManager) StopConnector(name string) error

StopConnector stops and removes a connector.

type StreamItem

type StreamItem struct {
	Result    SearchResult
	SourceIdx int // Index of the source channel
}

StreamItem represents a single search result within a stream, tracking its source.

type StreamSourceType

type StreamSourceType string

StreamSourceType defines supported streaming ingress sources.

const (
	StreamSourceKafka  StreamSourceType = "kafka"
	StreamSourcePulsar StreamSourceType = "pulsar"
	StreamSourceMemory StreamSourceType = "memory"
)

type StreamVectorEvent

type StreamVectorEvent struct {
	Op             string         `json:"op,omitempty"` // "upsert" (default) or "delete"
	ID             string         `json:"id"`
	Vector         []float32      `json:"vector,omitempty"`
	Embedding      []float32      `json:"embedding,omitempty"`
	Text           string         `json:"text,omitempty"`
	Metadata       map[string]any `json:"metadata,omitempty"`
	IdempotencyKey string         `json:"idempotency_key,omitempty"`
	TimestampUnix  int64          `json:"timestamp_unix,omitempty"`
}

StreamVectorEvent represents a decoded streaming vector upsert/delete event.

type StreamingAggregation

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

StreamingAggregation manages multiple vector aggregates for streaming data.

func NewStreamingAggregation

func NewStreamingAggregation(logger zerolog.Logger, config StreamingAggregationConfig) *StreamingAggregation

NewStreamingAggregation creates a new StreamingAggregation manager.

func (*StreamingAggregation) AddVector

func (s *StreamingAggregation) AddVector(vectorID string, vector []float32, timestamp time.Time) error

AddVector adds a new vector data point to the specified aggregate.

func (*StreamingAggregation) Clear

func (s *StreamingAggregation) Clear()

Clear removes all aggregate states.

func (*StreamingAggregation) CreateAggregate

func (s *StreamingAggregation) CreateAggregate(vectorID string, dimension int, aggType AggregationType) error

CreateAggregate initializes a new aggregate for a specific vector ID.

func (*StreamingAggregation) CreateAggregateAndAdd

func (s *StreamingAggregation) CreateAggregateAndAdd(vectorID string, vector []float32, timestamp time.Time) error

CreateAggregateAndAdd is a helper that creates an aggregate if it doesn't exist and then adds a vector.

func (*StreamingAggregation) GetAggregate

func (s *StreamingAggregation) GetAggregate(vectorID string) (*VectorAggregate, bool)

GetAggregate retrieves the full aggregate state for a vector ID.

func (*StreamingAggregation) GetAggregateCount

func (s *StreamingAggregation) GetAggregateCount() int

GetAggregateCount returns the number of active aggregates.

func (*StreamingAggregation) GetConfig

GetConfig returns the current configuration.

func (*StreamingAggregation) GetCumulative

func (s *StreamingAggregation) GetCumulative(vectorID string) ([]float32, error)

GetCumulative retrieves the current cumulative sum for a vector ID.

func (*StreamingAggregation) GetExponentialMovingAverage

func (s *StreamingAggregation) GetExponentialMovingAverage(vectorID string) ([]float32, error)

GetExponentialMovingAverage retrieves the current exponential moving average for a vector ID.

func (*StreamingAggregation) GetMovingAverage

func (s *StreamingAggregation) GetMovingAverage(vectorID string) ([]float32, error)

GetMovingAverage retrieves the current simple moving average for a vector ID.

func (*StreamingAggregation) GetStats

func (s *StreamingAggregation) GetStats() (received, aggregated, created, evicted int64)

GetStats returns current operational statistics for the streaming aggregation manager.

func (*StreamingAggregation) ListAggregates

func (s *StreamingAggregation) ListAggregates() []string

ListAggregates returns a list of all active vector IDs being aggregated.

func (*StreamingAggregation) RemoveAggregate

func (s *StreamingAggregation) RemoveAggregate(vectorID string)

RemoveAggregate deletes the aggregate state for a vector ID.

func (*StreamingAggregation) SetConfig

func (s *StreamingAggregation) SetConfig(config StreamingAggregationConfig)

SetConfig updates the configuration.

type StreamingAggregationConfig

type StreamingAggregationConfig struct {
	WindowSize      int     `json:"window_size"`
	DecayFactor     float64 `json:"decay_factor"`
	AggregationType string  `json:"aggregation_type"`
	MaxAggregates   int     `json:"max_aggregates"`
	AutoEvict       bool    `json:"auto_evict"`
	EnableWeighted  bool    `json:"enable_weighted"`
}

StreamingAggregationConfig defines the configuration for streaming aggregation.

type StreamingAggregationStats

type StreamingAggregationStats struct {
	EventsReceived    atomic.Int64
	EventsAggregated  atomic.Int64
	AggregatesCreated atomic.Int64
	AggregatesEvicted atomic.Int64
}

StreamingAggregationStats tracks operational statistics for streaming aggregation.

type StreamingParquetWriter

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

StreamingParquetWriter handles high-throughput serialization of Arrow batches directly from SlabArena to disk using zero-copy paths.

func NewStreamingParquetWriter

func NewStreamingParquetWriter(w io.Writer) *StreamingParquetWriter

NewStreamingParquetWriter creates a new Parquet writer

func (*StreamingParquetWriter) Close

func (p *StreamingParquetWriter) Close() error

Close finalizes the Parquet file and closes the writer.

func (*StreamingParquetWriter) WriteBatch

func (p *StreamingParquetWriter) WriteBatch(gd *types.GraphData) error

WriteBatch serializes GraphData to Parquet format using a slab-aware buffer.

func (*StreamingParquetWriter) WriteRaw

func (p *StreamingParquetWriter) WriteRaw(slab []byte) error

WriteRaw serialize raw Slab data (Phase 2 io_uring extension)

type TCPNoDelayListener

type TCPNoDelayListener struct {
	*net.TCPListener
}

TCPNoDelayListener wraps a TCPListener and sets TCP_NODELAY on all accepted connections. This disables Nagle's algorithm for lower latency at the cost of potential bandwidth efficiency.

func NewTCPNoDelayListener

func NewTCPNoDelayListener(l *net.TCPListener) *TCPNoDelayListener

NewTCPNoDelayListener creates a new listener that sets TCP_NODELAY on accepted connections.

func (*TCPNoDelayListener) Accept

func (l *TCPNoDelayListener) Accept() (net.Conn, error)

Accept waits for and returns the next connection, with TCP_NODELAY enabled.

type TTLPolicy

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

TTLPolicy manages the time-to-live policy for vectors, automatically deleting expired data.

func NewTTLPolicy

func NewTTLPolicy(vs *VectorStore, cfg TTLPolicyConfig) *TTLPolicy

NewTTLPolicy creates a new TTLPolicy with the given temporal index and configuration.

func (*TTLPolicy) GetDefaultTTL

func (tp *TTLPolicy) GetDefaultTTL() time.Duration

GetDefaultTTL returns the current default TTL duration.

func (*TTLPolicy) IsEnabled

func (tp *TTLPolicy) IsEnabled() bool

IsEnabled returns whether the TTL policy is currently enabled.

func (*TTLPolicy) SetDefaultTTL

func (tp *TTLPolicy) SetDefaultTTL(ttl time.Duration)

SetDefaultTTL updates the default TTL duration.

func (*TTLPolicy) SetEnabled

func (tp *TTLPolicy) SetEnabled(enabled bool)

SetEnabled enables or disables the TTL policy.

func (*TTLPolicy) Start

func (tp *TTLPolicy) Start(ctx context.Context)

Start begins the background cleanup process for the TTL policy.

func (*TTLPolicy) Stop

func (tp *TTLPolicy) Stop()

Stop terminates the background cleanup process for the TTL policy.

type TTLPolicyConfig

type TTLPolicyConfig struct {
	Enabled         bool
	DefaultTTL      time.Duration
	CleanupInterval time.Duration
}

TTLPolicyConfig defines the configuration for the TTL policy.

func DefaultTTLPolicyConfig

func DefaultTTLPolicyConfig() TTLPolicyConfig

DefaultTTLPolicyConfig returns a TTLPolicyConfig with production defaults.

type TemporalAggRequest

type TemporalAggRequest struct {
	AggType     TemporalAggType `json:"aggregation_type"`
	StartTime   int64           `json:"start_time"`
	EndTime     int64           `json:"end_time"`
	Interval    int64           `json:"interval"`
	MetricField string          `json:"metric_field,omitempty"`
}

TemporalAggRequest defines the parameters for a temporal aggregation request.

type TemporalAggType

type TemporalAggType string

TemporalAggType defines the type of temporal aggregation to perform.

const (
	// TemporalAggCount counts the number of occurrences in each time bucket.
	TemporalAggCount TemporalAggType = "count"
	// TemporalAggMin calculates the minimum value in each time bucket.
	TemporalAggMin TemporalAggType = "min"
	// TemporalAggMax calculates the maximum value in each time bucket.
	TemporalAggMax TemporalAggType = "max"
	// TemporalAggMean calculates the mean value in each time bucket.
	TemporalAggMean TemporalAggType = "mean"
	// TemporalAggSum calculates the sum of values in each time bucket.
	TemporalAggSum TemporalAggType = "sum"
)

type TemporalAggregationRequest

type TemporalAggregationRequest = core.TemporalAggregationRequest

TemporalAggregationRequest defines a request for aggregating data over a time window.

type TemporalAggregator

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

TemporalAggregator manages temporal aggregation of vector search results.

func NewTemporalAggregator

func NewTemporalAggregator(maxBuckets int) *TemporalAggregator

NewTemporalAggregator creates a new TemporalAggregator with the specified maximum bucket size.

func (*TemporalAggregator) Aggregate

Aggregate performs the requested temporal aggregation on a set of vector timestamps.

type TemporalCacheStats

type TemporalCacheStats struct {
	Hits      int64
	Misses    int64
	Expiries  int64
	Evictions int64
	Entries   int
}

TemporalCacheStats is a point-in-time snapshot of cache counters.

type TemporalConfig

type TemporalConfig struct {
	// Enabled indicates whether temporal features are active.
	Enabled bool
	// VersionHistory indicates whether to keep a full history of vector updates.
	VersionHistory bool
	// MaxVersions is the maximum number of versions to keep per vector.
	MaxVersions int
	// RetentionPeriod is the duration for which temporal data is kept.
	RetentionPeriod time.Duration
	// TTLEnabled indicates whether Time-To-Live (TTL) is active for vectors.
	TTLEnabled bool
	// DefaultTTL is the default duration a vector remains valid.
	DefaultTTL time.Duration
	// CleanupInterval is the frequency of background cleanup tasks.
	CleanupInterval time.Duration
	// AggregationEnabled indicates whether temporal aggregation features are active.
	AggregationEnabled bool
	// MaxBuckets is the maximum number of buckets for temporal aggregation.
	MaxBuckets int
}

TemporalConfig defines the configuration for temporal indexing and retention.

func DefaultTemporalConfig

func DefaultTemporalConfig() TemporalConfig

DefaultTemporalConfig returns a default configuration for temporal features.

type TemporalEntry

type TemporalEntry struct {
	ID   uint64
	Norm float32
}

type TemporalHNSWConfig

type TemporalHNSWConfig struct {
	MaxM           int
	EfConstruction int
	EfSearch       int
}

TemporalHNSWConfig defines configuration for time-aware HNSW indices, specifying connectivity and search parameters.

func DefaultTemporalHNSWConfig

func DefaultTemporalHNSWConfig() TemporalHNSWConfig

DefaultTemporalHNSWConfig returns default temporal search settings.

type TemporalHNSWIndex

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

TemporalHNSWIndex provides vector search capabilities with temporal partitioning, allowing for time-travel queries.

func NewTemporalHNSWIndex

func NewTemporalHNSWIndex(dimension int, config TemporalHNSWConfig) *TemporalHNSWIndex

NewTemporalHNSWIndex creates a new temporal index instance.

func (*TemporalHNSWIndex) Add

func (thi *TemporalHNSWIndex) Add(id uint64, vector []float32, timestamp int64) error

Add inserts a vector with a specific timestamp into the index.

func (*TemporalHNSWIndex) Close

func (thi *TemporalHNSWIndex) Close() error

Close releases resources held by the temporal index.

func (*TemporalHNSWIndex) Delete

func (thi *TemporalHNSWIndex) Delete(id uint64) error

Delete removes a vector from the temporal index.

func (*TemporalHNSWIndex) GetHNSW

func (thi *TemporalHNSWIndex) GetHNSW() *index.ArrowHNSW

GetHNSW returns the underlying ArrowHNSW index.

func (*TemporalHNSWIndex) GetMeta

func (thi *TemporalHNSWIndex) GetMeta() *arrow.Schema

GetMeta returns the schema for temporal metadata.

func (*TemporalHNSWIndex) SearchAsOf

func (thi *TemporalHNSWIndex) SearchAsOf(ctx context.Context, timestamp int64, k int) ([]SearchResult, error)

SearchAsOf returns nearest neighbors as they existed at a specific point in time.

func (*TemporalHNSWIndex) SearchRange

func (thi *TemporalHNSWIndex) SearchRange(ctx context.Context, startTime, endTime int64, k int) ([]SearchResult, error)

SearchRange returns nearest neighbors within a specific time interval.

func (*TemporalHNSWIndex) SearchSlidingWindow

func (thi *TemporalHNSWIndex) SearchSlidingWindow(ctx context.Context, windowSize int, k int) ([]SearchResult, error)

SearchSlidingWindow returns nearest neighbors within the most recent time window.

func (*TemporalHNSWIndex) Size

func (thi *TemporalHNSWIndex) Size() int

Size returns the total number of items in the temporal index.

type TemporalIndex

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

TemporalIndex provides efficient search and retrieval based on vector timestamps.

func NewTemporalIndex

func NewTemporalIndex(dimension int) *TemporalIndex

NewTemporalIndex creates a new TemporalIndex instance with async ingestion enabled by default. AddBatch offloads TemporalTree and SegmentTree updates to a background worker, returning immediately after storing vector data. Call SetAsyncIngestion(false) to restore synchronous behavior.

func (*TemporalIndex) ActiveCount

func (ti *TemporalIndex) ActiveCount() int

ActiveCount returns the number of non-tombstoned vectors in the index.

func (*TemporalIndex) Add

func (ti *TemporalIndex) Add(id uint64, vector []float32, timestamp int64, metadata []byte) error

Add inserts a new vector with a timestamp into the temporal index.

func (*TemporalIndex) AddBatch

func (ti *TemporalIndex) AddBatch(ids []uint64, vectors [][]float32, timestamps []int64, metadata [][]byte) error

AddBatch inserts multiple vectors into the TemporalIndex.

func (*TemporalIndex) Close

func (ti *TemporalIndex) Close() error

Close releases resources associated with the temporal index.

func (*TemporalIndex) Delete

func (ti *TemporalIndex) Delete(id uint64) error

Delete marks a vector as deleted (tombstoned) in the temporal index.

func (*TemporalIndex) DeleteByTime

func (ti *TemporalIndex) DeleteByTime(ctx context.Context, beforeTimestamp int64) (int, error)

DeleteByTime removes or tombstones vectors with timestamps before the specified value.

func (*TemporalIndex) GetBounds

func (ti *TemporalIndex) GetBounds() (int64, int64)

func (*TemporalIndex) GetHistory

func (ti *TemporalIndex) GetHistory(id uint64) []TemporalVector

GetHistory returns the temporal version history for a specific vector ID.

func (*TemporalIndex) GetVectorIndex

func (ti *TemporalIndex) GetVectorIndex() VectorIndex

func (*TemporalIndex) GetVectorsInRange

func (ti *TemporalIndex) GetVectorsInRange(startTime, endTime int64) []VectorTimestamp

GetVectorsInRange retrieves all vectors within a timestamp range as VectorTimestamp objects.

func (*TemporalIndex) GetVersion

func (ti *TemporalIndex) GetVersion(id uint64, timestamp int64) ([]float32, bool)

GetVersion retrieves the vector data for a specific ID as it existed at a given timestamp.

func (*TemporalIndex) MarshalJSON

func (ti *TemporalIndex) MarshalJSON() ([]byte, error)

MarshalJSON provides custom JSON serialization for TemporalIndex.

func (*TemporalIndex) Prewarm

func (ti *TemporalIndex) Prewarm(ctx context.Context) error

Prewarm populates the temporal cache with common search results.

func (*TemporalIndex) SearchAsOf

func (ti *TemporalIndex) SearchAsOf(ctx context.Context, timestamp int64, k int) ([]lbtypes.SearchResult, error)

SearchAsOf performs a vector search considering only data available at a specific timestamp.

func (*TemporalIndex) SearchRange

func (ti *TemporalIndex) SearchRange(ctx context.Context, startTime, endTime int64, k int) ([]lbtypes.SearchResult, error)

SearchRange performs a vector search over data within a specific timestamp range.

func (*TemporalIndex) SearchSlidingWindow

func (ti *TemporalIndex) SearchSlidingWindow(ctx context.Context, windowSize int, k int) ([]lbtypes.SearchResult, error)

SearchSlidingWindow performs a search over the last n vector updates.

func (*TemporalIndex) SearchSlidingWindowByTime

func (ti *TemporalIndex) SearchSlidingWindowByTime(ctx context.Context, duration time.Duration, k int) ([]lbtypes.SearchResult, error)

SearchSlidingWindowByTime performs a search over vector updates from the last duration.

func (*TemporalIndex) SetAsyncIngestion

func (ti *TemporalIndex) SetAsyncIngestion(async bool)

SetAsyncIngestion enables or disables asynchronous temporal ingestion. When enabled, AddBatch offloads TemporalTree and SegmentTree updates to a background worker, returning immediately after storing vector data in shards.

func (*TemporalIndex) SetGPUIndex

func (ti *TemporalIndex) SetGPUIndex(idx gputypes.Index)

SetGPUIndex sets the GPU acceleration index for this TemporalIndex.

func (*TemporalIndex) Size

func (ti *TemporalIndex) Size() int

Size returns the total number of vectors in the temporal index.

func (*TemporalIndex) Update

func (ti *TemporalIndex) Update(id uint64, vector []float32, timestamp int64, metadata []byte) error

Update updates an existing vector and metadata at a new timestamp.

type TemporalNode

type TemporalNode struct {
	Timestamp int64
	Offset    uint32 // Offset into entryArena
	Len       uint32 // Number of entries for this timestamp
	Cap       uint32 // Capacity of the allocated slice in entryArena
}

TemporalNode represents a set of vector IDs sharing a specific timestamp.

type TemporalPredicate

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

func (*TemporalPredicate) IsMatch

func (tp *TemporalPredicate) IsMatch(id uint32) bool

func (*TemporalPredicate) MatchBatch

func (tp *TemporalPredicate) MatchBatch(ids []uint32, dst []byte)

type TemporalResultCache

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

func NewTemporalResultCache

func NewTemporalResultCache(size int) *TemporalResultCache

NewTemporalResultCache creates a new TemporalResultCache with the specified capacity.

func (*TemporalResultCache) Get

Get retrieves search results from the cache if they exist and are not expired.

func (*TemporalResultCache) Set

func (c *TemporalResultCache) Set(key string, results []lbtypes.SearchResult, ttl time.Duration)

Set adds search results to the cache with the specified TTL.

func (*TemporalResultCache) SetDatasetLabel

func (c *TemporalResultCache) SetDatasetLabel(name string)

SetDatasetLabel names the dataset these counters belong to, so the exported metrics carry the same label as the rest of the store's series. It is called once when the dataset takes ownership of the index; counters observed before that report under "unknown" rather than being dropped.

func (*TemporalResultCache) Stats

Stats returns a snapshot of the counters. It is the only reader of them, which is the point of R11a: these were maintained and never observed.

type TemporalSearchRequest

type TemporalSearchRequest = core.TemporalSearchRequest

TemporalSearchRequest defines the parameters for a temporal search operation.

type TemporalTree

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

TemporalTree is a memory-efficient index structure for geographic or temporal vectors.

func NewTemporalTree

func NewTemporalTree(arena *memory.SlabArena) *TemporalTree

NewTemporalTree creates a new TemporalTree instance with an optional arena.

func (*TemporalTree) GetAfter

func (tt *TemporalTree) GetAfter(timestamp int64) []uint64

GetAfter returns all vector IDs with timestamps after the specified value.

func (*TemporalTree) GetBefore

func (tt *TemporalTree) GetBefore(timestamp int64) []uint64

GetBefore returns all vector IDs with timestamps before the specified value.

func (*TemporalTree) GetBounds

func (tt *TemporalTree) GetBounds() (int64, int64)

GetBounds returns the min and max timestamps in the tree.

func (*TemporalTree) GetEarliest

func (tt *TemporalTree) GetEarliest(n int) []uint64

GetEarliest returns the vector IDs from the first n timestamps.

func (*TemporalTree) GetLatest

func (tt *TemporalTree) GetLatest(n int) []uint64

GetLatest returns the vector IDs from the last n timestamps.

func (*TemporalTree) GetRange

func (tt *TemporalTree) GetRange(start, end int64) []uint64

GetRange returns all vector IDs within the specified timestamp range.

func (*TemporalTree) GetRangeReversed

func (tt *TemporalTree) GetRangeReversed(start, end int64) []uint64

GetRangeReversed returns all vector IDs within the specified timestamp range in descending order.

func (*TemporalTree) GetUniqueIDsInRange

func (tt *TemporalTree) GetUniqueIDsInRange(start, end int64) []uint64

GetUniqueIDsInRange returns unique vector IDs within the specified timestamp range, keeping only the most recent version of each ID.

func (*TemporalTree) GetUniqueLatest

func (tt *TemporalTree) GetUniqueLatest(n int) []uint64

GetUniqueLatest returns the n most recent unique vector IDs.

func (*TemporalTree) Insert

func (tt *TemporalTree) Insert(timestamp int64, id uint64, norm float32)

Insert adds a vector ID and its norm to the tree at the specified timestamp.

func (*TemporalTree) InsertBatch

func (tt *TemporalTree) InsertBatch(timestamps []int64, ids []uint64, norms []float32)

InsertBatch adds multiple vector IDs and their norms to the tree. It sorts entries by timestamp, locks once, and uses a cursor-based search to avoid repeated O(log n) binary searches and lock acquisitions.

func (*TemporalTree) Len

func (tt *TemporalTree) Len() int

Len returns the number of unique timestamps in the tree.

func (*TemporalTree) Release

func (tt *TemporalTree) Release()

Release deallocates the arenas used by the temporal tree.

type TemporalVector

type TemporalVector struct {
	ID        uint64
	Vector    []float32
	Norm      float32 // Pre-calculated norm
	Timestamp int64
	Metadata  []byte
	Tombstone bool
}

TemporalVector represents a vector with an associated timestamp for temporal search.

type TemporalVersionHistoryRequest

type TemporalVersionHistoryRequest = core.TemporalVersionHistoryRequest

TemporalVersionHistoryRequest defines a request for retrieving the version history of a vector.

type TenantQuota

type TenantQuota struct {
	MaxVectors              int64   `json:"max_vectors,omitempty"`
	MaxStorageBytes         int64   `json:"max_storage_bytes,omitempty"`
	MaxQueriesPerWindow     int64   `json:"max_queries_per_window,omitempty"`
	MaxEgressBytesPerWindow int64   `json:"max_egress_bytes_per_window,omitempty"`
	WindowSeconds           int64   `json:"window_seconds,omitempty"`
	SoftLimitRatio          float64 `json:"soft_limit_ratio,omitempty"`
	EnforceHardLimits       bool    `json:"enforce_hard_limits"`
}

TenantQuota defines hard and soft usage limits per tenant.

type TenantUsageReport

type TenantUsageReport struct {
	TenantID            string        `json:"tenant_id"`
	Queries             int64         `json:"queries"`
	WindowQueries       int64         `json:"window_queries"`
	VectorsIngested     int64         `json:"vectors_ingested"`
	CurrentVectors      int64         `json:"current_vectors"`
	CurrentStorageBytes int64         `json:"current_storage_bytes"`
	EgressBytes         int64         `json:"egress_bytes"`
	WindowEgressBytes   int64         `json:"window_egress_bytes"`
	Reranks             int64         `json:"reranks"`
	Embeddings          int64         `json:"embeddings"`
	SoftWarnings        int64         `json:"soft_warnings"`
	HardRejections      int64         `json:"hard_rejections"`
	EstimatedCost       float64       `json:"estimated_cost"`
	Currency            string        `json:"currency"`
	Quota               *TenantQuota  `json:"quota,omitempty"`
	Buckets             []UsageBucket `json:"buckets,omitempty"`
	LastActivity        time.Time     `json:"last_activity"`
}

TenantUsageReport summarizes tenant resource consumption, quota state, and estimated cost.

type TimestampMap

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

TimestampMap tracks the latest LWW timestamp for each VectorID.

func NewTimestampMap

func NewTimestampMap() *TimestampMap

NewTimestampMap creates a new sharded TimestampMap for tracking LWW timestamps.

func (*TimestampMap) Get

func (tm *TimestampMap) Get(id VectorID) int64

Get returns the timestamp for a given ID.

func (*TimestampMap) Len

func (tm *TimestampMap) Len() int

Len returns the total number of entries tracked.

func (*TimestampMap) Update

func (tm *TimestampMap) Update(id VectorID, ts int64) bool

Update updates the timestamp if the new one is greater (LWW). Returns true if the update was applied.

type TrainingSample

type TrainingSample = index.TrainingSample

type TraversalHop

type TraversalHop struct {
	Step            int      `json:"step"`
	NodeID          uint32   `json:"node_id"`
	NeighborCount   int      `json:"neighbor_count"`
	SampleNeighbors []uint32 `json:"sample_neighbors,omitempty"`
	EstimatedDist   float32  `json:"estimated_dist,omitempty"`
	ImprovedBest    bool     `json:"improved_best"`
}

TraversalHop captures one HNSW graph navigation hop during DebugSearchPath / ExplainSearch.

type TraverseOptions

type TraverseOptions struct {
	MaxHops   int
	Direction Direction
	Weighted  bool
	Decay     float32
}

TraverseOptions configures the graph traversal behavior.

func DefaultTraverseOptions

func DefaultTraverseOptions() TraverseOptions

DefaultTraverseOptions returns a default traversal configuration.

type UDSListener

type UDSListener struct {
	net.Listener
}

UDSListener wraps a Unix Domain Socket listener and increments a counter for accepted connections.

func NewUDSListener

func NewUDSListener(l net.Listener) *UDSListener

NewUDSListener creates a new listener that counts UDS connections.

func (*UDSListener) Accept

func (l *UDSListener) Accept() (net.Conn, error)

Accept waits for and returns the next connection, incrementing the UDS connection counter.

type Uint8Type

type Uint8Type interface{}

Uint8Type identifies uint8 code type (used by SQ8)

type Uint64Type

type Uint64Type interface{}

Uint64Type identifies uint64 code type (used by BQ)

type UpdateResult

type UpdateResult struct {
	Success    bool
	NewVersion uint64
	Conflict   bool
	Error      error
}

UpdateResult represents the outcome of an optimistic update operation.

type UringReader

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

UringReader utilizes io_uring for high-performance, concurrent non-blocking reads.

func NewUringReader

func NewUringReader(path string) (*UringReader, error)

func (*UringReader) Close

func (r *UringReader) Close() error

func (*UringReader) ReadAt

func (r *UringReader) ReadAt(buf []byte, offset int64) (int, error)

ReadAt reads data into buf from the specified offset using io_uring. This implementation is thread-safe and allows multiple concurrent reads. It retries on short reads to satisfy the io.ReaderAt contract.

type UsageBucket

type UsageBucket struct {
	WindowStart     time.Time `json:"window_start"`
	Queries         int64     `json:"queries"`
	VectorsIngested int64     `json:"vectors_ingested"`
	StorageBytesMax int64     `json:"storage_bytes_max"`
	EgressBytes     int64     `json:"egress_bytes"`
	Reranks         int64     `json:"reranks"`
}

UsageBucket stores time-windowed usage totals for billing rollups.

type UsageMeter

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

UsageMeter tracks per-tenant consumption, evaluates soft/hard quotas, exports Prometheus + OpenTelemetry metrics, and generates billing reports.

func NewUsageMeter

func NewUsageMeter(logger zerolog.Logger) *UsageMeter

NewUsageMeter initializes a per-tenant usage meter with default pricing and OTel counters.

func (*UsageMeter) CheckAndConsumeIngest

func (m *UsageMeter) CheckAndConsumeIngest(ctx context.Context, tenantID string, vectors, storageBytes int64) QuotaDecision

CheckAndConsumeIngest validates vector & storage quotas and records ingestion usage.

func (*UsageMeter) CheckAndConsumeQuery

func (m *UsageMeter) CheckAndConsumeQuery(ctx context.Context, tenantID string, estimatedEgressBytes int64) QuotaDecision

CheckAndConsumeQuery validates query/egress quotas and records a query execution.

func (*UsageMeter) ExportHTTPHandler

func (m *UsageMeter) ExportHTTPHandler() http.Handler

ExportHTTPHandler serves GET /api/v1/usage/export?format=json|csv&tenant=<id>.

func (*UsageMeter) ExportReport

func (m *UsageMeter) ExportReport(format, tenantID string) ([]byte, string, error)

ExportReport formats usage data as "json" or "csv".

func (*UsageMeter) GetAllUsage

func (m *UsageMeter) GetAllUsage() []TenantUsageReport

GetAllUsage returns sorted usage reports across all known tenants.

func (*UsageMeter) GetTenantUsage

func (m *UsageMeter) GetTenantUsage(tenantID string) TenantUsageReport

GetTenantUsage returns the live usage and cost report for one tenant.

func (*UsageMeter) HTTPHandler

func (m *UsageMeter) HTTPHandler() http.Handler

HTTPHandler serves GET /api/v1/usage?tenant=<id>.

func (*UsageMeter) RecordEgress

func (m *UsageMeter) RecordEgress(ctx context.Context, tenantID string, egressBytes int64)

RecordEgress adds post-response egress bytes to a tenant's usage.

func (*UsageMeter) RecordRerank

func (m *UsageMeter) RecordRerank(tenantID string, count int64)

RecordRerank records reranking calls for a tenant.

func (*UsageMeter) SetPricing

func (m *UsageMeter) SetPricing(p PricingModel)

SetPricing overrides the pricing model.

func (*UsageMeter) SetQuota

func (m *UsageMeter) SetQuota(tenantID string, q TenantQuota) error

SetQuota sets a soft/hard resource quota for a tenant.

type VectorAggregate

type VectorAggregate struct {
	VectorID      string
	Dimension     int
	AggregateType AggregationType
	WindowSize    int
	DecayFactor   float64
	// contains filtered or unexported fields
}

VectorAggregate stores the aggregated state for a specific vector ID.

type VectorClock

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

VectorClock implements a vector clock for causal ordering in distributed systems

func NewVectorClock

func NewVectorClock(nodeID string) *VectorClock

NewVectorClock creates a new vector clock for the given node

func (*VectorClock) Compare

func (vc *VectorClock) Compare(other *VectorClock) ClockComparison

Compare compares this vector clock with another Returns: ClockEqual, ClockBefore, ClockAfter, or ClockConcurrent

func (*VectorClock) Copy

func (vc *VectorClock) Copy() *VectorClock

Copy creates a deep copy of the vector clock

func (*VectorClock) Deserialize

func (vc *VectorClock) Deserialize(data []byte) error

Deserialize restores vector clock from bytes

func (*VectorClock) Get

func (vc *VectorClock) Get(nodeID string) uint64

Get returns the clock value for a specific node

func (*VectorClock) Increment

func (vc *VectorClock) Increment()

Increment increments this node's clock value

func (*VectorClock) Merge

func (vc *VectorClock) Merge(other *VectorClock)

Merge combines another vector clock into this one, taking max values

func (*VectorClock) MergeAsync

func (vc *VectorClock) MergeAsync(other *VectorClock)

MergeAsync enqueues another vector clock into this one asynchronously for bounded P95 latency.

func (*VectorClock) NodeID

func (vc *VectorClock) NodeID() string

NodeID returns the node identifier for this clock

func (*VectorClock) Serialize

func (vc *VectorClock) Serialize() []byte

Serialize converts the vector clock to bytes for network transfer

func (*VectorClock) Set

func (vc *VectorClock) Set(nodeID string, value uint64)

Set sets the clock value for a specific node

func (*VectorClock) StartCompactor

func (vc *VectorClock) StartCompactor(bufferSize int)

StartCompactor initializes a lock-free background thread to merge delta timestamps.

func (*VectorClock) StopCompactor

func (vc *VectorClock) StopCompactor()

StopCompactor stops the background clock compaction thread.

type VectorDataType

type VectorDataType = types.VectorDataType

VectorDataType represents the underlying numeric type of vector elements.

type VectorID

type VectorID = core.VectorID

VectorID is a unique identifier for a vector in the system.

type VectorIndex

type VectorIndex = types.VectorIndexer

VectorIndex is an interface for vector indexing operations.

func NewAutoShardingIndex

func NewAutoShardingIndex(ds *Dataset, config AutoShardingConfig) VectorIndex

NewAutoShardingIndex creates a new auto-sharding index. Initially, it uses a standard HNSWIndex.

type VectorPool

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

VectorPool manages reusable float32 slices to reduce allocation churn

func NewVectorPool

func NewVectorPool() *VectorPool

NewVectorPool creates a new vector pool

func (*VectorPool) Get

func (vp *VectorPool) Get(dim int) *[]float32

Get retrieves a vector buffer of the specified dimension from the pool

func (*VectorPool) Put

func (vp *VectorPool) Put(vec *[]float32)

Put returns a vector buffer to the pool for reuse

func (*VectorPool) Stats

func (vp *VectorPool) Stats() (hits, misses, puts int64)

Stats returns pool statistics

type VectorProvenance

type VectorProvenance struct {
	Dataset      string         `json:"dataset"`
	VectorID     string         `json:"vector_id"`
	SourceURI    string         `json:"source_uri,omitempty"`
	Model        string         `json:"model,omitempty"`
	ModelVersion string         `json:"model_version,omitempty"`
	ChunkIndex   int            `json:"chunk_index,omitempty"`
	ContentHash  string         `json:"content_hash,omitempty"`
	TenantID     string         `json:"tenant_id,omitempty"`
	Lineage      []string       `json:"lineage,omitempty"`
	IngestedAt   time.Time      `json:"ingested_at"`
	Extra        map[string]any `json:"extra,omitempty"`
}

VectorProvenance tracks lineage, embedding model/version, source URI, and timestamps per vector.

type VectorSearcher

type VectorSearcher interface {
	Search(ctx context.Context, query []float32, k int, options SearchOptions) ([]lbtypes.SearchResult, error)
	GetDimension() int
}

VectorSearcher is the interface for performing vector similarity search.

type VectorStore

type VectorStore struct {
	flight.BaseFlightServer

	// Mesh integration
	Mesh *mesh.Gossip

	// Circuit Breakers for fault tolerance
	Breakers *CircuitBreakerRegistry

	// Disk IO Scheduler for background tasks
	DiskIO *DiskIOScheduler
	// contains filtered or unexported fields
}

VectorStore implements flight.FlightServer and provides vector storage and search with support for HNSW, IVF, and learned indexing.

func NewVectorStore

func NewVectorStore(mem memory.Allocator, logger zerolog.Logger, maxMemoryBytes int64, _ int64, _ time.Duration) *VectorStore

NewVectorStore creates a new VectorStore instance.

func NewVectorStoreWithHybridConfig

func NewVectorStoreWithHybridConfig(mem memory.Allocator, logger zerolog.Logger, cfg HybridSearchConfig) (*VectorStore, error)

NewVectorStoreWithHybridConfig creates a VectorStore with hybrid search enabled.

func NewVectorStoreWithPipeline

func NewVectorStoreWithPipeline(mem memory.Allocator, logger zerolog.Logger, workers, bufferSize int) *VectorStore

NewVectorStoreWithPipeline creates a VectorStore with DoGet pipeline enabled

func NewVectorStoreWithPipelineThreshold

func NewVectorStoreWithPipelineThreshold(mem memory.Allocator, logger zerolog.Logger, workers, bufferSize, threshold int) *VectorStore

NewVectorStoreWithPipelineThreshold creates a VectorStore with custom pipeline threshold

func (*VectorStore) AccessValidator

func (s *VectorStore) AccessValidator() security.AccessValidator

AccessValidator returns the active AccessValidator combining RBAC and OIDC when enabled, or nil if authentication is disabled.

func (*VectorStore) AdjustWorkerCounts

func (s *VectorStore) AdjustWorkerCounts(indexing, ingestion int)

AdjustWorkerCounts scales indexing and ingestion workers dynamically.

func (*VectorStore) ApplyDelta

func (s *VectorStore) ApplyDelta(name string, rec arrow.RecordBatch, seq uint64, ts int64) error

ApplyDelta applies an Arrow record batch as a delta to the specified dataset.

func (*VectorStore) AuditLogger

func (s *VectorStore) AuditLogger() *security.AuditLogger

AuditLogger returns the store's AuditLogger, lazily creating one if needed.

func (*VectorStore) AuthorizeDatasetAccess

func (s *VectorStore) AuthorizeDatasetAccess(ctx context.Context, perm Permission, datasetPath string) (*security.TenantContext, error)

AuthorizeDatasetAccess validates RBAC, OIDC, & tenant boundaries when authentication is enabled. When neither RBAC nor OIDC is configured, all requests are allowed.

func (*VectorStore) BackupManager

func (vs *VectorStore) BackupManager() (*BackupManager, error)

BackupManager returns the current backup manager.

func (*VectorStore) BlockEnqueueIndexJob

func (vs *VectorStore) BlockEnqueueIndexJob(job types.IndexJob, timeout time.Duration) bool

BlockEnqueueIndexJob attempts to send to the preferred NUMA-local queue or global queue, blocking up to timeout.

func (*VectorStore) CanTenantListDataset

func (s *VectorStore) CanTenantListDataset(ctx context.Context, datasetPath string) bool

CanTenantListDataset checks whether the caller's TenantContext allows seeing the named dataset.

func (*VectorStore) CheckIngestionBackpressure

func (vs *VectorStore) CheckIngestionBackpressure() bool

CheckIngestionBackpressure checks if the system is under heavy load and should throttle incoming requests. Returns true if backpressure should be applied.

func (*VectorStore) CheckNamespaceRateLimit

func (vs *VectorStore) CheckNamespaceRateLimit(namespace string) error

CheckNamespaceRateLimit is a helper for VectorStore to verify rate limits.

func (*VectorStore) CleanupGPUIndexPool

func (vs *VectorStore) CleanupGPUIndexPool() int

CleanupGPUIndexPool removes expired idle indexes from the pool

func (*VectorStore) CloneDataset

func (vs *VectorStore) CloneDataset(ctx context.Context, source, target string, backend storage.SnapshotBackend) error

CloneDataset clones a dataset by exporting and then importing it under a new name.

func (*VectorStore) Close

func (s *VectorStore) Close() error

Close performs a graceful shutdown with a default timeout. It is an alias for Shutdown(context.Background()) but handy for defer.

func (*VectorStore) ClosePersistence

func (vs *VectorStore) ClosePersistence() error

ClosePersistence closes the persistence engine.

func (*VectorStore) CreateBackup

func (vs *VectorStore) CreateBackup(config BackupConfig) (*BackupManager, error)

CreateBackup configures and initializes the backup manager for the vector store.

func (*VectorStore) CreateNamespace

func (vs *VectorStore) CreateNamespace(name string) error

CreateNamespace creates a new namespace with the given name. Returns error if namespace already exists.

func (*VectorStore) CreateOnlineBackup

func (vs *VectorStore) CreateOnlineBackup(ctx context.Context, datasetName, destination string) (BackupMetadata, error)

CreateOnlineBackup captures an online archive snapshot and persists it both in BackupManager and optional backend (local/S3/GCS).

func (*VectorStore) DeleteNamespace

func (vs *VectorStore) DeleteNamespace(name string) error

DeleteNamespace removes a namespace and all its associated datasets from the store.

func (*VectorStore) DeleteVectorByID

func (s *VectorStore) DeleteVectorByID(_ context.Context, datasetName, rawID string) error

DeleteVectorByID marks a vector ID as deleted (tombstoned) in the target dataset.

func (*VectorStore) DisableAdaptiveGC

func (vs *VectorStore) DisableAdaptiveGC()

DisableAdaptiveGC stops the adaptive GC controller

func (*VectorStore) DoAction

func (s *VectorStore) DoAction(action *flight.Action, stream flight.FlightService_DoActionServer) error

DoAction handles custom actions like deletion, status, and graph operations.

func (*VectorStore) DoExchange

DoExchange implements bidirectional Arrow Flight streaming for mesh replication. This provides the foundation for peer-to-peer Arrow stream transfer.

Protocol: - Client sends FlightData messages with FlightDescriptor indicating dataset - Server receives, processes, and can send data back - Enables future mesh replication between peers

func (*VectorStore) DoGet

DoGet handles data retrieval and vector search queries via Arrow Tickets.

func (*VectorStore) DoMetaAction

func (s *VectorStore) DoMetaAction(action *flight.Action, stream flight.FlightService_DoActionServer) error

doMetaAction handles management commands on VectorStore DoMetaAction handles meta-specific actions for the cluster MetaServer.

func (*VectorStore) DoPut

func (*VectorStore) DropDataset

func (vs *VectorStore) DropDataset(ctx context.Context, name string) error

DropDataset removes a dataset from the store immediately (Fast Path). It unlinks the dataset from the map (RCU) and schedules cleanup asynchronously.

func (*VectorStore) EdgeSearchHTTPHandler

func (s *VectorStore) EdgeSearchHTTPHandler() http.Handler

EdgeSearchHTTPHandler provides HTTP and gRPC-Web search transport for WASM, Browser, Cloudflare Workers, and Deno clients without requiring native HTTP/2 gRPC.

func (*VectorStore) EdgeSyncHTTPHandler

func (s *VectorStore) EdgeSyncHTTPHandler() http.Handler

EdgeSyncHTTPHandler accepts batched offline-first edge mutations and returns conflict-free state.

func (*VectorStore) EnableAdaptiveGC

func (vs *VectorStore) EnableAdaptiveGC(config gc.AdaptiveGCConfig)

EnableAdaptiveGC starts the adaptive GC controller with the given configuration. This is optional and disabled by default. Call this after NewVectorStore if you want dynamic GOGC adjustment based on allocation rate and memory pressure.

func (*VectorStore) EnableOIDC

func (s *VectorStore) EnableOIDC(mgr *security.OIDCManager)

EnableOIDC configures OIDC federation on the VectorStore.

func (*VectorStore) EnableRBAC

func (s *VectorStore) EnableRBAC(mgr *RBACManager)

EnableRBAC configures RBAC, RLS, and audit logging on the VectorStore.

func (*VectorStore) EnqueueIndexJob

func (vs *VectorStore) EnqueueIndexJob(job types.IndexJob) bool

EnqueueIndexJob routes an index job to the preferred NUMA-local queue or global fallback queue.

func (*VectorStore) ExchangeOIDCToken

func (s *VectorStore) ExchangeOIDCToken(ctx context.Context, rawToken string, ttl time.Duration) (*APIKey, string, error)

ExchangeOIDCToken validates a federated OIDC JWT and issues a short-lived Longbow session API key bound to the federated identity's tenant and scope.

func (*VectorStore) ExecuteGraphQL

func (s *VectorStore) ExecuteGraphQL(ctx context.Context, query string, variables map[string]any, opName string) map[string]any

ExecuteGraphQL parses and runs a GraphQL query/mutation against VectorStore.

func (*VectorStore) ExportDataset

func (vs *VectorStore) ExportDataset(name string, backend storage.SnapshotBackend) (int64, error)

ExportDataset exports a dataset to a storage backend in Parquet format.

func (*VectorStore) FederatedSearch

func (s *VectorStore) FederatedSearch(ctx context.Context, collections, tags []string, queryVec []float32, k, rrfK int) ([]SearchResult, error)

FederatedSearch executes parallel k-NN across multiple collections or tag-matched collections and merges results via Reciprocal Rank Fusion (RRF).

func (*VectorStore) FilterResultsByRLS

func (s *VectorStore) FilterResultsByRLS(ctx context.Context, datasetPath string, results []SearchResult) []SearchResult

FilterResultsByRLS filters search results through row-level security policies when RBAC/OIDC/RLS is active.

func (*VectorStore) FlushWAL

func (s *VectorStore) FlushWAL() error

FlushWAL flushes any pending WAL writes.

func (*VectorStore) GeoSearch

func (s *VectorStore) GeoSearch(ctx context.Context, req *types.GeoSearchRequest) ([]SearchResult, error)

GeoSearch executes geospatial radius, bounding-box, or geo+vector hybrid search, including optional global mesh scatter-gather and RLS filtering.

func (*VectorStore) GetActiveDatasets

func (vs *VectorStore) GetActiveDatasets() []string

GetActiveDatasets returns a list of active dataset names.

func (*VectorStore) GetActiveEmbedding

func (s *VectorStore) GetActiveEmbedding() (provider, model string)

GetActiveEmbedding returns the currently active embedding provider and model.

func (*VectorStore) GetAdmissionController

func (vs *VectorStore) GetAdmissionController() *AdmissionController

GetAdmissionController returns the admission controller for the store.

func (*VectorStore) GetAutoScaleConfig

func (vs *VectorStore) GetAutoScaleConfig() AutoScaleConfig

GetAutoScaleConfig retrieves the current auto-scaling configuration.

func (*VectorStore) GetAutoShardingConfig

func (vs *VectorStore) GetAutoShardingConfig() AutoShardingConfig

GetAutoShardingConfig returns the current auto-sharding configuration

func (*VectorStore) GetBM25Index

func (s *VectorStore) GetBM25Index(datasetName string) *BM25InvertedIndex

GetBM25Index returns the BM25 inverted index for text search for a dataset.

func (*VectorStore) GetCDC

func (s *VectorStore) GetCDC() *ChangeDataCapture

GetCDC returns the Change Data Capture instance.

func (*VectorStore) GetCapacityPlan

func (vs *VectorStore) GetCapacityPlan() (CapacityPlan, error)

GetCapacityPlan calculates the current resource usage and recommends scaling actions.

func (*VectorStore) GetCloudControlPlane

func (s *VectorStore) GetCloudControlPlane() *CloudControlPlane

GetCloudControlPlane returns the lazily initialized managed cloud & multi-region control plane.

func (*VectorStore) GetCollections

func (s *VectorStore) GetCollections() []string

GetCollections returns a list of names of all monitored collections.

func (*VectorStore) GetCurrentIndex

func (s *VectorStore) GetCurrentIndex(collection string) IndexType

GetCurrentIndex returns the current index type for a collection.

func (*VectorStore) GetDataset

func (s *VectorStore) GetDataset(name string) (*Dataset, error)

GetDataset retrieves a dataset by name.

func (*VectorStore) GetDatasetIndexStats

func (vs *VectorStore) GetDatasetIndexStats(name string) (nodeCount int64, maxLevel int32, isOffHeap bool, exists bool)

GetDatasetIndexStats returns core progress statistics for a dataset's index.

func (*VectorStore) GetDoGetPipelinePool

func (s *VectorStore) GetDoGetPipelinePool() *DoGetPipelinePool

GetDoGetPipelinePool returns the pipeline pool (nil if not configured)

func (*VectorStore) GetElasticController

func (s *VectorStore) GetElasticController() *ElasticShardingController

GetElasticController returns the VectorStore's elastic sharding & auto-scaling controller.

func (*VectorStore) GetFederatedRouter

func (s *VectorStore) GetFederatedRouter() *FederatedQueryRouter

GetFederatedRouter returns the lazily initialized federated cross-collection search router.

func (*VectorStore) GetFlightInfo

func (s *VectorStore) GetFlightInfo(ctx context.Context, desc *flight.FlightDescriptor) (*flight.FlightInfo, error)

GetFlightInfo returns metadata about a specific dataset.

func (*VectorStore) GetGCTuner

func (vs *VectorStore) GetGCTuner() *lbmem.GCTuner

GetGCTuner returns the memory tuner.

func (*VectorStore) GetGPUBackend

func (s *VectorStore) GetGPUBackend() gpu.GPUBackend

GetGPUBackend returns CPU for CPU-only builds

func (*VectorStore) GetGPUIndexPool

func (vs *VectorStore) GetGPUIndexPool() *gpu.GPUIndexPool

GetGPUIndexPool returns the GPU index pool for this store

func (*VectorStore) GetGPUIndexPoolStats

func (vs *VectorStore) GetGPUIndexPoolStats() gpu.GPUIndexPoolStats

GetGPUIndexPoolStats returns statistics about the GPU index pool

func (*VectorStore) GetGPUMemoryStats

func (s *VectorStore) GetGPUMemoryStats() (total, used, free int64)

GetGPUMemoryStats returns zeros for CPU-only builds

func (*VectorStore) GetHNSW2Config

func (s *VectorStore) GetHNSW2Config() *ArrowHNSWConfig

GetHNSW2Config returns the current HNSW configuration template.

func (*VectorStore) GetHybridSearchConfig

func (s *VectorStore) GetHybridSearchConfig() HybridSearchConfig

GetHybridSearchConfig returns the hybrid search configuration.

func (*VectorStore) GetIndexPredictor

func (s *VectorStore) GetIndexPredictor() *IndexPerformancePredictor

GetIndexPredictor returns the learned index performance predictor.

func (*VectorStore) GetIndexRecommendation

func (s *VectorStore) GetIndexRecommendation(features QueryFeatures) IndexPrediction

GetIndexRecommendation returns an index recommendation based on query features.

func (*VectorStore) GetIndexSize

func (s *VectorStore) GetIndexSize(collection string) float64

GetIndexSize returns the size of the index in megabytes for a collection.

func (*VectorStore) GetIndexedColumns

func (vs *VectorStore) GetIndexedColumns() []string

GetIndexedColumns returns columns currently being indexed

func (*VectorStore) GetLoadHints

func (vs *VectorStore) GetLoadHints() loadbalancing.LoadHints

GetLoadHints returns the current load balancing hints for this node.

func (*VectorStore) GetLogger

func (s *VectorStore) GetLogger() zerolog.Logger

GetLogger returns the logger

func (*VectorStore) GetMaterializedViewManager

func (s *VectorStore) GetMaterializedViewManager() *MaterializedViewManager

GetMaterializedViewManager returns the VectorStore's materialized view & aggregation manager.

func (*VectorStore) GetMemoryUsage

func (s *VectorStore) GetMemoryUsage(collection string) float64

GetMemoryUsage returns the total memory usage in megabytes for a collection.

func (*VectorStore) GetMesh

func (s *VectorStore) GetMesh() *mesh.Gossip

GetMesh returns the mesh

func (*VectorStore) GetMeshMembers

func (vs *VectorStore) GetMeshMembers() []mesh.Member

GetMeshMembers returns the current members from the mesh gossip instance.

func (*VectorStore) GetMultiModalPipeline

func (s *VectorStore) GetMultiModalPipeline() *MultiModalPipeline

GetMultiModalPipeline returns the VectorStore's multi-modal embedding & search pipeline.

func (*VectorStore) GetNUMATopology

func (vs *VectorStore) GetNUMATopology() *lbmem.NUMATopology

GetNUMATopology returns the detected NUMA topology of the system.

func (*VectorStore) GetNamespace

func (vs *VectorStore) GetNamespace(name string) *Namespace

GetNamespace returns a namespace by name, or nil if not found.

func (*VectorStore) GetNamespaceDatasetCount

func (vs *VectorStore) GetNamespaceDatasetCount(name string) int

GetNamespaceDatasetCount returns the number of datasets in a namespace.

func (*VectorStore) GetNamespaceRateLimit

func (vs *VectorStore) GetNamespaceRateLimit(namespace string) (RateLimitConfig, error)

GetNamespaceRateLimit retrieves the current rate limit configuration for a namespace.

func (*VectorStore) GetNeighborsBulk

func (vs *VectorStore) GetNeighborsBulk(ctx context.Context, datasetName string, nodeIDs []uint32) (map[uint32][]uint32, error)

GetNeighborsBulk retrieves the adjacency lists for multiple nodes in the vector index.

func (*VectorStore) GetPipelineStats

func (s *VectorStore) GetPipelineStats() PipelineStats

GetPipelineStats returns current pipeline statistics

func (*VectorStore) GetPipelineThreshold

func (s *VectorStore) GetPipelineThreshold() int

GetPipelineThreshold returns the batch count threshold for pipeline use

func (*VectorStore) GetProvenanceManager

func (s *VectorStore) GetProvenanceManager() *ProvenanceManager

GetProvenanceManager returns the VectorStore's vector provenance & explainability manager.

func (*VectorStore) GetQueriesPerSecond

func (s *VectorStore) GetQueriesPerSecond(collection string) float64

GetQueriesPerSecond returns the throughput in queries per second for a collection.

func (*VectorStore) GetQueryLatencies

func (s *VectorStore) GetQueryLatencies(collection string) (p50, p99, avg float64)

GetQueryLatencies returns the P50, P99, and average query latencies for a collection.

func (*VectorStore) GetRecall

func (s *VectorStore) GetRecall(collection string) float64

GetRecall returns the recall achieved by the index for a collection.

func (*VectorStore) GetRerankManager

func (s *VectorStore) GetRerankManager() *AdvancedRerankManager

GetRerankManager returns the VectorStore's advanced reranking & query rewriting manager.

func (*VectorStore) GetSchema

GetSchema returns the Arrow schema for a specific dataset.

func (*VectorStore) GetSchemaRegistry

func (s *VectorStore) GetSchemaRegistry() *SchemaConstraintRegistry

GetSchemaRegistry returns the VectorStore's schema constraint & evolution registry.

func (*VectorStore) GetStreamManager

func (s *VectorStore) GetStreamManager() *StreamIngestionManager

GetStreamManager returns the VectorStore's streaming CDC & connector manager, initializing it lazily.

func (*VectorStore) GetTemporalIndex

func (vs *VectorStore) GetTemporalIndex() *TemporalIndex

GetTemporalIndex is deprecated

func (*VectorStore) GetTextSearchManager

func (s *VectorStore) GetTextSearchManager() *AdvancedTextSearchManager

GetTextSearchManager returns the VectorStore's advanced full-text & analytics engine.

func (*VectorStore) GetTotalNamespaceCount

func (vs *VectorStore) GetTotalNamespaceCount() int

GetTotalNamespaceCount returns the total number of namespaces.

func (*VectorStore) GetUsageMeter

func (s *VectorStore) GetUsageMeter() *UsageMeter

GetUsageMeter returns the VectorStore's tenant usage & billing meter, initializing it lazily.

func (*VectorStore) GetVectorByID

func (s *VectorStore) GetVectorByID(datasetName, rawID string) (map[string]any, error)

GetVectorByID fetches a stored vector and its text/metadata fields by ID.

func (*VectorStore) GetWALQueueDepth

func (vs *VectorStore) GetWALQueueDepth() (count, size int)

GetWALQueueDepth returns the number of jobs and total size in bytes currently in the WAL queue.

func (*VectorStore) GetWebSocketServer

func (s *VectorStore) GetWebSocketServer() *WebSocketServer

GetWebSocketServer returns the WebSocket server instance.

func (*VectorStore) GraphQLHTTPHandler

func (s *VectorStore) GraphQLHTTPHandler() http.Handler

GraphQLHTTPHandler exposes POST / GET /api/v1/graphql endpoint.

func (*VectorStore) HandleVectorSearchAction

func (s *VectorStore) HandleVectorSearchAction(action *flight.Action, stream flight.FlightService_DoActionServer) error

HandleVectorSearchAction handles the VectorSearch DoAction request

func (*VectorStore) HandleVectorSearchExchange

func (s *VectorStore) HandleVectorSearchExchange(stream flight.FlightService_DoExchangeServer, firstMsg *flight.FlightData) error

HandleVectorSearchExchange handles binary protocol vector search

func (*VectorStore) HybridSearch

func (s *VectorStore) HybridSearch(ctx context.Context, name string, queryVec []float32, k int, filters map[string]string) ([]SearchResult, error)

HybridSearch performs a filtered vector search using inverted indexes for pre-filtering.

func (*VectorStore) HybridSearchWithBitmap

func (s *VectorStore) HybridSearchWithBitmap(ctx context.Context, req *HybridSearchRequest) ([]SearchResult, error)

HybridSearchWithBitmap performs hybrid search using a pre-computed bitmap for filtering. It combines dense vector search (filtered by the bitmap) with optional sparse keyword search (BM25) when a text query is provided, fusing results via Reciprocal Rank Fusion.

func (*VectorStore) ImportDataset

func (vs *VectorStore) ImportDataset(ctx context.Context, name string, backend storage.SnapshotBackend, schema *arrow.Schema) (int64, error)

ImportDataset imports a dataset from a storage backend in Parquet format.

func (*VectorStore) ImportDatasetFrom

func (vs *VectorStore) ImportDatasetFrom(ctx context.Context, snapshotName, datasetName string, backend storage.SnapshotBackend, schema *arrow.Schema) (int64, error)

ImportDatasetFrom imports a snapshot as a new dataset name.

func (*VectorStore) IndexRecordColumns

func (vs *VectorStore) IndexRecordColumns(datasetName string, rec arrow.RecordBatch, batchIdx int)

IndexRecordColumns indexes specific columns for fast equality lookups

func (*VectorStore) IngestionBackpressureDelay

func (vs *VectorStore) IngestionBackpressureDelay() time.Duration

IngestionBackpressureDelay returns a delay duration if the system is under moderate load. This implements "Soft Backpressure" to prevent the ingestion cliff.

func (*VectorStore) IngestionQueueCap

func (vs *VectorStore) IngestionQueueCap() int

IngestionQueueCap returns the capacity of the ingestion queue.

func (*VectorStore) IngestionQueueLen

func (vs *VectorStore) IngestionQueueLen() int

IngestionQueueLen returns the current length of the ingestion queue.

func (*VectorStore) InitGPUBackend

func (s *VectorStore) InitGPUBackend(backend gpu.GPUBackend, deviceID int) error

InitGPUBackend is a no-op for CPU-only builds

func (*VectorStore) InitPersistence

func (s *VectorStore) InitPersistence(cfg StorageConfig) error

InitPersistence initializes the storage layer, replays Write-Ahead Log (WAL), and loads snapshots for disaster recovery.

func (*VectorStore) IsGPUEnabled

func (s *VectorStore) IsGPUEnabled() bool

IsGPUEnabled returns false for CPU-only builds

func (*VectorStore) IsNUMAEnabled

func (vs *VectorStore) IsNUMAEnabled() bool

IsNUMAEnabled returns true if NUMA-aware memory allocation is active.

func (*VectorStore) IterateDatasets

func (vs *VectorStore) IterateDatasets(fn func(string, *Dataset))

IterateDatasets safely iterates over all datasets.

func (*VectorStore) ListDatasetsInNamespace

func (vs *VectorStore) ListDatasetsInNamespace(name string) []string

ListDatasetsInNamespace returns all dataset names belonging to the specified namespace.

func (*VectorStore) ListFlights

ListFlights returns a list of available datasets as FlightInfo objects.

func (*VectorStore) ListNamespaces

func (vs *VectorStore) ListNamespaces() []string

ListNamespaces returns all namespace names.

func (*VectorStore) MapInternalToUserIDs

func (s *VectorStore) MapInternalToUserIDs(ds *Dataset, results []SearchResult) []SearchResult

MapInternalToUserIDs maps internal HNSW IDs to user-provided IDs MapInternalToUserIDs maps internal HNSW IDs to user-provided IDs This is the public wrapper that acquires a read lock.

func (*VectorStore) MerkleRoot

func (vs *VectorStore) MerkleRoot(name string) [32]byte

MerkleRoot returns the root hash of the Merkle tree for a given dataset.

func (*VectorStore) MigrateNamespace

func (vs *VectorStore) MigrateNamespace(config NamespaceMigrationConfig) (*NamespaceMigrationResult, error)

MigrateNamespace moves or copies datasets between namespaces.

func (*VectorStore) NamespaceExists

func (vs *VectorStore) NamespaceExists(name string) bool

NamespaceExists checks if a namespace exists.

func (*VectorStore) OIDC

func (s *VectorStore) OIDC() *security.OIDCManager

OIDCManager returns the active OIDCManager (nil if disabled).

func (*VectorStore) OpenAPIHandler

func (s *VectorStore) OpenAPIHandler() http.Handler

OpenAPIHandler serves the OpenAPI v3.0.3 JSON specification for Longbow HTTP v1 APIs.

func (*VectorStore) PrewarmDataset

func (s *VectorStore) PrewarmDataset(name string, schema *arrow.Schema)

PrewarmDataset ensures a dataset is initialized in memory, creating it if necessary.

func (*VectorStore) PublishIndexBoundaries

func (vs *VectorStore) PublishIndexBoundaries()

PublishIndexBoundaries publishes the geospatial and temporal boundaries of all datasets to Gossip tags.

func (*VectorStore) RBAC

func (s *VectorStore) RBAC() *RBACManager

RBACManager returns the active RBACManager (nil if RBAC is disabled).

func (*VectorStore) RESTHealthHTTPHandler

func (s *VectorStore) RESTHealthHTTPHandler() http.Handler

RESTHealthHTTPHandler returns Liveness and active runtime metadata for /api/v1/health.

func (*VectorStore) RangeSearch

func (s *VectorStore) RangeSearch(ctx context.Context, dataset string, queryVec []float32, threshold float32, filters []qry.Filter, maxResults int) ([]SearchResult, error)

RangeSearch returns all vectors within the given distance threshold from queryVec.

func (*VectorStore) Recommend

Recommend implements the hybrid vector-graph recommendation logic (v0.1.9). It blends vector similarity to the centroid of seeds with graph-based connectivity.

func (*VectorStore) RecordQueryPerformance

func (s *VectorStore) RecordQueryPerformance(features QueryFeatures, latency float64, recall float64, index IndexType, provider, model string)

RecordQueryPerformance records a query—including its embedding context—for training the index predictor. provider and model identify the EmbeddingGenerator backend that produced the query vectors; pass empty strings when no embedding generator was used.

func (*VectorStore) RegisterCDCSubscriber

func (s *VectorStore) RegisterCDCSubscriber(dataset string, sub chan arrow.RecordBatch)

RegisterCDCSubscriber registers a subscriber for CDC events

func (*VectorStore) RegisterHTTPHandlers

func (s *VectorStore) RegisterHTTPHandlers(mux *http.ServeMux)

RegisterHTTPHandlers mounts feature HTTP API endpoints (REST v1, GraphQL, Cloud Control Plane, Usage Metering, and Edge Transport) onto the server's HTTP mux, wrapped with RBAC HTTP authentication when RBAC is enabled.

func (*VectorStore) ReleaseMemory

func (s *VectorStore) ReleaseMemory()

ReleaseMemory explicitly triggers garbage collection and returns memory to the OS.

func (*VectorStore) RestoreFromBackup

func (vs *VectorStore) RestoreFromBackup(backupID, datasetName string) error

RestoreFromBackup restores a dataset from a specific backup ID.

func (*VectorStore) RestoreWithPITR

func (vs *VectorStore) RestoreWithPITR(ctx context.Context, cfg PITRConfig) (RestoreVerificationReport, error)

RestoreWithPITR restores a dataset from an online snapshot archive and optionally replays WAL entries up to target time/sequence (Item 4.3 & 4.4).

func (*VectorStore) SearchByID

SearchByID looks up the stored vector for req.ID and returns its k nearest neighbors.

func (*VectorStore) SearchDatasetVectors

func (s *VectorStore) SearchDatasetVectors(ctx context.Context, dataset string, queryVec []float32, k int, filters []core.Filter) ([]SearchResult, error)

SearchDatasetVectors provides a shared dataset vector search path with RLS filtering.

func (*VectorStore) SearchHybrid

func (s *VectorStore) SearchHybrid(ctx context.Context, name string, queryVec []float32, textQuery string, k int, alpha float32, rrfK int, graphAlpha float32, graphDepth int, rawHybrid bool) ([]SearchResult, error)

SearchHybrid performs a hybrid search combining dense vector search and sparse keyword search. If alpha is < 0, it is automatically estimated using EstimateAlpha.

func (*VectorStore) SearchHybridWithFilters

func (s *VectorStore) SearchHybridWithFilters(ctx context.Context, name string, queryVec []float32, textQuery string, k int, alpha float32, rrfK int, graphAlpha float32, graphDepth int, rawHybrid bool, filters []query.Filter) ([]SearchResult, error)

SearchHybridWithFilters performs a hybrid search combining dense vector search, sparse BM25 search, optional GraphRAG expansion, and pre-filtering via structured metadata filters.

func (*VectorStore) SetActiveEmbedding

func (s *VectorStore) SetActiveEmbedding(provider, model string)

SetActiveEmbedding registers the currently active EmbeddingGenerator provider and model with the store. Call this after provisioning an EmbeddingGenerator so that SearchHybrid and other search paths can automatically attach embedding context to training samples.

func (*VectorStore) SetAutoGPUConfig

func (vs *VectorStore) SetAutoGPUConfig(deviceID int32)

SetAutoGPUConfig automatically detects and configures the best available GPU backend Metal on macOS, CUDA on Linux with NVIDIA, CPU fallback if no GPU

func (*VectorStore) SetAutoScaleConfig

func (vs *VectorStore) SetAutoScaleConfig(config AutoScaleConfig) error

SetAutoScaleConfig updates the auto-scaling configuration.

func (*VectorStore) SetAutoScaler

func (vs *VectorStore) SetAutoScaler(scaler *autoscale.AutoScaler)

SetAutoScaler registers an auto-scaler for load monitoring.

func (*VectorStore) SetAutoShardingConfig

func (vs *VectorStore) SetAutoShardingConfig(cfg AutoShardingConfig)

SetAutoShardingConfig updates the auto-sharding configuration

func (*VectorStore) SetBackupSchedule

func (vs *VectorStore) SetBackupSchedule(interval time.Duration)

SetBackupSchedule sets the interval for automatic backups.

func (*VectorStore) SetCDC

func (s *VectorStore) SetCDC(cdc *ChangeDataCapture)

SetCDC sets the Change Data Capture instance.

func (*VectorStore) SetCoordinator

func (vs *VectorStore) SetCoordinator(c *GlobalSearchCoordinator)

SetCoordinator sets the global search coordinator for the vector store.

func (*VectorStore) SetGCTuner

func (vs *VectorStore) SetGCTuner(tuner *lbmem.GCTuner)

SetGCTuner sets the memory tuner for backpressure.

func (*VectorStore) SetGPUConfig

func (vs *VectorStore) SetGPUConfig(backend gpu.GPUBackend, deviceID int32)

SetGPUConfig manually configures the GPU backend and device

func (*VectorStore) SetHNSW2Config

func (s *VectorStore) SetHNSW2Config(cfg *ArrowHNSWConfig)

SetHNSW2Config sets the HNSW configuration template for newly created datasets.

func (*VectorStore) SetHybridSearchConfig

func (s *VectorStore) SetHybridSearchConfig(cfg HybridSearchConfig)

SetHybridSearchConfig updates the hybrid search configuration.

func (*VectorStore) SetIndexPredictor

func (s *VectorStore) SetIndexPredictor(predictor *IndexPerformancePredictor)

SetIndexPredictor sets the learned index performance predictor.

func (*VectorStore) SetIndexedColumns

func (vs *VectorStore) SetIndexedColumns(cols []string)

SetIndexedColumns updates columns that should be indexed for fast equality lookups

func (*VectorStore) SetMemoryConfig

func (s *VectorStore) SetMemoryConfig(cfg MemoryConfig)

SetMemoryConfig updates the memory configuration

func (*VectorStore) SetMesh

func (vs *VectorStore) SetMesh(m *mesh.Gossip)

SetMesh sets the mesh gossip instance for the vector store and initializes the WAL replicator.

func (*VectorStore) SetNamespaceRateLimit

func (vs *VectorStore) SetNamespaceRateLimit(namespace string, config RateLimitConfig) error

SetNamespaceRateLimit configures rate limiting for a namespace in the VectorStore.

func (*VectorStore) SetOllamaPredictor

func (s *VectorStore) SetOllamaPredictor(predictor *LearnedIndexWithOllama)

SetOllamaPredictor sets the Ollama-backed learned index predictor.

func (*VectorStore) SetTemporalIndex

func (vs *VectorStore) SetTemporalIndex(cfg TemporalConfig)

SetTemporalIndex configures the temporal index for Part 22

func (*VectorStore) ShouldSpillToDisk

func (s *VectorStore) ShouldSpillToDisk(ds *Dataset, schema *arrow.Schema) bool

ShouldSpillToDisk evaluates whether dataset memory projection exceeds the configured physical RAM threshold (default 70%).

func (*VectorStore) Shutdown

func (s *VectorStore) Shutdown(ctx context.Context) error

Shutdown performs a graceful shutdown of the VectorStore. It stops accepting new requests, drains the index queue, flushes the WAL, and closes all file handles. The context controls the shutdown timeout.

func (*VectorStore) Snapshot

func (s *VectorStore) Snapshot(ctx context.Context) error

Snapshot triggers a snapshot of all state.

func (*VectorStore) StartBackupScheduler

func (vs *VectorStore) StartBackupScheduler(ctx context.Context, destination string)

StartBackupScheduler starts periodic automated backups and retention pruning for the configured interval (Item 4.5).

func (*VectorStore) StartEvictionTicker

func (s *VectorStore) StartEvictionTicker(interval time.Duration)

StartEvictionTicker starts the background eviction ticker (used by tests/shutdown)

func (*VectorStore) StartIndexingWorkers

func (s *VectorStore) StartIndexingWorkers(numWorkers int)

StartIndexingWorkers spawns a specified number of background indexing workers. Under DeterministicIngestEnabled, the pool is clamped to a single worker so that the order rows land in the graph depends only on the input stream and not on the scheduler.

func (*VectorStore) StartIngestionAutoscaler

func (s *VectorStore) StartIngestionAutoscaler(ctx context.Context)

StartIngestionAutoscaler starts an adaptive goroutine that dynamically scales ingestion workers.

func (*VectorStore) StartIngestionWorkers

func (s *VectorStore) StartIngestionWorkers(count int)

StartIngestionWorkers spawns a specified number of background ingestion workers.

func (*VectorStore) StartLifecycleManager

func (s *VectorStore) StartLifecycleManager(ctx context.Context)

StartLifecycleManager starts the lifecycle manager background task.

func (*VectorStore) StartMetricsTicker

func (s *VectorStore) StartMetricsTicker(d time.Duration)

StartMetricsTicker reports global store metrics to Prometheus

func (*VectorStore) StartWALCheckTicker

func (s *VectorStore) StartWALCheckTicker(d time.Duration)

StartWALCheckTicker starts periodic WAL integrity and size checks

func (*VectorStore) StopIndexingWorkers

func (s *VectorStore) StopIndexingWorkers(numWorkers int)

StopIndexingWorkers stops a specified number of background indexing workers.

func (*VectorStore) StopIngestionWorkers

func (s *VectorStore) StopIngestionWorkers(numWorkers int)

StopIngestionWorkers stops a specified number of background ingestion workers.

func (*VectorStore) StoreRecordBatch

func (s *VectorStore) StoreRecordBatch(ctx context.Context, name string, rec arrow.RecordBatch) error

StoreRecordBatch ingests a record batch into the specified dataset.

func (*VectorStore) SwitchIndex

func (s *VectorStore) SwitchIndex(collection string, to IndexType) error

SwitchIndex performs a live migration of a collection's vector index to a new type. It implements the IndexSwitcher interface used by the adaptive learned index loop. The migration is performed in the background by building a new index from source records and then atomically swapping the index pointer in the dataset.

func (*VectorStore) TemporalSearch

func (s *VectorStore) TemporalSearch(ctx context.Context, req *types.TemporalSearchRequest) ([]SearchResult, error)

TemporalSearch executes as_of, range, sliding_window, or sliding_window_time queries, including optional global mesh scatter-gather and RLS filtering.

func (*VectorStore) TotalIndexQueueDepth

func (vs *VectorStore) TotalIndexQueueDepth() int

TotalIndexQueueDepth returns the aggregated depth of all NUMA-local queues and the global index queue.

func (*VectorStore) TrackMemory

func (vs *VectorStore) TrackMemory(delta int64)

TrackMemory adds delta to current usage and logs if large.

func (*VectorStore) TriggerBackup

func (vs *VectorStore) TriggerBackup(datasetName string) error

TriggerBackup manually initiates a backup for a dataset by serializing all current records via Arrow IPC.

func (*VectorStore) TruncateWAL

func (s *VectorStore) TruncateWAL(seq uint64) error

TruncateWAL truncates the WAL up to the given sequence.

func (*VectorStore) UnregisterCDCSubscriber

func (s *VectorStore) UnregisterCDCSubscriber(dataset string, sub chan arrow.RecordBatch)

UnregisterCDCSubscriber unregisters a subscriber for CDC events

func (*VectorStore) UpdateConfig

func (s *VectorStore) UpdateConfig(maxMemory, maxWALSize int64, snapshotInterval time.Duration)

UpdateConfig updates store configuration parameters like memory limits dynamically.

func (*VectorStore) UpdateDatasets

func (vs *VectorStore) UpdateDatasets(fn func(map[string]*Dataset))

UpdateDatasets executes a CAS loop to update the dataset map safely. fn receives a copy of the current map to modify.

func (*VectorStore) UpdateGPUMemoryMetrics

func (s *VectorStore) UpdateGPUMemoryMetrics()

UpdateGPUMemoryMetrics is a no-op for CPU-only builds

func (*VectorStore) UpsertStreamEvents

func (s *VectorStore) UpsertStreamEvents(ctx context.Context, datasetName string, events []StreamVectorEvent) (int, error)

UpsertStreamEvents encodes JSON/struct vector events into an Arrow RecordBatch and waits for indexing.

func (*VectorStore) WaitForIndexing

func (vs *VectorStore) WaitForIndexing(name string)

WaitForIndexing blocks until all pending indexing jobs for the given dataset are complete.

func (*VectorStore) Warmup

func (vs *VectorStore) Warmup() WarmupStats

Warmup iterates through all datasets and warms up their indexes

type VectorTimestamp

type VectorTimestamp struct {
	ID        uint64    `json:"id"`
	Timestamp time.Time `json:"timestamp"`
	Vector    []float32 `json:"vector,omitempty"`
	Metadata  []byte    `json:"metadata,omitempty"`
}

VectorTimestamp pairs a vector with its creation/update timestamp for JSON export.

type VectorType

type VectorType interface{}

VectorType is a marker interface for all supported vector types

type VectorVersion

type VectorVersion struct {
	Version    uint64
	Vector     []float32
	Timestamp  time.Time
	ModifiedBy string
}

VectorVersion stores the version and metadata for a specific vector.

type VersionHistory

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

VersionHistory manages the storage and retrieval of multiple versions for each vector ID.

func NewVersionHistory

func NewVersionHistory(cfg VersionHistoryConfig) *VersionHistory

NewVersionHistory creates a new VersionHistory instance with the provided configuration.

func (*VersionHistory) Add

func (vh *VersionHistory) Add(id uint64, vector []float32, norm float32, timestamp int64, metadata []byte)

Add inserts a new version for a vector ID, pruning old versions if necessary.

func (*VersionHistory) GetHistory

func (vh *VersionHistory) GetHistory(id uint64) []VersionedVector

GetHistory returns the entire version history for a specific vector ID.

func (*VersionHistory) GetLatestVersion

func (vh *VersionHistory) GetLatestVersion(id uint64) (*VersionedVector, error)

GetLatestVersion retrieves the most recent version for a vector ID.

func (*VersionHistory) GetVersion

func (vh *VersionHistory) GetVersion(id uint64, version int) (*VersionedVector, error)

GetVersion retrieves a specific version of a vector by its ID and version number.

func (*VersionHistory) GetVersionAt

func (vh *VersionHistory) GetVersionAt(id uint64, timestamp int64) (*VersionedVector, error)

GetVersionAt retrieves the version of a vector that was active at a specific timestamp.

func (*VersionHistory) GetVersionsAtBatch

func (vh *VersionHistory) GetVersionsAtBatch(ids []uint64, timestamp int64, out map[uint64]VersionedVector)

GetVersionsAtBatch retrieves active versions for multiple IDs at a specific timestamp.

func (*VersionHistory) Prune

func (vh *VersionHistory) Prune(ctx context.Context, beforeTimestamp int64) int

Prune removes all versions with timestamps before the specified value.

func (*VersionHistory) Size

func (vh *VersionHistory) Size() int

Size returns the number of unique vector IDs tracked in the version history.

func (*VersionHistory) TotalVersions

func (vh *VersionHistory) TotalVersions() int

TotalVersions returns the total number of versions across all vector IDs.

type VersionHistoryConfig

type VersionHistoryConfig struct {
	// MaxVersions is the maximum number of versions to keep per vector ID.
	MaxVersions int
	// RetentionPeriod is the duration for which older versions are kept.
	RetentionPeriod time.Duration
}

VersionHistoryConfig defines the retention settings for version history.

func DefaultVersionHistoryConfig

func DefaultVersionHistoryConfig() VersionHistoryConfig

DefaultVersionHistoryConfig returns a default configuration for version history.

type VersionManager

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

VersionManager coordinates versioned datasets across the system.

func NewVersionManager

func NewVersionManager() *VersionManager

NewVersionManager creates a new VersionManager instance.

func (*VersionManager) DeleteDataset

func (vm *VersionManager) DeleteDataset(name string)

DeleteDataset removes a versioned dataset by name.

func (*VersionManager) GetDataset

func (vm *VersionManager) GetDataset(name string) (*VersionedDataset, bool)

GetDataset retrieves a versioned dataset by name.

func (*VersionManager) GetOrCreateDataset

func (vm *VersionManager) GetOrCreateDataset(name string) *VersionedDataset

GetOrCreateDataset retrieves a versioned dataset or creates one if it doesn't exist.

type VersionQuery

type VersionQuery struct {
	VersionID *int64
	AsOfTime  *time.Time
	Branch    string
}

VersionQuery defines the criteria for querying a specific version.

type VersionRetentionPolicy

type VersionRetentionPolicy struct {
	MaxVersions    int
	MaxAge         time.Duration
	KeepTombstones bool
}

VersionRetentionPolicy defines the rules for retaining dataset versions.

type VersionedData

type VersionedData struct {
	Dataset string
	Data    []byte
	Clock   *VectorClock
}

VersionedData wraps data with a vector clock for causal consistency

func NewVersionedData

func NewVersionedData(dataset string, data []byte, clock *VectorClock) *VersionedData

NewVersionedData creates versioned data with a vector clock

func (*VersionedData) Conflicts

func (vd *VersionedData) Conflicts(other *VersionedData) bool

Conflicts returns true if this data is concurrent with the other

func (*VersionedData) Supersedes

func (vd *VersionedData) Supersedes(other *VersionedData) bool

Supersedes returns true if this data happened after the other

type VersionedDataset

type VersionedDataset struct {
	Name     string
	Versions map[int64]RecordVersion
	Branches map[string]BranchConfig
	// contains filtered or unexported fields
}

VersionedDataset manages versions and branches for a single dataset.

func NewVersionedDataset

func NewVersionedDataset(name string) *VersionedDataset

NewVersionedDataset creates a new versioned dataset instance.

func (*VersionedDataset) AddVersion

func (vd *VersionedDataset) AddVersion(version RecordVersion)

AddVersion adds a new version to the dataset.

func (*VersionedDataset) ApplyRetentionPolicy

func (vd *VersionedDataset) ApplyRetentionPolicy(policy VersionRetentionPolicy) (int, error)

ApplyRetentionPolicy removes versions that exceed the retention criteria.

func (*VersionedDataset) CreateBranch

func (vd *VersionedDataset) CreateBranch(name string, baseVersionID int64) error

CreateBranch creates a new branch starting from the specified version.

func (*VersionedDataset) DeleteBranch

func (vd *VersionedDataset) DeleteBranch(name string) error

DeleteBranch removes a branch by its name.

func (*VersionedDataset) GetBranch

func (vd *VersionedDataset) GetBranch(name string) (BranchConfig, bool)

GetBranch retrieves the configuration for a branch by its name.

func (*VersionedDataset) GetVersion

func (vd *VersionedDataset) GetVersion(versionID int64) (RecordVersion, bool)

GetVersion retrieves a specific version by its ID.

func (*VersionedDataset) ListBranches

func (vd *VersionedDataset) ListBranches() []BranchConfig

ListBranches returns all branches in the dataset.

func (*VersionedDataset) ListVersions

func (vd *VersionedDataset) ListVersions() []RecordVersion

ListVersions returns all versions in the dataset.

func (*VersionedDataset) QueryVersion

func (vd *VersionedDataset) QueryVersion(q VersionQuery) (RecordVersion, error)

QueryVersion retrieves a version based on the specified query criteria.

type VersionedVector

type VersionedVector struct {
	ID        uint64
	Vector    []float32
	Norm      float32 // Pre-calculated norm
	Timestamp int64
	Metadata  []byte
	Version   int
}

VersionedVector represents a specific version of a vector with its metadata and timestamp.

type ViewRefreshPolicy

type ViewRefreshPolicy string

ViewRefreshPolicy controls how a materialized view stays synchronized with base datasets.

const (
	RefreshManual    ViewRefreshPolicy = "manual"
	RefreshScheduled ViewRefreshPolicy = "scheduled"
	RefreshStreaming ViewRefreshPolicy = "streaming"
)

type WSConnection

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

WSConnection wraps a WebSocket connection with its associated subscriptions.

func (*WSConnection) Close

func (ws *WSConnection) Close()

Close terminates the WebSocket connection and releases resources.

type WSConnectionPool

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

WSConnectionPool manages a pool of active WebSocket connections.

func NewWSConnectionPool

func NewWSConnectionPool(maxSize int, idleTimeout time.Duration) *WSConnectionPool

NewWSConnectionPool creates a new connection pool with the specified limits.

func (*WSConnectionPool) Add

func (p *WSConnectionPool) Add(conn *WSConnection) error

Add registers a new connection in the pool.

func (*WSConnectionPool) Close

func (p *WSConnectionPool) Close()

Close shuts down all connections in the pool.

func (*WSConnectionPool) Get

func (p *WSConnectionPool) Get(id string) (*WSConnection, bool)

Get retrieves a connection from the pool by its ID.

func (*WSConnectionPool) Len

func (p *WSConnectionPool) Len() int

Len returns the number of active connections in the pool.

func (*WSConnectionPool) Remove

func (p *WSConnectionPool) Remove(id string)

Remove deletes a connection from the pool and closes it.

type WSDataPayload

type WSDataPayload struct {
	Dataset string          `json:"dataset"`
	Event   string          `json:"event"`
	Data    json.RawMessage `json:"data"`
}

WSDataPayload contains the actual data being streamed over a WebSocket.

type WSMessage

type WSMessage struct {
	Type    WSMessageType   `json:"type"`
	Payload json.RawMessage `json:"payload,omitempty"`
	Error   string          `json:"error,omitempty"`
}

WSMessage represents a standard envelope for all WebSocket communications.

type WSMessageType

type WSMessageType string

WSMessageType defines the category of a WebSocket message.

const (
	// WSTypeSubscribe is the message type for subscribing to a dataset stream.
	WSTypeSubscribe WSMessageType = "subscribe"
	// WSTypeUnsubscribe is the message type for unsubscribing from a dataset stream.
	WSTypeUnsubscribe WSMessageType = "unsubscribe"
	// WSTypeData is the message type for sending data updates to the client.
	WSTypeData WSMessageType = "data"
	// WSTypeError is the message type for communicating error details to the client.
	WSTypeError WSMessageType = "error"
	// WSTypePing is the message type for sending ping health checks.
	WSTypePing WSMessageType = "ping"
	// WSTypePong is the message type for sending pong health responses.
	WSTypePong WSMessageType = "pong"
)

type WSSubscribePayload

type WSSubscribePayload struct {
	Dataset    string   `json:"dataset"`
	Columns    []string `json:"columns,omitempty"`
	EventTypes []string `json:"event_types,omitempty"`
}

WSSubscribePayload contains parameters for subscribing to a dataset.

type WarmupStats

type WarmupStats struct {
	DatasetsWarmed   int
	DatasetsSkipped  int
	TotalNodesWarmed int
	Duration         time.Duration
}

WarmupStats holds statistics about the warmup operation, including duration and node count.

func (WarmupStats) String

func (w WarmupStats) String() string

type WebSocketServer

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

WebSocketServer manages real-time data streaming to connected clients.

func NewWebSocketServer

func NewWebSocketServer(logger zerolog.Logger, cdc *ChangeDataCapture) *WebSocketServer

NewWebSocketServer creates a new server instance.

func (*WebSocketServer) GetConnectionCount

func (w *WebSocketServer) GetConnectionCount() int

GetConnectionCount returns the number of currently active connections.

func (*WebSocketServer) GetConnectionIDs

func (w *WebSocketServer) GetConnectionIDs() []string

GetConnectionIDs returns a list of IDs for all active connections.

func (*WebSocketServer) Start

func (w *WebSocketServer) Start(addr string) error

Start begins listening for WebSocket connections on the specified address.

func (*WebSocketServer) Stop

func (w *WebSocketServer) Stop() error

Stop shuts down the WebSocket server and closes all active connections.

type WebhookBillingExporter

type WebhookBillingExporter struct {
	URL        string
	HTTPClient *http.Client
}

WebhookBillingExporter posts JSON usage reports to a billing webhook URL.

func (*WebhookBillingExporter) ExportBilling

func (w *WebhookBillingExporter) ExportBilling(ctx context.Context, reports []TenantUsageReport) error

ExportBilling sends usage reports via HTTP POST JSON.

type WriteRequest

type WriteRequest struct {
	ID     uint64
	Buffer []byte
	Offset int64
	Result int32
	Done   chan error
}

WriteRequest tracks an asynchronous write operation.

type ZeroCopyBufferArrowHNSWConfig

type ZeroCopyBufferArrowHNSWConfig struct {
	Enabled            bool
	MaxRetainedBuffers int
	MaxBufferSize      int64
}

ZeroCopyBufferArrowHNSWConfig configures zero-copy buffer behavior

func DefaultZeroCopyBufferArrowHNSWConfig

func DefaultZeroCopyBufferArrowHNSWConfig() ZeroCopyBufferArrowHNSWConfig

DefaultZeroCopyBufferArrowHNSWConfig returns sensible defaults

func (ZeroCopyBufferArrowHNSWConfig) Validate

func (c ZeroCopyBufferArrowHNSWConfig) Validate() error

Validate checks configuration validity

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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