Documentation
¶
Overview ¶
Package measure implements measure-specific vectorized operators (scan, cursor, extract, limit, group-by, aggregation, top, output serialization).
Index ¶
- Constants
- Variables
- func AppendColumnRange(dst, src vectorized.Column, srcPos, n int) error
- func AppendColumnRangeCoerced(dst, src vectorized.Column, srcPos, n int) error
- func ApplyTopToReduce(reduced []*vectorized.RecordBatch, spec ReduceTopSpec, batchSize int) ([]*vectorized.RecordBatch, error)
- func ApplyTopToReduceContext(ctx context.Context, reduced []*vectorized.RecordBatch, spec ReduceTopSpec, ...) ([]*vectorized.RecordBatch, error)
- func BuildBatchSchema(measureSchema *databasev1.Measure, opts model.MeasureQueryOptions) (*vectorized.BatchSchema, error)
- func BuildMeasureBatchFromResult(r *model.MeasureResult, schema *vectorized.BatchSchema) (*model.MeasureBatch, error)
- func BuildOperators(opts model.MeasureQueryOptions, schema *vectorized.BatchSchema, ...) ([]vectorized.BreakerOperator, error)
- func DecodeFramesPerSource(frames [][]byte) ([][]*measurev1.InternalDataPoint, error)
- func DecodeFramesToInternalDataPoints(frames [][]byte) ([]*measurev1.InternalDataPoint, error)
- func DecodeMeasurePatternRequest(body []byte) (*measurev1.InternalQueryRequest, []model.IndexedPattern, error)
- func DrainPipelineToFrame(ctx context.Context, p *vectorized.Pipeline, schema *vectorized.BatchSchema) ([]byte, error)
- func EncodeMeasurePatternRequest(req *measurev1.InternalQueryRequest, patterns []model.IndexedPattern) ([]byte, error)
- func FormatReduceOutput(b *vectorized.RecordBatch) string
- func KeyComponentSupported(t vectorized.ColumnType) bool
- func PatternDecodeReservationBytes(body []byte) int64
- func PatternEncodeReservationBytes(req *measurev1.InternalQueryRequest, patterns []model.IndexedPattern) int64
- func RecordBatchExecution(bool)
- func RecordBatchResultClosed()
- func RecordBatchResultOpened()
- func RecordNativeFrameRows(uint64)
- func RecordNativeInputRows(uint64)
- func RecordNativeLeafCall()
- func ReduceFramesToInternalDataPoints(frames [][]byte, keyTagFamily string, keyTagNames []string, ...) ([]*measurev1.InternalDataPoint, error)
- func SerializeDataPointsToFrame(idps []*measurev1.InternalDataPoint) ([]byte, error)
- func SerializedRowCount() int64
- func SetRunsDisabled(disabled bool) (previous bool)
- func SetRunsVerification(verify bool) (previous bool)
- func WithFinalBatchSerialization(ctx context.Context) context.Context
- type AggFunc
- type AggMode
- type AggReduceSpec
- type AggSpec
- type AggValuePath
- func ReducePartialBatches(partials []*vectorized.RecordBatch, keyTagFamily string, keyTagNames []string, ...) ([]*vectorized.RecordBatch, AggValuePath, error)
- func ReducePartialBatchesToSchema(partials []*vectorized.RecordBatch, target *vectorized.BatchSchema, ...) ([]*vectorized.RecordBatch, AggValuePath, error)
- func ReduceRawFrames(frames [][]byte, keyTagFamily string, keyTagNames []string, bucketed bool, ...) ([]*vectorized.RecordBatch, AggValuePath, error)
- func ReduceRawFramesToSchema(frames [][]byte, target *vectorized.BatchSchema, scopes []int64, ...) ([]*vectorized.RecordBatch, AggValuePath, error)
- type BatchAggregation
- func (a *BatchAggregation) Close() error
- func (a *BatchAggregation) Consume(_ context.Context, b *vectorized.RecordBatch) error
- func (a *BatchAggregation) Finalize(_ context.Context) error
- func (a *BatchAggregation) Init(ctx context.Context) error
- func (a *BatchAggregation) NextBatch(_ context.Context) (*vectorized.RecordBatch, error)
- func (a *BatchAggregation) OutputSchema() *vectorized.BatchSchema
- func (a *BatchAggregation) SetAllKeysIndexResolved(allResolved bool)
- func (a *BatchAggregation) SetDedupScope(scope int64)
- func (a *BatchAggregation) SortInsertionByBucket()
- type BatchColumnFilter
- type BatchExecutionCounters
- type BatchGroupBy
- func (g *BatchGroupBy) Close() error
- func (g *BatchGroupBy) Consume(_ context.Context, b *vectorized.RecordBatch) error
- func (g *BatchGroupBy) Finalize(_ context.Context) error
- func (g *BatchGroupBy) Init(ctx context.Context) error
- func (g *BatchGroupBy) NextBatch(_ context.Context) (*vectorized.RecordBatch, error)
- func (g *BatchGroupBy) OutputSchema() *vectorized.BatchSchema
- type BatchLimit
- type BatchQueryRequest
- type BatchQueryResult
- type BatchScan
- type BatchSourceFromBatchResult
- type BatchTimeBucket
- func (bt *BatchTimeBucket) Close() error
- func (bt *BatchTimeBucket) Init(ctx context.Context) error
- func (bt *BatchTimeBucket) NextBatch(ctx context.Context) (*vectorized.RecordBatch, error)
- func (bt *BatchTimeBucket) OutputSchema() *vectorized.BatchSchema
- func (bt *BatchTimeBucket) SetAllKeysIndexResolved(allResolved bool)
- type BatchTop
- func (t *BatchTop) Close() error
- func (t *BatchTop) Consume(_ context.Context, b *vectorized.RecordBatch) error
- func (t *BatchTop) Finalize(_ context.Context) error
- func (t *BatchTop) Init(ctx context.Context) error
- func (t *BatchTop) NextBatch(_ context.Context) (*vectorized.RecordBatch, error)
- func (t *BatchTop) OutputSchema() *vectorized.BatchSchema
- type FrameEmitter
- type FrameLimits
- type FrameStreamEmitter
- type PartialReducer
- func (r *PartialReducer) Close()
- func (r *PartialReducer) Consume(b *vectorized.RecordBatch) error
- func (r *PartialReducer) ConsumeScoped(b *vectorized.RecordBatch, scope int64) error
- func (r *PartialReducer) Finish() ([]*vectorized.RecordBatch, AggValuePath, error)
- func (r *PartialReducer) FinishContext(ctx context.Context) ([]*vectorized.RecordBatch, AggValuePath, error)
- func (r *PartialReducer) Groups() int
- func (r *PartialReducer) OutputSchema() *vectorized.BatchSchema
- type RawFrameSource
- type ReduceTopSpec
- type SeriesCursor
- func (c *SeriesCursor) Advance(n int)
- func (c *SeriesCursor) Close()
- func (c *SeriesCursor) Current() (*model.MeasureResult, int)
- func (c *SeriesCursor) Err() error
- func (c *SeriesCursor) Exhausted() bool
- func (c *SeriesCursor) Init(qr model.MeasureQueryResult)
- func (c *SeriesCursor) RemainingInSeries() int
- type VectorizedConfig
- type VectorizedMIterator
- func (v *VectorizedMIterator) Close() error
- func (v *VectorizedMIterator) Current() []*measurev1.InternalDataPoint
- func (v *VectorizedMIterator) EmitFrame(ctx context.Context) ([]byte, error)
- func (v *VectorizedMIterator) EmitFrames(ctx context.Context, limits FrameLimits, emit func([]byte) error) error
- func (v *VectorizedMIterator) Err() error
- func (v *VectorizedMIterator) Next() bool
- func (v *VectorizedMIterator) Pipeline() *vectorized.Pipeline
- func (v *VectorizedMIterator) Schema() *vectorized.BatchSchema
Constants ¶
const MaxMeasurePatternRequestBytes = 4 << 20
MaxMeasurePatternRequestBytes bounds the encoded envelope independently of query memory admission. A request below this cap can still exceed the worker's decode reservation or the memory remaining for query execution.
Variables ¶
var ErrAggModeNotImplemented = errors.New("vectorized.measure: BatchAggregation mode not implemented")
ErrAggModeNotImplemented is returned by Consume / Finalize / NextBatch when AggMode falls outside the implemented modes. AggModeAll and AggModeMap have been implemented since G9f.2; AggModeReduce ships in G9f.3. The error remains for any future mode addition that lands without operator support, so an out-of-range mode fails loud rather than silently degrading.
Functions ¶
func AppendColumnRange ¶
func AppendColumnRange(dst, src vectorized.Column, srcPos, n int) error
AppendColumnRange delegates to the shared vectorized helper.
func AppendColumnRangeCoerced ¶ added in v0.11.2
func AppendColumnRangeCoerced(dst, src vectorized.Column, srcPos, n int) error
AppendColumnRangeCoerced copies n rows starting at srcPos from src into dst. When dst and src share the same underlying type it delegates to AppendColumnRange for the fast path. When dst is ColumnTypeTagValue and src is a native column type, each source cell is promoted to a *modelv1.TagValue wrapper so the merged schema remains type-consistent even across groups whose schemas diverged on this column. The symmetric ColumnTypeFieldValue coercion is handled similarly. Any other type mismatch delegates to AppendColumnRange so the existing error path is preserved.
Directional invariant: BuildMultiGroupBatchSchema only ever promotes (native → TagValue/FieldValue) on type divergence; it never demotes the other direction. So this helper handles "src is native, dst is passthrough" — never the inverse. If a future phase introduces a passthrough-to-native reshape it will surface here via the delegate's "dst <type> vs src tagvalue" error, which is the correct loud-failure outcome.
func ApplyTopToReduce ¶
func ApplyTopToReduce(reduced []*vectorized.RecordBatch, spec ReduceTopSpec, batchSize int) ([]*vectorized.RecordBatch, error)
ApplyTopToReduce composes the Reduce output through a BatchTop operator, returning the top-N rows by FieldName. This is the liaison-side completion of the distributed Top-over-Agg pattern: data nodes emit AggModeMap partials (optionally pre-topped via the per-node BatchTop), the liaison Reduces them, then a second BatchTop selects the global top-N. Mirrors the row path's two-pass Top approach — sorting by partial value on each node, then re-sorting the merged reductions on the coordinator.
fieldName MUST match a RoleField column in the reduced output schema (typically the AggReduceSpec.OutputName). N <= 0 returns reduced input unchanged.
reduced is normally ReduceRawFrames/ReducePartialBatches's own NextBatch-paginated output, so in practice no single batch here exceeds batchSize rows. But this function does not control its caller's batching discipline either, and BatchTop.Consume shares BatchAggregation's exposure to the design/0.12.0/limit-after-aggregation §5 uint16 wraparound (both drive their per-row loop from activeIndices), so an oversized batch is chunked via ConsumeChunked rather than assumed away.
func ApplyTopToReduceContext ¶ added in v0.12.0
func ApplyTopToReduceContext(ctx context.Context, reduced []*vectorized.RecordBatch, spec ReduceTopSpec, batchSize int) ([]*vectorized.RecordBatch, error)
ApplyTopToReduceContext is ApplyTopToReduce that stops with the context's error once ctx is done.
func BuildBatchSchema ¶
func BuildBatchSchema(measureSchema *databasev1.Measure, opts model.MeasureQueryOptions) (*vectorized.BatchSchema, error)
BuildBatchSchema derives a BatchSchema from a Measure schema and a query's projection list. The output column order is fixed:
timestamp, version, sid, shardID, then projected tags (in TagProjection order, family-by-family, name-by-name), then projected fields (in FieldProjection order).
Tag families and tag names that are not present in the Measure schema are dropped — the row path silently skips unknown tags as well, so this matches existing semantics. Fields not present in the schema yield a Null-typed column so projection still produces a slot in the output.
Column types — native by default:
Every projected tag and field whose schema type maps to a vectorized column type (tagTypeToColumnType / fieldTypeToColumnType) is emitted as a NATIVE typed column (int64 / float64 / string / bytes / int64[] / string[]). The storage decoder fills those columns without building the *modelv1.TagValue / *modelv1.FieldValue wrapper (strings and bytes borrow the cursor's decoded memory, numerics are decoded in bulk), so a scan pays per-cell wrapper allocations only for the rows that actually reach the egress serializer (serialize.go rebuilds one wrapper per surviving cell). Filters, limits, aggregation and top-N shrink that set before egress; a plain scan that emits every row pays the same wrapper cost the decode step used to pay, just later.
Passthrough columns (ColumnTypeTagValue / ColumnTypeFieldValue) remain only where a native column cannot represent the cell: a projected tag that the Measure schema does not declare (the null-slot case), and the multi-group / mixed-version divergence handled elsewhere (plan.BuildMultiGroupBatchSchema, decodeDistributedRowSources). A projected field that the schema does not declare also stays a passthrough column holding nulls.
func BuildMeasureBatchFromResult ¶
func BuildMeasureBatchFromResult(r *model.MeasureResult, schema *vectorized.BatchSchema) (*model.MeasureBatch, error)
BuildMeasureBatchFromResult converts a *model.MeasureResult produced by a row-shaped MeasureQueryResult.Pull() call into a *model.MeasureBatch whose columns match the supplied BatchSchema.
This is the G5b "dual-emit" wrapper helper: the storage layer can implement MeasureBatchResult.PullBatch by calling its existing Pull() and passing the result through this converter. It preserves the existing row-path decode pipeline; the architectural decode-elimination is left to G5c/G5d (block_cursor native column emit).
Schema-declared tag/field columns missing from the result are null-filled using pbv1.Null{Tag,Field}Value singletons — matching the multi-group projection behavior in fillTags / fillFields when one group's schema lacks a tag the other has.
Returns (nil, nil) when r is nil. Returns (nil, err) when a length invariant is violated (a value slice is shorter than the timestamp count).
func BuildOperators ¶
func BuildOperators( opts model.MeasureQueryOptions, schema *vectorized.BatchSchema, tracker *vectorized.MemoryTracker, batchSize int, mode AggMode, ) ([]vectorized.BreakerOperator, error)
BuildOperators translates the GroupBy + Agg slice of MeasureQueryOptions into a list of BreakerOperators that, chained after the scan source, form the vectorized aggregation pipeline.
Routing rules:
- GroupBy + Agg both set → emit a single BatchAggregation. The operator's own keyIndex map produces per-group buckets and folds the agg slot; a separate BatchGroupBy would double the row materialization.
- Agg set without GroupBy → scalar reduce: a BatchAggregation with no key columns. Every row maps to one group, so a single output row is emitted carrying the first-seen projected tags plus the agg result, matching the row path's aggAllIterator.
- GroupBy set without Agg → raw GroupBy: a first-seen-row-per-group BatchGroupBy. The output preserves the input schema; one row per group is emitted in group-insertion order, matching the row path's groupIterator + processor.go's current[0] read.
- Neither set → empty operator list; caller emits raw rows.
tracker is the per-pipeline MemoryTracker (G7a); it must be non-nil when any operator is emitted so per-group reservations route to the shared budget. batchSize controls the operator's output pagination.
mode selects the BatchAggregation strategy when an agg operator is built (Agg set): AggModeAll for single-node final reduce; AggModeMap for the distributed Map phase (G9f.2) that emits typed-column partials. mode is ignored for the raw-GroupBy branch (BatchGroupBy doesn't carry partial state — first-seen-row per group is already the final shape). AggModeReduce is rejected here loudly; its operator is built by the liaison-side reduce plan (G9f.3), not via BuildOperators.
func DecodeFramesPerSource ¶
func DecodeFramesPerSource(frames [][]byte) ([][]*measurev1.InternalDataPoint, error)
DecodeFramesPerSource decodes a sequence of vec raw frame bodies and returns one []*measurev1.InternalDataPoint slice per non-empty frame — preserving the per-data-node grouping the row path's sortedMIterator + sort.NewItemIter merger needs to dedup replicas. Each data node's scan output is internally sort-field ordered; sort.NewItemIter merges the per-source streams and loadOneGroup's hashDataPoint map removes (sid, timestamp) duplicates within each equal-sortField group. Concatenating into a single slice (as DecodeFramesToInternalDataPoints does) defeats the dedup because duplicate rows from different sources end up in different sortField groups across the flat sequence.
nil / empty frame bodies produce no slice in the output — the codec carve-out for empty bodies is honored here too.
func DecodeFramesToInternalDataPoints ¶
func DecodeFramesToInternalDataPoints(frames [][]byte) ([]*measurev1.InternalDataPoint, error)
DecodeFramesToInternalDataPoints decodes a sequence of vec raw frame bodies and concatenates their active rows into a single []*measurev1.InternalDataPoint, ready to feed the row-side pushedDownAggregatedIterator (agg path's flatten step).
For the NON-agg distributed merge path use DecodeFramesPerSource instead — concatenation here destroys the per-source ordering the sortedMIterator's cross-iterator merge + (sid, timestamp) dedup depends on, which is what caused replica duplicates to slip past the dedup map under flag-on.
nil/empty bodies are skipped — the codec layer's RawFrameCodec carve-out returns nil for an empty distributed result and the decoder is below that carve-out.
func DecodeMeasurePatternRequest ¶ added in v0.12.0
func DecodeMeasurePatternRequest(body []byte) (*measurev1.InternalQueryRequest, []model.IndexedPattern, error)
DecodeMeasurePatternRequest validates all lengths and counts before decoding payloads.
func DrainPipelineToFrame ¶
func DrainPipelineToFrame(ctx context.Context, p *vectorized.Pipeline, schema *vectorized.BatchSchema) ([]byte, error)
DrainPipelineToFrame consumes a vec pipeline and emits one columnar frame. Native scalar batches are encoded as they arrive, releasing borrowed scan storage before the next pull. Their wire buffers are joined into one response without materializing coalescing columns. A single native batch needs no join. Schemas requiring passthrough or array conversion use the coalescing fallback.
schema is the propagated terminal-operator output schema (typically the same as the egress pool's). It MUST match each emitted batch — a mismatch is a planner bug, not a data error, so this function will fail loud on a per-batch shape check instead of silently coercing.
The unary codec contract carries one body per response (api/data/codec.go), so encoded chunks and the final frame still require memory proportional to input.
The caller retains responsibility for closing the pipeline.
func EncodeMeasurePatternRequest ¶ added in v0.12.0
func EncodeMeasurePatternRequest(req *measurev1.InternalQueryRequest, patterns []model.IndexedPattern) ([]byte, error)
EncodeMeasurePatternRequest writes a bounded versioned envelope without changing protobuf contracts.
func FormatReduceOutput ¶
func FormatReduceOutput(b *vectorized.RecordBatch) string
FormatReduceOutput is a debug helper for the topology matrix harness: it renders the reduced batch as "key1=v1,key2=v2|<aggname>=<val>" lines for stable, sorted comparison against the AggModeAll oracle.
func KeyComponentSupported ¶ added in v0.12.0
func KeyComponentSupported(t vectorized.ColumnType) bool
KeyComponentSupported reports whether appendKeyComponent has a real encoding for t. Array column types have none — appendKeyComponent silently leaves dst unchanged for them instead of failing loud — so any caller that keys rows off such a column would collapse every row into one group. The analyzer's Agg/GroupBy tag-target rejection consults this predicate so its rejection list and this operator's actual behavior cannot drift apart (design §6).
func PatternDecodeReservationBytes ¶ added in v0.12.0
PatternDecodeReservationBytes covers the retained wire body, copied strings and the object graph created by protobuf decoding. The conservative expansion allowance is intentionally larger than encoding's byte-buffer charge: compact repeated/nested messages can allocate much more than their wire size. Reserve before decoding and retain the charge through response completion in the transport scope. Callers must enforce MaxMeasurePatternRequestBytes first. At that wire cap, this policy exceeds a 256 MiB query budget; the cap guarantees bounded parsing, not admission under every configured query memory budget.
func PatternEncodeReservationBytes ¶ added in v0.12.0
func PatternEncodeReservationBytes(req *measurev1.InternalQueryRequest, patterns []model.IndexedPattern) int64
PatternEncodeReservationBytes covers the temporary protobuf buffer and the enclosing wire body, plus bounded pattern strings, records and allocation overhead. The source request already exists; encoding does not recreate its object graph. Reserve before encoding and retain the charge until all broadcast futures finish, since transports can still reference the body after Broadcast.
func RecordBatchExecution ¶ added in v0.12.0
func RecordBatchExecution(bool)
RecordBatchExecution is disabled outside querymetrics builds.
func RecordBatchResultClosed ¶ added in v0.12.0
func RecordBatchResultClosed()
RecordBatchResultClosed is disabled outside querymetrics builds.
func RecordBatchResultOpened ¶ added in v0.12.0
func RecordBatchResultOpened()
RecordBatchResultOpened is disabled outside querymetrics builds.
func RecordNativeFrameRows ¶ added in v0.12.0
func RecordNativeFrameRows(uint64)
RecordNativeFrameRows is disabled outside querymetrics builds.
func RecordNativeInputRows ¶ added in v0.12.0
func RecordNativeInputRows(uint64)
RecordNativeInputRows is disabled outside querymetrics builds.
func RecordNativeLeafCall ¶ added in v0.12.0
func RecordNativeLeafCall()
RecordNativeLeafCall is disabled outside querymetrics builds.
func ReduceFramesToInternalDataPoints ¶
func ReduceFramesToInternalDataPoints( frames [][]byte, keyTagFamily string, keyTagNames []string, aggSpecs []AggReduceSpec, topSpec *ReduceTopSpec, batchSize int, tracker *vectorized.MemoryTracker, ) ([]*measurev1.InternalDataPoint, error)
ReduceFramesToInternalDataPoints is the liaison-side composition for distributed agg queries under flag-on: it decodes the per-data-node partial frames, runs the (shard, group)-deduped Reduce, optionally applies a final Top-N (when topSpec.N > 0), and serializes the resulting batches back to []*measurev1.InternalDataPoint so the row-side pushedDownAggregatedIterator + downstream MIterator surface stay unchanged.
The conversion back to proto is the price of bridging vec output into the row-path liaison's existing iterator. Once the row-path distributedPlan is replaced by a fully vec-distributed plan (out of scope for G9f.5), this round trip drops out.
Empty input (no non-empty frames) returns an empty slice with no error — matches the row path's behavior when every data node returned an empty distributed result.
func SerializeDataPointsToFrame ¶
func SerializeDataPointsToFrame(idps []*measurev1.InternalDataPoint) ([]byte, error)
SerializeDataPointsToFrame is the fallback wire-emit path for iterator wrappers (hiddenTagsMIterator, sortedMIterator) whose internal sort / strip / cross-group merge logic operates on []*InternalDataPoint rather than on a vec Pipeline. The wrapper drains itself via the row-side Next / Current API (so its existing strip / merge / dedup logic still runs); the resulting rows are reverse-serialized into a passthrough RecordBatch, convertPassthroughForFrame decodes the passthrough columns to typed wire columns, and frame.Encode produces the body.
This path is less efficient than the vec native pipeline drain — it allocates a *modelv1.TagValue / *FieldValue per cell during reverse- serialize — but it keeps the wrapper's egress semantics intact end- to-end on the wire (hidden tags stripped, cross-group order honored, version dedup applied) without re-implementing each one in columnar form.
idps in the empty/zero case yields a nil body, matching the codec layer's RawFrameCodec carve-out for empty distributed results.
func SerializedRowCount ¶ added in v0.12.0
func SerializedRowCount() int64
SerializedRowCount returns how many rows this process has materialized as InternalDataPoints. Tests use its delta to check that a result is converted to rows only once, at egress.
func SetRunsDisabled ¶ added in v0.12.0
SetRunsDisabled switches the runs fast paths of BatchAggregation and BatchTimeBucket off (true) or on (false) and returns the previous setting. It is for tests that compare the fast paths with the per-row path.
func SetRunsVerification ¶ added in v0.12.0
SetRunsVerification makes the runs fast paths cross-check every run against the rows it covers (true) and returns the previous setting. It is for tests.
Types ¶
type AggFunc ¶
type AggFunc int
AggFunc selects the reduction function applied to a column.
const ( AggSum AggFunc = iota AggCount AggMin AggMax AggMean // AggCountDistinct counts the distinct non-null values of the target // (design §7.3). It is exact and charged per inserted value against // the shared MemoryTracker, unlike the other functions' fixed-size // per-group accumulators. AggCountDistinct )
AggFunc values.
type AggMode ¶
type AggMode int
AggMode selects the per-node aggregation strategy.
- AggModeAll — single-node full reduce. emits one final value per (group, agg).
- AggModeMap — distributed Map phase (G9f.2). Emits a typed-column partial batch (one row per group) carrying the Partial state from aggregation.Map: Value for SUM/COUNT/MIN/MAX, plus a sidecar Count column (named "<output>__agg_count") for MEAN. The batch is prefixed with a RoleShardID column populated from the input batch's shard-id column at the first row that creates each group (matching the row path's incidental "first-idp" rule, measure_plan_aggregation.go:285); scalar reduce (len(keyIndices)==0) emits shard_id=0 (matching the row path's aggAllIterator.Current() at :364). The partial batch is then serialized by pkg/query/vectorized/measure/frame.Encode for cluster transport.
- AggModeReduce — coordinator's Reduce phase (G9f.3). Consumes the typed-column partial batches emitted by AggModeMap (one row per (shard, group)), dedupes them on (shard_id, group_key) — replica duplicates of the same shard collapse to one contribution, mirroring the row path's deduplicateAggregatedDataPointsWithShard — and combines them through aggregation.Reduce[N] into a final batch shaped like AggModeAll (tags + final value column, no shard column, no count sidecar). The aggregation.Reduce[N].Val() handles MEAN finalization (sum÷count) so the emit path stays type-symmetric with AggModeAll.
type AggReduceSpec ¶
AggReduceSpec configures one aggregation output for the liaison-side Reduce. OutputName MUST match the column name produced by the data-node AggModeMap for the same aggregation (i.e. the AggSpec.Output that drove buildAggOutputLayout). Func selects the reducer (must agree with the Map-side function — SUM-Map paired with SUM-Reduce, MEAN with MEAN, etc).
type AggSpec ¶
type AggSpec struct {
Output string
Func AggFunc
InputCol int // index into the input schema; must be int64 or float64
// HideTag is true when InputCol is a RoleTag column the analyzer
// injected into the projection solely so this spec could bind to it
// (design §5.2, model.MeasureAgg.HideTag). NewBatchAggregation excludes
// such a column from the carried-forward tag set so it is not also
// emitted as a first-seen tag beside its own result field.
HideTag bool
// TargetIndexResolved is true when InputCol resolves from the series
// index (an entity tag or an IndexRule-indexed tag), so its value is
// guaranteed constant and non-null across every row of one series
// (design §7.7, stage 8a run-folding). Only COUNT and COUNT_DISTINCT
// use it — see BatchAggregation.foldSpan.
TargetIndexResolved bool
}
AggSpec configures one aggregation output column.
type AggValuePath ¶
type AggValuePath string
AggValuePath records which column-type path bindAggReduceSpecs used to resolve the aggregation value column.
const ( // AggValuePathTyped means all agg specs resolved via a native int64 or // float64 column — the normal AggModeMap partial path. AggValuePathTyped AggValuePath = "typed" // AggValuePathFieldValueFallback means at least one agg spec fell back // to a ColumnTypeFieldValue passthrough column because no native typed // column was found — the DataPoint-egress passthrough path. AggValuePathFieldValueFallback AggValuePath = "fieldvalue-fallback" // AggValuePathUnresolved means bindAggReduceSpecs could not find any // matching column for at least one agg spec and returned an error. AggValuePathUnresolved AggValuePath = "unresolved" )
AggValuePath constants match the trace tag values required by US-VT-1.
func ReducePartialBatches ¶
func ReducePartialBatches( partials []*vectorized.RecordBatch, keyTagFamily string, keyTagNames []string, bucketed bool, aggSpecs []AggReduceSpec, batchSize int, tracker *vectorized.MemoryTracker, ) ([]*vectorized.RecordBatch, AggValuePath, error)
ReducePartialBatches is the in-memory counterpart of ReduceRawFrames — useful for tests and for callers that have already decoded their partials. Empty batches (nil or Len==0) are skipped; the first non-empty batch defines the schema and structural compatibility is checked against subsequent ones.
Returns the reduced batches and the AggValuePath that describes how the value column was resolved (typed, fieldvalue-fallback, or unresolved).
func ReducePartialBatchesToSchema ¶ added in v0.11.2
func ReducePartialBatchesToSchema( partials []*vectorized.RecordBatch, target *vectorized.BatchSchema, scopes []int64, keyTagFamily string, keyTagNames []string, bucketed bool, aggSpecs []AggReduceSpec, batchSize int, tracker *vectorized.MemoryTracker, ) ([]*vectorized.RecordBatch, AggValuePath, error)
ReducePartialBatchesToSchema is ReducePartialBatches with every non-empty partial first reshaped onto target (see checkPartialLayouts). A nil target keeps ReducePartialBatches' behavior. scopes, when set, holds one replica-dedup scope per partial, in the same order as partials; len(scopes) must equal len(partials). nil puts every partial in one scope.
func ReduceRawFrames ¶
func ReduceRawFrames( frames [][]byte, keyTagFamily string, keyTagNames []string, bucketed bool, aggSpecs []AggReduceSpec, batchSize int, tracker *vectorized.MemoryTracker, ) ([]*vectorized.RecordBatch, AggValuePath, error)
ReduceRawFrames runs the liaison-side Reduce phase on a sequence of vec partial frame bodies. Each frame is decoded into a RecordBatch and fed to a single AggModeReduce BatchAggregation that dedupes (shard_id, group_key) replica duplicates and combines partials across shards via aggregation.Reduce[N].
Empty/nil frame bodies are skipped — a data node emitting an empty distributed result sends a body-less SendResponse and the codec layer passes nil bytes through (see api/data/codec.go's RawFrameCodec carve-out for nil/empty). Treating those as zero-row partials matches the row path, which simply has no contributing rows to combine.
The first non-empty frame defines the partial schema (column count, roles, types, and names). Subsequent frames MUST share that schema — any structural mismatch is a producer bug, not a recoverable data error, and is reported loudly.
keyTagFamily and keyTagNames select which tags form the group key — the same family and names the request's GroupBy used. The family must travel with the names: tag-family validation does not reject the same tag name in two families (design doc §5.1), so resolveKeyIndices matches on (family, name), not name alone — matching the node-side GroupBy's own (plan.go's lookupGroupByKeyIndices). Tags present in the partial schema but NOT listed here are still carried forward in the output as the first-seen value per group (mirrors the data-node operator's first-seen non-key tag rule).
bucketed is true for a time-bucketed GroupBy (design §7.2): the bucket column is resolved as an additional leading key, ahead of keyTagNames. A bucketed reduce whose reference schema carries no RoleTimestamp column is the mixed-version case (design §10) — an older data node ignored time_bucket and returned whole-range partials — and resolveKeyIndices hard-errors rather than silently collapsing the series to one row.
Returns the final reduced batches in group-insertion order (paginated by batchSize) and the AggValuePath that describes how the value column was resolved. Callers walk the batches sequentially; one row per group.
func ReduceRawFramesToSchema ¶ added in v0.11.2
func ReduceRawFramesToSchema( frames [][]byte, target *vectorized.BatchSchema, scopes []int64, keyTagFamily string, keyTagNames []string, bucketed bool, aggSpecs []AggReduceSpec, batchSize int, tracker *vectorized.MemoryTracker, ) ([]*vectorized.RecordBatch, AggValuePath, error)
ReduceRawFramesToSchema is ReduceRawFrames for partials that may come from groups with different schemas. Every partial is reshaped onto target before reducing (see checkPartialLayouts), so target, not whichever partials happen to arrive, decides the reduced layout. A nil target requires every partial to share one layout, like ReduceRawFrames. scopes, when set, holds one replica-dedup scope per frame, in the same order as frames (its storage group, see BatchAggregation.SetDedupScope); len(scopes) must equal len(frames). nil puts every frame in one scope.
type BatchAggregation ¶
type BatchAggregation struct {
// contains filtered or unexported fields
}
BatchAggregation is a BreakerOperator that groups input rows by the configured key columns and reduces value columns via the configured AggSpec list.
Per-function arithmetic delegates to pkg/query/aggregation, the same package the row-based path uses. This keeps numeric semantics in lockstep across the two paths so a fix in one path is shared by the other.
Output schema = all projected tag columns (in input schema order — keys AND non-key tags) followed by one column per AggSpec. Non-key tags are carried forward as the first-seen value per group, matching the row path's aggregator (pkg/query/logical/measure/measure_plan_aggregation.go), which preserves any tag the request projected even when it is not a GroupBy key.
Output rows are emitted one per group, in group-insertion order, paginated by batchSize.
func NewBatchAggregation ¶
func NewBatchAggregation( input *vectorized.BatchSchema, keyIndices []int, aggs []AggSpec, mode AggMode, batchSize int, tracker *vectorized.MemoryTracker, entrySize int64, ) *BatchAggregation
NewBatchAggregation constructs a BatchAggregation. It builds the output schema internally (keys + agg outputs) and owns its output BatchPool.
tracker carries the per-pipeline memory budget; entrySize is the bytes reserved per new group bucket (key columns + slots + map entry overhead). Pass entrySize=0 to disable per-group bookkeeping. tracker must not be nil — use a large NewMemoryTracker for unit tests that don't care about budget.
Time bucketing (design §7.2) needs no dedicated parameter: when keyIndices contains a RoleTimestamp column, that column is treated as the bucket key — grouping by it is already handled generically by computeKey, and the only bucket-specific behavior (conditional D2 reversal: re-emitting the bucket start as a RoleTimestamp output column) is derived here from that same column. RoleTimestamp never legitimately appears in keyIndices for any other reason, so this inference is unambiguous.
func (*BatchAggregation) Close ¶
func (a *BatchAggregation) Close() error
Close releases the group map and refunds the outstanding memory reservation. Idempotent.
func (*BatchAggregation) Consume ¶
func (a *BatchAggregation) Consume(_ context.Context, b *vectorized.RecordBatch) error
Consume folds every active row into its group's accumulator. Null values are excluded from aggregation (count not incremented; sum/min/max unchanged).
Each new group reserves entrySize bytes from the shared MemoryTracker. If the budget is exhausted, Consume returns the wrapped tracker error and the row's group is not added — partial-batch state is consistent.
AggModeAll and AggModeMap share the per-row fold path; they diverge only at emit time (NextBatch). AggModeReduce uses a parallel combinePartial path: each input row is one (shard, group) partial; replica duplicates (same shard + same group_key) are dropped via dedupSeen, then the Partial is Combine'd into the group's Reduce accumulator. Cross-shard rows that share a group_key are KEPT and combined, matching the row path's deduplicateAggregatedDataPointsWithShard semantics.
func (*BatchAggregation) Finalize ¶
func (a *BatchAggregation) Finalize(_ context.Context) error
Finalize is a no-op for AggModeAll, AggModeMap, and AggModeReduce — Consume eagerly maintains every group's accumulator state (Map or Reduce), so there is no batched flush step.
func (*BatchAggregation) Init ¶
func (a *BatchAggregation) Init(ctx context.Context) error
Init prepares the group map. It does NOT validate the mode — mode rejection happens at the per-method level (Consume/Finalize/NextBatch) so the dispatcher matches the spec's distributed forward-compat language. For AggModeReduce, Init also resets the (shard, group_key) replica-dedup map so the operator can be reused across distributed reduce runs without a fresh allocation per call.
func (*BatchAggregation) NextBatch ¶
func (a *BatchAggregation) NextBatch(_ context.Context) (*vectorized.RecordBatch, error)
NextBatch emits one row per group in group-insertion order, paginated by batchSize. AggModeAll emits final values; AggModeMap emits typed-column partial state plus a leading shard-id column (see AggMode docs). AggModeReduce emits the same shape as AggModeAll — tags + final reduced value — but draws the value from aggregation.Reduce[N].Val() so MEAN finalization (sum÷count) happens inside the reducer.
func (*BatchAggregation) OutputSchema ¶
func (a *BatchAggregation) OutputSchema() *vectorized.BatchSchema
OutputSchema returns the schema of emitted batches: key columns followed by agg output columns.
func (*BatchAggregation) SetAllKeysIndexResolved ¶ added in v0.12.0
func (a *BatchAggregation) SetAllKeysIndexResolved(allResolved bool)
SetAllKeysIndexResolved marks every one of this BatchAggregation's keyIndices as resolved from the series index (an entity tag, or — for the bucket-key case, handled by the caller rather than this flag — any column a single Consume call is already guaranteed to hold constant), enabling the run-folding fast path (design §7.7, stage 8a): a whole Consume call's active rows are folded as one span instead of per row.
The caller is responsible for two guarantees this method does not itself verify: every tag in keyIndices is schema-index-resolved (an entity tag or an IndexRule-indexed tag — never inferred by sampling column values). vectorized/measure/plan.BuildOperators derives it from model.MeasureGroupBy.AllTagsIndexResolved (computed at analyze time from static schema facts). Consume itself splits each batch at series-ID boundaries, so a batch may mix series; BatchTimeBucket's streaming mode additionally pre-splits each batch into single-bucket runs. Defaults to false (per-row behavior) until called.
func (*BatchAggregation) SetDedupScope ¶ added in v0.12.0
func (a *BatchAggregation) SetDedupScope(scope int64)
SetDedupScope sets the scope AggModeReduce's replica dedup applies to the partials consumed next. Shard ids are only unique within a storage group, so the liaison scopes each partial by the group it came from: two groups reporting the same (shard, group key) are separate contributions, not replicas. Defaults to 0, a single scope.
func (*BatchAggregation) SortInsertionByBucket ¶ added in v0.12.0
func (a *BatchAggregation) SortInsertionByBucket()
SortInsertionByBucket stable-sorts emission order by each group's captured bucket timestamp (aggGroup.timeValue, design §7.2), ascending. A no-op when this aggregation carries no bucket key (bucketIdx < 0).
This exists for BatchTimeBucket's map-mode drain: its single persistent aggregator accumulates groups across the whole scan in first-seen order, but map mode exists precisely because the input may not be time-ordered — so emission order needs an explicit sort to satisfy the bucket-ascending output contract (design §7.5). Calling this on a streaming-mode instance is also safe but a no-op in effect: each such instance covers exactly one bucket, so every group already shares the same timeValue and the stable sort leaves insertion order untouched.
type BatchColumnFilter ¶ added in v0.12.0
type BatchColumnFilter struct {
// contains filtered or unexported fields
}
BatchColumnFilter is a FusibleOperator that keeps the rows whose value in one column satisfies a predicate. It narrows the selection and copies nothing. A predicate on a vectorized.ConstColumn, such as an entity tag of a batch lent from one series, is evaluated once per batch: the whole batch is kept or dropped.
The planner does not insert it today (a measure query's criteria are resolved against the series index before rows are read); it is the operator a row filter on scanned tags would use.
func NewBatchColumnFilter ¶ added in v0.12.0
func NewBatchColumnFilter(schema *vectorized.BatchSchema, colIdx int, keep func(col vectorized.Column, row int) bool) *BatchColumnFilter
NewBatchColumnFilter builds a filter on column colIdx of schema. keep must be a pure function of the cell it is given.
func (*BatchColumnFilter) Close ¶ added in v0.12.0
func (f *BatchColumnFilter) Close() error
Close is idempotent and a no-op.
func (*BatchColumnFilter) Init ¶ added in v0.12.0
func (f *BatchColumnFilter) Init(context.Context) error
Init is a no-op: the filter keeps no state.
func (*BatchColumnFilter) OutputSchema ¶ added in v0.12.0
func (f *BatchColumnFilter) OutputSchema() *vectorized.BatchSchema
OutputSchema returns the unchanged input schema.
func (*BatchColumnFilter) Process ¶ added in v0.12.0
func (f *BatchColumnFilter) Process(_ context.Context, b *vectorized.RecordBatch) error
Process narrows b's selection to the rows the predicate keeps.
type BatchExecutionCounters ¶ added in v0.12.0
type BatchExecutionCounters struct {
NativeBatchExecutions uint64
QLBatchExecutions uint64
IntermediateDataPoints uint64
FinalDataPoints uint64
LiveResults int64
NativeLeafCalls uint64
NativeInputRows uint64
NativeFrameRows uint64
}
BatchExecutionCounters records activation of the two real batch callers.
func BatchExecutionStats ¶ added in v0.12.0
func BatchExecutionStats() BatchExecutionCounters
BatchExecutionStats returns zero counters outside querymetrics builds.
type BatchGroupBy ¶
type BatchGroupBy struct {
// contains filtered or unexported fields
}
BatchGroupBy is a BreakerOperator that partitions input rows by the values of one or more key columns. Output preserves the input schema; rows are emitted in group-insertion order, with all rows of the first group flushed before the next group begins.
When firstOnly is set the operator keeps only the first-seen row of each group and drops subsequent rows. This reproduces the row path's raw GroupBy egress: the row aggregator wraps every group in a single InternalDataPoint slice and banyand/query/processor.go reads only current[0] per Next, so a raw GroupBy surfaces exactly one row (the first-seen) per group in group-insertion order.
Memory accounting follows a pessimistic-reserve, refund-unused pattern:
- entrySize is the per-new-group bucket overhead.
- rowSize is the per-row data cost (independent of group identity).
- On Consume, reserve worst-case = activeRows * (entrySize + rowSize).
- After actual consumption, refund (worstCaseNewGroups - actualNewGroups) * entrySize.
Close releases every outstanding reservation, even mid-Consume cancellations.
func NewBatchGroupBy ¶
func NewBatchGroupBy( schema *vectorized.BatchSchema, keyIndices []int, pool *vectorized.BatchPool, batchSize int, tracker *vectorized.MemoryTracker, entrySize, rowSize int64, ) *BatchGroupBy
NewBatchGroupBy constructs a BatchGroupBy.
- entrySize: per-new-group bucket overhead.
- rowSize: per-row data cost.
Pass rowSize=0 to charge only per-new-group; pass entrySize=0 to charge only per-row.
func NewBatchGroupByFirst ¶
func NewBatchGroupByFirst( schema *vectorized.BatchSchema, keyIndices []int, pool *vectorized.BatchPool, batchSize int, tracker *vectorized.MemoryTracker, entrySize int64, ) *BatchGroupBy
NewBatchGroupByFirst constructs a BatchGroupBy that emits only the first-seen row of each group (raw GroupBy without aggregation). It matches the row path: groupBy.Execute produces a groupIterator whose Current() returns the whole group, and processor.go keeps only current[0], so each group surfaces a single row in group-insertion order with the input schema unchanged.
func (*BatchGroupBy) Close ¶
func (g *BatchGroupBy) Close() error
Close releases every outstanding memory reservation. Idempotent.
func (*BatchGroupBy) Consume ¶
func (g *BatchGroupBy) Consume(_ context.Context, b *vectorized.RecordBatch) error
Consume reserves the worst-case bytes for new groups + per-row cost, accumulates rows into per-group buckets, then refunds the unused reservation.
func (*BatchGroupBy) Finalize ¶
func (g *BatchGroupBy) Finalize(_ context.Context) error
Finalize is a no-op for v1 — groups are already materialized.
func (*BatchGroupBy) Init ¶
func (g *BatchGroupBy) Init(ctx context.Context) error
Init prepares the group map.
func (*BatchGroupBy) NextBatch ¶
func (g *BatchGroupBy) NextBatch(_ context.Context) (*vectorized.RecordBatch, error)
NextBatch emits accumulated rows in group-insertion order, paginated by batchSize. Returns (nil, nil) when all groups are drained.
func (*BatchGroupBy) OutputSchema ¶
func (g *BatchGroupBy) OutputSchema() *vectorized.BatchSchema
OutputSchema returns the unchanged input schema.
type BatchLimit ¶
type BatchLimit struct {
// contains filtered or unexported fields
}
BatchLimit applies offset+limit windowing as a fusible in-place selection rewrite. State across batches is carried via a cumulative-seen counter.
When the window closes (seen >= offset+limit), the current batch's selection is sliced to whatever portion of the window it contributed and Process returns vectorized.ErrLimitExhausted. The fused stage translates that sentinel into "emit current batch, then EOF on next pull".
func NewBatchLimit ¶
func NewBatchLimit(schema *vectorized.BatchSchema, offset, limit uint32) *BatchLimit
NewBatchLimit constructs a fusible limit operator.
func (*BatchLimit) Init ¶
func (l *BatchLimit) Init(ctx context.Context) error
Init is a no-op. Limit has no per-pipeline setup.
func (*BatchLimit) OutputSchema ¶
func (l *BatchLimit) OutputSchema() *vectorized.BatchSchema
OutputSchema returns the unchanged input schema.
func (*BatchLimit) Process ¶
func (l *BatchLimit) Process(_ context.Context, b *vectorized.RecordBatch) error
Process rewrites b.Selection to keep only rows in [offset, offset+limit) of the cumulative active stream.
type BatchQueryRequest ¶ added in v0.12.0
type BatchQueryRequest struct {
Request *measurev1.QueryRequest
Patterns []model.IndexedPattern
// SeriesOrder permits the local source to visit complete series for an order-independent QL aggregate.
SeriesOrder bool
}
BatchQueryRequest selects the in-process batch result boundary for a native request. It is never serialized or sent to a data node.
type BatchQueryResult ¶ added in v0.12.0
type BatchQueryResult interface {
vectorized.PullOperator
NativeIteratorFrom(context.Context, vectorized.PullOperator) (executor.MIterator, error)
QueryTrace() *commonv1.Trace
}
BatchQueryResult is the transport-free native result contract used by liaison callers.
type BatchScan ¶
type BatchScan struct {
// contains filtered or unexported fields
}
BatchScan is the v1 PullOperator that wraps a MeasureQueryResult and produces RecordBatches. It uses a SeriesCursor to manage cross-series boundaries and bulk-extracts metadata, tags, and fields per series fill.
func NewBatchScan ¶
func NewBatchScan(qr model.MeasureQueryResult, schema *vectorized.BatchSchema, pool *vectorized.BatchPool, batchSize int, ) *BatchScan
NewBatchScan returns a BatchScan; call Init before NextBatch.
func (*BatchScan) NextBatch ¶
func (s *BatchScan) NextBatch(_ context.Context) (*vectorized.RecordBatch, error)
NextBatch fills a fresh batch up to batchSize rows. Returns:
- (batch, nil) for a valid batch with Len > 0;
- (nil, nil) for clean EOF;
- (nil, err) for storage error (the partial batch is dropped to GC).
func (*BatchScan) OutputSchema ¶
func (s *BatchScan) OutputSchema() *vectorized.BatchSchema
OutputSchema returns the schema declared at construction.
type BatchSourceFromBatchResult ¶
type BatchSourceFromBatchResult struct {
// contains filtered or unexported fields
}
BatchSourceFromBatchResult is a PullOperator that drives a model.MeasureBatchResult through PullBatch and accumulates rows into *vectorized.RecordBatch instances of the configured batchSize.
G5c (US-007 partial) — provides the wiring path that lets NewMIterator consume PullBatch output directly. Storage's queryResult / indexSortResult both implement MeasureBatchResult; the columns inside the *MeasureBatch are typed (passthrough today; native after US-005). BatchSourceFromBatchResult column-copies into a RecordBatch whose schema matches the source. extract.go is bypassed entirely on this path — the source columns are already typed.
Schema contract: the supplied schema must match every *MeasureBatch produced by br.PullBatch. Enforced loosely — the column-copy helper returns an error on TypedColumn[T] mismatches, which surfaces as a pipeline error.
func NewBatchSourceFromBatchResult ¶
func NewBatchSourceFromBatchResult(br model.MeasureBatchResult, schema *vectorized.BatchSchema, pool *vectorized.BatchPool, batchSize int, ) *BatchSourceFromBatchResult
NewBatchSourceFromBatchResult constructs the source. Init is required before NextBatch (no-op today, kept to satisfy PullOperator).
func (*BatchSourceFromBatchResult) Close ¶
func (s *BatchSourceFromBatchResult) Close() error
Close releases any in-flight pending MeasureBatch back to the column pool and then the underlying MeasureBatchResult exactly once. Idempotent.
func (*BatchSourceFromBatchResult) Init ¶
func (s *BatchSourceFromBatchResult) Init(ctx context.Context) error
Init satisfies PullOperator.
func (*BatchSourceFromBatchResult) NextBatch ¶
func (s *BatchSourceFromBatchResult) NextBatch(ctx context.Context) (*vectorized.RecordBatch, error)
NextBatch pulls *MeasureBatch instances from the underlying MeasureBatchResult and returns them as RecordBatches.
A storage batch of at least model.SmallBatchRows rows is passed on without copying (lend): its columns become the RecordBatch's columns, at the size storage produced them (up to a block, 8,192 rows), and the RecordBatch pins the storage batch until it is released. Smaller batches, which would let per-batch overhead dominate, are copied together into one pooled RecordBatch of up to batchSize rows. Row order is preserved either way.
EOF is sticky: once observed, subsequent calls return (nil, nil) without re-entering the source. Errors are sticky too.
func (*BatchSourceFromBatchResult) OutputSchema ¶
func (s *BatchSourceFromBatchResult) OutputSchema() *vectorized.BatchSchema
OutputSchema returns the schema declared at construction.
type BatchTimeBucket ¶ added in v0.12.0
type BatchTimeBucket struct {
// contains filtered or unexported fields
}
BatchTimeBucket is the time-bucketed counterpart of BatchAggregation (design §7.2). It floors each incoming batch's timestamp column to the bucket start, then delegates the actual grouping/folding to a sequence of ordinary BatchAggregation instances — one per closed bucket in streaming mode, or a single instance covering the whole scan in map mode — so every bucket-aware behavior (the conditional D2 reversal, tag carry-forward, AggModeMap/Reduce partial shapes) is exactly BatchAggregation's existing behavior, never duplicated here.
BatchTimeBucket is a PullOperator, not a BreakerOperator: it owns upstream directly and pulls from it lazily inside NextBatch, rather than being driven by breakerStage's "Consume the entire upstream, then serve" contract. That distinction is load-bearing for the memory-bound claim below — see NewBatchTimeBucket's wiring note.
Streaming mode (the part-scan default) holds only the current bucket's groups live at a time: consumeBatch splits each upstream batch into contiguous same-bucket runs (the input is time-ascending, so a run, once left behind, never recurs) and flushes+closes the open BatchAggregation whenever the bucket advances, bounding live group state to one bucket's groups instead of buckets × tagGroups. Because NextBatch drains any already-flushed output before pulling the next upstream batch, the flushed-but-not-yet-emitted queue is bounded too: at most the buckets that closed while processing a single upstream batch (typically one, since a batch is usually a thin, densely-packed time slice), not every bucket the whole scan will ever produce. A row whose bucket regresses is a monotonicity violation — streaming is correct only while the input is time-ordered — and consumeBatch fails loudly rather than silently reopening a flushed bucket.
Map mode (index-mode measures, which have no ascending-timestamp guarantee — design §7.2) never flushes mid-scan: every row folds into one persistent BatchAggregation keyed on (bucket, tags…) like any other GroupBy, and the whole result is produced once upstream is exhausted. This trades the memory bound for correctness on out-of-order input; NewBatchTimeBucket's streaming argument selects which mode a given operator instance runs.
func BuildTimeBucketOperator ¶ added in v0.12.0
func BuildTimeBucketOperator( upstream vectorized.PullOperator, opts model.MeasureQueryOptions, schema *vectorized.BatchSchema, tracker *vectorized.MemoryTracker, batchSize int, mode AggMode, ) (*BatchTimeBucket, error)
BuildTimeBucketOperator builds the BatchTimeBucket operator for a time-bucketed GroupBy (design §7.2), wrapping upstream directly. Unlike BuildOperators, this does not return a BreakerOperator to be attached via PipelineBuilder.Break: BatchTimeBucket is a PullOperator that pulls from upstream lazily inside its own NextBatch, which is what makes its memory bound real (see BatchTimeBucket's doc). Callers wire it in via PipelineBuilder.Transform instead. Check opts.GroupBy.GetTimeBucket() != nil before calling this rather than BuildOperators.
tagKeyIndices are the already resolved tag GroupBy keys (empty for a bucket-only GroupBy, i.e. no tag key at all). Agg is optional, exactly as for the non-bucketed case: when absent this is a bucketed raw GroupBy (first-seen row per (bucket, tags)), when present it is a bucketed aggregate — both shapes reuse the same BatchTimeBucket, since BatchAggregation with zero AggSpecs already produces the raw-GroupBy shape. (The analyzer currently rejects the no-Agg case for real requests — BatchAggregation's empty-AggSpec output layout drops every projected field, unlike BatchGroupByFirst's full-schema passthrough — but BuildTimeBucketOperator itself stays agnostic to that policy choice.)
func NewBatchTimeBucket ¶ added in v0.12.0
func NewBatchTimeBucket( upstream vectorized.PullOperator, input *vectorized.BatchSchema, keyIndices []int, timestampIdx int, widthNanos int64, aggs []AggSpec, mode AggMode, batchSize int, tracker *vectorized.MemoryTracker, entrySize int64, streaming bool, ) *BatchTimeBucket
NewBatchTimeBucket constructs a BatchTimeBucket wrapping upstream, the operator this one pulls batches from directly (see the type doc for why that — rather than a Consume/Finalize breaker contract — is what makes the memory bound real). upstream may be nil for a schema-only probe (no Init/NextBatch/Close call reaches it in that case) — GroupByAgg.Schema() uses this to read OutputSchema without a real pipeline.
keyIndices are the tag GroupBy keys (may be empty for a bucket-only GroupBy); timestampIdx is the input schema's RoleTimestamp column; widthNanos is the resolved bucket width (design §5.3), always > 0. streaming selects the part-scan streaming path (true) or the index-mode map fallback (false) — decided once by the analyzer from measureSchema.GetIndexMode(), never guessed here. tracker and entrySize are forwarded to each underlying BatchAggregation unchanged.
func (*BatchTimeBucket) Close ¶ added in v0.12.0
func (bt *BatchTimeBucket) Close() error
Close is idempotent; it closes any still-open bucket aggregator (the error path — the scan never reached EOF), releases the pending queue, and closes upstream.
func (*BatchTimeBucket) Init ¶ added in v0.12.0
func (bt *BatchTimeBucket) Init(ctx context.Context) error
Init initializes upstream. The first bucket opens lazily on the first NextBatch call.
func (*BatchTimeBucket) NextBatch ¶ added in v0.12.0
func (bt *BatchTimeBucket) NextBatch(ctx context.Context) (*vectorized.RecordBatch, error)
NextBatch drains any already-flushed output first; only once that queue is empty does it pull the next batch from upstream. This ordering is what bounds the flushed-but-unemitted queue to "whatever closed while processing one upstream batch" instead of "everything the whole scan will ever produce" — see the type doc.
Map mode's terminal aggregator is the one exception a per-upstream-batch bound doesn't cover on its own: it can represent the entire scan, not one bucket. Once upstream is exhausted, drainMapModeAggregator takes over and pulls that aggregator one page at a time — interleaved with normal pending/commitBuilder draining — rather than flushCurrentBucket's loop-until-nil, which would materialize every page into pending before this call ever returns the first one.
func (*BatchTimeBucket) OutputSchema ¶ added in v0.12.0
func (bt *BatchTimeBucket) OutputSchema() *vectorized.BatchSchema
OutputSchema returns the schema of emitted batches, precomputed at construction time.
func (*BatchTimeBucket) SetAllKeysIndexResolved ¶ added in v0.12.0
func (bt *BatchTimeBucket) SetAllKeysIndexResolved(allResolved bool)
SetAllKeysIndexResolved marks every tag GroupBy key this operator groups by as resolved from the series index, enabling the run-folding fast path (design §7.7, stage 8a) for its streaming per-bucket aggregators. See BatchAggregation.SetAllKeysIndexResolved for the underlying guarantees; map mode ignores this flag (openBucket forces it off there) since its single aggregator is not restricted to one bucket per Consume call. Defaults to false (today's per-row behavior) until called.
type BatchTop ¶
type BatchTop struct {
// contains filtered or unexported fields
}
BatchTop is a BreakerOperator that retains the top-N rows by a designated field column. asc=true keeps the lowest N; asc=false keeps the highest N.
Tie-break is stable on insertion order — earlier rows win. Nulls in the key column are treated as the lowest value (kept first in asc, evicted first in desc).
func NewBatchTop ¶
func NewBatchTop(schema *vectorized.BatchSchema, fieldCol, n int, asc bool, batchSize int) *BatchTop
NewBatchTop constructs a BatchTop. fieldCol is the index of the int64 or float64 column to sort by; n is the bound; asc selects ascending or descending order.
func (*BatchTop) Consume ¶
func (t *BatchTop) Consume(_ context.Context, b *vectorized.RecordBatch) error
Consume considers each active row for inclusion in the top-N heap.
n <= 0 is a no-op (matches the row-path's top-N convention) — without this guard the bounded-heap logic would dereference an empty heap on the first row.
func (*BatchTop) NextBatch ¶
func (t *BatchTop) NextBatch(_ context.Context) (*vectorized.RecordBatch, error)
NextBatch emits the sorted rows in batches of batchSize.
func (*BatchTop) OutputSchema ¶
func (t *BatchTop) OutputSchema() *vectorized.BatchSchema
OutputSchema returns the unchanged input schema.
type FrameEmitter ¶
FrameEmitter is the data-node wire-emit contract under flag-on: any MIterator that participates in a TopicInternalMeasureQuery response must encapsulate its own drain + encode strategy via this method, so the processor.go Rev can dispatch uniformly without case-by-case knowledge of each wrapper.
Implementations:
- VectorizedMIterator: drains the underlying vec Pipeline directly via DrainPipelineToFrame — the throughput-optimal path that never materializes proto datapoints.
- emptyMIterator: returns a nil body (matches the codec layer's RawFrameCodec carve-out for empty distributed results).
- hiddenTagsMIterator: drains via Next / Current (which already strips hidden criteria tags from the egress datapoints), then reverse-serializes the surviving rows into a passthrough RecordBatch through SerializeDataPointsToFrame.
- sortedMIterator: drains via Next / Current (which already applies cross-group merge + version dedup), then reverse- serializes through SerializeDataPointsToFrame.
The reverse-serialize path is less efficient than draining a vec Pipeline (one allocation per cell during passthrough rebuild) but keeps the wrapper's row-side semantics — hidden-tag strip, sort, dedup — as the single source of truth on the wire.
type FrameLimits ¶ added in v0.12.0
type FrameLimits struct {
// MaxBytes caps the estimated size of the rows of one frame; a row larger than the cap goes alone.
MaxBytes uint64
// MaxRows caps the rows of one frame.
MaxRows int
}
FrameLimits caps one frame of a streamed result. A zero field means no cap.
type FrameStreamEmitter ¶ added in v0.12.0
type FrameStreamEmitter interface {
EmitFrames(ctx context.Context, limits FrameLimits, emit func(frame []byte) error) error
}
FrameStreamEmitter is the streaming counterpart of FrameEmitter: an MIterator that implements it hands its result to emit one frame at a time, as its pipeline produces it, instead of draining it into one body. Every frame of a stream has the same column layout, so a receiver can merge them without seeing the whole result. emit returns once the frame has been sent; the frame is not used afterwards.
type PartialReducer ¶ added in v0.12.0
type PartialReducer struct {
// contains filtered or unexported fields
}
PartialReducer is ReducePartialBatchesToSchema as an operator that takes its partials one at a time, so a caller that receives them as a stream holds the reduced groups instead of every partial. The first non-empty partial defines the partial layout unless a target is given. The reducer copies what it keeps, so a partial can be released as soon as Consume returns.
func NewPartialReducer ¶ added in v0.12.0
func NewPartialReducer( target *vectorized.BatchSchema, keyTagFamily string, keyTagNames []string, bucketed bool, aggSpecs []AggReduceSpec, batchSize int, tracker *vectorized.MemoryTracker, ) *PartialReducer
NewPartialReducer returns a reducer with the parameters of ReducePartialBatchesToSchema.
func (*PartialReducer) Close ¶ added in v0.12.0
func (r *PartialReducer) Close()
Close releases the reducer's aggregation state and the memory it reserved. It is safe to call more than once.
func (*PartialReducer) Consume ¶ added in v0.12.0
func (r *PartialReducer) Consume(b *vectorized.RecordBatch) error
Consume folds one partial into the reduction. Empty partials are skipped.
func (*PartialReducer) ConsumeScoped ¶ added in v0.12.0
func (r *PartialReducer) ConsumeScoped(b *vectorized.RecordBatch, scope int64) error
ConsumeScoped is Consume for a partial from the replica-dedup scope given (its storage group, see BatchAggregation.SetDedupScope). Shard ids are only unique within a group, so partials of different groups must not be taken for replicas of one another.
func (*PartialReducer) Finish ¶ added in v0.12.0
func (r *PartialReducer) Finish() ([]*vectorized.RecordBatch, AggValuePath, error)
Finish returns the reduced batches in group-insertion order, bucket-ascending for a bucketed reduction, and the AggValuePath that describes how the value column was resolved. The reducer is spent afterwards.
func (*PartialReducer) FinishContext ¶ added in v0.12.0
func (r *PartialReducer) FinishContext(ctx context.Context) ([]*vectorized.RecordBatch, AggValuePath, error)
FinishContext is Finish that stops with the context's error once ctx is done, between the steps and between the output batches.
func (*PartialReducer) Groups ¶ added in v0.12.0
func (r *PartialReducer) Groups() int
Groups returns how many groups the reducer holds.
func (*PartialReducer) OutputSchema ¶ added in v0.12.0
func (r *PartialReducer) OutputSchema() *vectorized.BatchSchema
OutputSchema returns the schema of the reduced batches, or nil before the first non-empty partial.
type RawFrameSource ¶
type RawFrameSource interface {
// Pipeline returns the vec pipeline the iterator wraps. Drain it via
// vectorized.Pipeline.Next until nil; the iterator's own Close still
// owns the pipeline lifecycle.
Pipeline() *vectorized.Pipeline
// Schema returns the terminal-operator output schema — the same
// schema every emitted batch carries.
Schema() *vectorized.BatchSchema
}
RawFrameSource is the capability a vec MIterator exposes when the caller wants to short-circuit per-row proto serialization and instead drain the underlying Pipeline into a single columnar raw frame body (G9f.5.b). The data-node processor type-asserts to this interface when data.MeasureWireModeRaw() is true on TopicInternalMeasureQuery, calls DrainPipelineToFrame(ctx, src.Pipeline(), src.Schema()), then Close()s the wrapping iterator to release pooled batches + the pipeline. The row-path iterators do NOT implement this interface, so the type assertion failing is the correct fall-through signal.
IMPORTANT: a caller that drains the Pipeline directly MUST NOT also drive Next() on the MIterator afterwards — the pipeline is now empty and the iterator's internal cursor is stale. The data-node processor honors this by branching on RawFrameSource BEFORE the iterator's proto-collection loop.
type ReduceTopSpec ¶
ReduceTopSpec configures an optional post-Reduce Top-N step. FieldName names the agg output column to sort by; N is the number of rows to retain; Asc=true keeps the lowest N, Asc=false keeps the highest N (mirrors the row path's distributed Top-over-Agg pattern — see pkg/query/logical/measure/measure_plan_distributed.go's DistributedAnalyze, where Top is applied AFTER the distributedPlan on the liaison).
type SeriesCursor ¶
type SeriesCursor struct {
// contains filtered or unexported fields
}
SeriesCursor walks across MeasureResult instances yielded by a MeasureQueryResult, presenting either single-row access (NextRow) or bulk-copy access (Current+Advance) to BatchScan.
Sticky-error contract: once Pull yields a result with Error != nil, the cursor stores the error and every subsequent NextRow returns it. Init is the only way to reset.
func (*SeriesCursor) Advance ¶
func (c *SeriesCursor) Advance(n int)
Advance moves the cursor n rows forward. Crosses to the next series if the new position reaches the end of the current MeasureResult.
func (*SeriesCursor) Close ¶
func (c *SeriesCursor) Close()
Close releases the underlying MeasureQueryResult exactly once. Idempotent and safe after EOF.
func (*SeriesCursor) Current ¶
func (c *SeriesCursor) Current() (*model.MeasureResult, int)
Current returns the underlying MeasureResult and the cursor's position within it. Used by BatchScan's bulk-copy path to read parallel arrays directly.
func (*SeriesCursor) Err ¶
func (c *SeriesCursor) Err() error
Err returns the sticky storage error, or nil. Once non-nil it remains so until Init is called again.
func (*SeriesCursor) Exhausted ¶
func (c *SeriesCursor) Exhausted() bool
Exhausted reports whether the cursor has run out of input (clean EOF or after an error).
func (*SeriesCursor) Init ¶
func (c *SeriesCursor) Init(qr model.MeasureQueryResult)
Init resets the cursor and advances to the first non-empty series (or EOF/err).
func (*SeriesCursor) RemainingInSeries ¶
func (c *SeriesCursor) RemainingInSeries() int
RemainingInSeries returns how many rows are left in the current MeasureResult. 0 when at EOF, on error, or between series.
type VectorizedConfig ¶
VectorizedConfig controls the v1 vectorized Measure query path.
func DefaultConfig ¶
func DefaultConfig() VectorizedConfig
DefaultConfig returns the v1 default — 1024-row batches and a 256 MiB per-query memory budget.
func (VectorizedConfig) Validate ¶
func (c VectorizedConfig) Validate() error
Validate rejects nonsense configurations.
type VectorizedMIterator ¶
type VectorizedMIterator struct {
// contains filtered or unexported fields
}
VectorizedMIterator is the public adapter exposed to other packages. It is a thin facade over the unexported vectorizedMIterator so the executor interface is satisfied without leaking the package-private type.
func NewIteratorFromPipeline ¶
func NewIteratorFromPipeline(ctx context.Context, pipeline *vectorized.Pipeline, schema *vectorized.BatchSchema, pool *vectorized.BatchPool) *VectorizedMIterator
NewIteratorFromPipeline wraps an already-built *vectorized.Pipeline (with its source/operators already attached and Pipeline.Init called) as a VectorizedMIterator. Used by the G8 vec executor at pkg/query/vectorized/measure/plan to compose plan trees into the public MIterator contract without going through NewMIterator's leaf-substitution path. pool is the egress BatchPool the adapter recycles consumed batches into; schema is the terminal-operator output schema — same shape every batch will carry — used by the RawFrameSource capability path (G9f.5.b) to drain the pipeline into a single columnar raw frame body.
func NewMIterator ¶
func NewMIterator(ctx context.Context, qr model.MeasureQueryResult, measureSchema *databasev1.Measure, opts model.MeasureQueryOptions, cfg VectorizedConfig, ) (*VectorizedMIterator, error)
NewMIterator builds a vectorized adapter that drives a Pipeline over qr and satisfies executor.MIterator. The returned VectorizedMIterator owns the qr lifetime through the pipeline: Close → pipeline.Close → BatchScan.Close → SeriesCursor.Close → qr.Release. Callers must NOT release qr themselves on the success path.
On error, ownership of qr stays with the caller; the caller is responsible for releasing it. Construction is split so qr.Release-on-failure is decided at the call site (where build inputs other than qr are also tracked).
func (*VectorizedMIterator) Close ¶
func (v *VectorizedMIterator) Close() error
Close releases the pipeline (and through it the BatchScan, cursor, and underlying MeasureQueryResult). Returns the join of the sticky iteration error and the pipeline-close error, matching resultMIterator.Close.
func (*VectorizedMIterator) Current ¶
func (v *VectorizedMIterator) Current() []*measurev1.InternalDataPoint
Current returns the current row as a single-element slice (matches row-path contract).
func (*VectorizedMIterator) EmitFrame ¶
func (v *VectorizedMIterator) EmitFrame(ctx context.Context) ([]byte, error)
EmitFrame implements FrameEmitter on the public adapter — delegates to the inner iterator's vec-native DrainPipelineToFrame path so the data-node Rev under flag-on emits a columnar raw frame body directly without proto materialization. The exported facade must implement the method too because that is the type processor.go sees from the vec dispatch return.
func (*VectorizedMIterator) EmitFrames ¶ added in v0.12.0
func (v *VectorizedMIterator) EmitFrames(ctx context.Context, limits FrameLimits, emit func([]byte) error) error
EmitFrames implements FrameStreamEmitter on the public adapter.
func (*VectorizedMIterator) Err ¶
func (v *VectorizedMIterator) Err() error
Err returns any sticky storage error that terminated iteration.
func (*VectorizedMIterator) Next ¶
func (v *VectorizedMIterator) Next() bool
Next advances one DataPoint.
func (*VectorizedMIterator) Pipeline ¶
func (v *VectorizedMIterator) Pipeline() *vectorized.Pipeline
Pipeline implements RawFrameSource on the public adapter — delegates to the inner iterator so callers (e.g. the data-node Rev under flag-on) can drain the pipeline directly.
func (*VectorizedMIterator) Schema ¶
func (v *VectorizedMIterator) Schema() *vectorized.BatchSchema
Schema implements RawFrameSource on the public adapter.
Source Files
¶
- adapter.go
- aggregation.go
- aggregation_reduce.go
- aggregation_runs.go
- batch_metrics_disabled.go
- batch_query.go
- batchsource.go
- build_batch.go
- coerce.go
- config.go
- cursor.go
- doc.go
- extract.go
- filter.go
- groupby.go
- integration.go
- limit.go
- pattern_transport.go
- plan.go
- raw_emit.go
- raw_emit_stream.go
- reduce.go
- runs.go
- scan.go
- serialize.go
- timebucket.go
- timebucket_runs.go
- top.go
Directories
¶
| Path | Synopsis |
|---|---|
|
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. |
|
Package plan is the vectorized measure-query plan tree (G8).
|
Package plan is the vectorized measure-query plan tree (G8). |