vectorized

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 16 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package vectorized provides RecordBatch-based columnar execution primitives: schema, columns, operator interfaces, pipeline composition, and memory tracking.

Index

Constants

View Source
const DefaultBatchSize = 1024

DefaultBatchSize is the canonical batch row capacity of operator output. uint16 selection vectors cap batch size at 65536. Scan batches lent from storage blocks may be larger (up to a block, 8,192 rows) and are never padded or split to this size, so an operator must size itself from Len/ActiveLen, not from this constant.

View Source
const QueryMetricsEnabled = false

QueryMetricsEnabled reports whether test query counters are compiled in.

Variables

View Source
var ErrLimitExhausted = errors.New("vectorized: limit exhausted")

ErrLimitExhausted is returned by FusibleOperators that finished their work and want the fused stage to translate the signal into "emit current batch + EOF on next call".

View Source
var ErrMemoryBudgetExceeded = errors.New("memory budget exceeded")

ErrMemoryBudgetExceeded indicates exhaustion of the shared query memory allowance.

Functions

func AppendActiveRows

func AppendActiveRows(dst, src *RecordBatch) error

AppendActiveRows appends every active row of src (its Selection when present, else all [0,Len) rows) onto dst, column by column, advancing dst.Len. dst and src must share the same schema/column layout. It is the columnar analog of a row-wise copy used to flatten a Selection-narrowed batch into a dense one (frame emit) or to concatenate per-node batches (liaison merge).

func AppendColumnRange

func AppendColumnRange(dst, src Column, srcPos, n int) error

AppendColumnRange copies n rows starting at srcPos from src into dst. Both columns must share the same TypedColumn[T] type. Validity bits are propagated cell-by-cell via dst.MarkNullAt when src.IsNull reports null at the corresponding row.

String and slice-typed cell values ([]byte / []int64 / []string) are not deep-copied here: dst shares their payloads with src. A cell may borrow storage memory that src's batch pins through RecordBatch.Owners, so a caller whose dst outlives src's batch must pin the same owners on dst's batch (Owners.PinAll) or clone what it keeps.

func BeginResponseEncoding added in v0.12.0

func BeginResponseEncoding(ctx context.Context) context.Context

BeginResponseEncoding starts coverage for one final serialization. A new run replaces any unfinished or unconsumed predecessor in the same query scope.

func ColumnCapacityClass added in v0.12.0

func ColumnCapacityClass(capacity int) int

ColumnCapacityClass groups capacities by powers of two above the canonical batch size, so normal small batches never evict cached native block slabs.

func ConstSupported added in v0.12.0

func ConstSupported(t ColumnType) bool

ConstSupported reports whether a ConstColumn can stand for a column of type t.

func ConsumeChunked added in v0.11.2

func ConsumeChunked(op BreakerOperator, scratch, b *RecordBatch, batchSize int) error

ConsumeChunked feeds b's active rows to op.Consume in slices of at most batchSize rows, copying each slice into scratch instead of handing op the whole batch.

It exists because RecordBatch.Selection is []uint16, so an operator that materializes its active rows as a selection over [0, Len) wraps silently once Len exceeds 65,536: early rows are consumed a second time and the rows past the wrap are never visited, with no error. Any BreakerOperator handed a batch it did not size itself shares that exposure, so calling this rather than op.Consume(b) is what keeps such a batch from reaching it whole. See docs/design/0.12.0/limit-after-aggregation §5.

Widening Selection to []uint32 was considered and rejected: that would let a consumer materialize an arbitrarily large working set and merely survive indexing it, whereas chunking keeps the per-step footprint bounded by batchSize regardless of what the producer sent. Note the bound is on this function's working set only -- b itself stays fully resident for the duration of the call, and only one chunk is copied at a time.

A non-nil Selection on b is walked rather than discarded, so a caller's pre-selection is preserved. scratch must share b's column layout; it is Reset before each chunk, so every row it carries is active by construction.

func EstimatedActiveBytes added in v0.12.0

func EstimatedActiveBytes(batch *RecordBatch) uint64

EstimatedActiveBytes is EstimatedRetainedBytes for the rows the batch's selection keeps: the payload of a row the selection drops is not counted, and a column is charged for the active rows, not for its capacity. A consumer that copies only the active rows (the response serializer) must be charged for those: a batch that a limit cut down to one row still holds the storage of every row it was read with, and charging for that made a limit of 1 cost as much as the whole batch.

func EstimatedRetainedBytes added in v0.11.1

func EstimatedRetainedBytes(batch *RecordBatch) uint64

EstimatedRetainedBytes estimates row references, column capacity and payloads retained by a merge operator. Protobuf values are charged their payload once plus a fixed object overhead; this is not an exact Go heap measurement. Shared payloads may be counted twice.

func FillEmbeddedConstFrom added in v0.12.0

func FillEmbeddedConstFrom(c *ConstColumn, src Column, row, n int) bool

FillEmbeddedConstFrom is AcquireConstFrom for a column whose storage the caller provides: c becomes a constant of n rows holding the value of row of src, and ReleaseColumn only resets it, never pools it. It reports false, having changed nothing, when src cannot be constant. c must stay put until it is released.

func FinishResponseEncoding added in v0.12.0

func FinishResponseEncoding(ctx context.Context, success bool)

FinishResponseEncoding marks a drained final serialization complete, or revokes coverage on error or early Close. Completed coverage survives Close.

func HasResponseEncoding added in v0.12.0

func HasResponseEncoding(ctx context.Context) bool

HasResponseEncoding reports whether final serialization retains its pointer slabs for response identity coverage. The slabs share the protobuf budget.

func OutstandingOwnerPins added in v0.12.0

func OutstandingOwnerPins() int64

OutstandingOwnerPins returns the number of owner references that Owners sets hold and have not released. It is zero when no live batch borrows memory.

func RecordResponseEncoding added in v0.12.0

func RecordResponseEncoding(ctx context.Context, points []*measurev1.InternalDataPoint, bound uint64, covered bool) error

RecordResponseEncoding records an already preflighted batch and its wire-size bound. Callers retain the pointer slab without reusing it for another batch.

func ReleaseColumn

func ReleaseColumn(c Column)

ReleaseColumn returns a column to its per-type pool. The column is Reset (length cleared, validity cleared) before being put back. A nil column is a no-op so callers can release defensively. Unknown column types are also no-ops — the column is simply dropped on the floor for the GC.

func ReserveResponseEncoding added in v0.12.0

func ReserveResponseEncoding(ctx context.Context, response any) (func(), error)

ReserveResponseEncoding reserves encoding and transport copies beside the retained protobuf response. A transport scope holds the reservation until RPC completion; direct callers must invoke the returned release after materialization.

func ResetQueryMemoryPeak added in v0.12.0

func ResetQueryMemoryPeak() bool

ResetQueryMemoryPeak succeeds without changing counters outside querymetrics builds.

func SelectRows added in v0.12.0

func SelectRows(b *RecordBatch, colIdx int, keep func(col Column, row int) bool)

SelectRows narrows b's selection to the active rows for which keep reports true, preserving their order. keep sees the column and a row of it.

A predicate on a ConstColumn has the same answer for every row, so it is evaluated once: a batch it rejects gets an empty selection and a batch it accepts is left untouched, whatever its size. Any other column is evaluated row by row.

func WithLiveLeaseAccounting added in v0.12.0

func WithLiveLeaseAccounting(ctx context.Context) context.Context

WithLiveLeaseAccounting makes the query tracker created under ctx hand released bytes back to the query lease, so the lease tracks what the query holds right now instead of everything it ever reserved. A streaming scan needs it: it reserves and releases memory for every block it reads, and a result of any size must run inside the lease. Queries that collect their whole result keep the default, where charges only accumulate.

func WithQueryMemoryScope added in v0.12.0

func WithQueryMemoryScope(ctx context.Context) context.Context

WithQueryMemoryScope shares a lazily configured tracker with downstream execution. The processor supplies the actual memory limit when it initializes the tracker; the caller can subsequently account final encoding against that same allowance.

func WithQueryMemoryTracker added in v0.12.0

func WithQueryMemoryTracker(ctx context.Context, limit int64) context.Context

WithQueryMemoryTracker installs one shared tracker unless the query already owns one. Admission lease charging is conservative and monotonic; live tracker reservations are refundable.

Types

type BatchHints added in v0.12.0

type BatchHints struct {
	// SeriesEnds lists, for a batch that holds several series, the exclusive end
	// row index (in column order) of every maximal run of rows of one series. It is
	// meaningful only when SeriesKnown is set; empty then means the batch is a
	// single series. The slice is borrowed from the producer and valid until the
	// batch's Owners are released.
	SeriesEnds []int
	// TimeOrder is the direction of time within each series run, in the order the
	// batch's active rows are read.
	TimeOrder TimeOrder
	// SeriesKnown is set when SeriesEnds is exact. Without it nothing is known about
	// which series the rows belong to, and an empty SeriesEnds means nothing.
	SeriesKnown bool
}

BatchHints are facts a producer knows about a batch and a consumer would have to scan the rows to rediscover. They let an aggregation split a batch into runs of rows that share a grouping key (see SeriesRuns) without looking at every row.

Every hint is relative to the rows as the producer emitted them. A Selection that only narrows the batch keeps them true: it keeps the order of the rows it names. An operator that reorders rows, or copies them into a batch of its own, must not pass a hint on.

type BatchOperator

type BatchOperator interface {
	Init(ctx context.Context) error
	OutputSchema() *BatchSchema
	Close() error
}

BatchOperator is the lifecycle base. All operators implement it.

Close is idempotent and safe to call at any phase — after Init, mid-Consume, after Finalize, or after any error. It must release every MemoryTracker.Reserve the operator made during its lifetime.

type BatchPool

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

BatchPool reuses RecordBatches across pipeline iterations. All batches in a pool share the same schema and capacity.

Caller contract: Put a batch only when it is consistent. Error paths must discard rather than Put — see fusedStage.NextBatch.

func NewBatchPool

func NewBatchPool(schema *BatchSchema, capacity int) *BatchPool

NewBatchPool returns a pool whose Get yields freshly Reset batches.

func (*BatchPool) Get

func (p *BatchPool) Get() *RecordBatch

Get returns a Reset batch. Caller may write rows up to capacity.

func (*BatchPool) Put

func (p *BatchPool) Put(b *RecordBatch)

Put returns a batch to the pool and releases the owners it pins; the caller is declaring the batch dead. Nil batches, lent batches and batches with a foreign schema are not pooled (a foreign batch still has its owners released).

type BatchSchema

type BatchSchema struct {
	Columns         []ColumnDef
	TagFamilyGroups []TagFamilyGroup // ordered tag-column groups by family
	FieldColumns    []int            // ordered field column indices
	// contains filtered or unexported fields
}

BatchSchema is the immutable column layout shared by every RecordBatch in a pipeline.

func NewBatchSchema

func NewBatchSchema(cols []ColumnDef) *BatchSchema

NewBatchSchema builds a BatchSchema and precomputes lookup indices.

func (*BatchSchema) ElementIDIndex

func (s *BatchSchema) ElementIDIndex() int

ElementIDIndex returns the element-id column index, or -1 if absent.

func (*BatchSchema) FieldIndex

func (s *BatchSchema) FieldIndex(name string) (int, bool)

FieldIndex returns the column index for a field name.

func (*BatchSchema) OrderKeyIndex

func (s *BatchSchema) OrderKeyIndex() int

OrderKeyIndex returns the order-key column index, or -1 if absent.

func (*BatchSchema) SeriesIDIndex

func (s *BatchSchema) SeriesIDIndex() int

SeriesIDIndex returns the series-id column index, or -1 if absent.

func (*BatchSchema) ShardIDIndex

func (s *BatchSchema) ShardIDIndex() int

ShardIDIndex returns the shard-id column index, or -1 if absent.

func (*BatchSchema) TagIndex

func (s *BatchSchema) TagIndex(family, name string) (int, bool)

TagIndex returns the column index for a (family, name) tag. Lookup uses a struct key, so it does not allocate.

func (*BatchSchema) TimestampIndex

func (s *BatchSchema) TimestampIndex() int

TimestampIndex returns the timestamp column index, or -1 if absent.

func (*BatchSchema) VersionIndex

func (s *BatchSchema) VersionIndex() int

VersionIndex returns the version column index, or -1 if absent.

type BreakerOperator

type BreakerOperator interface {
	BatchOperator
	Consume(ctx context.Context, b *RecordBatch) error
	Finalize(ctx context.Context) error
	NextBatch(ctx context.Context) (*RecordBatch, error)
}

BreakerOperator buffers all input via Consume, then produces output via NextBatch after Finalize is called.

type Column

type Column interface {
	Type() ColumnType
	Len() int
	IsNull(i int) bool
	Reset()
	AppendNull()
	MarkNullAt(i int)
}

Column is the storage-agnostic view of one column in a RecordBatch.

func AcquireBoundedColumn added in v0.12.0

func AcquireBoundedColumn(t ColumnType, capacity int) Column

AcquireBoundedColumn acquires a reset column and drops oversized cached backing buffers before the column is attached to a query batch. Normal batch-size reuse is preserved; retained capacity is at most twice max(capacity, DefaultBatchSize).

func AcquireColumn

func AcquireColumn(t ColumnType, capacity int) Column

AcquireColumn returns a recycled Column of the requested type. The returned column is Reset (length 0, validity cleared) and has a backing capacity of at least the requested size. Callers must pair every AcquireColumn with a matching ReleaseColumn once they are done with the column.

Capacity behavior: pooled columns retain whichever capacity they had at the last Release. If a pooled column is too small for the new request the backing slice is reallocated; otherwise the existing backing slice is reused. Capacity classes isolate native block slabs from ordinary operator batches.

func Materialize added in v0.12.0

func Materialize(col Column) Column

Materialize returns col itself, or an expanded copy when it is a ConstColumn.

func NewColumnForType

func NewColumnForType(t ColumnType, capacity int) Column

NewColumnForType constructs a fresh Column of the given type with the requested backing capacity. Callers that want pool recycling should use AcquireColumn / ReleaseColumn directly — those are wired into the MeasureBatch pool's Acquire path. NewColumnForType deliberately stays non-pooled so callers (operator-internal slot buffers, the egress coalesce buffer, etc.) that never Release their columns do not skew the pool refcount used by the test-teardown HaveZeroRef invariant.

Panics on unknown type — programmer error, not data error.

type ColumnDef

type ColumnDef struct {
	Name      string
	TagFamily string
	Role      ColumnRole
	Type      ColumnType
	Scale     uint8
	// Entity marks a RoleTag column that is one of the measure's entity tags: its
	// value is a function of the series, so it is the same for every row of one
	// series. A scan that knows its rows' series uses that to carry the column as a
	// ConstColumn and to group by it once per series run. It is a property of
	// storage-produced batches only and is not carried on the wire.
	Entity bool
}

ColumnDef describes one column in a BatchSchema.

type ColumnRole

type ColumnRole int

ColumnRole identifies the semantic role of a column within a RecordBatch.

const (
	RoleTimestamp ColumnRole = iota
	RoleVersion
	RoleSeriesID
	RoleShardID
	RoleTag
	RoleField
	RoleElementID
	RoleOrderKey
)

Column roles. Each batch schema may include at most one column per metadata role.

type ColumnType

type ColumnType int

ColumnType is the runtime type tag for a Column.

const (
	ColumnTypeInt64 ColumnType = iota
	ColumnTypeFloat64
	ColumnTypeString
	ColumnTypeBytes
	ColumnTypeInt64Array
	ColumnTypeStrArray
	ColumnTypeTagValue
	ColumnTypeFieldValue
	ColumnTypeDecimal
)

ColumnType variants. Each value corresponds to a TypedColumn[T] specialization.

The TagValue / FieldValue variants are passthrough columns: they hold the original *modelv1.TagValue / *modelv1.FieldValue pointers from the scan source unchanged, eliminating the decode/re-encode round trip when no operator consumes the typed value. They are only useful when the scan output is destined for the egress serializer; an operator that needs typed primitives should pick a typed column type instead.

func (ColumnType) String

func (c ColumnType) String() string

String returns a human label used in diagnostics and error messages.

type ConstColumn added in v0.12.0

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

ConstColumn is a Column whose every row holds the same value: one typed scalar (int64, float64, string or bytes) or a typed null, plus a row count. A storage batch lent from a single series uses it for the series' entity tags, which are the same in every row of the batch, so the value is stored once instead of per row, grouping by it costs one key per batch, and a predicate on it keeps or drops the whole batch.

A ConstColumn reports the logical ColumnType of the typed column it stands for (ColumnTypeInt64, ColumnTypeFloat64, ColumnTypeString or ColumnTypeBytes), so a BatchSchema and the planners built on it do not change: only a consumer that reaches into the cells has to know the column may be constant. It tells them apart with AsConst; a consumer that does not specialize calls Expand (or Materialize) for an ordinary TypedColumn.

A string or bytes value may borrow memory a storage cursor owns. The column follows the rules of any other borrowing column: the batch that carries it pins the owner through RecordBatch.Owners, and a consumer that keeps the value past the batch's life clones it first.

A ConstColumn is immutable once built: it is read-only and cannot be appended to.

func AcquireConstFrom added in v0.12.0

func AcquireConstFrom(src Column, row, n int) (*ConstColumn, bool)

AcquireConstFrom returns a pooled ConstColumn of n rows holding the value of row of src, or a null of src's type when that row is null. It reports false, having built nothing, when src is not a typed column of a ConstSupported type or row is out of range. String and bytes values are not copied. Release the column with ReleaseColumn.

func AsConst added in v0.12.0

func AsConst(col Column) (*ConstColumn, bool)

AsConst returns col as a ConstColumn when it is one.

func NewConstBytes added in v0.12.0

func NewConstBytes(v []byte, n int) *ConstColumn

NewConstBytes returns a column of n rows that all hold v. The column does not copy v.

func NewConstFloat64 added in v0.12.0

func NewConstFloat64(v float64, n int) *ConstColumn

NewConstFloat64 returns a column of n rows that all hold v.

func NewConstInt64 added in v0.12.0

func NewConstInt64(v int64, n int) *ConstColumn

NewConstInt64 returns a column of n rows that all hold v.

func NewConstNull added in v0.12.0

func NewConstNull(t ColumnType, n int) *ConstColumn

NewConstNull returns a column of n null rows of type t. t must be one a ConstColumn can stand for (see ConstSupported).

func NewConstString added in v0.12.0

func NewConstString(v string, n int) *ConstColumn

NewConstString returns a column of n rows that all hold v. The column does not copy v.

func (*ConstColumn) AppendNull added in v0.12.0

func (c *ConstColumn) AppendNull()

AppendNull panics: a ConstColumn is immutable.

func (*ConstColumn) AppendTo added in v0.12.0

func (c *ConstColumn) AppendTo(dst Column, n int) error

AppendTo appends n copies of the value to dst, a TypedColumn of the same type, marking them null when the constant is. Strings and bytes are shared, not copied.

func (*ConstColumn) Bytes added in v0.12.0

func (c *ConstColumn) Bytes() []byte

Bytes returns the value of a bytes column; nil for a null one. The caller must not modify it.

func (*ConstColumn) Equal added in v0.12.0

func (c *ConstColumn) Equal(o *ConstColumn) bool

Equal reports whether o holds the same value and type as c. Row counts are not compared.

func (*ConstColumn) Expand added in v0.12.0

func (c *ConstColumn) Expand() Column

Expand returns an ordinary TypedColumn holding the value in each of the column's rows. It is the shared materialization for a consumer that does not specialize on constants. Strings and bytes are shared with c, so the expanded column is valid for as long as c is.

func (*ConstColumn) Float64 added in v0.12.0

func (c *ConstColumn) Float64() float64

Float64 returns the value of a float64 column; zero for a null one.

func (*ConstColumn) Int64 added in v0.12.0

func (c *ConstColumn) Int64() int64

Int64 returns the value of an int64 column; zero for a null one.

func (*ConstColumn) IsNull added in v0.12.0

func (c *ConstColumn) IsNull(i int) bool

IsNull reports whether row i is null: every row of a null column is, none of any other.

func (*ConstColumn) IsNullValue added in v0.12.0

func (c *ConstColumn) IsNullValue() bool

IsNullValue reports whether the constant is null.

func (*ConstColumn) Len added in v0.12.0

func (c *ConstColumn) Len() int

Len returns the number of rows.

func (*ConstColumn) MarkNullAt added in v0.12.0

func (c *ConstColumn) MarkNullAt(int)

MarkNullAt panics: a ConstColumn is immutable.

func (*ConstColumn) Reset added in v0.12.0

func (c *ConstColumn) Reset()

Reset drops the value and the row count, so a pooled column keeps no reference to borrowed memory.

func (*ConstColumn) SetFrom added in v0.12.0

func (c *ConstColumn) SetFrom(src Column, row, n int) bool

SetFrom makes c a constant of n rows holding the value of row of src (a null of src's type when that row is null). It reports false, having changed nothing, when src is not a typed column of a ConstSupported type or row is out of range.

func (*ConstColumn) Str added in v0.12.0

func (c *ConstColumn) Str() string

Str returns the value of a string column; empty for a null one.

func (*ConstColumn) Type added in v0.12.0

func (c *ConstColumn) Type() ColumnType

Type returns the logical type of the column.

type FusibleOperator

type FusibleOperator interface {
	BatchOperator
	Process(ctx context.Context, b *RecordBatch) error
}

FusibleOperator transforms a batch in place. No state across batches.

Process must not retain references to the batch beyond the call. Returning ErrLimitExhausted signals "emit this batch then EOF on the next pull".

type MemoryCounters added in v0.12.0

type MemoryCounters struct {
	LiveReservedBytes int64
	PeakReservedBytes int64
	LeaseChargedBytes uint64
}

MemoryCounters reports live reservations, peak reservations and cumulative admission charges.

func QueryMemoryStats added in v0.12.0

func QueryMemoryStats() MemoryCounters

QueryMemoryStats returns zero counters outside querymetrics builds.

type MemoryTracker

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

MemoryTracker is a lock-free per-query memory budget.

Reserve grows used iff used+bytes <= limit; otherwise it returns an error and leaves used unchanged. Release shrinks used. Used reads the current value.

func NewMemoryTracker

func NewMemoryTracker(limit int64) *MemoryTracker

NewMemoryTracker returns a tracker with the given byte limit.

func QueryMemoryTracker added in v0.12.0

func QueryMemoryTracker(ctx context.Context, limit int64) *MemoryTracker

QueryMemoryTracker returns the shared query tracker, or a standalone tracker for legacy callers.

func QueryMemoryTrackerFromContext added in v0.12.0

func QueryMemoryTrackerFromContext(ctx context.Context) (*MemoryTracker, bool)

QueryMemoryTrackerFromContext returns an installed query tracker without creating one.

func (*MemoryTracker) Limit added in v0.12.0

func (m *MemoryTracker) Limit() int64

Limit returns the byte limit of the tracker.

func (*MemoryTracker) Peak added in v0.12.0

func (m *MemoryTracker) Peak() int64

Peak returns the most bytes the tracker has held at once.

func (*MemoryTracker) Release

func (m *MemoryTracker) Release(bytes int64)

Release returns bytes to the budget. A negative bytes value indicates a programmer error and panics.

func (*MemoryTracker) Reserve

func (m *MemoryTracker) Reserve(bytes int64) error

Reserve attempts to allocate bytes from the budget. On success used grows by bytes; on failure used is unchanged.

A negative bytes value indicates a programmer error (Reserve must not be used to decrement) and panics. Zero bytes is a valid no-op.

func (*MemoryTracker) Used

func (m *MemoryTracker) Used() int64

Used returns the current outstanding reservation.

type NativeReceiveScope added in v0.12.0

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

NativeReceiveScope reserves every pending native receive before streams open. The transport owns reservations when present; otherwise Close releases them.

func NativeReceiveScopeFromContext added in v0.12.0

func NativeReceiveScopeFromContext(ctx context.Context) (*NativeReceiveScope, bool)

NativeReceiveScopeFromContext returns the native measure receive guard, if any.

func WithNativeReceiveScope added in v0.12.0

func WithNativeReceiveScope(ctx context.Context, tracker *MemoryTracker) (context.Context, *NativeReceiveScope)

WithNativeReceiveScope installs a Go-only guard for measure batch broadcasts.

func (*NativeReceiveScope) Close added in v0.12.0

func (s *NativeReceiveScope) Close()

Close releases reservations not transferred to the RPC transport scope.

func (*NativeReceiveScope) IngressReserved added in v0.12.0

func (s *NativeReceiveScope) IngressReserved() bool

IngressReserved reports that native ingress copies already have reservations.

func (*NativeReceiveScope) ReserveFanout added in v0.12.0

func (s *NativeReceiveScope) ReserveFanout(streams int, window, maxMessage int64) (int, error)

ReserveFanout reserves bounded HTTP/2 windows and message workspace before opening streams. Fixed windows and parser workspace are reserved first, then a quarter of the remaining allowance is partitioned among message copies; the rest remains available for decoded batches and final responses. Guarded calls must use the native codec's exact-length flattening; the ordinary grpc codec's pooled 1MiB materialization tier would exceed this reservation. Uneven responses may still fail their per-stream cap.

type Owner added in v0.12.0

type Owner interface {
	Retain()
	Release()
}

Owner is a reference-counted holder of memory that batch columns borrow without copying. A block cursor is the canonical Owner: its decoded value buffers back the string and bytes cells of every batch built from it, and it returns to its pool only after the last borrower has released its reference.

Retain adds one reference. Release drops one; the owner reclaims its memory when the count reaches zero. Releasing more times than retained is a bug.

type Owners added in v0.12.0

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

Owners is the set of owners a batch pins. Each member holds exactly one reference taken on behalf of the set, so the borrowed memory stays valid until the set is released.

A missed Release only keeps an owner from being recycled; the garbage collector still frees it. Releasing early is the dangerous direction, so callers release only when they can prove no borrowed value is read again.

The zero value is an empty set. Owners is not safe for concurrent use.

func (*Owners) Contains added in v0.12.0

func (s *Owners) Contains(o Owner) bool

Contains reports whether o is pinned.

func (*Owners) Len added in v0.12.0

func (s *Owners) Len() int

Len returns the number of distinct owners pinned.

func (*Owners) Pin added in v0.12.0

func (s *Owners) Pin(o Owner)

Pin takes one reference on o on behalf of the set. Pinning an owner the set already holds is a no-op, so the set never holds two references to one owner.

func (*Owners) PinAll added in v0.12.0

func (s *Owners) PinAll(from *Owners)

PinAll takes a reference on every owner in from on behalf of s. from keeps its own references.

func (*Owners) Release added in v0.12.0

func (s *Owners) Release()

Release drops the reference held on every owner and empties the set. It is idempotent: a second call finds the set empty.

func (*Owners) TransferTo added in v0.12.0

func (s *Owners) TransferTo(dst *Owners)

TransferTo moves every owner to dst without touching reference counts, then empties s. An owner dst already holds is released once, because dst needs only one reference to it.

type Pipeline

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

Pipeline is the composed sequence of stages from source to final breaker. It exposes a single PullOperator-shaped Next method to the driver.

func (*Pipeline) Close

func (p *Pipeline) Close() error

Close closes the head stage. Idempotent — repeat calls are no-ops.

func (*Pipeline) Init

func (p *Pipeline) Init(ctx context.Context) error

Init cascades initialization down through every stage to the source. Must be called once before the first Next, after Build. Re-calling is safe but pointless — each stage's Init is idempotent only if its underlying operator's Init is.

func (*Pipeline) Next

func (p *Pipeline) Next(ctx context.Context) (*RecordBatch, error)

Next returns the next batch from the head stage.

func (*Pipeline) Tracker

func (p *Pipeline) Tracker() *MemoryTracker

Tracker returns the shared per-pipeline MemoryTracker, or nil if the builder did not set one. Operators that bookkeep memory should be constructed with this tracker so they all draw from a single budget.

type PipelineBuilder

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

PipelineBuilder fluently composes a Pipeline.

Apply/Break ordering: every Apply call queues a fusible into the currently-open fused segment. Break closes that segment, wraps it with the supplied breaker, and starts a new (empty) segment on top. So the observable stage order matches the call order: each fusible runs before any breaker that was added later, and after any breaker that was added earlier. Plan-tree builders rely on this — e.g. a Limit Apply'd after a GroupByAgg Break must execute on the aggregated output, not on the raw source rows.

func NewPipelineBuilder

func NewPipelineBuilder() *PipelineBuilder

NewPipelineBuilder starts a builder.

func (*PipelineBuilder) Apply

Apply queues a FusibleOperator into the current open fused segment.

func (*PipelineBuilder) Break

Break closes the current fused segment and wraps it with br, starting a new empty segment for subsequent Apply calls to attach above the breaker.

func (*PipelineBuilder) Build

func (b *PipelineBuilder) Build() (*Pipeline, error)

Build validates and constructs the Pipeline. Each closed segment becomes fusedStage(prev, preFused) → breakerStage(_, breaker); any fusibles still queued after the last Break form a final fused stage on top of the chain.

func (*PipelineBuilder) From

From sets the leaf source.

func (*PipelineBuilder) Transform added in v0.12.0

func (b *PipelineBuilder) Transform(fn func(upstream PullOperator) PullOperator) *PipelineBuilder

Transform closes the current segment — any queued Applies, plus any completed Break steps — into a single concrete PullOperator, passes it to fn, and makes fn's result the new base for whatever Apply/Break/Transform calls follow (and for the eventual Build).

Unlike Break, the operator fn returns is a plain PullOperator, not a BreakerOperator driven by breakerStage's "drain the entire upstream via Consume, then serve via NextBatch" contract. Use Transform for an operator that needs to pull from upstream lazily, batch by batch, interleaving its own flushed output with further upstream consumption — e.g. one whose memory bound depends on never holding more than what a single upstream batch can produce. Wrapping such an operator as a BreakerOperator instead would force the entire upstream to be buffered before anything downstream is emitted, defeating the point.

func (*PipelineBuilder) WithMemoryTracker

func (b *PipelineBuilder) WithMemoryTracker(t *MemoryTracker) *PipelineBuilder

WithMemoryTracker attaches a shared MemoryTracker to the pipeline. Operators that bookkeep memory (BatchGroupBy, BatchAggregation) should be constructed with this same tracker so reservations stack against a single budget.

type PullOperator

type PullOperator interface {
	BatchOperator
	NextBatch(ctx context.Context) (*RecordBatch, error)
}

PullOperator produces batches. It is the source of a pipeline.

NextBatch contract:

  • (non-nil, nil) → valid batch with Len > 0
  • (nil, nil) → EOF; caller must not call NextBatch again
  • (nil, non-nil) → error; pipeline stops

NextBatch may block — channel-backed implementations are explicitly supported for future distributed remote-scan operators.

type RecordBatch

type RecordBatch struct {
	Schema    *BatchSchema
	Columns   []Column
	Selection []uint16
	// Owners pins the memory that string, bytes and string-array cells borrow
	// without copying. Reset and BatchPool.Put release it; an operator that
	// keeps a cell beyond the batch's life must clone it first (see
	// vectorized/measure's cloneOneValue) or pin the same owners.
	Owners Owners
	// Hints describes the batch's rows to an operator that can exploit it. A
	// producer sets it only when it is exact, and an operator that copies rows into
	// another batch does not carry it over (see BatchHints).
	Hints BatchHints
	Len   int
	// Lent marks a batch whose Columns were lent by a storage batch that the
	// batch's Owners hold. The columns return to their pools when Owners are
	// released, so a lent batch is single-use: Reset drops its columns instead
	// of clearing them and BatchPool.Put discards it rather than pooling it.
	Lent bool
}

RecordBatch is the unit of work flowing through the pipeline. All columns share Len logical rows. Selection optionally narrows that to a subset.

Selection contract:

  • nil → all rows in [0, Len) are active
  • [] → zero rows active (post-fusible-filter empty case)
  • non-empty → only the listed row indices are active

Operators must use ActiveLen() to compute the effective row count.

func NewRecordBatch

func NewRecordBatch(schema *BatchSchema, capacity int) *RecordBatch

NewRecordBatch allocates a batch with column capacities sized to capacity rows.

func (*RecordBatch) ActiveLen

func (b *RecordBatch) ActiveLen() int

ActiveLen returns the number of rows operators should process.

nil Selection → Len. Non-nil Selection → len(Selection), even when zero.

func (*RecordBatch) ReleaseOwners added in v0.12.0

func (b *RecordBatch) ReleaseOwners()

ReleaseOwners drops the references this batch holds on borrowed memory. After it returns no borrowed string, bytes or string-array cell of the batch may be read. It is idempotent.

func (*RecordBatch) Reset

func (b *RecordBatch) Reset()

Reset clears every column and the selection vector and releases the batch's owners. Schema is preserved.

func (*RecordBatch) SeriesRuns added in v0.12.0

func (b *RecordBatch) SeriesRuns(dst []int) ([]int, bool)

SeriesRuns appends to dst the exclusive end of every maximal run of consecutive active rows that belong to one series, as positions in the active order (the i-th active row is row i of a nil Selection, Selection[i] otherwise), and reports true. It reports false, leaving dst alone, when the batch does not say which series its rows belong to (Hints.SeriesKnown is unset). A batch with no active rows yields no runs.

The runs are the generic description of where a grouping key changes: a key that is a function of the series is constant within each run, so an aggregation looks its group up once per run instead of once per row.

type TagFamilyGroup

type TagFamilyGroup struct {
	Family  string
	Columns []int
}

TagFamilyGroup pre-computes the (family, [column indices]) layout used by the row-by-row serializer. Storing it on the schema lets the hot path stamp out one TagFamily per family per row without re-grouping or allocating a `map[string]*modelv1.TagFamily` on every row.

type TimeOrder added in v0.12.0

type TimeOrder int8

TimeOrder is the direction in which timestamps run within a single series of a batch's active rows.

const (
	// TimeOrderUnknown promises nothing.
	TimeOrderUnknown TimeOrder = 0
	// TimeOrderAsc means timestamps never decrease from one active row to the next
	// of the same series run.
	TimeOrderAsc TimeOrder = 1
	// TimeOrderDesc means timestamps never increase.
	TimeOrderDesc TimeOrder = -1
)

TimeOrder values.

type TypedColumn

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

TypedColumn is a generic Column with element type T. One instance per supported T — use the typed constructors below.

A column normally owns its backing slice. Borrow lends it a slice owned by someone else (a storage cursor's decoded values); such a column is read-only as far as the backing array goes: every mutator that would write element memory first replaces the slice with a private copy, and Reset and the pool release drop the slice instead of truncating it, so a pooled column can never write into memory it only borrowed.

func NewBytesColumn

func NewBytesColumn(capacity int) *TypedColumn[[]byte]

NewBytesColumn constructs a TypedColumn[[]byte] with the given capacity.

func NewColumnFromSlice added in v0.12.0

func NewColumnFromSlice[T any](t ColumnType, data []T) *TypedColumn[T]

NewColumnFromSlice returns a column of type t that owns data, with no nulls. The column keeps data as its backing array, so the caller must not use data afterwards.

func NewFieldValueColumn

func NewFieldValueColumn(capacity int) *TypedColumn[*modelv1.FieldValue]

NewFieldValueColumn is the field-side counterpart of NewTagValueColumn.

func NewFloat64Column

func NewFloat64Column(capacity int) *TypedColumn[float64]

NewFloat64Column constructs a TypedColumn[float64] with the given capacity.

func NewInt64ArrayColumn

func NewInt64ArrayColumn(capacity int) *TypedColumn[[]int64]

NewInt64ArrayColumn constructs a TypedColumn[[]int64] with the given capacity.

func NewInt64Column

func NewInt64Column(capacity int) *TypedColumn[int64]

NewInt64Column constructs a TypedColumn[int64] with the given capacity.

func NewStrArrayColumn

func NewStrArrayColumn(capacity int) *TypedColumn[[]string]

NewStrArrayColumn constructs a TypedColumn[[]string] with the given capacity.

func NewStringColumn

func NewStringColumn(capacity int) *TypedColumn[string]

NewStringColumn constructs a TypedColumn[string] with the given capacity.

func NewTagValueColumn

func NewTagValueColumn(capacity int) *TypedColumn[*modelv1.TagValue]

NewTagValueColumn constructs a TypedColumn[*modelv1.TagValue] passthrough column. Cells hold the original *modelv1.TagValue pointers from the scan source; the egress serializer returns those pointers directly, avoiding the decode-into-typed / re-encode-into-protobuf round trip that otherwise dominates allocation cost when no operator consumes the column.

func (*TypedColumn[T]) Append

func (c *TypedColumn[T]) Append(v T)

Append adds a value, marking it valid.

func (*TypedColumn[T]) AppendNull

func (c *TypedColumn[T]) AppendNull()

AppendNull adds a zero-value placeholder and marks it null.

func (*TypedColumn[T]) AppendSlice added in v0.12.0

func (c *TypedColumn[T]) AppendSlice(vs []T)

AppendSlice adds every value of vs, marking them valid.

func (*TypedColumn[T]) Borrow added in v0.12.0

func (c *TypedColumn[T]) Borrow(src []T)

Borrow makes the column a zero-copy view of src with every row valid. src must stay valid and unmodified until the column is Reset or released; the caller is responsible for pinning whatever owns it. The column's previous contents are discarded.

The slice is capacity-limited, so even a stray append reallocates rather than writing past src.

func (*TypedColumn[T]) Borrowed added in v0.12.0

func (c *TypedColumn[T]) Borrowed() bool

Borrowed reports whether the column's backing slice belongs to someone else.

func (*TypedColumn[T]) Data

func (c *TypedColumn[T]) Data() []T

Data returns the backing slice for bulk access. The caller must not write through it when Borrowed reports true.

func (*TypedColumn[T]) IsNull

func (c *TypedColumn[T]) IsNull(i int) bool

IsNull reports whether row i is null.

func (*TypedColumn[T]) Len

func (c *TypedColumn[T]) Len() int

Len returns the current row count.

func (*TypedColumn[T]) MarkNullAt

func (c *TypedColumn[T]) MarkNullAt(i int)

MarkNullAt marks an existing row at index i as null. Length is unchanged.

func (*TypedColumn[T]) MayHaveNulls added in v0.12.0

func (c *TypedColumn[T]) MayHaveNulls() bool

MayHaveNulls reports whether any row may be null. False is a guarantee, so a range loop over Data can skip the per-row validity check; true only means the check is needed.

func (*TypedColumn[T]) Reset

func (c *TypedColumn[T]) Reset()

Reset clears length and validity. Capacity is retained, except that a borrowed slice is dropped and the column returns to its own array: the borrowed one is never the column's to truncate and refill.

func (*TypedColumn[T]) SetAt

func (c *TypedColumn[T]) SetAt(i int, v T)

SetAt overwrites the value at index i without changing length or validity. The validity bit at i is cleared (row becomes valid). Panics if i is out of range — matches the same contract as a direct slice write.

func (*TypedColumn[T]) SetNullsFromValidity added in v0.12.0

func (c *TypedColumn[T]) SetNullsFromValidity(valid []byte)

SetNullsFromValidity replaces the column's null set with an Arrow validity bitmap over the column's rows: bit i of valid (least significant bit first) set means row i holds a value, clear means it is null. valid must hold at least (Len()+7)/8 bytes and is not retained.

func (*TypedColumn[T]) Type

func (c *TypedColumn[T]) Type() ColumnType

Type returns the static ColumnType this column was built with.

Directories

Path Synopsis
Package frame defines the shared, engine-agnostic non-proto columnar binary frame carried as the SendResponse.body for a vec-native query topic.
Package frame defines the shared, engine-agnostic non-proto columnar binary frame carried as the SendResponse.body for a vec-native query topic.
Package measure implements measure-specific vectorized operators (scan, cursor, extract, limit, group-by, aggregation, top, output serialization).
Package measure implements measure-specific vectorized operators (scan, cursor, extract, limit, group-by, aggregation, top, output serialization).
frame
Package frame binds the shared vec columnar frame codec (pkg/query/vectorized/frame) to the measure engine.
Package frame binds the shared vec columnar frame codec (pkg/query/vectorized/frame) to the measure engine.
plan
Package plan is the vectorized measure-query plan tree (G8).
Package plan is the vectorized measure-query plan tree (G8).
Package stream implements stream-specific vectorized query operators: the pull pipeline that scans elements into columnar batches and merges them in index or timestamp order at egress.
Package stream implements stream-specific vectorized query operators: the pull pipeline that scans elements into columnar batches and merges them in index or timestamp order at egress.
frame
Package frame binds the shared vec columnar frame codec (pkg/query/vectorized/frame) to the stream engine.
Package frame binds the shared vec columnar frame codec (pkg/query/vectorized/frame) to the stream engine.
Package trace implements trace-specific vectorized query operators: the two-phase pull pipeline that resolves trace IDs (Phase 1) and materializes spans grouped per trace (Phase 2).
Package trace implements trace-specific vectorized query operators: the two-phase pull pipeline that resolves trace IDs (Phase 1) and materializes spans grouped per trace (Phase 2).

Jump to

Keyboard shortcuts

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