memory

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: 24 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 (
	MadvRandom     = unix.MADV_RANDOM
	MadvSequential = unix.MADV_SEQUENTIAL
	MadvWillNeed   = unix.MADV_WILLNEED
	MadvDontNeed   = unix.MADV_DONTNEED
)
View Source
const (
	// DefaultArenaChunkSize is 4MB
	DefaultArenaChunkSize = 4 * 1024 * 1024
)

Variables

View Source
var ErrOutOfMemory = &SlabAllocError{msg: "segmented arena out of memory"}

ErrOutOfMemory is returned when no arena tier has capacity.

View Source
var SizeClasses = []SizeClass{
	{MinSize: 0, MaxSize: 64, SlabSize: 1 << 20, AllocName: "tiny"},
	{MinSize: 65, MaxSize: 256, SlabSize: 2 << 20, AllocName: "small"},
	{MinSize: 257, MaxSize: 1024, SlabSize: 4 << 20, AllocName: "medium"},
	{MinSize: 1025, MaxSize: 4096, SlabSize: 8 << 20, AllocName: "large"},
	{MinSize: 4097, MaxSize: 16384, SlabSize: 16 << 20, AllocName: "xlarge"},
	{MinSize: 16385, MaxSize: 65536, SlabSize: 32 << 20, AllocName: "huge"},
}

SizeClasses is the default set of size classes for memory allocation.

Functions

func AdviseHugePage

func AdviseHugePage(b []byte) error

AdviseHugePage hints the OS to use hugepages for the memory backing this slab. This can significantly reduce TLB misses during random access to large buffers.

func BeginBulkOperation

func BeginBulkOperation()

BeginBulkOperation starts a bulk memory operation, disabling GC.

func CastToSlice

func CastToSlice(ptr unsafe.Pointer, length int) []byte

CastToSlice converts a pointer and length to a byte slice without allocation.

func DebugSlabPoolsSnapshot

func DebugSlabPoolsSnapshot() string

DebugSlabPoolsSnapshot returns a multi-line string with the state of all global slab pools plus the global off-heap allocator total.

func EndBulkOperation

func EndBulkOperation()

EndBulkOperation ends a bulk memory operation, restoring GC.

func GetCurrentCPU

func GetCurrentCPU() int

GetCurrentCPU returns the current CPU number or -1 if unavailable. This is Linux-specific using getcpu syscall.

func GetGlobalOffHeapAllocated

func GetGlobalOffHeapAllocated() int64

GetGlobalOffHeapAllocated returns the total bytes currently allocated via the global off-heap allocator. This includes slabs in use by arenas, slabs sitting in the SlabPool, and any other off-heap mappings.

func GetGlobalSlabPoolUnusedMemory

func GetGlobalSlabPoolUnusedMemory() int64

GetGlobalSlabPoolUnusedMemory returns the total memory sitting idle in all global slab pools.

func GetPhysicalMemory

func GetPhysicalMemory() int64

GetPhysicalMemory returns the total available physical RAM or container memory limit in bytes. It checks in order: 1. LONGBOW_PHYSICAL_RAM environment variable (supports bytes or suffixes: KB, MB, GB, KiB, MiB, GiB). 2. Container cgroup memory limits (cgroup v2 memory.max, cgroup v1 memory.limit_in_bytes). 3. /proc/meminfo MemTotal (on Linux) or platform syscalls. 4. Default fallback (16 GB).

func GetSlab

func GetSlab(capacity int) []byte

GetSlab retrieves a slab of capacity 'cap'. If cap matches standard sizes, it returns a pooled slice. Non-standard capacities are rounded up to the next pool size for recycling. The returned slice has len=cap (fully usable buffer). NOTE: buffer content is DIRTY (not zeroed) if reused.

func IsBulkOperationActive

func IsBulkOperationActive() bool

IsBulkOperationActive returns true if a bulk operation is currently in progress.

func Madvise

func Madvise(b []byte, advice int) error

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

func MadviseHugePages

func MadviseHugePages(ptr unsafe.Pointer, size int) error

MadviseHugePages advises the kernel to use Transparent Huge Pages (THP) for the memory region. This reduces TLB misses on large multi-megabyte arenas.

func MbindMemory

func MbindMemory(ptr unsafe.Pointer, size int, nodeID int) error

MbindMemory binds the specified memory range to a NUMA node. This uses the mbind(2) system call with MPOL_BIND policy.

func Mmap

func Mmap(fd int, offset int64, length int, writable bool) ([]byte, error)

Mmap maps a file into memory.

func Munmap

func Munmap(b []byte) error

Munmap unmaps a previously mapped memory region.

func PinThreadToCore

func PinThreadToCore(coreID int) error

PinThreadToCore pins the current goroutine to a specific CPU core.

func PinToNUMANode

func PinToNUMANode(topo *NUMATopology, nodeID int) error

PinToNUMANode pins the current goroutine to CPUs on the specified NUMA node. This ensures that the goroutine runs on CPUs local to the NUMA node, reducing remote memory access latency.

func PutSlab

func PutSlab(b []byte)

PutSlab returns a slab to the pool for reuse.

func RegisterArena

func RegisterArena(s *ArenaStatsRecord)

RegisterArena adds an arena's stats record to the global registry.

func ReleaseGlobalSlabPoolsUnused

func ReleaseGlobalSlabPoolsUnused() int

ReleaseGlobalSlabPoolsUnused forces all global slab pools to release excess slabs back to the OS.

func ReleaseSlab

func ReleaseSlab(b []byte) error

ReleaseSlab hints the OS that the memory backing this slab can be reclaimed. On Linux/Darwin, this uses madvise(MADV_DONTNEED) to mark pages as reclaimable. The slice remains valid but accessing it may cause a page fault and re-zero.

func ResetPhysicalMemoryCache

func ResetPhysicalMemoryCache()

ResetPhysicalMemoryCache clears the cached physical memory value (for testing).

func TrackAllocation

func TrackAllocation(size int64)

TrackAllocation records a memory allocation in the global profiler.

func TrackFree

func TrackFree(size int64)

TrackFree records a memory free in the global profiler.

func UnregisterArena

func UnregisterArena(s *ArenaStatsRecord)

UnregisterArena removes an arena's stats record from the global registry.

Types

type AccessInfo

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

AccessInfo tracks access frequency for a single allocation.

type Analysis

type Analysis struct {
	ProfilerStats   Stats
	RuntimeStats    RuntimeStats
	HeapUtilization float64
	Pressure        Pressure
	Recommendations []string
}

Analysis contains the results of a memory usage analysis.

type Analyzer

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

Analyzer analyzes memory usage and provides recommendations.

func NewAnalyzer

func NewAnalyzer() *Analyzer

NewAnalyzer creates a new memory analyzer.

func (*Analyzer) AnalyzeUsage

func (ma *Analyzer) AnalyzeUsage() Analysis

AnalyzeUsage analyzes the current memory usage.

type ArenaAllocator

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

ArenaAllocator implements memory.Allocator using a pool of large buffers. It is designed to reduce GC pressure by reusing large chunks of memory. It is NOT thread-safe for allocation within a single Arena instance (except via the pool), but typical Arrow usage is single-threaded per record batch construction. However, to be safe and strictly compliant, we use a mutex for the current chunk.

func NewArenaAllocator

func NewArenaAllocator() *ArenaAllocator

NewArenaAllocator creates a new allocator backed by a shared pool.

func (*ArenaAllocator) Allocate

func (a *ArenaAllocator) Allocate(size int) []byte

Allocate allocates a slice of size b.

func (*ArenaAllocator) Allocated

func (a *ArenaAllocator) Allocated() int64

Allocated returns total bytes currently allocated.

func (*ArenaAllocator) AssertSize

func (a *ArenaAllocator) AssertSize(sz int) error

AssertSize is a test helper that returns an error if size mismatch occurs

func (*ArenaAllocator) Free

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

Free is a no-op for the arena, as we free everything at Release(). However, strictly compliant allocators might track bytes liberated.

func (*ArenaAllocator) Reallocate

func (a *ArenaAllocator) Reallocate(size int, b []byte) []byte

Reallocate resizes a slice.

func (*ArenaAllocator) Release

func (a *ArenaAllocator) Release()

Release returns all chunks to the pool. MUST be called when the batch/request flows are done.

type ArenaStats

type ArenaStats struct {
	TotalCapacity int64
	UsedBytes     int64
}

ArenaStats holds memory usage information about the arena.

type ArenaStatsRecord

type ArenaStatsRecord struct {
	TotalCapacity atomic.Int64
	UsedBytes     atomic.Int64
	Active        atomic.Bool
}

ArenaStatsRecord holds atomic counters for arena pressure tracking. This object is registered in the global registry to avoid leaking the arena itself.

func GetGlobalArenas

func GetGlobalArenas() []*ArenaStatsRecord

GetGlobalArenas returns a snapshot of all registered arena stats records.

type BulkOperation

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

BulkOperation tracks the state of a batch memory operation.

type ClassUsage

type ClassUsage struct {
	TotalCapacity int64
	UsedBytes     int64
	Utilization   float64
}

ClassUsage contains memory usage statistics for a specific size class.

type CompactableArena

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

CompactableArena wraps TypedArena with compaction support

func NewCompactableArena

func NewCompactableArena[T any](slabSize int) *CompactableArena[T]

NewCompactableArena creates a new compactable typed arena

func (*CompactableArena[T]) AllocSlice

func (ca *CompactableArena[T]) AllocSlice(count int) (SliceRef, error)

AllocSlice allocates a typed slice (thread-safe)

func (*CompactableArena[T]) AllocSliceDirty

func (ca *CompactableArena[T]) AllocSliceDirty(count int) (SliceRef, error)

AllocSliceDirty allocates a typed slice without zeroing (thread-safe)

func (*CompactableArena[T]) Compact

func (ca *CompactableArena[T]) Compact(liveRefs []SliceRef) ([]SliceRef, *CompactionStats, error)

Compact performs compaction with exclusive lock Returns new references in the same order as liveRefs input

func (*CompactableArena[T]) Get

func (ca *CompactableArena[T]) Get(ref SliceRef) []T

Get retrieves a typed slice (thread-safe for reads)

func (*CompactableArena[T]) TotalAllocated

func (ca *CompactableArena[T]) TotalAllocated() int64

TotalAllocated returns total bytes allocated (thread-safe)

type CompactionStats

type CompactionStats struct {
	SlabsCompacted   int     // Number of slabs that were compacted
	BytesReclaimed   int64   // Bytes of memory reclaimed
	LiveDataCopied   int64   // Bytes of live data copied
	FragmentationPct float64 // Fragmentation percentage before compaction
}

CompactionStats tracks statistics from arena compaction operations

func CompactArena

func CompactArena[T any](ta *TypedArena[T], liveRefs []SliceRef) (*CompactionStats, error)

CompactArena consolidates fragmented slabs in a TypedArena. It copies live data to new slabs and releases old fragmented ones. This is useful after many allocations and deallocations have fragmented memory.

type GCTuner

type GCTuner struct {
	IsAggressive       bool
	EnableGPUTuning    bool
	GPUUtilizationHigh float32 // Threshold for "high" GPU utilization (0-100)
	GPUUtilizationLow  float32 // Threshold for "low" GPU utilization (0-100)

	// GetPhysicalStats allows mocking the physical memory stats (off-heap)
	GetPhysicalStats func() (int64, int64)
	// contains filtered or unexported fields
}

GCTuner adjusts GOGC dynamically based on memory usage and GPU utilization.

func NewGCTuner

func NewGCTuner(limitBytes int64, highGOGC, lowGOGC int, logger *zerolog.Logger) *GCTuner

NewGCTuner creates a tuner. limitBytes should be close to container memory limit. GPU tuning is enabled by default when a GPU is available.

func (*GCTuner) AddArena

func (t *GCTuner) AddArena(a *ArenaStatsRecord)

AddArena registers an arena for tuning

func (*GCTuner) GetUtilizationRatio

func (t *GCTuner) GetUtilizationRatio() float64

GetUtilizationRatio returns the last measured memory utilization ratio (0.0 to 1.0+).

func (*GCTuner) IsBursting

func (t *GCTuner) IsBursting() bool

IsBursting returns true if the tuner has detected a heavy ingestion burst.

func (*GCTuner) IsHighPressure

func (t *GCTuner) IsHighPressure() bool

IsHighPressure returns true if memory utilization is above 85% of limit.

func (*GCTuner) RegisterCleanup

func (t *GCTuner) RegisterCleanup(fn func())

RegisterCleanup adds a function to be called when memory pressure is critical (>88%)

func (*GCTuner) RemoveArena

func (t *GCTuner) RemoveArena(a *ArenaStatsRecord)

RemoveArena unregisters an arena

func (*GCTuner) SetEmergencyGCCooldown

func (t *GCTuner) SetEmergencyGCCooldown(d time.Duration)

SetEmergencyGCCooldown sets the minimum duration between emergency GC cycles.

func (*GCTuner) Start

func (t *GCTuner) Start(ctx context.Context, interval time.Duration)

Start runs the tuner loop until context is canceled.

type MemStatsReader

type MemStatsReader interface {
	ReadMemStats(m *runtime.MemStats)
}

MemStatsReader interfaces runtime.ReadMemStats for testing

type NUMAAllocator

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

NUMAAllocator is a NUMA-aware memory allocator for Arrow buffers. On Linux with NUMA, it attempts to allocate memory on the specified node. On other platforms, it falls back to the default Go allocator.

func NewNUMAAllocator

func NewNUMAAllocator(topo *NUMATopology, nodeID int) *NUMAAllocator

NewNUMAAllocator creates a new NUMA-aware allocator for the specified node.

func (*NUMAAllocator) Allocate

func (a *NUMAAllocator) Allocate(size int) []byte

Allocate allocates memory, preferably on the NUMA node.

func (*NUMAAllocator) Free

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

Free frees memory (handled by Go GC).

func (*NUMAAllocator) Reallocate

func (a *NUMAAllocator) Reallocate(size int, b []byte) []byte

Reallocate reallocates memory.

type NUMATopology

type NUMATopology struct {
	NumNodes     int     // Number of NUMA nodes
	CPUs         [][]int // CPUs[nodeID] = list of CPU IDs on that node
	PhysicalCPUs [][]int // PhysicalCPUs[nodeID] = list of unique physical core IDs on that node
}

NUMATopology represents the NUMA topology of the system.

func DetectNUMATopology

func DetectNUMATopology() (*NUMATopology, error)

DetectNUMATopology detects the NUMA topology on Linux systems. Returns a single-node topology if NUMA is not available.

func (*NUMATopology) GetNodeForCPU

func (t *NUMATopology) GetNodeForCPU(cpu int) int

GetNodeForCPU returns the node ID for a given CPU, or -1 if not found.

func (*NUMATopology) String

func (t *NUMATopology) String() string

String returns a human-readable representation of the topology.

type OffHeapAllocator

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

OffHeapAllocator implements a non-GC scanned allocator using mmap. This is used for large buffers to reduce runtime.scanObject overhead.

func GetGlobalOffHeapAllocator

func GetGlobalOffHeapAllocator() *OffHeapAllocator

GetGlobalOffHeapAllocator returns the global off-heap allocator used internally by slab pools. This allocator's Allocated() count is reflected in GetGlobalOffHeapAllocated() and the GC tuner. External subsystems (e.g., FlatAdjacency for PackedNeighbors) should use this allocator instead of creating private OffHeapAllocator instances, so their memory is visible to memory pressure accounting.

func NewOffHeapAllocator

func NewOffHeapAllocator() *OffHeapAllocator

NewOffHeapAllocator creates a new mmap-based allocator.

func (*OffHeapAllocator) Allocate

func (a *OffHeapAllocator) Allocate(size int) []byte

Allocate allocates a byte slice of the given size from the OS. The memory is NOT managed by the Go GC.

func (*OffHeapAllocator) Allocated

func (a *OffHeapAllocator) Allocated() int64

Allocated returns total bytes currently allocated via this allocator.

func (*OffHeapAllocator) Free

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

Free releases the memory back to the OS.

func (*OffHeapAllocator) Reallocate

func (a *OffHeapAllocator) Reallocate(size int, b []byte) []byte

Reallocate resizes a slice.

type Pressure

type Pressure string

Pressure represents the level of memory pressure.

const (
	// PressureLow indicates low memory pressure.
	PressureLow Pressure = "low"
	// PressureMedium indicates medium memory pressure.
	PressureMedium Pressure = "medium"
	// PressureHigh indicates high memory pressure.
	PressureHigh Pressure = "high"
	// PressureCritical indicates critical memory pressure.
	PressureCritical Pressure = "critical"
)

type Profiler

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

Profiler tracks memory allocation and free events.

func GetProfiler

func GetProfiler() *Profiler

GetProfiler returns the global memory profiler.

func (*Profiler) GetStats

func (mp *Profiler) GetStats() Stats

GetStats returns the current memory statistics.

func (*Profiler) RecordAllocation

func (mp *Profiler) RecordAllocation(size int64)

RecordAllocation records a memory allocation of the given size.

func (*Profiler) RecordFree

func (mp *Profiler) RecordFree(size int64)

RecordFree records a memory free of the given size.

type RuntimeStats

type RuntimeStats struct {
	HeapAlloc          uint64
	HeapSys            uint64
	HeapIdle           uint64
	HeapInuse          uint64
	HeapReleased       uint64
	HeapObjects        uint64
	StackInuse         uint64
	StackSys           uint64
	MSpanInuse         uint64
	MSpanSys           uint64
	MCacheInuse        uint64
	MCacheSys          uint64
	BuckHashSys        uint64
	GCSys              uint64
	OtherSys           uint64
	GCCPUFraction      float64
	NumGC              uint32
	NumForcedGC        uint32
	GCCPUFractionTotal float64
	NumGoroutines      int
}

RuntimeStats contains memory statistics from the Go runtime.

func GetRuntimeStats

func GetRuntimeStats() RuntimeStats

GetRuntimeStats returns current Go runtime memory statistics.

type SegmentConfig

type SegmentConfig struct {
	Tier        SegmentTier
	SlabSize    int   // power-of-2 slab size for this tier
	TargetBytes int64 // max total bytes for this tier (0 = unlimited)
	AccessThres int64 // min access count to be promoted to this tier
}

SegmentConfig configures each tier in the segmented arena.

func DefaultSegmentConfigs

func DefaultSegmentConfigs() [3]SegmentConfig

DefaultSegmentConfigs returns sensible defaults for vector storage.

type SegmentTier

type SegmentTier int

SegmentTier represents the heat tier of an arena segment.

const (
	TierHot SegmentTier = iota
	TierWarm
	TierCold
)

type SegmentedArena

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

SegmentedArena provides three-tier vector storage with LRU-aware promotion/demotion. Hot tier: small slabs, fast allocation, frequently accessed vectors. Warm tier: medium slabs, moderate access frequency. Cold tier: large slabs, mmap-backed, infrequently accessed vectors.

func NewSegmentedArena

func NewSegmentedArena(cfgs [3]SegmentConfig) *SegmentedArena

NewSegmentedArena creates a three-tier segmented arena.

func (*SegmentedArena) AllocCold

func (sa *SegmentedArena) AllocCold(size int) (uint64, error)

AllocCold allocates into the cold tier.

func (*SegmentedArena) AllocHot

func (sa *SegmentedArena) AllocHot(size int) (uint64, error)

AllocHot allocates into the hot tier.

func (*SegmentedArena) AllocWarm

func (sa *SegmentedArena) AllocWarm(size int) (uint64, error)

AllocWarm allocates into the warm tier.

func (*SegmentedArena) Close

func (sa *SegmentedArena) Close()

func (*SegmentedArena) GetAccessInfo

func (sa *SegmentedArena) GetAccessInfo(offset uint64) (hits int64, lastAccess time.Time)

GetAccessInfo returns access statistics for a given offset.

func (*SegmentedArena) GetTier

func (sa *SegmentedArena) GetTier(tier SegmentTier) *SlabArena

GetTier returns the SlabArena for a given tier.

func (*SegmentedArena) RecordAccess

func (sa *SegmentedArena) RecordAccess(offset uint64)

RecordAccess records a vector access for LRU tracking.

func (*SegmentedArena) ShouldPromote

func (sa *SegmentedArena) ShouldPromote(offset uint64, currentTier SegmentTier) bool

ShouldPromote checks whether a ref's access pattern justifies promotion to the next tier.

func (*SegmentedArena) Stats

func (sa *SegmentedArena) Stats() SegmentedArenaStats

Stats returns aggregate statistics for all tiers.

type SegmentedArenaStats

type SegmentedArenaStats struct {
	HotSlabs        int
	HotUsed         int64
	HotCapacity     int64
	WarmSlabs       int
	WarmUsed        int64
	WarmCapacity    int64
	ColdSlabs       int
	ColdUsed        int64
	ColdCapacity    int64
	TotalPromotions int64
	TotalEvictions  int64
}

SegmentedArenaStats exposes metrics for monitoring.

type SizeClass

type SizeClass struct {
	MinSize   int
	MaxSize   int
	SlabSize  int
	AllocName string
}

SizeClass defines the configuration for a specific memory size range.

type SizeClassArena

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

SizeClassArena provides optimized allocation for different object sizes using multiple arenas.

func NewSizeClassArena

func NewSizeClassArena[T any]() *SizeClassArena[T]

NewSizeClassArena creates a new size-classed arena.

func (*SizeClassArena[T]) AllocSlice

func (sca *SizeClassArena[T]) AllocSlice(count int) (SliceRef, string, error)

func (*SizeClassArena[T]) AllocSliceDirty

func (sca *SizeClassArena[T]) AllocSliceDirty(count int) (SliceRef, string, error)

func (*SizeClassArena[T]) Compact

func (sca *SizeClassArena[T]) Compact(liveRefs map[string][]SliceRef) (map[string]*CompactionStats, error)

func (*SizeClassArena[T]) Get

func (sca *SizeClassArena[T]) Get(ref SliceRef) []T

func (*SizeClassArena[T]) MemoryUsage

func (sca *SizeClassArena[T]) MemoryUsage() UsageSummary

MemoryUsage returns a summary of memory usage across all size classes.

func (*SizeClassArena[T]) Stats

func (sca *SizeClassArena[T]) Stats() map[string]ArenaStats

type SlabAllocError

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

SlabAllocError is returned when arena allocation fails.

func (*SlabAllocError) Error

func (e *SlabAllocError) Error() string

type SlabArena

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

SlabArena manages large blocks of memory.

func NewSlabArena

func NewSlabArena(slabSizeBytes int) *SlabArena

NewSlabArena creates a new arena with specified slab byte size.

func NewSlabArenaWithAllocator

func NewSlabArenaWithAllocator(slabSizeBytes int, alloc memory.Allocator) *SlabArena

NewSlabArenaWithAllocator creates a new arena using a specific allocator for slabs.

func (*SlabArena) Alloc

func (a *SlabArena) Alloc(size int) (uint64, error)

Alloc reserves space for 'size' bytes. Returns a GLOBAL offset. Guarantees zero-initialized memory.

func (*SlabArena) AllocAligned

func (a *SlabArena) AllocAligned(size, align int) (uint64, error)

AllocAligned reserves space with specific alignment.

func (*SlabArena) AllocDirty

func (a *SlabArena) AllocDirty(size int) (uint64, error)

AllocDirty reserves space for 'size' bytes. Returns a GLOBAL offset. MEMORY IS NOT GUARANTEED TO BE ZEROED. Use this only when you will immediately overwrite the entire range.

func (*SlabArena) BeginBatch

func (a *SlabArena) BeginBatch(maxGeneration uint64) SlabBatch

BeginBatch opens a batch-scoped view of the arena for reads that share a single maxGeneration. The result is meant to live in a local variable for the duration of one batch.

func (*SlabArena) BumpGeneration

func (a *SlabArena) BumpGeneration() uint64

BumpGeneration increments the arena's generation ID. All subsequent allocations will occur in a new slab belonging to this generation.

func (*SlabArena) ConvertToOffHeap

func (a *SlabArena) ConvertToOffHeap(alloc memory.Allocator) error

ConvertToOffHeap migrates all existing slabs to off-heap memory using the provided allocator.

func (*SlabArena) Free

func (a *SlabArena) Free()

Free releases all memory associated with the arena.

func (*SlabArena) Get

func (a *SlabArena) Get(offset uint64, length uint32) []byte

Get retrieves the byte slice from the arena. This is a highly optimized fast-path for committed reads.

func (*SlabArena) GetGeneration

func (a *SlabArena) GetGeneration() uint64

GetGeneration returns the current generation ID of the arena.

func (*SlabArena) GetPointer

func (a *SlabArena) GetPointer(offset uint64) unsafe.Pointer

GetPointer returns unsafe.Pointer to the data. Use with caution.

func (*SlabArena) GetPointerWithGeneration

func (a *SlabArena) GetPointerWithGeneration(offset uint64, maxGeneration uint64) unsafe.Pointer

GetPointerWithGeneration returns unsafe.Pointer to the data enforcing generation isolation.

func (*SlabArena) GetWithGeneration

func (a *SlabArena) GetWithGeneration(offset uint64, length uint32, maxGeneration uint64) []byte

GetWithGeneration retrieves the byte slice from the arena, enforcing generation isolation. When maxGeneration is math.MaxUint64, generation isolation is bypassed for performance (the generation check is elided since committed data is always accessible).

func (*SlabArena) IsOffHeap

func (a *SlabArena) IsOffHeap() bool

IsOffHeap returns true if the arena is backed by off-heap memory.

func (*SlabArena) Load

func (a *SlabArena) Load(r io.Reader) error

Load deserializes the arena's contents from the given reader.

func (*SlabArena) LoadMmap

func (a *SlabArena) LoadMmap(f *os.File) error

LoadMmap maps the arena's contents from the given file using mmap.

func (*SlabArena) Release

func (a *SlabArena) Release()

Release decrements the reference count and calls Free if it reaches zero.

func (*SlabArena) Retain

func (a *SlabArena) Retain()

Retain increments the reference count.

func (*SlabArena) Save

func (a *SlabArena) Save(w io.Writer) error

Save serializes the arena's contents to the given writer.

func (*SlabArena) SlabSize

func (a *SlabArena) SlabSize() int

SlabSize returns the capacity of each slab in this arena.

func (*SlabArena) Stats

func (a *SlabArena) Stats() ArenaStats

Stats returns the current memory usage statistics for the arena.

func (*SlabArena) StatsRecord

func (a *SlabArena) StatsRecord() *ArenaStatsRecord

StatsRecord returns the underlying atomic stats record.

func (*SlabArena) TotalAllocated

func (a *SlabArena) TotalAllocated() int64

TotalAllocated returns the total bytes allocated across all slabs.

type SlabBatch

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

SlabBatch is a short-lived, batch-scoped view of a SlabArena.

It resolves the slab table and the generation policy exactly once and then hands out per-vector slices from a hot-slab cache, replacing the per-call atomic table load, slab-index division, slab pointer chase and generation comparison performed by GetWithGeneration.

Visibility rules are identical to GetWithGeneration:

  • a zero length yields nil;
  • offsets past the last slab yield nil;
  • placeholder slots (oversized allocations) resolve through the same backwards scan to the owning real slab, with the same uint32 offset arithmetic;
  • a slab is visible only when maxGeneration is math.MaxUint64 or the slab's generation is <= maxGeneration;
  • ranges that run past the owning slab's data are rejected.

A SlabBatch is a value, never a global, so it cannot be silently shared across a generation bump or an arena mutation. Slab generations are immutable, so bumping the arena generation never retroactively changes what an already-resolved batch returns; newly allocated data lands in newer slabs that a batch holding an older maxGeneration still cannot see. Structural arena mutations (Free, Compact, Load, LoadMmap, ConvertToOffHeap, or a concurrent Alloc that appends a slab) replace the slab table, and Get detects that by identity on every call and re-resolves, so a batch can never hand out data that the reference accessor would refuse.

A batch, and every slice obtained from it, is only valid inside the reader pin that guards the arena (GraphData.AcquireReader/ReleaseReader), exactly as the slices returned by GetWithGeneration are.

func (*SlabBatch) Get

func (b *SlabBatch) Get(offset uint64, length uint32) []byte

Get returns the bytes for one vector under the batch's generation policy.

func (*SlabBatch) MaxGeneration

func (b *SlabBatch) MaxGeneration() uint64

MaxGeneration returns the generation the batch was opened with.

func (*SlabBatch) Stale

func (b *SlabBatch) Stale() bool

Stale reports whether the arena's slab table was replaced after the batch resolved it. Get re-resolves transparently, so Stale is only needed by callers that want to observe an arena mutation mid-batch.

type SlabPool

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

SlabPool recycles byte slices of a fixed size to avoid repeated allocations and OS zeroing costs. It is specifically designed for 1MB slabs used by standard SlabArena configurations.

func (*SlabPool) ActiveCount

func (p *SlabPool) ActiveCount() int64

ActiveCount returns the number of slabs currently in use

func (*SlabPool) DebugSnapshot

func (p *SlabPool) DebugSnapshot() string

DebugSnapshot returns a multi-line string with the current state of this slab pool.

func (*SlabPool) Get

func (p *SlabPool) Get() []byte

Get retrieves a slab from the pool or allocates a new one.

func (*SlabPool) PooledCount

func (p *SlabPool) PooledCount() int64

PooledCount returns the number of slabs currently in the pool

func (*SlabPool) Put

func (p *SlabPool) Put(b []byte)

Put returns a slab to the pool for reuse.

func (*SlabPool) ReleaseUnused

func (p *SlabPool) ReleaseUnused() int

ReleaseUnused forces the pool to release excess slabs back to the OS. This is useful for explicit memory management after heavy workloads.

type SliceRef

type SliceRef struct {
	Offset uint64
	Len    uint32
	Cap    uint32
}

SliceRef is a handle to a slice in the arena. It is used by TypedArena and external consumers.

func AllocateOptimized

func AllocateOptimized[T any](sca *SizeClassArena[T], data []T) (SliceRef, string, error)

AllocateOptimized allocates a slice of the given size in the best-fitting size class.

func CopyBetweenArenas

func CopyBetweenArenas[T any](srcArena, dstArena *TypedArena[T], srcRef SliceRef) (SliceRef, error)

CopyBetweenArenas copies data from one arena to another.

func (SliceRef) IsNil

func (r SliceRef) IsNil() bool

IsNil returns true if the slice reference is empty.

type Stats

type Stats struct {
	Duration         time.Duration
	TotalAllocations int64
	TotalAllocBytes  int64
	TotalFrees       int64
	TotalFreedBytes  int64
	PeakUsage        int64
	CurrentUsage     int64
	GCCount          uint32
	LastGC           time.Time
}

Stats contains memory usage statistics.

func (*Stats) AllocationRate

func (ms *Stats) AllocationRate() float64

AllocationRate returns the number of allocations per second.

func (*Stats) FragmentationRatio

func (ms *Stats) FragmentationRatio() float64

FragmentationRatio returns the ratio of allocated memory that has been freed.

func (*Stats) ThroughputMBps

func (ms *Stats) ThroughputMBps() float64

ThroughputMBps returns the memory throughput in MB per second.

type TierState

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

TierState holds per-tier state.

type TrackingAllocator

type TrackingAllocator struct {
	memory.Allocator
	// Exposed for testing validity, but main purpose is metrics
	BytesAllocated atomic.Int64
	BytesFreed     atomic.Int64
}

TrackingAllocator wraps a base memory.Allocator and updates Prometheus metrics

func NewTrackingAllocator

func NewTrackingAllocator(base memory.Allocator) *TrackingAllocator

NewTrackingAllocator creates a new allocator that wraps the given base allocator. If base is nil, it uses memory.DefaultAllocator.

func (*TrackingAllocator) Allocate

func (a *TrackingAllocator) Allocate(size int) []byte

Allocate reserves space for 'size' bytes and updates metrics.

func (*TrackingAllocator) Free

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

Free releases the given byte slice and updates metrics.

func (*TrackingAllocator) Reallocate

func (a *TrackingAllocator) Reallocate(size int, b []byte) []byte

Reallocate resizes the given byte slice and updates metrics.

type TypedArena

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

TypedArena wraps a SlabArena to provide typed slice access.

func NewTypedArena

func NewTypedArena[T any](arena *SlabArena) *TypedArena[T]

NewTypedArena creates a new typed arena wrapper around a SlabArena.

func (*TypedArena[T]) AllocSlice

func (ta *TypedArena[T]) AllocSlice(count int) (SliceRef, error)

func (*TypedArena[T]) AllocSliceAligned

func (ta *TypedArena[T]) AllocSliceAligned(count, align int) (SliceRef, error)

AllocSliceAligned allocates an aligned slice.

func (*TypedArena[T]) AllocSliceDirty

func (ta *TypedArena[T]) AllocSliceDirty(count int) (SliceRef, error)

AllocSliceDirty allocates a slice but DOES NOT guarantee zero initialization. Use this only if you intend to overwrite the entire slice immediately.

func (*TypedArena[T]) BeginBatch

func (ta *TypedArena[T]) BeginBatch(maxGeneration uint64) TypedBatch[T]

BeginBatch opens a batch-scoped typed view, resolving the underlying arena, its slab table and the generation policy once.

func (*TypedArena[T]) BumpGeneration

func (ta *TypedArena[T]) BumpGeneration() uint64

BumpGeneration increments the underlying arena's generation.

func (*TypedArena[T]) Compact

func (ta *TypedArena[T]) Compact(liveRefs []SliceRef) (*CompactionStats, error)

Compact consolidates fragmented slabs in the arena. It copies live data to new slabs and releases old ones. This method is thread-safe and locks the arena for exclusive access.

func (*TypedArena[T]) Free

func (ta *TypedArena[T]) Free()

func (*TypedArena[T]) Get

func (ta *TypedArena[T]) Get(ref SliceRef) []T

Get retrieves a typed slice from the arena using a SliceRef.

func (*TypedArena[T]) GetPointer

func (ta *TypedArena[T]) GetPointer(ref SliceRef) unsafe.Pointer

GetPointer returns unsafe.Pointer to the typed data at ref.

func (*TypedArena[T]) GetPointerWithGeneration

func (ta *TypedArena[T]) GetPointerWithGeneration(ref SliceRef, maxGeneration uint64) unsafe.Pointer

GetPointerWithGeneration returns unsafe.Pointer to the typed data at ref enforcing generation isolation.

func (*TypedArena[T]) GetWithGeneration

func (ta *TypedArena[T]) GetWithGeneration(ref SliceRef, maxGeneration uint64) []T

GetWithGeneration retrieves a typed slice from the arena, enforcing generation isolation. When maxGeneration is math.MaxUint64, generation isolation is bypassed for performance.

func (*TypedArena[T]) Release

func (ta *TypedArena[T]) Release()

func (*TypedArena[T]) Retain

func (ta *TypedArena[T]) Retain()

func (*TypedArena[T]) SetGeneration

func (ta *TypedArena[T]) SetGeneration(gen uint64)

SetGeneration sets the underlying arena's generation.

func (*TypedArena[T]) Slab

func (ta *TypedArena[T]) Slab() *SlabArena

func (*TypedArena[T]) TotalAllocated

func (ta *TypedArena[T]) TotalAllocated() int64

TotalAllocated returns total bytes allocated in the arena.

type TypedBatch

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

TypedBatch is the typed-arena counterpart of SlabBatch.

func (*TypedBatch[T]) Get

func (b *TypedBatch[T]) Get(ref SliceRef) []T

Get returns the typed slice for ref, applying the same rules as TypedArena.GetWithGeneration at the batch's generation.

func (*TypedBatch[T]) Stale

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

Stale reports whether the batch no longer tracks the arena it was opened on.

type UsageSummary

type UsageSummary struct {
	TotalCapacity      int64
	TotalUsed          int64
	OverallUtilization float64
	ByClass            map[string]ClassUsage
	SortedClasses      []string
}

UsageSummary provides an overview of memory usage across all size classes.

type VectorArena

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

VectorArena is a specialized arena for vector storage that integrates with the slab arena and provides vector-specific allocation methods with proper alignment for SIMD operations.

func NewVectorArena

func NewVectorArena(slabSizeBytes int) *VectorArena

NewVectorArena creates a new vector arena with the specified slab size.

func (*VectorArena) AllocVector

func (va *VectorArena) AllocVector(dim int, vecType VectorType) (uint64, interface{}, error)

AllocVector allocates a vector of the specified dimension and type. Returns a global offset and a typed slice that points to the off-heap memory.

func (*VectorArena) Free

func (va *VectorArena) Free()

Free releases all memory back to the slab arena.

func (*VectorArena) GetVector

func (va *VectorArena) GetVector(offset uint64, dim int, vecType VectorType) (interface{}, error)

GetVector returns a typed slice for the vector at the specified offset.

func (*VectorArena) RegisterArena

func (va *VectorArena) RegisterArena()

RegisterArena registers the vector arena with the global registry.

func (*VectorArena) Stats

func (va *VectorArena) Stats() ArenaStats

Stats returns statistics about the vector arena usage.

type VectorID

type VectorID uint32

VectorID is an alias for uint32 to represent vector identifiers.

type VectorType

type VectorType int

VectorType defines the supported vector data types.

const (
	// VectorTypeFloat32 is a 32-bit floating point vector
	VectorTypeFloat32 VectorType = iota
	// VectorTypeFloat16 is a 16-bit floating point vector
	VectorTypeFloat16
	// VectorTypeInt8 is an 8-bit integer vector
	VectorTypeInt8
	// VectorTypeComplex64 is a complex 64-bit vector
	VectorTypeComplex64
)

Jump to

Keyboard shortcuts

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