types

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: 30 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

Index

Constants

View Source
const (
	GraphSnapshotVersion = 1
	SerializationMagic   = 0x4C424752 // "LBGR" (LongBow GRaph)
)
View Source
const ArrowMaxLayers = 16

ArrowMaxLayers is the maximum number of layers in HNSW hierarchy

View Source
const ChunkSize = 1024

ChunkSize is the size of data chunks for memory allocation

View Source
const LocationChunkSize = 1024

LocationChunkSize is the size of chunks in the location store

View Source
const MaxNeighbors = 256

MaxNeighbors is the maximum number of neighbors per node in HNSW

View Source
const NodeLockMask uint32 = 1 << 31

NodeLockMask is used for atomic per-node locking in the Version field. HNSW version fields are uint32: [Lock Bit (1 bit) | Version (31 bits)]

Variables

This section is empty.

Functions

func ChunkID

func ChunkID(id uint32) int

ChunkID returns the chunk index for a given vector identifier

func ChunkOffset

func ChunkOffset(id uint32) int

ChunkOffset returns the offset within a chunk for a given vector identifier

func IsHighPriority

func IsHighPriority(ctx context.Context) bool

IsHighPriority returns true if the context has high priority flag set.

func LogClientAction

func LogClientAction(ctx context.Context, logger zerolog.Logger, m *mesh.Gossip, action string, meta map[string]any)

LogClientAction logs an action performed by a client, resolving their identity if possible.

func NewVectorDimensionMismatchError

func NewVectorDimensionMismatchError(id, expected, actual int) error

NewVectorDimensionMismatchError creates a new ErrVectorDimensionMismatch.

func PackLocation

func PackLocation(loc Location) uint64

PackLocation packs a Location into a uint64.

func ToGRPCStatus

func ToGRPCStatus(err error) error

ToGRPCStatus converts standard errors to gRPC status codes

func WithHighPriority

func WithHighPriority(ctx context.Context) context.Context

WithHighPriority returns a context with high priority flag set.

Types

type AndExpr

type AndExpr struct {
	Conditions []FilterExpr
}

Logical Operators

func (*AndExpr) Evaluate

func (a *AndExpr) Evaluate(metadata *LazyMetadata) bool

type ArrowBitset

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

ArrowBitset is a memory-efficient bitset implementation for tracking visited nodes during HNSW search operations. It's optimized for Arrow-based vector operations.

func NewArrowBitset

func NewArrowBitset(initialSize int) *ArrowBitset

NewArrowBitset creates a new ArrowBitset with the specified initial capacity.

func (*ArrowBitset) Capacity

func (b *ArrowBitset) Capacity() int

Capacity returns the current capacity in bits.

func (*ArrowBitset) Clear

func (b *ArrowBitset) Clear()

Clear resets all bits to 0.

func (*ArrowBitset) ClearSIMD

func (b *ArrowBitset) ClearSIMD()

Clear resets all bits to 0. Consistent with HNSW usage.

func (*ArrowBitset) Count

func (b *ArrowBitset) Count() int

Count returns the number of set bits in the bitset.

func (*ArrowBitset) FilterAndMarkUnvisited

func (b *ArrowBitset) FilterAndMarkUnvisited(ids []uint32, maxCommitted int64, allowUncommitted bool, dst []uint32) []uint32

FilterAndMarkUnvisited filters candidate IDs against the bitset, appends previously unvisited IDs that satisfy the commit threshold to dst, and marks them as visited. It minimizes branching and eliminates individual Set/IsSet overhead.

func (*ArrowBitset) Grow

func (b *ArrowBitset) Grow(newSize int)

Grow ensures the bitset can accommodate positions up to newSize.

func (*ArrowBitset) IsSet

func (b *ArrowBitset) IsSet(pos int) bool

IsSet returns true if the bit at position pos is 1 (visited).

func (*ArrowBitset) Set

func (b *ArrowBitset) Set(pos int)

Set marks the bit at position pos as 1 (visited).

func (*ArrowBitset) Size

func (b *ArrowBitset) Size() int

Size returns the maximum position that has been set.

type ArrowHNSWConfig

type ArrowHNSWConfig struct {
	M              int
	MMax           int
	MMax0          int
	EfConstruction int32
	EfSearch       int32

	AdaptiveEf          bool
	AdaptiveEfMin       int
	AdaptiveEfThreshold int
	InitialCapacity     int

	Workers      int
	Quantization bool
	SQ8Enabled   bool

	UseDisk  bool
	DiskPath string

	Metric   core.DistanceMetric
	Logger   any
	DataType VectorDataType

	BQEnabled bool
	PQEnabled bool
	PQM       int
	PQK       int

	Dims                    int
	SelectionHeuristicLimit int

	ParallelSearch ParallelSearchConfig

	AdaptiveMEnabled   bool
	AdaptiveMThreshold int

	Float16Enabled         bool
	SQ8TrainingThreshold   int
	PQTrainingThreshold    int
	PackedAdjacencyEnabled bool
	SearchLayerSampleRate  float64

	Registerer        prometheus.Registerer
	TurboQuantEnabled bool
	TurboQuantBits    int
	LockFreeThreshold int  // Layer threshold for CAS-based lock-free updates (e.g. 2)
	NUMANode          int  // Target NUMA node for memory pinning (-1 for default)
	SharedVectorSpace bool // If true, perform zero-copy lookups from primary Dataset records

	// Automatic Spill-to-Disk Paging and Auto-Quantization (v0.3.0)
	AutoSpillToDisk       bool
	SpillThresholdRatio   float64 // Default 0.70 (70% of physical RAM)
	AutoQuantize          bool
	AutoQuantizeThreshold int64 // Default 500,000 vectors
	AutoQuantizeBits      int   // Default 4 bits
}

ArrowHNSWConfig defines the hyperparameters and runtime settings for an HNSW index.

func DefaultArrowHNSWConfig

func DefaultArrowHNSWConfig() ArrowHNSWConfig

DefaultArrowHNSWConfig returns a configuration with sensible defaults

type AtomicBitset

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

AtomicBitset implements a lock-free (for readers) bitset using Copy-On-Write logic. It is optimized for scenarios with frequent reads (Contains) and infrequent writes (Set/Delete).

func NewAtomicBitset

func NewAtomicBitset() *AtomicBitset

func (*AtomicBitset) Clear

func (b *AtomicBitset) Clear(i int)

func (*AtomicBitset) Clone

func (b *AtomicBitset) Clone() *AtomicBitset

func (*AtomicBitset) Contains

func (b *AtomicBitset) Contains(i int) bool

func (*AtomicBitset) Count

func (b *AtomicBitset) Count() uint64

func (*AtomicBitset) Release

func (b *AtomicBitset) Release()

func (*AtomicBitset) Reset

func (b *AtomicBitset) Reset()

func (*AtomicBitset) Set

func (b *AtomicBitset) Set(i int)

func (*AtomicBitset) ToUint32Array

func (b *AtomicBitset) ToUint32Array() []uint32

type BQEncoder

type BQEncoder struct {
	Dimensions int
}

BQEncoder compresses float vectors into binary codes (1 bit per dimension). It uses sign-based quantization: > 0 => 1, <= 0 => 0.

func NewBQEncoder

func NewBQEncoder(dims int) *BQEncoder

NewBQEncoder creates a new Binary Quantization encoder.

func (*BQEncoder) CodeSize

func (e *BQEncoder) CodeSize() int

CodeSize returns number of uint64s required for storage.

func (*BQEncoder) Decode

func (e *BQEncoder) Decode(codes []uint64) []float32

Decode reconstructs a float32 vector from binary codes. It maps 1 -> 1.0 and 0 -> -1.0.

func (*BQEncoder) Encode

func (e *BQEncoder) Encode(vec []float32) []uint64

Encode quantizes a float32 vector into a slice of uint64s. Returns (dims + 63) / 64 uint64s.

func (*BQEncoder) Float32ToHamming

func (e *BQEncoder) Float32ToHamming(score float32) int

Float32ToHamming converts a similarity score to max Hamming distance threshold.

func (*BQEncoder) HammingDistance

func (e *BQEncoder) HammingDistance(a, b []uint64) int

HammingDistance computes the Hamming distance between two binary vectors.

func (*BQEncoder) HammingDistanceBatch

func (e *BQEncoder) HammingDistanceBatch(query []uint64, candidates [][]uint64, results []int)

HammingDistanceBatch computes distances from a query to multiple candidates.

func (*BQEncoder) ScoreToFloat32

func (e *BQEncoder) ScoreToFloat32(hamming int) float32

ScoreToFloat32 converts Hamming distance to a similarity score (0..1). Similarity = 1 - (Hamming / Dimensions)

type BatchCandidates

type BatchCandidates struct {
	Candidates []Candidate
}

BatchCandidates represents search results for a batch of queries

type BatchRemapInfo

type BatchRemapInfo struct {
	NewBatchIdx int
	NewRowIdxs  []int
}

BatchRemapInfo contains information about a batch of vectors being remapped to new locations.

type BitVector

type BitVector []uint64

BitVector is a flat bitset for fast document filtering.

func NewBitVector

func NewBitVector(size int) BitVector

NewBitVector creates a bit vector of the given size in bits.

func (BitVector) And

func (bv BitVector) And(other BitVector)

And performs bitwise AND between two bit vectors.

func (BitVector) Count

func (bv BitVector) Count() int

Count returns the number of set bits.

func (BitVector) Get

func (bv BitVector) Get(i uint32) bool

Get returns true if the bit at index i is set.

func (BitVector) Set

func (bv BitVector) Set(i uint32)

Set sets the bit at index i.

func (BitVector) Test

func (bv BitVector) Test(i uint32) bool

Test reports whether the bit at index i is set. It is the membership primitive for filter probing: a single indexed word load, one shift/mask and one compare, with an out-of-range index answering false instead of panicking, so callers can probe ids in traversal loops without a preceding bounds check.

type Bitset

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

Bitset is a thread-safe wrapper around a roaring.Bitmap. A Bitset that draws its bitmap from the shared pool owns it and hands it back on Release; a Bitset built from a caller's roaring.Bitmap does not own it and must not hand it back, or the pool would end up holding the same pointer twice and could then hand it to two owners at once.

func NewBitset

func NewBitset() *Bitset

func NewBitsetFromRoaring

func NewBitsetFromRoaring(bm *roaring.Bitmap) *Bitset

func (*Bitset) And

func (b *Bitset) And(other *roaring.Bitmap)

func (*Bitset) AsRoaring

func (b *Bitset) AsRoaring() *roaring.Bitmap

func (*Bitset) Clear

func (b *Bitset) Clear(i int)

Clear resets the bit at index i. A negative index is ignored, for the same reason Set ignores one.

func (*Bitset) Clone

func (b *Bitset) Clone() *Bitset

Clone creates a thread-safe copy of the bitset. The copy holds a fresh roaring.Bitmap that never came from the pool, so it does not own one either.

func (*Bitset) Contains

func (b *Bitset) Contains(i int) bool

Contains reports whether the bit at index i is set. A negative index is never contained; without the guard it would alias bit 4294967295.

func (*Bitset) Count

func (b *Bitset) Count() uint64

Count returns the number of set bits.

func (*Bitset) Release

func (b *Bitset) Release()

Release detaches the bitset from its bitmap and returns the bitmap to the pool when the bitset owns it. A bitset built by NewBitsetFromRoaring aliases a bitmap the caller still owns, and a Clone holds a fresh one that never came from the pool, so neither is returned: putting a bitmap the pool did not hand out lets the pool end up holding the same pointer twice, and a later Get then hands one object to two owners, which is both a data race and a cross-request leak of the previous owner's contents. Release is idempotent.

func (*Bitset) Set

func (b *Bitset) Set(i int)

Set marks the bit at index i. A negative index is ignored, matching ArrowBitset: the index is converted to a roaring uint32, so without the guard Set(-1) would set bit 4294967295 instead of doing nothing.

func (*Bitset) Slice

func (b *Bitset) Slice(offset, length int) *Bitset

Slice returns a new Bitset containing bits in range [offset, offset+length) shifted by -offset. Used for splitting batches with tombstones. A negative offset or length yields an empty result rather than wrapping into a huge uint32 bound.

func (*Bitset) ToUint32Array

func (b *Bitset) ToUint32Array() []uint32

ToUint32Array returns the set bits as a slice of uint32.

type Candidate

type Candidate = basecore.Candidate

Candidate represents a search result candidate before metadata retrieval.

type CompactionWorkerInterface

type CompactionWorkerInterface interface {
	Start()
	Stop()
	IsRunning() bool
	Trigger(dataset string)
}

CompactionWorkerInterface defines the control interface for background index compaction.

type ContainsExpr

type ContainsExpr struct {
	Field string
	Value string
}

func (*ContainsExpr) Evaluate

func (c *ContainsExpr) Evaluate(metadata *LazyMetadata) bool

type DeltaSync

type DeltaSync struct {
	FromVersion  uint64
	ToVersion    uint64
	NewLocations []core.Location
	StartIndex   int
}

DeltaSync represents incremental changes between versions.

type EqExpr

type EqExpr struct {
	Field string
	Value interface{}
}

Comparison Operators

func (*EqExpr) Evaluate

func (e *EqExpr) Evaluate(metadata *LazyMetadata) bool

type ErrNeighborSelectionLengthMismatch

type ErrNeighborSelectionLengthMismatch struct {
	DistancesLen int
	IDsLen       int
}

ErrNeighborSelectionLengthMismatch represents a mismatch between distances and IDs lengths during neighbor selection.

func (*ErrNeighborSelectionLengthMismatch) Error

type ErrVectorDimensionMismatch

type ErrVectorDimensionMismatch struct {
	ID       int
	Expected int
	Actual   int
}

ErrVectorDimensionMismatch represents a mismatch between vector dimensions.

func (*ErrVectorDimensionMismatch) Error

type FederatedSearchRequest

type FederatedSearchRequest = basecore.FederatedSearchRequest

FederatedSearchRequest alias for basecore.FederatedSearchRequest.

type FilterExpr

type FilterExpr interface {
	Evaluate(metadata *LazyMetadata) bool
}

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 GeExpr

type GeExpr struct {
	Field string
	Value interface{}
}

func (*GeExpr) Evaluate

func (e *GeExpr) Evaluate(metadata *LazyMetadata) bool

type GeoBoundingBox

type GeoBoundingBox = basecore.GeoBoundingBox

GeoBoundingBox alias for basecore.GeoBoundingBox.

type GeoPoint

type GeoPoint = basecore.GeoPoint

GeoPoint alias for basecore.GeoPoint.

type GeoSearchRequest

type GeoSearchRequest = basecore.GeoSearchRequest

GeoSearchRequest alias for basecore.GeoSearchRequest.

type GraphData

type GraphData struct {
	// Metadata
	Capacity      int                   // Total number of nodes the graph can currently hold.
	Dims          int                   // Number of dimensions for the vectors.
	Type          VectorDataType        // Underlying data type of the vectors.
	SQ8Enabled    bool                  // Whether Scalar Quantization (8-bit) is enabled.
	SQ8Ready      uint32                // 0=not ready, 1=ready (atomic).
	BQEnabled     bool                  // Whether Binary Quantization is enabled.
	PQEnabled     bool                  // Whether Product Quantization is enabled.
	PQM           int                   // Number of sub-spaces for Product Quantization.
	GlobalVersion uint64                // Incremented on structural changes for cache validation.
	BackingGraph  any                   // Interface to a persistent storage (e.g., *DiskGraph).
	Name          string                // Unique identifier for the dataset (used in metrics).
	Allocator     arrowmemory.Allocator // Optional allocator for NUMA-aware memory placement.

	// Vectors (primary storage, usually float32)
	Vectors [][]float32

	// VectorsF32 stores arena offsets for Float32 vectors (off-heap, GC-free)
	VectorsF32 []uint64

	// VectorsPQ for quantized vectors
	VectorsPQ []uint64

	// VectorsInt8 for raw int8 vectors
	VectorsInt8 []uint64

	// VectorsInt16 for raw int16 vectors (off-heap, GC-free)
	VectorsInt16 []uint64

	// VectorsUint16 for raw uint16 vectors (off-heap, GC-free)
	VectorsUint16 []uint64

	// VectorsF16 for half-precision
	VectorsF16 []uint64

	// VectorsBQ for binary quantized vectors
	VectorsBQ []uint64

	// VectorsSQ8 for scalar quantized vectors
	VectorsSQ8 []uint64

	// VectorsTQ for TurboQuant compressed vectors
	VectorsTQ []uint64

	// VectorsFloat64
	VectorsFloat64 [][]float64

	// VectorsComplex64
	VectorsComplex64 [][]complex64

	// VectorsComplex128
	VectorsComplex128 [][]complex128

	// Complex128Magnitudes holds pre-computed L2 magnitudes for complex128 vectors.
	// Indexed by global id. Used during search for triangle-inequality pruning.
	Complex128Magnitudes []float64

	// VectorsInt64 stores arena offsets for Int64 vectors (off-heap, GC-free)
	VectorsInt64 []uint64

	// VectorsUint64 stores arena offsets for Uint64 vectors (off-heap, GC-free)
	VectorsUint64 []uint64

	// VectorsInt32 stores arena offsets for Int32 vectors (off-heap, GC-free)
	VectorsInt32 []uint64

	// VectorsUint32 stores arena offsets for Uint32 vectors (off-heap, GC-free)
	VectorsUint32 []uint64

	// VectorsFloat64Offsets stores arena offsets for Float64 vectors (off-heap, GC-free)
	VectorsFloat64Offsets []uint64

	// VectorsComplex64Offsets stores arena offsets for Complex64 vectors (off-heap, GC-free)
	VectorsComplex64Offsets []uint64

	// VectorsComplex128Offsets stores arena offsets for Complex128 vectors (off-heap, GC-free)
	VectorsComplex128Offsets []uint64

	// Neighbors (Layer -> Chunk -> Arena Offset)
	Neighbors [][]uint64

	// Levels (Chunk -> Data)
	Levels [][]uint32

	// Versions (Layer -> Chunk -> Arena Offset)
	Versions [][]uint64

	// Counts (Layer -> Chunk -> Arena Offset)
	Counts [][]uint64

	// Memory Arenas
	Float32Arena    *memory.TypedArena[float32]
	Float64Arena    *memory.TypedArena[float64]
	Uint8Arena      *memory.TypedArena[uint8]
	Uint16Arena     *memory.TypedArena[uint16]
	Uint32Arena     *memory.TypedArena[uint32]
	Uint64Arena     *memory.TypedArena[uint64]
	Int8Arena       *memory.TypedArena[int8]
	Int16Arena      *memory.TypedArena[int16]
	Int32Arena      *memory.TypedArena[int32]
	Int64Arena      *memory.TypedArena[int64]
	Float16Arena    *memory.TypedArena[float16.Num]
	Complex64Arena  *memory.TypedArena[complex64]
	Complex128Arena *memory.TypedArena[complex128]

	// PackedNeighbors
	PackedNeighbors []PackedNeighbors

	TurboQuantEnabled bool
	TurboQuantBits    int

	// ArrowRefs holds references to external Arrow arrays providing vector data.
	// Used for zero-copy ingestion paths.
	ArrowRefs []arrow.Array

	// Sharded locks for fine-grained concurrency control
	ShardedMus [1024]PaddedMutex

	SharedVectorSpace bool // If true, skip primary vector storage allocation

	// OnNeighborsMiss is a callback hook triggered when neighbor data for a layer is accessed but evicted (offset == 0).
	OnNeighborsMiss func(layer int) error

	// OnEvict is a callback hook triggered when a layer is evicted.
	OnEvict func(layer int)
	// contains filtered or unexported fields
}

GraphData holds the vector data and graph topology. It effectively implements the component storage for ArrowHNSW.

func DeserializeGraphData

func DeserializeGraphData(r io.Reader) (*GraphData, error)

Deserialize reads GraphData from the reader.

func NewGraphData

func NewGraphData(capacity, dim int, mmap bool, useDisk bool, fd int,
	quantization bool, sq8 bool, persistent bool,
	dataType VectorDataType, bqEnabled bool, pqEnabled bool,
	tqEnabled bool, tqBits int, name string, alloc arrowmemory.Allocator,
	sharedVectorSpace bool) *GraphData

func (*GraphData) AcquireReader

func (g *GraphData) AcquireReader()

func (*GraphData) BeginFloat32ChunkBatch

func (g *GraphData) BeginFloat32ChunkBatch(maxGen uint64) VectorChunkBatch[float32]

BeginFloat32ChunkBatch opens a batch-scoped view over the float32 chunk table, matching GetVectorsChunkWithGen / GetVectorsChunkFast.

func (*GraphData) BeginFloat64ChunkBatch

func (g *GraphData) BeginFloat64ChunkBatch(maxGen uint64) VectorChunkBatch[float64]

BeginFloat64ChunkBatch opens a batch-scoped view over the float64 chunk table, matching GetVectorsFloat64ChunkWithGen / GetVectorsFloat64ChunkFast.

func (*GraphData) BeginInt8ChunkBatch

func (g *GraphData) BeginInt8ChunkBatch(maxGen uint64) VectorChunkBatch[int8]

BeginInt8ChunkBatch opens a batch-scoped view over the int8 chunk table, matching GetVectorsInt8ChunkWithGen / GetVectorsInt8ChunkFast.

func (*GraphData) BeginInt16ChunkBatch

func (g *GraphData) BeginInt16ChunkBatch(maxGen uint64) VectorChunkBatch[int16]

BeginInt16ChunkBatch opens a batch-scoped view over the int16 chunk table, matching GetVectorsInt16ChunkWithGen / GetVectorsInt16ChunkFast.

func (*GraphData) BeginInt32ChunkBatch

func (g *GraphData) BeginInt32ChunkBatch(maxGen uint64) VectorChunkBatch[int32]

BeginInt32ChunkBatch opens a batch-scoped view over the int32 chunk table, matching GetVectorsInt32ChunkWithGen / GetVectorsInt32ChunkFast.

func (*GraphData) BeginInt64ChunkBatch

func (g *GraphData) BeginInt64ChunkBatch(maxGen uint64) VectorChunkBatch[int64]

BeginInt64ChunkBatch opens a batch-scoped view over the int64 chunk table, matching GetVectorsInt64ChunkWithGen / GetVectorsInt64ChunkFast.

func (*GraphData) BeginTQChunkBatch

func (g *GraphData) BeginTQChunkBatch(maxGen uint64) VectorChunkBatch[byte]

BeginTQChunkBatch opens a batch-scoped view over the TurboQuant chunk table, matching GetVectorsTQChunkWithGen / GetVectorsTQChunkFast.

TurboQuant rows have a fixed packed stride rather than padded dimensions, so the stride is passed as the batch's element width: Vector(chunkID, index, stride) returns exactly the bytes GetVectorsTQChunkWithGen would have sliced for that id, with the same nil results for a non-resident chunk, a zero offset and a generation-hidden slab.

func (*GraphData) BeginUint16ChunkBatch

func (g *GraphData) BeginUint16ChunkBatch(maxGen uint64) VectorChunkBatch[uint16]

BeginUint16ChunkBatch opens a batch-scoped view over the uint16 chunk table, matching GetVectorsUint16ChunkWithGen / GetVectorsUint16ChunkFast.

func (*GraphData) BeginUint32ChunkBatch

func (g *GraphData) BeginUint32ChunkBatch(maxGen uint64) VectorChunkBatch[uint32]

BeginUint32ChunkBatch opens a batch-scoped view over the uint32 chunk table, matching GetVectorsUint32ChunkWithGen / GetVectorsUint32ChunkFast.

func (*GraphData) BeginUint64ChunkBatch

func (g *GraphData) BeginUint64ChunkBatch(maxGen uint64) VectorChunkBatch[uint64]

BeginUint64ChunkBatch opens a batch-scoped view over the uint64 chunk table, matching GetVectorsUint64ChunkWithGen / GetVectorsUint64ChunkFast.

func (*GraphData) BumpGeneration

func (g *GraphData) BumpGeneration() uint64

BumpGeneration increments the generation for all arenas in the graph.

func (*GraphData) Clone

func (g *GraphData) Clone() *GraphData

func (*GraphData) CloneForSnapshot

func (g *GraphData) CloneForSnapshot() *GraphData

CloneForSnapshot creates a deep copy of the graph topology (Neighbors, Counts, Levels) and a shallow copy of vectors (assuming append-only). This allows serialization to proceed concurrently with modifications.

func (*GraphData) CopyArenaReferences

func (g *GraphData) CopyArenaReferences(clone *GraphData)

CopyArenaReferences copies arena pointers to the clone.

func (*GraphData) DiskStore

func (g *GraphData) DiskStore() any

func (*GraphData) EnsureChunk

func (g *GraphData) EnsureChunk(cID, cOff, dims int) error

func (*GraphData) EnsureChunks

func (g *GraphData) EnsureChunks(newCap, dims int) error

EnsureChunks ensures that all chunks up to newCap are allocated.

func (*GraphData) EstimateMemory

func (g *GraphData) EstimateMemory() int64

func (*GraphData) GetComplex128Magnitude

func (g *GraphData) GetComplex128Magnitude(id uint32) float64

func (*GraphData) GetCountsChunk

func (g *GraphData) GetCountsChunk(layer, chunkID int) []int32

func (*GraphData) GetCountsChunkFast

func (g *GraphData) GetCountsChunkFast(layer, chunkID int) []int32

GetCountsChunkFast returns a counts chunk using a non-atomic offset read.

func (*GraphData) GetCountsChunkWithGen

func (g *GraphData) GetCountsChunkWithGen(layer, chunkID int, maxGen uint64) []int32

func (*GraphData) GetLevelsChunk

func (g *GraphData) GetLevelsChunk(chunkID int) []uint32

func (*GraphData) GetNeighbors

func (g *GraphData) GetNeighbors(layer int, id uint32, buf []uint32) []uint32

func (*GraphData) GetNeighborsChunk

func (g *GraphData) GetNeighborsChunk(layer, chunkID int) []uint32

func (*GraphData) GetNeighborsChunkFast

func (g *GraphData) GetNeighborsChunkFast(layer, chunkID int) []uint32

GetNeighborsChunkFast returns a neighbors chunk using a non-atomic offset read.

func (*GraphData) GetNeighborsChunkWithGen

func (g *GraphData) GetNeighborsChunkWithGen(layer, chunkID int, maxGen uint64) []uint32

func (*GraphData) GetNeighborsLockFree

func (g *GraphData) GetNeighborsLockFree(layer int, id uint32) []uint32

GetNeighborsLockFree returns neighbors without seqlock checks. Should only be used when the node lock is already held.

func (*GraphData) GetNeighborsWithGen

func (g *GraphData) GetNeighborsWithGen(layer int, id uint32, buf []uint32, maxGen uint64) []uint32

GetNeighborsWithGen returns the neighbor list for a node with generation isolation.

func (*GraphData) GetNodeCount

func (g *GraphData) GetNodeCount() int

GetNodeCount returns the current capacity of the graph (number of addressable nodes).

func (*GraphData) GetPaddedDims

func (g *GraphData) GetPaddedDims() int

func (*GraphData) GetPaddedDimsForType

func (g *GraphData) GetPaddedDimsForType(dt VectorDataType) int

GetPaddedDimsForType returns the padded dimension for a specific vector type to ensure SIMD alignment.

func (*GraphData) GetVector

func (g *GraphData) GetVector(id uint32) (any, error)

func (*GraphData) GetVectorBQ

func (g *GraphData) GetVectorBQ(id uint32) ([]uint64, error)

func (*GraphData) GetVectorPQ

func (g *GraphData) GetVectorPQ(id uint32) []byte

func (*GraphData) GetVectorPQWithGen

func (g *GraphData) GetVectorPQWithGen(id uint32, maxGen uint64) []byte

func (*GraphData) GetVectorSQ8

func (g *GraphData) GetVectorSQ8(id uint32) []byte

func (*GraphData) GetVectorWithGen

func (g *GraphData) GetVectorWithGen(id uint32, maxGen uint64) (any, error)

func (*GraphData) GetVectorsBQChunk

func (g *GraphData) GetVectorsBQChunk(chunkID int) []uint64

func (*GraphData) GetVectorsBQChunkFast

func (g *GraphData) GetVectorsBQChunkFast(chunkID int) []uint64

GetVectorsBQChunkFast returns a BQ chunk using a non-atomic offset read.

func (*GraphData) GetVectorsBQChunkWithGen

func (g *GraphData) GetVectorsBQChunkWithGen(chunkID int, maxGen uint64) []uint64

func (*GraphData) GetVectorsChunk

func (g *GraphData) GetVectorsChunk(chunkID int) []float32

func (*GraphData) GetVectorsChunkBasePtrWithGen

func (g *GraphData) GetVectorsChunkBasePtrWithGen(chunkID int, maxGen uint64) (unsafe.Pointer, int)

GetVectorsChunkBasePtrWithGen returns the base pointer to the float32 chunk memory and element capacity.

func (*GraphData) GetVectorsChunkFast

func (g *GraphData) GetVectorsChunkFast(chunkID int) []float32

GetVectorsChunkFast returns the vector chunk using a non-atomic offset read. Safe because chunk offset arrays are written once by EnsureChunk and are GetVectorsChunkFast returns the vector chunk using a non-atomic offset read. This is an optimization for search threads. For committed data (no generation isolation).

func (*GraphData) GetVectorsChunkFastWithGen

func (g *GraphData) GetVectorsChunkFastWithGen(chunkID int, maxGen uint64) []float32

GetVectorsChunkFastWithGen returns the vector chunk using an atomic offset read with generation isolation.

func (*GraphData) GetVectorsChunkWithGen

func (g *GraphData) GetVectorsChunkWithGen(chunkID int, maxGen uint64) []float32

GetVectorsChunkWithGen returns the vector chunk for the given ID with generation isolation. Uses non-atomic offset read for performance. Chunk offset arrays are written once by EnsureChunk and stable during search; the arena handles concurrent safety internally.

func (*GraphData) GetVectorsComplex64Chunk

func (g *GraphData) GetVectorsComplex64Chunk(chunkID int) []complex64

GetVectorsComplex64Chunk returns a chunk of complex64 vectors.

func (*GraphData) GetVectorsComplex64ChunkFast

func (g *GraphData) GetVectorsComplex64ChunkFast(chunkID int) []complex64

GetVectorsComplex64ChunkFast returns a complex64 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsComplex64ChunkWithGen

func (g *GraphData) GetVectorsComplex64ChunkWithGen(chunkID int, maxGen uint64) []complex64

func (*GraphData) GetVectorsComplex128Chunk

func (g *GraphData) GetVectorsComplex128Chunk(chunkID int) []complex128

GetVectorsComplex128Chunk returns a chunk of complex128 vectors.

func (*GraphData) GetVectorsComplex128ChunkFast

func (g *GraphData) GetVectorsComplex128ChunkFast(chunkID int) []complex128

GetVectorsComplex128ChunkFast returns a complex128 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsComplex128ChunkWithGen

func (g *GraphData) GetVectorsComplex128ChunkWithGen(chunkID int, maxGen uint64) []complex128

func (*GraphData) GetVectorsF16Chunk

func (g *GraphData) GetVectorsF16Chunk(chunkID int) []float16.Num

func (*GraphData) GetVectorsF16ChunkFast

func (g *GraphData) GetVectorsF16ChunkFast(chunkID int) []float16.Num

GetVectorsF16ChunkFast returns a float16 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsF16ChunkWithGen

func (g *GraphData) GetVectorsF16ChunkWithGen(chunkID int, maxGen uint64) []float16.Num

func (*GraphData) GetVectorsFloat64Chunk

func (g *GraphData) GetVectorsFloat64Chunk(chunkID int) []float64

GetVectorsFloat64Chunk returns a chunk of float64 vectors.

func (*GraphData) GetVectorsFloat64ChunkFast

func (g *GraphData) GetVectorsFloat64ChunkFast(chunkID int) []float64

GetVectorsFloat64ChunkFast returns a float64 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsFloat64ChunkWithGen

func (g *GraphData) GetVectorsFloat64ChunkWithGen(chunkID int, maxGen uint64) []float64

func (*GraphData) GetVectorsInt8Chunk

func (g *GraphData) GetVectorsInt8Chunk(chunkID int) []int8

func (*GraphData) GetVectorsInt8ChunkFast

func (g *GraphData) GetVectorsInt8ChunkFast(chunkID int) []int8

GetVectorsInt8ChunkFast returns an int8 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsInt8ChunkWithGen

func (g *GraphData) GetVectorsInt8ChunkWithGen(chunkID int, maxGen uint64) []int8

func (*GraphData) GetVectorsInt16Chunk

func (g *GraphData) GetVectorsInt16Chunk(chunkID int) []int16

func (*GraphData) GetVectorsInt16ChunkFast

func (g *GraphData) GetVectorsInt16ChunkFast(chunkID int) []int16

GetVectorsInt16ChunkFast returns an int16 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsInt16ChunkWithGen

func (g *GraphData) GetVectorsInt16ChunkWithGen(chunkID int, maxGen uint64) []int16

func (*GraphData) GetVectorsInt32Chunk

func (g *GraphData) GetVectorsInt32Chunk(chunkID int) []int32

GetVectorsInt32Chunk returns a chunk of int32 vectors.

func (*GraphData) GetVectorsInt32ChunkFast

func (g *GraphData) GetVectorsInt32ChunkFast(chunkID int) []int32

GetVectorsInt32ChunkFast returns an int32 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsInt32ChunkWithGen

func (g *GraphData) GetVectorsInt32ChunkWithGen(chunkID int, maxGen uint64) []int32

func (*GraphData) GetVectorsInt64Chunk

func (g *GraphData) GetVectorsInt64Chunk(chunkID int) []int64

GetVectorsInt64Chunk returns a chunk of int64 vectors.

func (*GraphData) GetVectorsInt64ChunkFast

func (g *GraphData) GetVectorsInt64ChunkFast(chunkID int) []int64

GetVectorsInt64ChunkFast returns an int64 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsInt64ChunkWithGen

func (g *GraphData) GetVectorsInt64ChunkWithGen(chunkID int, maxGen uint64) []int64

func (*GraphData) GetVectorsPQChunk

func (g *GraphData) GetVectorsPQChunk(chunkID int) []byte

GetVectorsPQChunk returns the PQ vectors chunk for the given ID.

func (*GraphData) GetVectorsPQChunkFast

func (g *GraphData) GetVectorsPQChunkFast(chunkID int) []byte

GetVectorsPQChunkFast returns a PQ chunk using a non-atomic offset read.

func (*GraphData) GetVectorsPQChunkWithGen

func (g *GraphData) GetVectorsPQChunkWithGen(chunkID int, maxGen uint64) []byte

func (*GraphData) GetVectorsSQ8Chunk

func (g *GraphData) GetVectorsSQ8Chunk(chunkID int) []byte

func (*GraphData) GetVectorsSQ8ChunkFast

func (g *GraphData) GetVectorsSQ8ChunkFast(chunkID int) []byte

GetVectorsSQ8ChunkFast returns an SQ8 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsSQ8ChunkWithGen

func (g *GraphData) GetVectorsSQ8ChunkWithGen(chunkID int, maxGen uint64) []byte

func (*GraphData) GetVectorsTQChunk

func (g *GraphData) GetVectorsTQChunk(chunkID int) []byte

func (*GraphData) GetVectorsTQChunkFast

func (g *GraphData) GetVectorsTQChunkFast(chunkID int) []byte

GetVectorsTQChunkFast returns a TurboQuant chunk using a non-atomic offset read.

func (*GraphData) GetVectorsTQChunkWithGen

func (g *GraphData) GetVectorsTQChunkWithGen(chunkID int, maxGen uint64) []byte

func (*GraphData) GetVectorsUint8Chunk

func (g *GraphData) GetVectorsUint8Chunk(chunkID int) []uint8

func (*GraphData) GetVectorsUint8ChunkFast

func (g *GraphData) GetVectorsUint8ChunkFast(chunkID int) []uint8

GetVectorsUint8ChunkFast returns a uint8 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsUint8ChunkWithGen

func (g *GraphData) GetVectorsUint8ChunkWithGen(chunkID int, maxGen uint64) []uint8

func (*GraphData) GetVectorsUint16Chunk

func (g *GraphData) GetVectorsUint16Chunk(chunkID int) []uint16

func (*GraphData) GetVectorsUint16ChunkFast

func (g *GraphData) GetVectorsUint16ChunkFast(chunkID int) []uint16

GetVectorsUint16ChunkFast returns a uint16 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsUint16ChunkWithGen

func (g *GraphData) GetVectorsUint16ChunkWithGen(chunkID int, maxGen uint64) []uint16

func (*GraphData) GetVectorsUint32Chunk

func (g *GraphData) GetVectorsUint32Chunk(chunkID int) []uint32

GetVectorsUint32Chunk returns a chunk of uint32 vectors.

func (*GraphData) GetVectorsUint32ChunkFast

func (g *GraphData) GetVectorsUint32ChunkFast(chunkID int) []uint32

GetVectorsUint32ChunkFast returns a uint32 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsUint32ChunkWithGen

func (g *GraphData) GetVectorsUint32ChunkWithGen(chunkID int, maxGen uint64) []uint32

func (*GraphData) GetVectorsUint64Chunk

func (g *GraphData) GetVectorsUint64Chunk(chunkID int) []uint64

GetVectorsUint64Chunk returns a chunk of uint64 vectors.

func (*GraphData) GetVectorsUint64ChunkFast

func (g *GraphData) GetVectorsUint64ChunkFast(chunkID int) []uint64

GetVectorsUint64ChunkFast returns a uint64 chunk using a non-atomic offset read.

func (*GraphData) GetVectorsUint64ChunkWithGen

func (g *GraphData) GetVectorsUint64ChunkWithGen(chunkID int, maxGen uint64) []uint64

func (*GraphData) GetVersion

func (g *GraphData) GetVersion(layer int, id uint32) uint32

GetVersion returns the current version/lock state of a node at a given layer.

func (*GraphData) GetVersionsChunk

func (g *GraphData) GetVersionsChunk(layer, chunkID int) []uint32

func (*GraphData) GetVersionsChunkFast

func (g *GraphData) GetVersionsChunkFast(layer, chunkID int) []uint32

GetVersionsChunkFast returns a versions chunk using a non-atomic offset read.

func (*GraphData) GetVersionsChunkWithGen

func (g *GraphData) GetVersionsChunkWithGen(layer, chunkID int, maxGen uint64) []uint32

func (*GraphData) GrowMetadataSlices

func (g *GraphData) GrowMetadataSlices(numChunks int)

func (*GraphData) LockNode

func (g *GraphData) LockNode(layer int, id uint32) uint32

LockNode acquires a per-node spinlock.

func (*GraphData) MergeFrom

func (g *GraphData) MergeFrom(other *GraphData)

MergeFrom merges non-zero chunk offsets, arenas, and node levels from other into g so that publishing g via compareAndSwapData never clobbers chunks or levels allocated by a concurrent AddBatch on other.

func (*GraphData) NeedsChunk

func (g *GraphData) NeedsChunk(cID int) bool

func (*GraphData) PQDims

func (g *GraphData) PQDims() int

func (*GraphData) PackedSize

func (g *GraphData) PackedSize() int

func (*GraphData) PreAllocate

func (g *GraphData) PreAllocate(capacity int) error

func (*GraphData) Release

func (g *GraphData) Release()

func (*GraphData) ReleaseChunk

func (g *GraphData) ReleaseChunk(cID int)

ReleaseChunk releases the memory for a vector chunk back to the OS using MADV_DONTNEED. This is used for incremental handover during index migration.

func (*GraphData) ReleaseFloat32Chunk

func (g *GraphData) ReleaseFloat32Chunk(cID int)

ReleaseFloat32Chunk releases monolithic Float32Arena vector storage for a specific chunk.

func (*GraphData) ReleaseNeighborsChunk

func (g *GraphData) ReleaseNeighborsChunk(layer, cID int)

ReleaseNeighborsChunk releases neighbor storage for a specific layer and chunk.

func (*GraphData) ReleaseReader

func (g *GraphData) ReleaseReader()

ReleaseReader decrements the reader count acquired by AcquireReader. Pairs 1:1 with AcquireReader. Use defer to be panic-safe.

func (*GraphData) RelocateToOffHeap

func (g *GraphData) RelocateToOffHeap() error

func (*GraphData) RestoreArena

func (g *GraphData) RestoreArena(source *GraphData)

RestoreArena restores arena references if lost (helper)

func (*GraphData) Serialize

func (g *GraphData) Serialize(w io.Writer) error

Serialize writes the GraphData to the writer in a portable binary format.

func (*GraphData) SetComplex128Magnitude

func (g *GraphData) SetComplex128Magnitude(id uint32, mag float64)

SetComplex128Magnitude stores the L2 magnitude for a complex128 vector.

func (*GraphData) SetExternalVectorsChunk

func (g *GraphData) SetExternalVectorsChunk(chunkID int, data []float32, ref arrow.Array) error

SetExternalVectorsChunk maps a chunk of the graph directly to an external slice. This is used for zero-copy ingestion from Arrow buffers.

func (*GraphData) SetGeneration

func (g *GraphData) SetGeneration(gen uint64)

SetGeneration sets the generation for all arenas in the graph.

func (*GraphData) SetNeighbors

func (g *GraphData) SetNeighbors(id uint32, neighbors []uint32) error

func (*GraphData) SetNeighborsAtLayer

func (g *GraphData) SetNeighborsAtLayer(layer int, id uint32, neighbors []uint32) error

func (*GraphData) SetVector

func (g *GraphData) SetVector(id uint32, vec any) error

func (*GraphData) SetVectorBQ

func (g *GraphData) SetVectorBQ(id uint32, vec []uint64) error

func (*GraphData) SetVectorPQ

func (g *GraphData) SetVectorPQ(id uint32, code []byte) error

func (*GraphData) SetVectorsBatch

func (g *GraphData) SetVectorsBatch(startID uint32, vecs [][]float32) error

SetVectorsBatch sets multiple vectors in the same chunk efficiently. This is optimized for bulk insertion where vectors belong to the same chunk.

func (*GraphData) SetZeroCopyMapping

func (g *GraphData) SetZeroCopyMapping(chunkID int, data []float32, ref arrow.Array) error

SetZeroCopyMapping maps a chunk of the graph directly to an external slice of memory. This is used for Zero-Copy Arrow ingestion. It ensures that GetVectorsChunk will return this external slice by bypassing the arena-based storage for this specific chunk.

func (*GraphData) ShallowStructuralClone

func (g *GraphData) ShallowStructuralClone() *GraphData

ShallowStructuralClone creates a new GraphData that shares the per-chunk vector slice headers (Vectors, VectorsFloat64, VectorsComplex64, VectorsComplex128) with the original, but still deep-copies the structural slices (Levels, Neighbors, Counts, Versions, offset slices) and retains the typed-arena Slabs.

Why this is safe:

  1. The per-chunk vector data lives in the shared typed-arena Slab, and the Slab is ref-counted. The new GraphData's typed-arena retains the Slab (same as Clone), so the data is alive as long as the new GraphData is alive.

  2. The per-chunk slice headers (Vectors[i], etc.) are read-only after publication. They are set once by SetExternalVectorsChunk or SetZeroCopyMapping during initial setup, and the modern write path uses VectorsF32[cID] (offset) + Float32Arena.Get(...) to write to NEW chunks; it does NOT write to Vectors[i] directly. Sharing the slice header between old and new is therefore safe — both readers see the same read-only data.

  3. The structural slices (Levels, Neighbors, Counts, Versions) and the offset slices (VectorsF32, VectorsInt8, etc.) are deep-copied because their elements are mutated via atomic CAS operations or atomic StoreUint64 by EnsureChunk. Sharing them would corrupt the old GraphData.

  4. The PackedNeighbors and ArrowRefs fields are retained (same as Clone) because they are reference-counted by external code.

Memory savings at int8 50k dim=384: ~19 MB per Clone (50 chunks × 1000 vectors × 384 bytes). Reduces Clone's heap pressure from ~26.5 MB to ~7 MB per Clone call. At 50k inserts with 5 concurrent batches, this is a ~95 MB reduction in transient heap allocations.

Intended use: the per-batch private-clone path in ArrowHNSW.insertInternal, where the writer needs a private copy of the published GraphData but will only write to NEW chunks (or freshly-allocated structural elements). NOT a general-purpose replacement for Clone — the persistence path and any code that mutates Vectors[i] directly should still use Clone. Callers MUST verify that the writer does not write to a chunk via the shared Vectors[i] path (i.e., the writer must go through the Vectors<Type>Offset → typed-arena.Get path).

func (*GraphData) SnapshotSafe

func (g *GraphData) SnapshotSafe() bool

SnapshotSafe checks if the graph is in a state safe for snapshotting (e.g. no resizing).

func (*GraphData) StoreCountsChunk

func (gd *GraphData) StoreCountsChunk(layer int, chunkID uint32, chunk []int32)

StoreCountsChunk stores a chunk of counts for testing.

func (*GraphData) StoreNeighborsChunk

func (gd *GraphData) StoreNeighborsChunk(layer int, chunkID uint32, chunk []uint32)

StoreNeighborsChunk stores a chunk of neighbors for testing. It allocates space in the Arena and copies the data.

func (*GraphData) StorePQChunk

func (gd *GraphData) StorePQChunk(chunkID uint32, chunk []byte)

StorePQChunk stores a chunk of PQ vectors for testing.

func (*GraphData) StoreSQ8Chunk

func (gd *GraphData) StoreSQ8Chunk(chunkID uint32, chunk []byte)

StoreSQ8Chunk stores a chunk of SQ8 vectors for testing.

func (*GraphData) StoreVectorsChunk

func (gd *GraphData) StoreVectorsChunk(chunkID uint32, chunk []float32)

StoreVectorsChunk stores a chunk of vectors for testing. It assumes dims matches context, though here we just copy bytes/floats. Actually, vectors are float32.

func (*GraphData) StoreVersionsChunk

func (gd *GraphData) StoreVersionsChunk(layer int, chunkID uint32, chunk []uint32)

StoreVersionsChunk stores a chunk of versions for testing.

func (*GraphData) TryLockNode

func (g *GraphData) TryLockNode(layer int, id uint32) (uint32, bool)

TryLockNode attempts to acquire the lock once.

func (*GraphData) UnlockNode

func (g *GraphData) UnlockNode(layer int, id, oldVersion uint32)

UnlockNode releases the per-node spinlock and increments the version.

func (*GraphData) Unregister

func (g *GraphData) Unregister()

type GraphDataInterface

type GraphDataInterface interface {
	// Data access operations
	GetVector(id uint32) (any, error)
	SetVector(id uint32, vec any) error
	GetNeighbors(layer int, id uint32, buffer []uint32) []uint32

	// Metadata operations
	Capacity() int
	Dims() int
	Type() VectorDataType

	// Lifecycle operations
	Close() error
}

GraphDataInterface defines the interface for accessing underlying graph storage.

type GtExpr

type GtExpr struct {
	Field string
	Value interface{}
}

func (*GtExpr) Evaluate

func (e *GtExpr) Evaluate(metadata *LazyMetadata) bool

type HNSWGraphInterface

type HNSWGraphInterface interface {
	// Graph construction
	Insert(id uint32, vec any, level int) error
	Delete(id uint32) error

	// Search operations
	SearchLayer(ctx context.Context, entryPoint uint32, ef, layer int, results []Candidate) ([]Candidate, error)
	SelectNeighbors(candidates []Candidate, m int) []Candidate

	// Graph maintenance
	NeedsCompaction() bool
	Compact() error

	// Metadata
	NodeCount() int
	MaxLevel() int
}

HNSWGraphInterface defines the specific operations required for HNSW-style graphs.

type HNSWPredicate

type HNSWPredicate interface {
	// IsMatch returns true if the vector ID matches the predicate's metadata criteria.
	IsMatch(id uint32) bool

	// MatchBatch evaluates a batch of vector IDs and writes the results (0 or 1) to dst.
	// dst must have the same length as ids.
	MatchBatch(ids []uint32, dst []byte)
}

HNSWPredicate defines an interface for metadata filtering during HNSW traversal. It allows for early-exit and skipping nodes that don't match criteria.

type IndexDataProvider

type IndexDataProvider interface {
	GetName() string
	GetRecords() []arrow.RecordBatch
	GetSchema() *arrow.Schema
	TurboQuantBits() int
	GetTombstones() map[int]*Bitset
	GetPQEncoder() *pq.PQEncoder
	RLockData()
	RUnlockData()
	GenerateFilterBitset(filters []core.Filter, expr FilterExpr) (*Bitset, error)
	ResetTombstones()
	GetIndex() any
	GetMetric() core.DistanceMetric
	GetLogger() zerolog.Logger
	GetTopo() *memory.NUMATopology
	GetEvictionManager() any
	GetDiskStore() any
}

IndexDataProvider provides the necessary data and synchronization for index building and search.

type IndexJob

type IndexJob struct {
	DatasetName  string
	Record       arrow.RecordBatch
	BatchIdx     int
	CreatedAt    time.Time
	HighPriority bool // If true, job should be prioritized by workers
	NodeID       int  // Preferred NUMA node ID (-1 for any/global)
}

IndexJob represents a background task to index an Arrow RecordBatch.

type IndexJobQueueConfig

type IndexJobQueueConfig struct {
	MainChannelSize    int           // Primary channel buffer size
	OverflowBufferSize int           // Secondary overflow buffer size
	DropOnOverflow     bool          // If true, drop jobs when both buffers full
	DrainInterval      time.Duration // How often to drain overflow to main channel
}

IndexJobQueueConfig defines the behavior of the producer-consumer indexing queue.

func DefaultIndexJobQueueConfig

func DefaultIndexJobQueueConfig() IndexJobQueueConfig

DefaultIndexJobQueueConfig returns sensible defaults for production.

type IndexJobQueueStats

type IndexJobQueueStats struct {
	TotalSent     uint64 // Total jobs sent
	DirectSent    uint64 // Jobs sent directly to main channel
	OverflowCount uint64 // Jobs sent to overflow buffer
	DrainedCount  uint64 // Jobs drained from overflow to main
	DroppedCount  uint64 // Jobs dropped when both buffers full
}

IndexJobQueueStats provides visibility into the state of the indexing queue.

type LazyMetadata

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

LazyMetadata decodes binary metadata on first access and caches the result. This prevents multiple decodings during complex filter evaluation.

func NewLazyMetadata

func NewLazyMetadata(data []byte) *LazyMetadata

func (*LazyMetadata) Get

func (l *LazyMetadata) Get() (map[string]interface{}, error)

func (*LazyMetadata) GetField

func (l *LazyMetadata) GetField(field string) (interface{}, bool)

type LeExpr

type LeExpr struct {
	Field string
	Value interface{}
}

func (*LeExpr) Evaluate

func (e *LeExpr) Evaluate(metadata *LazyMetadata) bool

type Location

type Location = basecore.Location

Location represents the physical batch and row coordinates of a record.

func UnpackLocation

func UnpackLocation(val uint64) Location

UnpackLocation unpacks a uint64 into a Location.

type LockFreeMap

type LockFreeMap[K comparable, T any] struct {
	// contains filtered or unexported fields
}

LockFreeMap is a thread-safe map of lock-free slices.

func NewLockFreeMap

func NewLockFreeMap[K comparable, T any]() *LockFreeMap[K, T]

NewLockFreeMap creates a new thread-safe map for managing multiple lock-free slices.

func (*LockFreeMap[K, T]) Get

func (l *LockFreeMap[K, T]) Get(key K) ([]T, bool)

func (*LockFreeMap[K, T]) Keys

func (l *LockFreeMap[K, T]) Keys() []K

func (*LockFreeMap[K, T]) Len

func (l *LockFreeMap[K, T]) Len() int

func (*LockFreeMap[K, T]) Set

func (l *LockFreeMap[K, T]) Set(key K, data []T)

type LockFreeSlice

type LockFreeSlice[T any] struct {
	// contains filtered or unexported fields
}

LockFreeSlice provides lock-free reads with copy-on-write updates for any slice type. This is an evolution of the LockFreeNeighborList designed for general use.

func NewLockFreeSlice

func NewLockFreeSlice[T any]() *LockFreeSlice[T]

NewLockFreeSlice creates a new lock-free slice.

func NewLockFreeSliceFrom

func NewLockFreeSliceFrom[T any](data []T) *LockFreeSlice[T]

NewLockFreeSliceFrom creates a new lock-free slice initialized with data.

func (*LockFreeSlice[T]) Append

func (l *LockFreeSlice[T]) Append(item T) int

Append adds an element to the end of the slice and returns the new length.

Growth is geometric, so appending N elements costs O(N) in total instead of the O(N^2) an external `make`/`copy` on every append costs. When the backing array already has spare capacity the element is written past the *published* length: a reader that already loaded the old slice header can only observe [0:len], so an in-flight append is invisible to it and the array needs no copy at all.

func (*LockFreeSlice[T]) Len

func (l *LockFreeSlice[T]) Len() int

Len returns the current number of elements. It is a single atomic load, so unlike summing a caller-maintained counter it cannot drift.

func (*LockFreeSlice[T]) Read

func (l *LockFreeSlice[T]) Read() []T

Read returns the current slice without acquiring any locks.

func (*LockFreeSlice[T]) Update

func (l *LockFreeSlice[T]) Update(newSlice []T)

Update performs a copy-on-write update.

func (*LockFreeSlice[T]) UpdateInPlace

func (l *LockFreeSlice[T]) UpdateInPlace(newSlice []T)

UpdateInPlace updates the slice without copying.

type LtExpr

type LtExpr struct {
	Field string
	Value interface{}
}

func (*LtExpr) Evaluate

func (e *LtExpr) Evaluate(metadata *LazyMetadata) bool

type MapRCU

type MapRCU[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapRCU provides a high-performance concurrent sharded map with RCU-like semantics. Instead of cloning the entire map on every mutation (which previously generated >1.2GB of heap allocations during batch ingestion), updates are partitioned across 64 independent shards, mutating only the target shard's hash table in place.

func NewMapRCU

func NewMapRCU[K comparable, V any]() *MapRCU[K, V]

NewMapRCU creates a new sharded concurrent map.

func (*MapRCU[K, V]) BulkDelete

func (m *MapRCU[K, V]) BulkDelete(keys []K)

BulkDelete removes multiple keys across shards.

func (*MapRCU[K, V]) BulkStore

func (m *MapRCU[K, V]) BulkStore(updates map[K]V)

BulkStore updates multiple keys across shards without copying the entire map.

func (*MapRCU[K, V]) Delete

func (m *MapRCU[K, V]) Delete(key K)

Delete removes a key from the map.

func (*MapRCU[K, V]) Get

func (m *MapRCU[K, V]) Get(key K) (V, bool)

Get retrieves a value from the map.

func (*MapRCU[K, V]) Len

func (m *MapRCU[K, V]) Len() int

Len returns the total number of elements across all shards.

func (*MapRCU[K, V]) Load

func (m *MapRCU[K, V]) Load() map[K]V

Load returns a snapshot of the current map for backward compatibility.

func (*MapRCU[K, V]) Range

func (m *MapRCU[K, V]) Range(f func(key K, val V) bool)

Range iterates over all entries across all shards.

func (*MapRCU[K, V]) Store

func (m *MapRCU[K, V]) Store(key K, val V)

Store updates the map for a given key.

type NeighborApplier

type NeighborApplier interface {
	ApplyNeighbors(old []uint32) []uint32
}

PackedNeighbors interface for graph adjacency management with atomic support. NeighborApplier computes a node's next neighbour list from its current one.

It is an interface rather than a func because of who calls it: bulk linkage runs UpdateNeighbors once per node plus once per reverse link, and a closure capturing the target, the sources, the limits and the pooled context is heap-allocated on every one of those calls. An applier can live on the caller's pooled search context instead, where it is reused (roadmap Item 33).

Apply may be called more than once for one update - the packed path retries on a lost CAS - so an implementation must derive its result from old and its own inputs alone.

type NotExpr

type NotExpr struct {
	Condition FilterExpr
}

func (*NotExpr) Evaluate

func (n *NotExpr) Evaluate(metadata *LazyMetadata) bool

type OrExpr

type OrExpr struct {
	Conditions []FilterExpr
}

func (*OrExpr) Evaluate

func (o *OrExpr) Evaluate(metadata *LazyMetadata) bool

type PackedNeighbors

type PackedNeighbors interface {
	// GetNeighbors returns the list of neighbor IDs for a given node.
	GetNeighbors(id uint32) ([]uint32, bool)
	// GetPackedNeighbors returns a packed representation of neighbors for atomic operations.
	GetPackedNeighbors(id uint32) (uint64, bool)
	// GetNeighborsFromPacked extracts a list of neighbor IDs from a packed uint64.
	GetNeighborsFromPacked(packed uint64) []uint32
	// SetNeighbors updates the neighbor list for a node.
	SetNeighbors(id uint32, neighbors []uint32) error
	// CASNeighbors performs an atomic compare-and-swap on the neighbor list.
	CASNeighbors(id uint32, oldPacked uint64, new []uint32) bool
	// GetNeighborsF16 returns neighbors and their distances in float16 precision.
	GetNeighborsF16(id uint32) ([]uint32, []float16.Num, bool)
	// Release frees the underlying memory resources.
	Release()
	// Retain increments the reference count of the structure.
	Retain()
	// SetNeighborsF16 updates neighbors and their distances in float16 precision.
	SetNeighborsF16(id uint32, neighbors []uint32, dists []float16.Num) error
	// EnsureCapacity ensures the underlying storage can accommodate the given node ID.
	EnsureCapacity(id uint32)
	// Lock acquires a node-specific lock (usually a shard lock).
	Lock(id uint32)
	// Unlock releases a node-specific lock.
	Unlock(id uint32)
	// UpdateNeighbors performs an atomic read-modify-write update using an applier.
	UpdateNeighbors(id uint32, applier NeighborApplier) error
	// GetNeighborsWithGen returns the neighbor list for a node with generation isolation.
	GetNeighborsWithGen(id uint32, maxGen uint64) ([]uint32, bool)
	// GetNeighborsF16WithGen returns neighbors and their distances with generation isolation.
	GetNeighborsF16WithGen(id uint32, maxGen uint64) ([]uint32, []float16.Num, bool)
	// GetNeighborsFromPackedWithGen extracts neighbors from a packed uint64 with generation isolation.
	GetNeighborsFromPackedWithGen(packed uint64, maxGen uint64) []uint32
	// IsOffHeap returns true if the backing storage is off-heap.
	IsOffHeap() bool
	// EvictToDisk writes all neighbor chunks for the given layer to w
	// and clears in-memory storage. Returns (numChunks, chunkSizes, bytesWritten, error).
	// chunkSizes is pre-allocated; the implementation writes into it and may grow
	// it as needed. The caller uses the returned slice.
	EvictToDisk(gd *GraphData, layer int, chunkSizes []int, w interface{ Write([]byte) (int, error) }) (nChunks int, outChunkSizes []int, bytesWritten int64, err error)
	// RestoreFromDisk reads neighbor chunks back from r, repopulating storage.
	RestoreFromDisk(gd *GraphData, layer int, chunkSizes []int, r interface{ Read([]byte) (int, error) }) error
	// GetNeighborsWithGenFast is like GetNeighborsWithGen but skips ref-counting.
	// Caller must guarantee the PackedNeighbors remains alive during the call.
	GetNeighborsWithGenFast(id uint32, maxGen uint64) ([]uint32, bool)
}

type PaddedMutex

type PaddedMutex struct {
	sync.Mutex
	// contains filtered or unexported fields
}

PaddedMutex is a sync.Mutex padded to a full 64-byte cache line to prevent false sharing.

type ParallelSearchConfig

type ParallelSearchConfig struct {
	Enabled      bool
	Workers      int
	Threshold    int
	MinChunkSize int
	MaxChunkSize int
}

ParallelSearchConfig controls the degree of parallelism for vector similarity search.

func DefaultParallelSearchConfig

func DefaultParallelSearchConfig() ParallelSearchConfig

DefaultParallelSearchConfig returns sensible defaults for parallel search

type RangeSearchRequest

type RangeSearchRequest = basecore.RangeSearchRequest

RangeSearchRequest alias for basecore.RangeSearchRequest.

type RowLocation

type RowLocation struct {
	BatchIdx int
	RowIdx   int
}

RowLocation represents the physical address of a row (Batch + Row offset).

type SearchContext

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

SearchContext holds pre-allocated buffers for HNSW search operations to reduce allocation churn during high-frequency searches

type SearchOptions

type SearchOptions struct {
	IncludeVectors bool
	VectorFormat   VectorDataType
	Filter         any        // Legacy filter mechanism
	FilterExpr     FilterExpr // Rich AST JSON Filter
	ExactK         bool
	Ef             int            // Entry factor for HNSW search (controls search breadth)
	Consistency    string         // "eventual" | "strong" | "" (default = eventual)
	VectorType     VectorDataType // Explicit index type selection for search (float32, turboquant)
	TurboQuantBits int            // Bit depth for TurboQuant search (2, 4, 8)
	Predicate      HNSWPredicate  // Predicate for early-exit filtering
	ForceQuantized bool           // Internal flag to force quantized navigation on upper HNSW layers
	MaxResults     int            // Optional result cap for bounded range queries
}

SearchOptions defines the options for search operations

func DefaultSearchOptions

func DefaultSearchOptions() SearchOptions

DefaultSearchOptions returns SearchOptions with production defaults.

type SearchPool

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

SearchPool manages reusable SearchContext objects

func NewSearchPool

func NewSearchPool() *SearchPool

NewSearchPool creates a new search context pool

func (*SearchPool) Get

func (sp *SearchPool) Get() *SearchContext

Get retrieves a SearchContext from the pool and resets its results.

func (*SearchPool) Put

func (sp *SearchPool) Put(ctx *SearchContext)

Put returns a SearchContext to the pool after clearing its contents.

func (*SearchPool) Stats

func (sp *SearchPool) Stats() (gets, puts int64)

Stats returns current search pool hit/miss statistics.

type SearchResult

type SearchResult = basecore.SearchResult

SearchResult represents a final search result with ID, distance, and metadata.

type SearchResultBucket

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

SearchResultBucket represents a pool of result slices with a specific capacity

type SearchResultPool

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

SearchResultPool manages reusable SearchResult slices organized by capacity buckets

func NewSearchResultPool

func NewSearchResultPool() *SearchResultPool

NewSearchResultPool creates a new result pool with common capacity buckets

func (*SearchResultPool) Get

func (sp *SearchResultPool) Get(capacity int) []SearchResult

Get retrieves a SearchResult slice from the appropriate capacity bucket.

func (*SearchResultPool) Put

func (sp *SearchResultPool) Put(slice []SearchResult)

Put returns a SearchResult slice to the appropriate bucket after clearing it.

func (*SearchResultPool) Stats

func (sp *SearchResultPool) Stats() map[string]map[string]int64

Stats returns statistics for all capacity buckets in the result pool.

type StorageInterface

type StorageInterface interface {
	// Persistence operations
	Save(data any) error
	Load() (any, error)
	Flush() error

	// Metadata
	Path() string
	Size() int64
}

StorageInterface defines the interface for generic persistent storage operations.

type SyncState

type SyncState struct {
	Version    uint64
	Dims       int
	EntryPoint uint32
	MaxLevel   int32
	Generation uint64
	Locations  []core.Location
	GraphData  []byte
}

SyncState represents the serializable state of a vector index.

type TemporalAggregationRequest

type TemporalAggregationRequest = basecore.TemporalAggregationRequest

TemporalAggregationRequest alias for basecore.TemporalAggregationRequest.

type TemporalSearchRequest

type TemporalSearchRequest = basecore.TemporalSearchRequest

TemporalSearchRequest alias for basecore.TemporalSearchRequest.

type VectorChunkBatch

type VectorChunkBatch[T any] struct {
	// contains filtered or unexported fields
}

func (*VectorChunkBatch[T]) Chunk

func (b *VectorChunkBatch[T]) Chunk(chunkID int) []T

Chunk returns the whole chunk, or nil when the reference chunk accessor would return nil.

func (*VectorChunkBatch[T]) Stale

func (b *VectorChunkBatch[T]) Stale() bool

Stale reports whether the arena was structurally mutated after the batch was opened. The batch re-resolves transparently, so this is only for callers that want to observe the mutation.

func (*VectorChunkBatch[T]) Vector

func (b *VectorChunkBatch[T]) Vector(chunkID, index, dims int) []T

Vector returns the dims-long vector stored at index within chunkID, or nil when the reference per-vector accessor would not have served it (chunk not resident, hidden by generation isolation, or index past the chunk).

func (*VectorChunkBatch[T]) Width

func (b *VectorChunkBatch[T]) Width() int

Width returns the per-vector element count the batch strides by: the padded dimension count for the fixed-width types, and the packed byte stride for TurboQuant. It is the length to pass as the dims argument of Vector.

type VectorDataType

type VectorDataType int

VectorDataType represents the data type of vector elements

const (
	// VectorTypeUnknown represents an uninitialized or unsupported vector type.
	VectorTypeUnknown VectorDataType = iota
	// VectorTypeFloat32 represents a 32-bit floating point vector.
	VectorTypeFloat32
	// VectorTypeInt8 represents an 8-bit integer vector.
	VectorTypeInt8
	// VectorTypeUint8 represents an 8-bit unsigned integer vector.
	VectorTypeUint8
	// VectorTypeFloat16 represents a 16-bit floating point vector.
	VectorTypeFloat16
	// VectorTypeFloat64 represents a 64-bit floating point vector.
	VectorTypeFloat64
	// VectorTypeComplex64 represents a 64-bit complex number vector.
	VectorTypeComplex64
	// VectorTypeComplex128 represents a 128-bit complex number vector.
	VectorTypeComplex128
	// VectorTypeInt16 represents a 16-bit integer vector.
	VectorTypeInt16
	// VectorTypeUint16 represents a 16-bit unsigned integer vector.
	VectorTypeUint16
	// VectorTypeInt32 represents a 32-bit integer vector.
	VectorTypeInt32
	// VectorTypeUint32 represents a 32-bit unsigned integer vector.
	VectorTypeUint32
	// VectorTypeInt64 represents a 64-bit integer vector.
	VectorTypeInt64
	// VectorTypeUint64 represents a 64-bit unsigned integer vector.
	VectorTypeUint64
	// VectorTypeBQ represents a binary quantized vector.
	VectorTypeBQ
	// VectorTypePQ represents a product quantized vector.
	VectorTypePQ
	// VectorTypeTQ represents a TurboQuant compressed vector.
	VectorTypeTQ
)

func MapStringToVectorDataType

func MapStringToVectorDataType(s string) VectorDataType

MapStringToVectorDataType maps a string representation to its VectorDataType

func (VectorDataType) ElementSize

func (vdt VectorDataType) ElementSize() int

ElementSize returns the size in bytes of one element of this data type

func (VectorDataType) String

func (vdt VectorDataType) String() string

String returns a string representation of the vector data type

type VectorID

type VectorID = basecore.VectorID

VectorID is a type alias for the unique identifier of a vector.

type VectorIndexer

type VectorIndexer interface {
	// Core indexing operations
	AddByLocation(ctx context.Context, batchIdx, rowIdx int) (uint32, error)
	AddByRecord(ctx context.Context, rec arrow.RecordBatch, rowIdx, batchIdx int) (uint32, error)
	Search(ctx context.Context, query any, k int, filter any) ([]Candidate, error)
	SearchVectors(ctx context.Context, q any, k int, filters []core.Filter, options any) ([]SearchResult, error)
	SearchVectorsWithBitmap(ctx context.Context, q any, k int, filter *roaring.Bitmap, options any) ([]SearchResult, error)

	// RangeSearch returns all vectors within a similarity threshold.
	// This is useful for clustering, duplicate detection, and radius-based queries.
	// Returns all vectors where distance <= threshold (or score >= minScore for similarity metrics).
	SearchVectorsInRange(ctx context.Context, q any, threshold float32, filters []core.Filter, options any) ([]SearchResult, error)
	IsSharded() bool
	RelocateToOffHeap() error

	// Metadata operations
	Size() int
	Len() int
	GetEntryPoint() uint32
	GetLocation(id uint32) (any, bool) // Using any to avoid cycle with store.Location? No, types can define Location alias or use any.
	GetVectorID(loc any) (uint32, bool)
	GetDimension() uint32
	SetIndexedColumns(cols []string)

	// Diagnostic/Repair
	// GetRawNeighbors returns internal neighbor IDs for diagnostics
	GetRawNeighbors(id uint32) ([]uint32, error)

	// GetNeighbors returns the k nearest neighbors for a given vector ID
	GetNeighbors(ctx context.Context, id uint32, k int) ([]SearchResult, error)
	PreWarm(targetSize int)

	// Maintenance
	Warmup() int
	EstimateMemory() int64

	// GetIndexType returns the type of the index (e.g., "hnsw", "sharded_hnsw", "brute_force", "adaptive")
	GetIndexType() string

	// PQ
	TrainPQ(vectors [][]float32) error
	GetPQEncoder() *pq.PQEncoder

	// Lifecycle operations
	Close() error

	// Batch operations
	AddBatch(ctx context.Context, recs []arrow.RecordBatch, rowIdxs, batchIdxs []int) ([]uint32, error)
	DeleteBatch(ctx context.Context, ids []uint32) error

	// Sync/Serialization operations
	ExportState() ([]byte, error)
	ImportState(data []byte) error
	ExportGraph(w io.Writer) error
	ImportGraph(r io.Reader) error
	ExportDelta(fromVersion uint64) (*DeltaSync, error)
	ApplyDelta(delta *DeltaSync) error

	// Parallel Search
	SetParallelSearchConfig(cfg ParallelSearchConfig)
	GetParallelSearchConfig() ParallelSearchConfig

	// Maintenance
	RemapLocations(ctx context.Context, mapping map[uint32]any) error

	// Migration
	ReleaseMonolithicChunk(cID int) error

	// GPU
	GetGPUIndex() any // Returns types.Index (gpu index)
}

VectorIndexer defines the core operations for vector similarity search indexes.

type VectorSearchRequest

type VectorSearchRequest = basecore.VectorSearchRequest

VectorSearchRequest alias for basecore.VectorSearchRequest.

Jump to

Keyboard shortcuts

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