diff --git a/src/promql/src/histogram_eval/aggregate.rs b/src/promql/src/histogram_eval/aggregate.rs index 9e1721c8b59..0ffcca5e8e8 100644 --- a/src/promql/src/histogram_eval/aggregate.rs +++ b/src/promql/src/histogram_eval/aggregate.rs @@ -156,7 +156,8 @@ fn aggregate_point<'a>( /// The Kahan sum or the mean of `histograms` in order, without compaction; `None` when there is /// none or they mix exponential and custom buckets. Prometheus `sum_over_time` and /// `avg_over_time` run the same steps as the aggregations. Histograms are consumed one at a -/// time, so the first error ends the fold. +/// time, so the first error ends the fold. The result is derived, so it carries no start +/// timestamp. pub(crate) fn sum_or_avg( op: HistogramAggregate, histograms: impl IntoIterator>, @@ -236,5 +237,11 @@ pub(crate) fn sum_or_avg( } }, } + // The result was derived from its inputs, so it carries no start timestamp of its own, like + // every other operation that builds one. Clearing it here covers the fold that added nothing: + // the first histogram of a window becomes the result as it arrived, and the adds above are + // what drop the field otherwise, which would make the payload depend on the sample count. + // The bucket layout is left as the fold built it -- compaction belongs to the caller. + value.start_timestamp = None; Ok(Some(value)) } diff --git a/src/promql/src/histogram_eval/float_histogram.rs b/src/promql/src/histogram_eval/float_histogram.rs index acce48c1776..22d016418ad 100644 --- a/src/promql/src/histogram_eval/float_histogram.rs +++ b/src/promql/src/histogram_eval/float_histogram.rs @@ -35,6 +35,22 @@ type Buckets = Vec<(i32, f64)>; #[derive(Debug, Clone)] pub(crate) struct FloatHistogram { pub(crate) reset_hint: CounterResetHint, + /// The start timestamp of the sample this histogram was read from, in milliseconds. + /// + /// It is metadata of GreptimeDB's histogram row, not part of the histogram value that + /// Prometheus's `FloatHistogram` models. This owned form preserves it -- [`Self::try_from_view`] + /// reads it off the sample and [`Self::push_to`] writes it back -- while every operation that + /// derives a histogram from its input ([`Self::add`], [`Self::kahan_add`], [`Self::mul`], + /// [`Self::div`], [`Self::compact`], [`Self::copy_to_schema`], with the constructors beside + /// them) clears it. [`Self::equals`] does not compare it. + /// + /// Both halves are this module's own policy and say nothing about how Prometheus propagates + /// these timestamps: its `FloatHistogram` does not carry the field, while its rate and reset + /// evaluation receives start timestamps through a separate channel. This crate's native range + /// kernel does not read the field; the legacy extrapolation path does, to synthesize a zero + /// point. So a selection that keeps the field preserves what was stored, and does not by itself + /// make a native rate agree with the legacy one. + pub(crate) start_timestamp: Option, pub(crate) schema: i32, pub(crate) zero_threshold: f64, pub(crate) zero_count: f64, @@ -62,6 +78,7 @@ impl FloatHistogram { pub(crate) fn try_from_view(view: &HistogramView<'_>) -> Result { Ok(Self { reset_hint: view.reset_hint, + start_timestamp: view.start_timestamp, schema: view.schema, zero_threshold: view.zero_threshold, zero_count: view.zero_count, @@ -130,7 +147,7 @@ impl FloatHistogram { count: self.count, zero_count: self.zero_count, reset_hint: self.reset_hint, - start_timestamp: None, + start_timestamp: self.start_timestamp, custom_values: &self.custom_values, positive: BucketSideView { span_offsets: &positive_offsets, @@ -151,6 +168,7 @@ impl FloatHistogram { pub(crate) fn empty_like(&self) -> Self { Self { reset_hint: CounterResetHint::Unknown, + start_timestamp: None, schema: self.schema, zero_threshold: 0.0, zero_count: 0.0, @@ -169,6 +187,8 @@ impl FloatHistogram { /// Go `Mul`. pub(crate) fn mul(&mut self, factor: f64) { + // A result this operation derived, so it carries no start timestamp of its own. + self.start_timestamp = None; self.zero_count *= factor; self.count *= factor; self.sum *= factor; @@ -182,6 +202,8 @@ impl FloatHistogram { /// Go `Div`; dividing by zero removes every bucket. pub(crate) fn div(&mut self, scalar: f64) { + // A result this operation derived, so it carries no start timestamp of its own. + self.start_timestamp = None; self.zero_count /= scalar; self.count /= scalar; self.sum /= scalar; @@ -215,6 +237,8 @@ impl FloatHistogram { /// Go `Compact(0)`: drops empty buckets. pub(crate) fn compact(&mut self) { + // A result this operation derived, so it carries no start timestamp of its own. + self.start_timestamp = None; self.positive.retain(|&(_, count)| count != 0.0); self.negative.retain(|&(_, count)| count != 0.0); self.layout = None; @@ -223,13 +247,19 @@ impl FloatHistogram { /// Go `CopyToSchema`; `target` must not exceed the schema. pub(crate) fn copy_to_schema(&self, target: i32) -> Result { if target == self.schema { - return Ok(self.clone()); + // The copy is a histogram this call produced, like the reduced one below: a start + // timestamp belongs to the sample that carried it, not to a value derived from it. + return Ok(Self { + start_timestamp: None, + ..self.clone() + }); } if self.uses_custom_buckets() || target == CUSTOM_BUCKETS_SCHEMA || target > self.schema { return Err(incompatible_schema()); } Ok(Self { reset_hint: CounterResetHint::Unknown, + start_timestamp: None, schema: target, zero_threshold: self.zero_threshold, zero_count: self.zero_count, @@ -255,6 +285,8 @@ impl FloatHistogram { fn add_or_sub(&mut self, other: &Self, subtract: bool) -> Result { check_schemas(self, other)?; self.layout = None; + // A result this operation derived, so it carries no start timestamp of its own. + self.start_timestamp = None; let mut outcome = AddOutcome { counter_reset_collision: self.adjust_counter_reset(other), custom_bounds_reconciled: false, @@ -323,6 +355,8 @@ impl FloatHistogram { ) -> Result<(Self, AddOutcome)> { check_schemas(self, other)?; self.layout = None; + // A result this operation derived, so it carries no start timestamp of its own. + self.start_timestamp = None; let mut outcome = AddOutcome { counter_reset_collision: self.adjust_counter_reset(other), custom_bounds_reconciled: false, @@ -410,6 +444,7 @@ impl FloatHistogram { fn new_compensation(&self) -> Self { Self { reset_hint: self.reset_hint, + start_timestamp: None, schema: self.schema, zero_threshold: self.zero_threshold, zero_count: 0.0, diff --git a/src/promql/src/histogram_eval/tests.rs b/src/promql/src/histogram_eval/tests.rs index 8b815b0a49d..258e747a4cb 100644 --- a/src/promql/src/histogram_eval/tests.rs +++ b/src/promql/src/histogram_eval/tests.rs @@ -16,6 +16,9 @@ use std::collections::BTreeMap; use std::sync::Arc; use datafusion::error::DataFusionError; +use datatypes::series::histogram::{ + BucketSideView, CounterResetHint, HistogramBatchBuilder, HistogramView, +}; use datatypes::series::samples::{FieldSpec, SampleRef, Series, SeriesSchema}; use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; @@ -383,6 +386,75 @@ fn histogram_points(series: &Series) -> BTreeMap { .collect() } +/// The start timestamp is payload of a histogram that was read, and not of one that was computed. +/// +/// This pins GreptimeDB's own payload policy, not a Prometheus expectation: the timestamp is read +/// off a sample ([`FloatHistogram::try_from_view`]) and written back +/// ([`FloatHistogram::push_to`]), which is what a selection needs to hand a sample on unchanged, +/// and every operation that derives a value from its input clears it. Nothing else depends on the +/// field: the type derives `Debug` and `Clone` only, so it has no equality, hash or serialized form +/// that could compare it, and [`FloatHistogram::equals`] is Go `Equals` on counts and bucket layout. +#[test] +fn a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one() { + let offsets = [0]; + let lengths = [2]; + let buckets = [1.0, 2.0]; + let view = HistogramView { + schema: 0, + zero_threshold: 0.0, + zero_count: 0.0, + count: 3.0, + sum: 3.0, + reset_hint: CounterResetHint::Unknown, + start_timestamp: Some(1500), + custom_values: &[], + positive: BucketSideView { + span_offsets: &offsets, + span_lengths: &lengths, + buckets: &buckets, + }, + negative: BucketSideView { + span_offsets: &[], + span_lengths: &[], + buckets: &[], + }, + }; + let histogram = FloatHistogram::try_from_view(&view).unwrap(); + assert_eq!(histogram.start_timestamp, Some(1500)); + + // Writing it back keeps it, which is what makes a selected sample a sample. + let mut builder = HistogramBatchBuilder::new(); + histogram.push_to(&mut builder).unwrap(); + let table = builder.finish().unwrap(); + assert_eq!( + table.view(0).unwrap().start_timestamp, + Some(1500), + "the histogram was written back without the start timestamp it was read with" + ); + + // A value derived from it carries none, whichever operation derived it. + let mut added = histogram.clone(); + added.add(&histogram).unwrap(); + assert_eq!(added.start_timestamp, None); + let mut summed = histogram.clone(); + let (compensation, _) = summed.kahan_add(&histogram, None).unwrap(); + assert_eq!(summed.start_timestamp, None); + assert_eq!(compensation.start_timestamp, None); + let mut multiplied = histogram.clone(); + multiplied.mul(2.0); + assert_eq!(multiplied.start_timestamp, None); + let mut divided = histogram.clone(); + divided.div(2.0); + assert_eq!(divided.start_timestamp, None); + let mut compacted = histogram.clone(); + compacted.compact(); + assert_eq!(compacted.start_timestamp, None); + assert_eq!(histogram.copy_to_schema(0).unwrap().start_timestamp, None); + assert_eq!(histogram.empty_like().start_timestamp, None); + // The one it was read into is still the sample it was read from. + assert_eq!(histogram.start_timestamp, Some(1500)); +} + /// `histogram_quantile` drops all metadata labels; the single-histogram functions drop only /// `__name__`, as Prometheus does. #[test] diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 25e2c4a3c94..7684ee2aa2b 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -30,6 +30,18 @@ //! outer window reads the inner result as the samples it is, not as something to be resampled onto //! the outer grid first. //! +//! An instant selection owns no evaluator, because [`select_instants`] takes a complete source +//! axis: the node buffers the chunks of the series it is selecting until the chunk that carries +//! `is_last`, selects the last sample at or before each grid point of it, and hands the series over +//! as one chunk addressed on its own grid. Nothing is decided for a series before it ends, which is +//! the price of the kernel taking one axis rather than a chunk of one. +//! +//! A vector–vector binary node is the one kind that reads two inputs: it retains the chunks of both +//! operands and runs the matching kernel once the input has ended, because the operation pairs two +//! whole vectors point by point and nothing is decided for a point until both sides are complete. +//! The chunks of one logical series are assembled into the single series the kernel matches before it +//! runs, so a series that arrived in many chunks is one candidate, not one per chunk. +//! //! A node kind this runtime does not execute yet is rejected when the execution is built, naming //! the kind and its position. An unsupported tree therefore never starts, rather than answering //! half a query or panicking halfway through one. @@ -61,28 +73,34 @@ //! collects the root's chunks and merges them with the same helper. use std::collections::hash_map::Entry; -use std::collections::{HashMap, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; use datafusion::error::{DataFusionError, Result}; use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation}; use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet; use datatypes::arrow::array::{Array, Float64Array}; -use datatypes::arrow::buffer::Buffer; -use datatypes::series::histogram::HistogramBatch; -use datatypes::series::raw::RawSeriesChunk; +use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; +use datatypes::series::histogram::{HistogramBatch, HistogramView}; +use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{ - DenseSamplesRef, SampleRef, Samples, Series, SeriesFields, SeriesSchema, + DenseSamplesRef, RowCursor, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; -use datatypes::series::time::{GridRange, TimeAxis}; +use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis}; use datatypes::series::{MetricName, SeriesOrdering}; -use crate::grid_series::{LabelSet, label_set, merge_same_labelset}; +use crate::grid_series::{ + GridSample, GridSeriesBuilder, LabelSet, label_set, merge_same_labelset, owned, +}; +use crate::instant_eval::select_instants; use crate::map::{MathOp, drop_metric_name, map_math}; use crate::native::batch::EvaluatedChunk; use crate::native::metrics::{NodeMetrics, NodePath}; -use crate::native::plan::{NativeExpr, NativeTree}; +use crate::native::plan::{BoundInstant, NativeExpr, NativeNode, NativeTree}; use crate::range_eval::RangeEvaluator; +use crate::vector_match::{ + BinaryMatching, binary_vectors_with_reservation, validate_binary_operand, +}; #[cfg(test)] mod tests; @@ -180,6 +198,98 @@ fn series_bytes(series: &Series) -> usize { .saturating_add(metric_bytes(&series.metric)) } +/// The bytes one chunk a binary operand retains holds on its own. +/// +/// It is [`series_bytes`] with the samples a chunk's rows occupy in place of the allocations they +/// are slices of: a series delivered in a thousand chunks holds a thousand slices of one buffer, so +/// counting that buffer once per chunk would make the operand's figure grow with the number of +/// chunks rather than with the data in them. The slices of one series add up to the allocation they +/// share, which is the figure a deduplication across the chunks would arrive at. +/// +/// The histogram tables a chunk's segments reference are not part of the figure: a table is one +/// allocation however many chunks index into it, so it is not a per-chunk cost at all. Dropping it +/// here is therefore only half the story -- it must not become a figure the operand never charges. +/// [`unbilled_tables`] is the other half, and the operand bills each table once through it. +fn operand_chunk_bytes(series: &Series) -> usize { + series_bytes(series) + .saturating_sub(fields_bytes(&series.fields)) + .saturating_add(sample_slice_bytes(&series.fields)) +} + +/// The bytes the samples of one series' fields take as the slices they are. +/// +/// A dense segment is counted by the rows it holds -- not by the buffer its slice belongs to -- and a +/// field of native histograms by its column of indices, because the table those indices point into +/// is one allocation the chunks of the series share. A nested segment holds rows of its own in the +/// chunks it is made of, so it is left to them. +fn sample_slice_bytes(fields: &SeriesFields) -> usize { + fields + .iter() + .flat_map(|field| field.segments()) + .map(|segment| match segment.dense() { + Some(DenseSamplesRef::Float(values)) => { + values.len().saturating_mul(std::mem::size_of::()) + } + Some(DenseSamplesRef::Histogram(histograms)) => histograms + .indices() + .len() + .saturating_mul(std::mem::size_of::()), + Some(DenseSamplesRef::Mixed(mixed)) => mixed + .floats() + .len() + .saturating_mul(std::mem::size_of::()) + .saturating_add( + mixed + .histograms() + .indices() + .len() + .saturating_mul(std::mem::size_of::()), + ), + // `segments` hands out dense segments only, so a nested chunk never reaches here. + None => 0, + }) + .fold(0usize, usize::saturating_add) +} + +/// The histogram tables `series` is the first to reference, and the bytes they hold. +/// +/// A table is one allocation the chunks of a series share, so it is neither a per-chunk cost -- +/// counting it per chunk would make a series delivered in a thousand chunks cost a thousand tables +/// -- nor no cost at all, which is what leaving it out of every chunk leaves the figure at. What it +/// is, is a cost of the operand that first retains a chunk referencing it: the identities it returns +/// are the tables `billed` does not hold yet, and the figure is what those tables hold +/// ([`table_bytes`]). The caller bills the figure as it stands and adds the identities to `billed` +/// once the chunk is retained, which is what makes the two halves of the figure agree. +/// +/// The identity is the address of the allocation behind the `Arc`. It names one table for as long as +/// it is remembered, because a chunk referencing a table keeps it alive and no later allocation can +/// be given the same address. A table two segments or two fields of the one chunk reference is +/// listed once. Each identity is also one slot in the set that remembers it, which is charged as it +/// is written -- one entry at a time, like the boundary list's, and not from the capacity the set +/// grows to -- so remembering a table is paid for beside the table itself. +fn unbilled_tables(series: &Series, billed: &HashSet) -> (Vec, usize) { + let mut fresh: Vec = Vec::new(); + let mut bytes = 0usize; + for field in series.fields.iter() { + for segment in field.segments() { + let table = match segment.dense() { + Some(DenseSamplesRef::Histogram(histograms)) => histograms.batch(), + Some(DenseSamplesRef::Mixed(mixed)) => mixed.histograms().batch(), + _ => continue, + }; + let identity = Arc::as_ptr(table) as usize; + if billed.contains(&identity) || fresh.contains(&identity) { + continue; + } + fresh.push(identity); + bytes = bytes + .saturating_add(table_bytes(table)) + .saturating_add(std::mem::size_of::()); + } + } + (fresh, bytes) +} + /// A rough workspace estimate for merging fragments that hold `rows` rows between them. /// /// It allows for sorted row indices, readers, sample descriptors and output headers. Like the @@ -261,10 +371,14 @@ fn buffer_bytes(buffer: &Buffer) -> usize { enum NodeTag { /// Forwards the chunks it is given. Input, + /// Buffers one series and selects the last sample at or before each of its grid points. + Instant, /// Feeds its input to its own [`RangeEvaluator`]. Window, /// Applies point-wise operations to its input chunks. Map, + /// Matches two evaluated vectors and applies one operation to every matched pair of series. + Binary, } impl NodeTag { @@ -272,8 +386,10 @@ impl NodeTag { fn describe(self) -> &'static str { match self { Self::Input => "input", + Self::Instant => "instant selection", Self::Window => "window", Self::Map => "map", + Self::Binary => "binary", } } } @@ -282,7 +398,8 @@ impl NodeTag { #[derive(Clone, Copy, Debug)] struct NodeSpec { tag: NodeTag, - /// The index of this node's input, which is the node the build pass reaches next. + /// The index of this node's input, which is the node the build pass reaches next: the one + /// input of a unary node, the left operand of a binary node, and none for an input node. input: Option, } @@ -836,21 +953,945 @@ struct MapRuntime { schema: Arc, } +/// What an instant node holds: the chunks of the one series it is selecting, until that series ends. +/// +/// [`select_instants`] takes a complete source axis, so this node cannot decide a grid point from +/// the samples one chunk carries the way a window decides a range from what it has retained: it +/// buffers a whole series and hands one chunk over for it. What it holds is therefore the series' +/// own bytes, not a fixed window of them, and the reservation follows the buffer. +struct InstantRuntime { + /// The bound selection: how far back it reads, the offset it reads at, and the grid its values + /// are addressed on. + selection: BoundInstant, + /// The layout the chunk it hands out is addressed on: its input's fields on that grid. + schema: Arc, + /// Where the rows the selection picked are gathered, one series at a time. + output: GridSeriesBuilder, + /// The chunks of the series being selected, in arrival order; empty while no series is open. + chunks: Vec, + /// What `chunks` hold, added as each chunk arrives and given back when the series is gathered. + /// + /// Each chunk is measured once, with the estimate a queued chunk is charged with: an allocation + /// two chunks of the series share is counted once per chunk, which is the over-count a figure + /// that keeps no state across chunks accepts. + held: usize, +} + +impl InstantRuntime { + /// The run-time state of the instant selection `op`, reading the samples of `input`. + fn try_new(input: &SeriesSchema, op: &BoundInstant) -> Result { + // The chunk this node hands out is addressed on the selection's own grid, so the grid the + // rows are gathered on is the binding's rather than a copy of it. + let schema = Arc::new(SeriesSchema { + fields: Arc::clone(&input.fields), + eval_grid: Some(Arc::clone(&op.output_grid)), + }); + Ok(Self { + selection: op.clone(), + output: GridSeriesBuilder::try_new(Arc::clone(&schema))?, + schema, + chunks: Vec::new(), + held: 0, + }) + } + + /// The bytes the buffered chunks of the open series hold. + fn buffered_bytes(&self) -> usize { + self.held + } + + /// The bytes gathering the series `closing` ends is about to allocate beside its chunks. + /// + /// An upper bound derived from what the selection has in hand rather than a measurement: the + /// rows the series holds once `closing` has joined it, the fields it carries, the points the + /// selection can decide for it, and, per field, the largest histogram a row of it can carry. + /// Each term is one thing the gather allocates: + /// + /// - The concatenated axis ([`buffered_time`]): one `i64` per row, reserved by the row count. + /// - The descriptors that read it ([`buffered_fields`]): one [`Samples`] per (chunk, field) for + /// the per-field vectors, three per segment for the vector [`Samples::try_from_chunks`] + /// flattens them into -- the segment it came from, the vector it is flattened into and the + /// `Arc<[Samples]>` the result is copied into -- and one `Vec` header per field. + /// - The two arrays [`select_instants`] returns: a `u64` source row index and an `i64` + /// evaluation timestamp per point, reserved by the count they can reach at most. + /// - The rows [`GridSeriesBuilder`] keeps: one `usize` grid index, one `f64` per field and a + /// validity byte per (row, field). A field of native histograms adds one `Option` index + /// per row and the payload of the histogram that index names, charged at the largest one the + /// field holds and per *point* rather than per row: one source row can be selected by every + /// point the selection decides, so the point count is what that payload is multiplied by. + /// - The row the selection fills, one [`GridSample`] slot per field, and one [`RowCursor`] per + /// field to read the axis with. + /// - Doubling: every column the builder keeps is a `Vec` that grows by doubling, so each is + /// charged twice what it ends up holding, which bounds its capacity rather than its length. + /// + /// Left out, deliberately: the headers and Arrow buffers behind the buffered chunks (the + /// node's own reservation already holds them, allocation by allocation), the `Vec` headers the + /// gather drops before it returns, `Series`' own header and the runs [`GridSeriesBuilder`] + /// hands the output over with, which the output chunk is charged for by whoever reads it, and + /// the temporaries [`FloatHistogram::push_to`] builds for one row. None of those is + /// proportional to the points the selection decides, which is the amplification the pool has to + /// be asked for, and all of them are constant per gather or already counted row by row. + /// + /// The estimate applies to every gather: nothing refuses one before it allocates, so the points + /// the series can be decided at are reserved for whatever their number is. + /// + /// [`FloatHistogram::push_to`]: crate::histogram_eval::float_histogram::FloatHistogram::push_to + fn gather_bytes(&self, closing: &RawSeriesChunk) -> usize { + // The points the selection decides, not the points the grid plans: the gather clips its + // scan to the series it holds, so a figure over the whole grid would charge the pool for + // rows this series can never produce. + let points = self.selected_points(closing); + let chunks = self.chunks.len().saturating_add(1); + let rows = self + .chunks + .iter() + .chain(std::iter::once(closing)) + .map(|chunk| chunk.time.len()) + .fold(0usize, usize::saturating_add); + let fields = self.schema.fields.len(); + let descriptor = std::mem::size_of::(); + let segments = self + .chunks + .iter() + .chain(std::iter::once(closing)) + .flat_map(|chunk| chunk.fields.as_slice()) + .map(|field| field.segments().len()) + .fold(0usize, usize::saturating_add); + let axis = rows.saturating_mul(std::mem::size_of::()); + let layout = chunks + .saturating_mul(fields) + .saturating_mul(descriptor) + .saturating_add(segments.saturating_mul(3).saturating_mul(descriptor)) + .saturating_add(fields.saturating_mul(std::mem::size_of::>())); + let selection = + points.saturating_mul(std::mem::size_of::() + std::mem::size_of::()); + let mut rows_of_points = points.saturating_mul( + std::mem::size_of::() + fields.saturating_mul(std::mem::size_of::() + 1), + ); + for largest in self.largest_histograms(closing).iter().flatten() { + rows_of_points = rows_of_points.saturating_add( + points.saturating_mul(std::mem::size_of::>().saturating_add(*largest)), + ); + } + let row = fields.saturating_mul( + std::mem::size_of::>() + std::mem::size_of::>(), + ); + axis.saturating_add(layout) + .saturating_add(selection) + .saturating_add(row) + .saturating_add(rows_of_points.saturating_mul(2)) + } + + /// The number of grid points [`select_instants`] clips the buffered series to. + /// + /// The gather clips its scan to the series it holds instead of reading the whole planned grid: + /// the candidate points run from the first sample's instant to the last sample's plus the + /// lookback, aligned to the grid and held inside the query range. A workspace is charged per + /// point, so the count has to be the clipped one -- charging the planned grid charges the pool + /// for rows a short series can never produce, and a pool sized for what the series costs then + /// refuses the gather. The clipping below is [`select_instants`]' own, repeated rather than + /// approximated: an estimate that disagrees with the kernel is a bug here rather than a + /// conservative bound. It is the kernel's own candidate count -- the one it sizes its arrays + /// with -- so it bounds the rows it can report even though a candidate at the lookback edge + /// itself selects nothing. Both ends come from chunks the node already holds, so the count + /// reads two timestamps rather than the rows. + fn selected_points(&self, closing: &RawSeriesChunk) -> usize { + let spec = self.selection.output_grid.spec(); + // The selection refuses these itself, before it can decide anything. + if spec.step_ms <= 0 || self.selection.lookback_ms < 0 { + return 0; + } + let query_start = i128::from(spec.start_ms); + let query_end = i128::from(grid_end_ms(spec)); + if query_end < query_start { + return 0; + } + let series = || self.chunks.iter().chain(std::iter::once(closing)); + let (Some(first), Some(last)) = ( + series().find_map(|chunk| chunk.time.as_buffer().first().copied()), + series() + .rev() + .find_map(|chunk| chunk.time.as_buffer().last().copied()), + ) else { + // A series of no sample decides no point. + return 0; + }; + let offset = i128::from(self.selection.offset_ms); + let lookback = i128::from(self.selection.lookback_ms); + let first = i128::from(first) + offset; + let last = i128::from(last) + offset; + let useful_last = if lookback == 0 { + last + } else { + last + lookback - 1 + }; + let max_start = first.max(query_start); + let min_end = useful_last.min(query_end); + if max_start > min_end { + return 0; + } + let step = i128::from(spec.step_ms); + let aligned_start = query_start + (max_start - query_start) / step * step; + let aligned_end = query_end - (query_end - min_end) / step * step; + let points = (aligned_end - aligned_start) / step + 1; + usize::try_from(points).unwrap_or(usize::MAX) + } + + /// The largest histogram a row of each field can carry, `None` for a field of floats. + /// + /// A row of native histograms is copied into the builder once per grid point that selects it, + /// so what such a field costs is one histogram per point: the largest row is the one to charge, + /// because any row can be the one every decided point picks. + fn largest_histograms(&self, closing: &RawSeriesChunk) -> Vec> { + let mut largest = vec![None; self.schema.fields.len()]; + for chunk in self.chunks.iter().chain(std::iter::once(closing)) { + for (slot, field) in largest.iter_mut().zip(chunk.fields.as_slice()) { + if let Some(bytes) = histogram_row_bytes(field) { + *slot = Some(slot.unwrap_or(0).max(bytes)); + } + } + } + largest + } + + /// Buffers one chunk of the series being selected, and gathers that series when it ends. + /// + /// `None` means the series is still open: the selection reads one whole axis, so nothing is + /// decided for a series until the chunk carrying `is_last` arrives. + fn push(&mut self, path: &NodePath, chunk: RawSeriesChunk) -> Result> { + if let Some(open) = self.chunks.first() + && (open.primary_key.as_slice() != chunk.primary_key.as_slice() + || open.metric != chunk.metric) + { + // One axis is gathered before the kernel reads any of it, so a chunk of another series + // has nowhere to go: it would be selected as though its samples were the open series'. + return Err(series_changed(path)); + } + let closing = chunk.is_last; + self.held = self.held.saturating_add(raw_bytes(&chunk)); + self.chunks.push(chunk); + if !closing { + return Ok(None); + } + self.gather(path).map(Some) + } + + /// Selects the instants of the buffered series, hands it over closed, and drops the buffer. + fn gather(&mut self, path: &NodePath) -> Result { + let chunk = self.select(path)?; + // The selection copied what it needed out of the buffered chunks, so a series that has been + // answered must not keep charging the pool for them. + self.chunks.clear(); + self.chunks.shrink_to_fit(); + self.held = 0; + Ok(chunk) + } + + /// The last sample at or before each grid point of the buffered series, as one chunk. + fn select(&mut self, path: &NodePath) -> Result { + let Some(first) = self.chunks.first() else { + return Err(DataFusionError::Execution(format!( + "the instant selection at {path} holds no series to select" + ))); + }; + let metric = first.metric.clone().ok_or_else(|| no_labels(path))?; + // The buffered chunks are one series, so they are read as the one axis the selection takes. + let time = buffered_time(&self.chunks)?; + let fields = buffered_fields(&self.chunks, self.schema.fields.len())?; + let grid = Arc::clone(&self.selection.output_grid); + let spec = grid.spec(); + // The grid's own points are what the selection decides, so the range and the step it is + // asked for are the grid's: `start..=start + (len - 1) * step`, step by step. + let (indices, timestamps) = select_instants( + &time, + &fields, + spec.start_ms..=grid_end_ms(spec), + spec.step_ms, + self.selection.lookback_ms, + self.selection.offset_ms, + )?; + self.output.begin_series(); + // One cursor per field, so a row is read as the field holds it rather than by walking the + // chunks of a field from its start once per row. + let mut cursors: Vec> = fields.iter().map(Samples::cursor).collect(); + // `GridSample` is not `Clone`, so the row is filled slot by slot rather than from one value. + let mut row: Vec> = (0..fields.len()).map(|_| None).collect(); + let mut read: Option = None; + for (index, timestamp) in indices.iter().zip(×tamps) { + let index = *index as usize; + // The selection steps the grid's range by its step, so every timestamp it reports is a + // point of the grid and the position is the point's index in it. + let position = grid_position(&grid, *timestamp)?; + // Two grid points can select one source row, and the row is read once for both. + if read != Some(index) { + for (slot, cursor) in row.iter_mut().zip(&mut cursors) { + let sample = cursor.at(index).ok_or_else(|| missing_row(path, index))?; + *slot = owned(sample)?; + } + read = Some(index); + } + // A position no field holds a value at is not a row: the builder drops it, which is + // what keeps a hole in the grid out of the result instead of padding it. + self.output.push_samples(position, &row)?; + } + // The rows the selection picked are the rows this series holds, and the whole series is + // decided at once, so this one chunk closes it. + match self.output.finish(metric.clone())? { + Some(series) => EvaluatedChunk::try_new(series, true), + None => no_row_chunk(&self.schema, metric), + } + } +} + +/// One operand of a binary node, chunk by chunk, until it ends. +/// +/// What is kept is the series each chunk carries, not a concatenation of them: a chunk is retained +/// as it arrives and nothing is copied on the way in, because the chunks of a series can share an +/// allocation and the figure the operand charges for is the data it holds rather than a running copy +/// of it. +/// +/// The kernel matches whole series by label set, so the chunks are assembled into one series per +/// logical series once the input has ended: a series that arrived in a thousand chunks is otherwise +/// a thousand candidates on this side for every candidate of the other, and its own rows would be +/// paired a chunk at a time. +#[derive(Default)] +struct BinaryOperand { + /// The series whose last chunk did not close it, with the position after its last row. + /// + /// `None` when no series is open: nothing has arrived yet, or the last series closed. A label + /// set may be closed more than once -- a node that rewrites labels can make two series one -- + /// so a chunk that starts a series again is not an error, only one that starts it before the + /// series already open ended, or names another series while it is open. + open: Option<(MetricName, usize)>, + /// The chunks this operand handed over, in arrival order. + series: Vec, + /// The chunk count at which each logical series closed, exclusive, in arrival order. + /// + /// The chunks `start..end` of one entry are one logical series: a label set that closes and + /// starts again is two of them, so a list of ends is what keeps the two apart where a label set + /// alone would read them as one. Only a chunk carrying `is_last` records an end, and it does so + /// whether or not it carries a row. + ends: Vec, + /// The histogram tables the chunks this operand holds index into, by the address of the + /// allocation behind their `Arc`. + /// + /// A table is one allocation however many chunks of a series index into it, so it is billed + /// once -- by the first chunk that references it -- rather than once per chunk, and the tables + /// this set names are the ones already billed. That is what keeps a series delivered in a + /// thousand chunks from costing a thousand tables, and what keeps a table from costing nothing: + /// a chunk's own figure leaves its tables out ([`operand_chunk_bytes`]), so a table billed by + /// neither this operand nor this set is a table no reservation covers. One slot per billed + /// table is charged with it, so the set's own storage is not a figure no reservation covers + /// either. + tables: HashSet, + /// The bytes `series` and `ends` hold, folded in as chunks arrive. + /// + /// Each chunk is measured once, with the figure of what it holds on its own + /// ([`operand_chunk_bytes`]): the samples its rows occupy and the descriptors it keeps, not the + /// allocation those samples are slices of, so a series delivered in many chunks is charged the + /// data it holds rather than the same buffer once per chunk. The histogram tables the chunks + /// reference are the other half of that figure: one allocation the chunks share, billed once -- + /// with the one slot that remembers it -- the first time a chunk referencing it arrives + /// ([`unbilled_tables`]). + held: usize, +} + +impl BinaryOperand { + /// The bytes `chunk` would add to what this operand holds, read without retaining it. + /// + /// It is what [`Self::enqueue`] adds for the same chunk: what the chunk holds on its own, the + /// histogram tables it is the first to reference, and the one entry a chunk that closes its + /// series records in the boundary list. The boundary list holds one `usize` per closed series and + /// is charged one entry at a time as it is written, rather than from the capacity it grows to -- + /// following that `Vec`'s first-four-then-double policy would be a second copy of it to keep in + /// step, and one entry within a factor of two is the granularity the accounting aims at. The + /// figure is what a caller reserves before it retains the chunk, so the pool admits it before + /// the operand holds it. + fn pending(&self, chunk: &EvaluatedChunk) -> usize { + let end = if chunk.is_last { + std::mem::size_of::() + } else { + 0 + }; + let (_, tables) = unbilled_tables(&chunk.series, &self.tables); + tables + .saturating_add(operand_chunk_bytes(&chunk.series)) + .saturating_add(end) + } + + /// Retains one chunk, folding the estimate it is charged with into what the operand holds. + fn enqueue(&mut self, chunk: EvaluatedChunk) { + let closing = chunk.is_last; + // The tables this chunk is the first to reference, read before they are recorded: the same + // figure `pending` billed, so what is reserved for the chunk and what it grows the operand + // by are one. + let (tables, bytes) = unbilled_tables(&chunk.series, &self.tables); + // The boundary list is storage the operand keeps, and it grows before the chunk is recorded + // in it: an end is charged for before it exists, the same figure `pending` reported. + self.held = self + .held + .saturating_add(if closing { + std::mem::size_of::() + } else { + 0 + }) + .saturating_add(operand_chunk_bytes(&chunk.series)) + .saturating_add(bytes); + // From here the operand keeps those tables alive itself, so a chunk arriving later that + // references one is charged its own slices and not the table again. + self.tables.extend(tables); + self.series.push(chunk.series); + if closing { + self.ends.push(self.series.len()); + } + } + + /// The chunk ranges of the logical series this operand closed, in arrival order. + /// + /// Read after the input ended: a series that is still open has no end, and + /// [`BinaryRuntime::closed`] refuses such an input before anything is assembled. + fn boundaries(&self) -> impl Iterator> + '_ { + self.ends.iter().scan(0, |start, &end| { + let range = *start..end; + *start = end; + Some(range) + }) + } + + /// The bytes assembling this operand's chunks into logical series allocate, before they do. + /// + /// One series per closed logical series, on `schema`'s grid, and nothing that copies a sample: + /// the descriptors the chunks' fields are made of are collected and shared. What is counted is + /// therefore metadata only, and it is a rough figure per field, per segment and per run rather + /// than a model of the containers the work builds: + /// + /// - per series, the assembled entry and the field list ([`SeriesFields`] takes a one-field list + /// out of its vector and boxes a wider one, so neither copies); + /// - per chunk and field, the descriptor collected out of it; + /// - per segment, three descriptors: the one the flatten copies out, the slot the `Arc<[Samples]>` + /// it is copied into holds, and the doubling of the vector it is copied out of; + /// - per run the boundary covers, the span [`Self::assemble`] collects and the span and + /// row-offset arrays [`TimeAxis::from_grid_spans`] copies them into. + /// + /// No term follows how a `Vec` happens to grow -- there is no branch on a capacity here and no + /// first-allocation floor -- so a change to the flatten's growth policy cannot make this figure + /// wrong. What it is instead is a rough per-field, per-segment and per-run estimate, within a + /// small factor of what the assembly holds at its peak, which is the granularity a reservation + /// is made at. + fn assembly_bytes(&self, schema: &SeriesSchema) -> Option { + let samples = std::mem::size_of::(); + let grids = std::mem::size_of::(); + let width = schema.fields.len(); + let mut bytes = 0usize; + for boundary in self.boundaries() { + let chunks = &self.series[boundary]; + // The runs the boundary covers, and the segments its fields hold: a chunk's field can + // itself be chunked, and flattening it copies one descriptor per segment. + let mut runs = 0usize; + let mut segments = 0usize; + for chunk in chunks { + runs = runs.checked_add(chunk.time.runs().count())?; + for field in chunk.fields.iter() { + segments = segments.checked_add(field.segments().len())?; + } + } + // The descriptors of a field's chunks, the flatten's descriptors and the `Arc` they are + // copied into; a field with no segment still builds an empty `Samples`, which is one + // descriptor. + let descriptors = chunks + .len() + .checked_mul(width)? + .checked_add(segments.checked_mul(3)?.checked_add(width)?)?; + // The axis: the spans collected, and the span and offset arrays a run layout copies + // them into. + let axis = runs.checked_mul( + grids + .checked_mul(2)? + .checked_add(std::mem::size_of::())?, + )?; + bytes = bytes + .checked_add(std::mem::size_of::())? + .checked_add(width.checked_mul(samples)?)? + .checked_add(descriptors.checked_mul(samples)?)? + .checked_add(axis)?; + } + Some(bytes) + } + + /// The logical series this operand closed, each as one series on `schema`'s grid. + /// + /// The chunks of a logical series are collected, not concatenated: the fields keep one + /// descriptor per segment of every chunk, the axis keeps the runs the chunks cover, and the + /// buffers behind both are shared with the chunks this operand still holds. The series is what + /// the kernel matches and reads, so it must be on the schema's grid and hold as many rows as its + /// axis places, which is what [`Series::try_new`] checks. What it allocates is + /// [`Self::assembly_bytes`], which a caller reserves before this runs. + fn assemble(&self, schema: &SeriesSchema, path: &NodePath, side: usize) -> Result> { + let grid = schema.eval_grid.clone().ok_or_else(|| { + DataFusionError::Execution(format!( + "the binary node at {path} assembles its {} operand on an evaluation grid, and the \ + operand's schema names none", + side_name(side) + )) + })?; + let mut assembled = Vec::with_capacity(self.ends.len()); + for boundary in self.boundaries() { + let chunks = &self.series[boundary]; + let metric = chunks.first().map(|chunk| chunk.metric.clone()).ok_or_else(|| { + DataFusionError::Execution(format!( + "the binary node at {path} closed a logical series of its {} operand without a \ + chunk to assemble", + side_name(side) + )) + })?; + let runs = chunks + .iter() + .map(|chunk| chunk.time.runs().count()) + .fold(0usize, usize::saturating_add); + let mut spans = Vec::with_capacity(runs); + for chunk in chunks { + for run in chunk.time.runs() { + spans.push(GridSpan::new(run.position, run.len)); + } + } + let mut fields = Vec::with_capacity(schema.fields.len()); + for index in 0..schema.fields.len() { + let mut segments = Vec::with_capacity(chunks.len()); + for chunk in chunks { + let field = chunk.fields.get(index).ok_or_else(|| { + DataFusionError::Execution(format!( + "the binary node at {path} cannot assemble its {} operand: a chunk of \ + it carries {} fields, not {}", + side_name(side), + chunk.fields.len(), + schema.fields.len() + )) + })?; + segments.push(field.clone()); + } + fields.push(Samples::try_from_chunks(segments).map_err(series_error)?); + } + let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?; + let time = TimeAxis::from_grid_spans(grid.clone(), spans).map_err(series_error)?; + assembled.push(Series::try_new(schema, metric, time, fields).map_err(series_error)?); + } + Ok(assembled) + } + + /// Drops the retained chunks, giving back what they hold. + fn release(&mut self) { + self.open = None; + self.series.clear(); + self.series.shrink_to_fit(); + self.ends.clear(); + self.ends.shrink_to_fit(); + // The tables the cleared chunks were keeping alive are gone with them, so their addresses + // name nothing this operand holds any more. + self.tables.clear(); + self.tables.shrink_to_fit(); + self.held = 0; + } +} + +/// What a binary node holds: both operands until they end. +/// +/// The operation pairs two whole vectors point by point, so this node cannot answer from the chunks +/// in hand the way a map does: it retains every chunk each operand hands over, assembles the chunks +/// of each logical series into the one series the kernel matches, and runs the kernel once, after the +/// input has ended and both operands closed. The chunks it produces are queued in the node's own +/// output queue and handed over from there. +struct BinaryRuntime { + /// The operation and its modifiers, bound by the compiler. + matching: Arc, + /// The layout each operand is bound to, what a chunk of it is checked against: `0` is the left + /// operand and `1` the right one, the order the tree declares them in. + schemas: [Arc; 2], + /// The retained chunks of each operand, in the same order. + operands: [BinaryOperand; 2], + /// Whether the kernel has run. It runs at most once: the operands it read are gone afterwards. + computed: bool, +} + +/// What side `index` is called in an error. +fn side_name(index: usize) -> &'static str { + match index { + 0 => "left", + _ => "right", + } +} + +impl BinaryRuntime { + /// The run-time state of the binary operation `matching` over its two operands. + fn new(matching: Arc, schemas: [Arc; 2]) -> Self { + Self { + matching, + schemas, + operands: [BinaryOperand::default(), BinaryOperand::default()], + computed: false, + } + } + + /// The bytes the retained operands hold. + fn retained_bytes(&self) -> usize { + self.operands + .iter() + .map(|operand| operand.held) + .fold(0usize, usize::saturating_add) + } + + /// The bytes assembling both operands into logical series allocates, before it does. + fn assembly_bytes(&self) -> Option { + let [left, right] = &self.operands; + let [left_schema, right_schema] = &self.schemas; + left.assembly_bytes(left_schema)? + .checked_add(right.assembly_bytes(right_schema)?) + } + + /// The logical series both operands closed, ready for the kernel to match. + fn assemble(&self, path: &NodePath) -> Result<[Vec; 2]> { + let [left, right] = &self.operands; + let [left_schema, right_schema] = &self.schemas; + Ok([ + left.assemble(left_schema, path, 0)?, + right.assemble(right_schema, path, 1)?, + ]) + } + + /// The bytes the chunk of `side` would add to that operand's retention. + /// + /// It is read from the operand before the chunk is retained, so the figure is the one the + /// operand grows by: what the chunk holds on its own and the room its end takes in the operand's + /// boundary list. + fn pending(&self, path: &NodePath, side: usize, chunk: &EvaluatedChunk) -> Result { + self.operands + .get(side) + .map(|operand| operand.pending(chunk)) + .ok_or_else(|| no_binary(path)) + } + + /// Reports an operand that ended inside a series. + /// + /// A side hands over one series at a time, so the only series that can be open is the last one + /// it handed over: a chunk that did not say `is_last` leaves it open, and nothing came after it + /// to close it. The kernel is not run over such an operand: it would answer the pairs of a + /// series whose remaining rows were never read. + fn closed(&self, path: &NodePath) -> Result<()> { + for (side, operand) in self.operands.iter().enumerate() { + let Some((metric, _)) = &operand.open else { + continue; + }; + return Err(DataFusionError::Execution(format!( + "the input of the binary node at {path} ended before the last chunk of a series: \ + its {} operand handed over {metric:?} without the chunk that closes it", + side_name(side) + ))); + } + Ok(()) + } + + /// Retains one chunk of the operand at `side`, checking it against that operand's binding. + fn retain(&mut self, path: &NodePath, side: usize, chunk: EvaluatedChunk) -> Result<()> { + // What a bound tree says an operand produces is not proof of what a chunk carries: a + // `Series` keeps its fields public, so a chunk built by struct literal can carry another + // number of fields, or fewer samples than its axis places rows. The kernel's own check is + // run here, before the chunk enters the buffer, and the position and side are added to what + // it reports. + let Some(schema) = self.schemas.get(side) else { + return Err(no_binary(path)); + }; + validate_binary_operand(schema.as_ref(), std::slice::from_ref(&chunk.series)).map_err( + |error| { + DataFusionError::Execution(format!( + "the binary node at {path} rejected its {} operand: {error}", + side_name(side) + )) + }, + )?; + // An empty chunk closes a series without holding a row, so it says nothing about where that + // series ended: only a chunk that carries rows can be read as going backwards. + let (first, last) = ( + chunk.series.time.first_position(), + chunk.series.time.last_position(), + ); + let metric = chunk.series.metric.clone(); + let Some(operand) = self.operands.get_mut(side) else { + return Err(no_binary(path)); + }; + // The position a chunk of the open series may start at: the row after the last one that + // series handed over. Nothing is open after a series closed, so the next one starts over. + let end = operand.open.as_ref().map_or(0, |(_, end)| *end); + if let Some((open, _)) = &operand.open + && *open != metric + { + return Err(DataFusionError::Execution(format!( + "the binary node at {path} combines whole series, and its {} operand handed over \ + {metric:?} before {open:?} ended", + side_name(side) + ))); + } + if let Some(first) = first + && first < end + { + return Err(DataFusionError::Execution(format!( + "the chunks of {metric:?} handed to the {} operand of the binary node at {path} do \ + not continue each other: one starts at position {first}, after the series already \ + reached {end}", + side_name(side) + ))); + } + operand.open = (!chunk.is_last).then(|| (metric, last.map_or(end, |last| last + 1))); + operand.enqueue(chunk); + Ok(()) + } + + /// Runs the kernel over both operands and returns the series it produced. + /// + /// The chunks of each operand are assembled into the logical series they make up first, because + /// the kernel matches whole series by label set: a series that arrived in many chunks would + /// otherwise be a candidate per chunk on its own side and be paired with every candidate of the + /// other, which is quadratic in the chunk count of one series rather than in the series count. + /// + /// The reservation covers the retained chunks, the assembled series the kernel reads and the + /// kernel's own live workspace, and it is what the pool admits before each of them allocates. + /// The kernel reports that workspace coarsely -- where a long-lived result buffer grows, once per + /// phase of its walk, and in the blocks a growing output buffer is reserved in -- rather than per + /// grid point, and the total is resized as a phase's storage is released. It keeps covering the + /// returned results until the caller queues them. + fn compute(&mut self, path: &NodePath, buffer: &mut NodeBuffer) -> Result>> { + // The kernel reads the operands once and drops them, so a second call has nothing to read + // and nothing left to produce: what it produced the first time is in the node's queue, and + // the reservation is already the queue's. + if self.computed { + return Ok(None); + } + self.closed(path)?; + let [left_schema, right_schema] = &self.schemas; + let retained = self.retained_bytes(); + // The assembled series are live while the kernel reads them and share the buffers the + // retained chunks hold, so what they add is metadata, and it is reserved before it exists: + // the assembly allocates as it goes, and a figure read from it afterwards would be a figure + // the pool never admitted. + let assembly = self + .assembly_bytes() + .ok_or_else(|| reservation_overflow(path))?; + buffer.grow(assembly)?; + let assembled = match self.assemble(path) { + Ok(assembled) => assembled, + Err(error) => { + // Nothing the assembly allocated outlives this call, so the node falls back to what + // it still holds. A failure of that resize is the pool's to report; the driver stops + // the execution either way and releases every node. + buffer.resize(retained)?; + return Err(error); + } + }; + let [left, right] = &assembled; + // The operands are still held while the kernel runs, so what this node holds is the operands, + // the assembled series and the workspace the kernel reports; the callback resizes the + // reservation to that sum as the live workspace changes. + let metrics = Arc::clone(&buffer.metrics); + let output = { + // The timer covers this node's own work only: it is dropped before the driver polls + // the input again. + let _timer = metrics.timer(); + binary_vectors_with_reservation( + &self.matching, + left_schema, + left, + right_schema, + right, + &mut |workspace| { + let bytes = retained + .checked_add(assembly) + .and_then(|held| held.checked_add(workspace)) + .ok_or_else(|| reservation_overflow(path))?; + buffer.resize(bytes) + }, + ) + }; + // The operands and the assembled series have been handed to the kernel and the reservation + // covers the workspace it allocated past them, so a failure is the driver's to release: it + // stops the execution and every node with it. + let output = output?; + // The assembled series were the kernel's input and are read by nothing after it, so they go + // before the chunks they share their buffers with: what this node holds from here on is what + // the kernel returned, and the pool is not charged for a vector nothing reads again. + drop(assembled); + for operand in &mut self.operands { + operand.release(); + } + self.computed = true; + Ok(Some(output)) + } +} + +/// The buffered chunks as the one source axis they make up: their timestamps in arrival order. +/// +/// The axis type validates the result as strictly increasing, which is also what refuses a series +/// whose chunks do not continue each other. +fn buffered_time(chunks: &[RawSeriesChunk]) -> Result { + let len = chunks.iter().map(|chunk| chunk.time.len()).sum(); + let mut timestamps: Vec = Vec::with_capacity(len); + for chunk in chunks { + timestamps.extend_from_slice(chunk.time.as_buffer()); + } + RawTimestamps::try_new(ScalarBuffer::from(timestamps)).map_err(series_error) +} + +/// The buffered chunks as one axis: per field, the chunks' samples in arrival order. +/// +/// A field retains the chunks it arrived in instead of copying them out, so the axis costs one +/// descriptor per chunk and the selection reads the values where they already are. +fn buffered_fields(chunks: &[RawSeriesChunk], fields: usize) -> Result { + let mut per_field: Vec> = vec![Vec::with_capacity(chunks.len()); fields]; + for chunk in chunks { + for (field, slot) in chunk.fields.iter().zip(&mut per_field) { + slot.push(field.clone()); + } + } + let fields = per_field + .into_iter() + .map(|chunks| Samples::try_from_chunks(chunks).map_err(series_error)) + .collect::>>()?; + SeriesFields::try_from_vec(fields).map_err(series_error) +} + +/// The bytes the builder's table holds for one row of the field, `None` for a field of floats. +/// +/// The largest row of the field rather than its total: every grid point that selects one source row +/// copies that row, so the widest histogram the field holds is what a point can cost. +fn histogram_row_bytes(field: &Samples) -> Option { + let holds_histograms = field.segments().iter().any(|segment| { + matches!( + segment.dense(), + Some(DenseSamplesRef::Histogram(_) | DenseSamplesRef::Mixed(_)) + ) + }); + if !holds_histograms { + return None; + } + Some( + field + .iter() + .filter_map(|sample| match sample { + SampleRef::Histogram(view) => Some(histogram_bytes(&view)), + _ => None, + }) + .fold(0, usize::max), + ) +} + +/// The bytes the histogram table holds for one row of `view`. +/// +/// The row `HistogramBatchBuilder::push` writes: its scalar columns, the offset each of the seven +/// bucket lists pays for it, and the values those lists hold -- the custom bounds, and each side's +/// bucket counts with the span offsets and lengths that place them. The spans are the view's own, +/// because a histogram handed on unchanged keeps its layout through +/// [`crate::histogram_eval::float_histogram::FloatHistogram::push_to`]. +fn histogram_bytes(view: &HistogramView<'_>) -> usize { + // Schema, zero threshold, sum, count, zero count, reset hint and start timestamp, the narrow + // columns counted at the width of the widest. + let scalars = 7 * std::mem::size_of::(); + // One offset per list column: custom bounds, two span columns and one bucket column per side. + let list_offsets = 7 * std::mem::size_of::(); + let custom = view + .custom_values + .len() + .saturating_mul(std::mem::size_of::()); + let sides = [view.positive, view.negative] + .iter() + .map(|side| { + side.span_offsets + .len() + .saturating_mul(2) + .saturating_mul(std::mem::size_of::()) + .saturating_add( + side.buckets + .len() + .saturating_mul(std::mem::size_of::()), + ) + }) + .fold(0usize, usize::saturating_add); + scalars + .saturating_add(list_offsets) + .saturating_add(custom) + .saturating_add(sides) +} + +/// The last timestamp of `spec`, which is inclusive: its `len` points step from its start. +/// +/// [`GridSpec::try_new`] checked that the point fits `i64`, so widening it here cannot overflow. +fn grid_end_ms(spec: GridSpec) -> i64 { + (i128::from(spec.start_ms) + i128::from(spec.step_ms) * (i128::from(spec.len) - 1)) as i64 +} + +/// The position of the grid point at `timestamp`, which the selection reported as one of its own. +/// +/// The selection steps the range it is given by the step it is given, so every timestamp it reports +/// is `start_ms + position * step_ms` for one position of the grid: subtracting the start and +/// dividing by the step gives that position back. A timestamp off that lattice, or one past the end +/// of the grid, is a disagreement between the selection and its binding rather than a sample to +/// skip, so it is reported instead of dropped. +fn grid_position(grid: &EvalGrid, timestamp: i64) -> Result { + let spec = grid.spec(); + let offset = i128::from(timestamp) - i128::from(spec.start_ms); + let step = i128::from(spec.step_ms); + let position = offset.div_euclid(step); + if offset.rem_euclid(step) != 0 || position < 0 || position >= i128::from(spec.len) { + return Err(DataFusionError::Execution(format!( + "the instant selection reported the timestamp {timestamp}ms, which is not a point of \ + its grid {spec:?}" + ))); + } + Ok(position as usize) +} + +/// A closing chunk carrying `metric` and no row at all. +/// +/// A series whose selection picked no source row still closes exactly once, on a chunk that holds +/// nothing: the labels say which series closed, and the address says it closed before its first +/// point, as the empty chunk a window hands out for such a series does. +fn no_row_chunk(schema: &SeriesSchema, metric: MetricName) -> Result { + let grid = schema.eval_grid.clone().ok_or_else(|| { + DataFusionError::Execution( + "an instant selection produces an evaluated chunk, which is addressed on a grid" + .to_string(), + ) + })?; + let empty = Samples::from_float(Float64Array::from(Vec::::new())); + let fields = + SeriesFields::try_from_vec(vec![empty; schema.fields.len()]).map_err(series_error)?; + let time = GridRange::try_new(grid, 0, 0).map_err(series_error)?; + let series = + Series::try_new(schema, metric, TimeAxis::Grid(time), fields).map_err(series_error)?; + EvaluatedChunk::try_new(series, true) +} + /// The per-node run-time state of a node. struct NodeRuntime { buffer: NodeBuffer, /// The chunks this node holds for its consumer, each with the estimate it was queued with. /// - /// An input node's queue is filled by the caller, and a window's by the chunks it computed while - /// flushing its collected input; no node uses it for both. A chunk is measured once, as it - /// enters, and the figure it was queued with is given back as it leaves, so neither the queue - /// nor the handover walks it. + /// An input node's queue is filled by the caller, a window's by the chunks it computed while + /// flushing its collected input, and a binary node's by the results its kernel produced; no node + /// uses it for both. A chunk is measured once, as it enters, and the figure it was queued with + /// is given back as it leaves, so neither the queue nor the handover walks it. queued: VecDeque<(NativeChunk, usize)>, + /// What an instant node holds: the chunks of the series it is selecting, and, while it gathers + /// that series, the workspace the gather reserved for. `None` for every other kind of node. + instant: Option, /// A window node's evaluator, with its own input and output grid; `None` before it is built and /// once it is closed. window: Option, /// What a map node applies. map: Option, + /// What a binary node holds. + binary: Option, + /// The layout the caller's chunks of an input node are checked against. + /// + /// A tree with a binary node reads two inputs, and each of them is bound to its own layout, so + /// the binding is kept per input rather than once for the tree. + source_schema: Option>, /// What this node has already handed out under each output label set, for a node that rewrites /// labels: a window drops the metric name and the empty-valued labels, a map drops the name. emitted: Option, @@ -892,12 +1933,14 @@ impl NodeRuntime { Ok(()) } - /// Hands over the next queued source chunk, if there is one. + /// Hands over the next queued chunk, if there is one, giving back what it was queued with. /// - /// The handover is what [`Self::open_source_series`] follows: after this call the flag says - /// whether the series the consumer just received a chunk of is still open, which is what closing - /// the execution reads to tell a truncated input from one that ended cleanly. - fn pop_source(&mut self) -> Result> { + /// It is the one way a chunk leaves this node's queue: an input node hands over what the caller + /// queued, and a binary node hands over what its kernel produced. `values` is how that node + /// counts the values it hands over, because the two do not count the same thing: an input's + /// figure has always been its positions, while a binary result holds one value per field and a + /// field may have none at a position it decided. + fn pop_queued(&mut self, values: fn(&NativeChunk) -> usize) -> Result> { let Some((chunk, bytes)) = self.queued.pop_front() else { return Ok(None); }; @@ -909,17 +1952,31 @@ impl NodeRuntime { let _timer = metrics.timer(); self.buffer.shrink(bytes)?; } - metrics.record_output(1, chunk.positions()); - // An evaluated source is already addressed on its grid, so its decided positions are grid - // points; a raw source carries timestamps, which are not positions on any grid. + metrics.record_output(1, values(&chunk)); + // An evaluated chunk is addressed on its grid, so its decided positions are grid points; a + // raw source carries timestamps, which are not positions on any grid. if let NativeChunk::Evaluated(chunk) = &chunk { metrics.record_grid_points(chunk.series.time.len()); } + Ok(Some(chunk)) + } + + /// Hands over the next queued source chunk, if there is one. + /// + /// The handover is what [`Self::open_source_series`] follows: after this call the flag says + /// whether the series the consumer just received a chunk of is still open, which is what closing + /// the execution reads to tell a truncated input from one that ended cleanly. Only an input node + /// follows that flag, so only it reads the handover this way: a binary node's queue holds the + /// results of series that already closed on their way in. + fn pop_source(&mut self) -> Result> { + let Some(chunk) = self.pop_queued(NativeChunk::positions)? else { + return Ok(None); + }; // Assigned rather than only set: a chunk that closes its series is what says no series is // open any more, so the flag follows the handover and not the history of handovers. self.open_source_series = !chunk.is_last(); if chunk.is_last() { - metrics.record_completed_series(1); + self.buffer.metrics.record_completed_series(1); } Ok(Some(chunk)) } @@ -1029,6 +2086,171 @@ impl NodeRuntime { Ok(output) } + /// Retains one operand chunk of this node's binary operation. + /// + /// Nothing is decided for a point yet: the kernel needs both operands whole, so a chunk is only + /// kept until the input ends. What the node holds is the estimate of every chunk it retained, + /// and the reservation is set to that figure once the chunk is in: the operand's own total is + /// what the node keeps, so a second chunk does not have to be admitted beside the first one's + /// estimate again. + /// + /// The chunk is reserved for before it is retained, by the figure the operand reports for it, so + /// the pool admits the memory before the node holds it and a refused chunk leaves the operand + /// where it was. + fn retain_binary(&mut self, path: &NodePath, side: usize, chunk: NativeChunk) -> Result<()> { + let NativeChunk::Evaluated(chunk) = chunk else { + return Err(DataFusionError::Execution(format!( + "the binary node at {path} consumes evaluated chunks, not raw samples" + ))); + }; + // The figure is read before the chunk is retained, because reserving after the fact would be + // reserving for memory the node already holds. + let pending = self + .binary + .as_ref() + .ok_or_else(|| no_binary(path))? + .pending(path, side, &chunk)?; + let positions = chunk.series.time.len(); + self.buffer.grow(pending)?; + let metrics = Arc::clone(&self.buffer.metrics); + { + let _timer = metrics.timer(); + let binary = self.binary.as_mut().ok_or_else(|| no_binary(path))?; + binary.retain(path, side, chunk)?; + let retained = binary.retained_bytes(); + self.buffer.resize(retained)?; + } + metrics.record_input(1, positions); + Ok(()) + } + + /// Runs this node's binary kernel and queues the chunks it produced. + fn compute_binary(&mut self, path: &NodePath) -> Result<()> { + let output = { + let binary = self.binary.as_mut().ok_or_else(|| no_binary(path))?; + binary.compute(path, &mut self.buffer)? + }; + // A kernel that already ran has moved its result into the queue, which the handover below + // charges for: leaving the reservation alone here is what keeps a queued result covered. + let Some(output) = output else { + return Ok(()); + }; + // The results are queued the way a node that produces a chunk per input queues what it + // hands on: the queue is the one source of chunk order and of the bytes queued chunks hold. + let mut closed = 0usize; + for series in output { + // The kernel decided every point of a result series at once, so the one chunk it is + // handed over as closes it. + let chunk = NativeChunk::Evaluated(EvaluatedChunk::try_new(series, true)?); + // The result is already admitted: the kernel kept it inside the workspace its callback + // reserved. What the queue keeps is the estimate of the chunk that holds it. + let bytes = chunk.bytes(); + self.queued.push_back((chunk, bytes)); + closed += 1; + } + // This node's own accounting of closed series is the results it closed, one per matched + // series: an operand chunk that closed its input series is a closure of the node below, and + // counting it here as well would report the same work twice. + self.buffer.metrics.record_completed_series(closed); + // The operands the reservation covered are gone and the queue holds what the kernel + // returned, so the reservation settles on the queue: what a queued result is given back + // with as it leaves is exactly the figure it is held for here. + let queued = self + .queued + .iter() + .fold(0usize, |total, (_, bytes)| total.saturating_add(*bytes)); + self.buffer.resize(queued) + } + + /// Feeds one chunk to this node's instant selection. + /// + /// `None` means the series this chunk belongs to has not ended: the selection reads one whole + /// axis, so it decides nothing until the chunk carrying `is_last` arrives. + fn instant(&mut self, path: &NodePath, chunk: NativeChunk) -> Result> { + let NativeChunk::Raw(chunk) = chunk else { + return Err(DataFusionError::Execution(format!( + "the instant selection at {path} consumes raw samples, not an evaluated chunk" + ))); + }; + let (positions, closing) = (chunk.time.len(), chunk.is_last); + // The chunk is held from here on: a selection keeps every chunk of a series until the one + // that closes it, so what this node reserves for is the series it has buffered. + self.buffer.grow(raw_bytes(&chunk))?; + // The chunk that closes the series gathers it in one go, and the gather allocates a + // workspace of its own beside the buffered chunks: the axis it concatenates, the descriptors + // that read it, the two arrays the selection returns and the rows the builder keeps. That + // workspace is reserved here, before it exists, so a pool too small for it refuses the + // gather instead of learning about it afterwards. Without this the reservation would fall + // back to the buffered chunks alone -- nothing at all, on the chunk that ends the series -- + // and a selection over a million grid points would take its tens of megabytes without + // asking. [`InstantRuntime::gather_bytes`] derives the figure, because the chunks it counts + // are that node's. + let Some(instant) = self.instant.as_ref() else { + return Err(DataFusionError::Execution(format!( + "the node at {path} holds no instant selection" + ))); + }; + let scratch = if closing { + instant.gather_bytes(&chunk) + } else { + 0 + }; + self.buffer.grow(scratch)?; + let metrics = Arc::clone(&self.buffer.metrics); + let outcome = { + // The timer covers this node's own work only: it is dropped before the driver polls + // the input again. + let _timer = metrics.timer(); + match self.instant.as_mut() { + Some(instant) => instant.push(path, chunk), + // Rejected when the state was built, since a selection reads raw samples; kept as + // an error rather than a panic so an impossible tree cannot take the process down. + None => Err(DataFusionError::Execution(format!( + "the node at {path} holds no instant selection" + ))), + } + }; + metrics.record_input(1, positions); + if closing { + // A series closes exactly once, on the chunk carrying `is_last`: the selection gathers + // the whole series on it, so it is counted here rather than on the chunk handed out. + metrics.record_completed_series(1); + } + // A failed gather gives its workspace back here rather than leaving it to the driver: the + // driver releases every node when the execution stops, but the workspace is this call's and + // not something the node keeps, so holding the pool's budget for it until the stopped + // executor is dropped would charge the pool for memory nothing reads any more. + let output = match outcome { + Ok(output) => output, + Err(error) => { + self.settle_buffered()?; + return Err(error); + } + }; + if let Some(output) = &output { + metrics.record_grid_points(output.series.time.len()); + metrics.record_output(1, valid_values(output)); + } + // What this node still holds is the chunks of the series it is selecting: a whole series is + // held until it ends, so the reservation is what those chunks hold rather than a figure + // that grows with the chunk count of anything already answered. The chunk just consumed and + // the workspace of the gather it closed are both gone, so this is what gives them back. + self.settle_buffered()?; + Ok(output) + } + + /// Sets this node's reservation to the chunks of the series it is still gathering. + /// + /// The chunk the node just consumed and the workspace of a gather it closed are not part of it: + /// the first has left the buffer and the second has been handed to the output. + fn settle_buffered(&mut self) -> Result<()> { + let buffered = self + .instant + .as_ref() + .map_or(0, InstantRuntime::buffered_bytes); + self.buffer.resize(buffered) + } + /// Keeps one fragment of this node's collected input, charged for as it arrives. /// /// The fragment is measured once, here, and its estimate stands until the flush that merges it @@ -1124,12 +2346,15 @@ impl NodeRuntime { /// Returns everything this node holds, including queued chunks. fn release(&mut self) { - // The window goes first: dropping the evaluator is what gives back the memory its - // reservation was taken for. Returning the reservation while the evaluator still held the - // samples would let the pool admit memory the process has not released, for as long as the - // caller keeps the stopped executor alive. The label sets this node handed out and the - // fragments it collected go with it. + // A node's own state goes first: dropping the evaluator and the buffered series is what + // gives back the memory their reservation was taken for. Returning the reservation while + // they still held the samples would let the pool admit memory the process has not released, + // for as long as the caller keeps the stopped executor alive. The label sets this node + // handed out and the fragments it collected go with it. self.window = None; + self.instant = None; + self.binary = None; + self.source_schema = None; self.emitted = None; self.merge = None; // A node that holds no chunk holds no series either, so nothing it handed over is still @@ -1156,10 +2381,13 @@ pub struct NativeExecutionState { paths: Vec, /// The per-node state, in the same order. runtimes: Vec, - /// The index of the tree's input node. - source: usize, - /// Whether the source hands over evaluated chunks rather than raw samples. - source_is_evaluated: bool, + /// The index of every node, so a caller names a node the way the metrics do. + by_path: HashMap, + /// The index of every input node, in traversal order: where a caller's chunks enter. + /// + /// A tree of unary nodes has one, and a binary node adds one per operand: a tree of nested + /// binary nodes has as many as it has leaves, and a queued chunk names the one it belongs to. + sources: Vec, } impl NativeExecutionState { @@ -1173,25 +2401,25 @@ impl NativeExecutionState { metrics_set: &ExecutionPlanMetricsSet, partition: usize, ) -> Result { - // One pass down the tree names and registers every node in the order + // One pass over the tree names and registers every node in the order // `crate::native::metrics::walk` gives it: the same rule `EXPLAIN` uses, so a node cannot be - // shown at one position and registered at another. Every node this runtime executes is - // unary, so that order is the chain from the root to the input, and a node's input is the - // next one the pass reaches. + // shown at one position and registered at another. That order reaches a node's left operand + // before its right one, so the input a spec names -- the one input of a unary node, the left + // operand of a binary node -- is the node the pass reaches next. let mut nodes: Vec = Vec::new(); let mut paths: Vec = Vec::new(); let mut runtimes: Vec = Vec::new(); // The bound expression of each node, in the same order: the pass below reads the node it // configures from here, so nothing about an operation is copied onto the node's spec. let mut exprs: Vec<&NativeExpr> = Vec::new(); - let mut source: Option<(usize, Arc)> = None; - let mut node = tree.root(); - let mut path = NodePath::root(); - loop { + // The nodes the pass has not reached yet, the next one last: a node pushes its inputs back + // to front, so the one popped next is the one its parent's spec names. + let mut pending: Vec<(&NativeNode, NodePath)> = vec![(tree.root(), NodePath::root())]; + while let Some((node, path)) = pending.pop() { let index = nodes.len(); let handles = Arc::new(NodeMetrics::default()); handles.register(&path, metrics_set, partition); - let (tag, child) = match &node.expr { + let tag = match &node.expr { NativeExpr::Input(bound) => { // Every node here reads one series at a time and assumes its chunks arrive // together: a window feeds a series to its evaluator up to the chunk carrying @@ -1205,37 +2433,54 @@ impl NativeExecutionState { if bound.ordering == SeriesOrdering::Interleaved { return Err(unsupported_ordering(bound.ordering, &path)); } - let samples = node.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution(format!( - "the input node at {path} does not produce samples" - )) - })?; - source = Some((index, samples)); - (NodeTag::Input, None) + NodeTag::Input } - NativeExpr::Window { input, .. } => (NodeTag::Window, Some(input.as_ref())), - NativeExpr::Map { input, .. } => (NodeTag::Map, Some(input.as_ref())), + NativeExpr::Instant { .. } => NodeTag::Instant, + NativeExpr::Window { .. } => NodeTag::Window, + NativeExpr::Map { .. } => NodeTag::Map, + // A binary node is built here and narrowed below: legality is a wider set of operand + // types than the kernel takes, so the shape is checked where the operands' layouts + // are read. + NativeExpr::Binary { .. } => NodeTag::Binary, // The kinds below are legal in a bound tree, and `validate` stays the authority on // that; this runtime simply does not execute them yet. Rejected before a single // chunk is read: a tree the runtime cannot execute must not start, because a // partial answer would be one the caller never asked for. NativeExpr::Scalar(_) => return Err(not_implemented("Scalar", &path)), - NativeExpr::Instant { .. } => return Err(not_implemented("Instant", &path)), NativeExpr::Aggregate { .. } => return Err(not_implemented("Aggregate", &path)), - NativeExpr::Binary { .. } => return Err(not_implemented("Binary", &path)), }; let buffer = NodeBuffer::new(&path, handles, &pool); let mut runtime = NodeRuntime { buffer, queued: VecDeque::new(), + instant: None, window: None, map: None, + binary: None, + source_schema: None, emitted: None, merge: None, open_source_series: false, }; match &node.expr { - NativeExpr::Input(_) => {} + NativeExpr::Input(_) => { + // What the caller's chunks of this input are checked against: a raw source + // carries timestamps, an evaluated one is addressed on a grid. + runtime.source_schema = node.output.samples().cloned(); + } + NativeExpr::Instant { input, op } => { + let input_schema = input.output.samples().ok_or_else(|| { + DataFusionError::Execution(format!( + "the instant selection at {path} consumes samples, but its input \ + produces none" + )) + })?; + runtime.instant = Some(InstantRuntime::try_new(input_schema, op)?); + // A selection keeps the labels of the series it reads, empty-valued ones + // included, so it is not one of the nodes that can turn two series into one + // label set and it keeps no table of what it handed out: the node that drops a + // label is the one that can collide, and it records its own. + } NativeExpr::Map { op, .. } => { let schema = node.output.samples().cloned().ok_or_else(|| { DataFusionError::Execution(format!( @@ -1270,27 +2515,64 @@ impl NativeExecutionState { // from two series. runtime.emitted = Some(Emitted::default()); } - NativeExpr::Scalar(_) - | NativeExpr::Instant { .. } - | NativeExpr::Aggregate { .. } - | NativeExpr::Binary { .. } => { + NativeExpr::Binary { + left, + right, + matching, + } => { + // The one shape this runtime executes is two evaluated vectors: a scalar side is + // a broadcast the kernel does not take, and a raw side has no positions to be + // matched at. Both are rejected as this node, before the pass reaches the + // operand that produced them, so the position named is the one that asked for + // them. + match (left.output.samples(), right.output.samples()) { + (Some(left), Some(right)) + if left.eval_grid.is_some() && right.eval_grid.is_some() => + { + // Each operand's layout is the one its own child produces, and the walk + // only built this node when both produce evaluated samples. + runtime.binary = Some(BinaryRuntime::new( + Arc::new(matching.clone()), + [Arc::clone(left), Arc::clone(right)], + )); + } + _ => return Err(not_implemented("Binary", &path)), + } + // A binary operation matches by label set, so a result label set may be + // produced at points that do not collide; the kernel groups and merges them + // itself, which is why this node keeps no ledger of what it handed out. + } + NativeExpr::Scalar(_) | NativeExpr::Aggregate { .. } => { // Rejected above, where the pass has the position to name. } } - // The input is the node the pass reaches next: the chain has no other node between - // this one and its input, and nothing is read off the positions afterwards. + // The inputs this node reads, in the order the tree declares them: a unary node's one + // input, a binary node's left and right operand, and none for an input node. They are + // pushed back to front, so the node the spec names is the one the pass reaches next and + // nothing but its own subtree lies between the two. + let reads_input = match &node.expr { + NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::Aggregate { .. } => { + false + } + NativeExpr::Instant { input, .. } + | NativeExpr::Window { input, .. } + | NativeExpr::Map { input, .. } => { + pending.push((input.as_ref(), path.input())); + true + } + NativeExpr::Binary { left, right, .. } => { + pending.push((right.as_ref(), path.right())); + pending.push((left.as_ref(), path.left())); + true + } + }; nodes.push(NodeSpec { tag, - input: child.map(|_| index + 1), + input: reads_input.then_some(index + 1), }); exprs.push(&node.expr); paths.push(path.clone()); runtimes.push(runtime); - let Some(child) = child else { - break; - }; - node = child; - path = path.input(); } // One reverse pass sets where a merge has to happen, from the input upwards: the pass above @@ -1321,7 +2603,26 @@ impl NativeExecutionState { nodes[index].input.is_some_and(|child| holds_shared[child]); match nodes[index].tag { NodeTag::Input => {} + NodeTag::Instant => { + // A selection keeps the labels it read, so it is not where two series + // become one label set and its own output carries its input's flag. Its + // input is the source -- `validate` binds a selection to raw samples, and + // no node above a source produces them -- and a source hands each series' + // chunks over together, so the flag is false there in every tree this + // runtime runs. Should the pass ever compute it true, the selection still + // needs no collected input: it reads one series at a time and refuses a + // chunk of another before it is buffered. + holds_shared[index] = input_holds_shared; + } NodeTag::Map => holds_shared[index] = true, + NodeTag::Binary => { + // The kernel matches its operands by label set and files one result row per + // label set and point, merging the rows of one set whatever piece they came + // from: what it hands out is one series per label set, so nothing above has + // to join pieces of a series. Its own operands are read whole -- it retains + // them until the input ends -- so its flag is false whatever theirs are. + holds_shared[index] = false; + } NodeTag::Window => { let (drops_metric_name, input_schema) = match expr { NativeExpr::Window { input, op } => ( @@ -1373,17 +2674,45 @@ impl NativeExecutionState { } } - // The supported nodes are unary, so a tree of them has exactly one input node; it is where - // the caller's chunks enter. - let (source, source_schema) = source.ok_or_else(|| { - DataFusionError::Execution("the native tree has no input node".to_string()) - })?; + // A caller names a node by the position the metrics give it, and a chunk it queues is bound + // to the input that position names, so every position is indexed once the pass has given the + // whole tree one. + let by_path: HashMap = paths + .iter() + .enumerate() + .map(|(index, path)| (path.clone(), index)) + .collect(); + // Every input node is where a caller's chunks can enter, and each of them is named by its + // own position when a caller queues a chunk. A tree of unary nodes has one input; a binary + // node adds one per operand, so a tree of nested binary nodes has as many as it has leaves. + let sources: Vec = nodes + .iter() + .enumerate() + .filter(|(_, node)| node.tag == NodeTag::Input) + .map(|(index, _)| index) + .collect(); + if sources.is_empty() { + return Err(DataFusionError::Execution( + "the native tree has no input node".to_string(), + )); + } + // A caller's chunks are samples: a source that hands over aggregate state is not something + // this runtime can be handed, and it is refused when the state is built rather than when the + // first chunk is queued at it. + for &source in &sources { + if runtimes[source].source_schema.is_none() { + return Err(DataFusionError::Execution(format!( + "the input node at {} does not produce samples", + paths[source] + ))); + } + } Ok(Self { nodes, paths, runtimes, - source, - source_is_evaluated: source_schema.eval_grid.is_some(), + by_path, + sources, }) } @@ -1393,6 +2722,20 @@ impl NativeExecutionState { Some(&self.runtimes[index].buffer.metrics) } + /// The position of the right operand of the binary node at `index`. + /// + /// A spec names one input, the node the build pass reaches next: a unary node's only input and a + /// binary node's left operand. The right operand is the one input a spec cannot name, so it is + /// read from the position the node itself sits at, which the pass resolved and indexed. + fn right_input(&self, index: usize) -> Result { + let path = &self.paths[index]; + self.by_path.get(&path.right()).copied().ok_or_else(|| { + DataFusionError::Execution(format!( + "the native tree has no node at the right input of {path}" + )) + }) + } + /// The bytes this execution currently reserves from the pool. pub fn reserved_bytes(&self) -> usize { self.runtimes @@ -1414,6 +2757,32 @@ impl NativeExecutionState { .count() } + /// How many nodes still hold the chunks of a series an instant selection was gathering. + /// + /// Test-only, and for the same reason as [`Self::nodes_holding_windows`]: the buffered chunks + /// have to be dropped, not only the bytes they were reserved for, and that is not observable + /// from the pool. + #[cfg(test)] + pub(crate) fn nodes_holding_instants(&self) -> usize { + self.runtimes + .iter() + .filter(|runtime| runtime.instant.is_some()) + .count() + } + + /// How many nodes still hold the operands a binary operation retained. + /// + /// Test-only, and for the same reason as [`Self::nodes_holding_windows`]: an execution that + /// stopped has to drop the vectors it retained, not only the number that says how many bytes + /// they were reserved for. + #[cfg(test)] + pub(crate) fn nodes_holding_binary(&self) -> usize { + self.runtimes + .iter() + .filter(|runtime| runtime.binary.is_some()) + .count() + } + /// The input that ended before its last chunk, if there is one. /// /// It is read before anything is merged: a window that collects its input closes every series @@ -1427,6 +2796,28 @@ impl NativeExecutionState { .map(|(path, _)| truncated_input(path)) } + /// Reports a stream that ended inside a series, without closing any node. + /// + /// Closing is destructive -- a window's evaluator takes itself apart -- and the binary nodes + /// still have to compute after this check, so what is read here is only the state that follows + /// what each node was handed: an input node reports the series it handed over without the chunk + /// that ends it, and a binary node reports an operand that is still open on either side. A + /// truncation is therefore refused before a binary kernel allocates its workspace, rather than + /// after one has already been computed on half a vector. + fn unclosed(&self) -> Result<()> { + // A source series that never ended is refused before anything is merged: the close a merge + // synthesises would make it look like one that did. + if let Some(error) = self.truncated() { + return Err(error); + } + for (path, runtime) in self.paths.iter().zip(&self.runtimes) { + if let Some(binary) = &runtime.binary { + binary.closed(path)?; + } + } + Ok(()) + } + /// Closes every node, reporting an input that ended mid-series. /// /// A drain finds nothing left to emit: a window reports its results on the chunk that closes @@ -1466,6 +2857,21 @@ impl NativeExecutionState { pub struct NativeExecutor { state: NativeExecutionState, phase: Phase, + /// Whether the caller ended the input. + /// + /// Until then a pull that finds nothing means nothing has settled yet, and a binary node + /// retains what its operands hand over without computing: the whole vector has to be there + /// before a point of it is answered. [`NativeExecutor::finish`] drains once, checks that every + /// stream closed, and only then sets this flag and drains again, which is what lets a binary + /// node answer its result -- and a binary node beneath another one do the same in turn. + inputs_finished: bool, + /// Whether the caller ended the input. + /// + /// Until then a pull that finds nothing means nothing has settled yet. After it, the same pull + /// runs the next stage of the ending -- the truncation check, a binary node's computation, the + /// merge a collecting window owes -- and only a pull that finds every stage done closes the + /// nodes and returns their reservations. + ended: bool, } /// Whether the execution can still produce chunks. @@ -1485,6 +2891,8 @@ impl NativeExecutor { Self { state, phase: Phase::Running, + inputs_finished: false, + ended: false, } } @@ -1493,21 +2901,40 @@ impl NativeExecutor { &self.state } - /// Queues one raw source chunk. + /// Queues one raw source chunk at the tree's only input. + /// + /// A tree with a binary node reads two inputs, and a chunk queued at "the input" would be one + /// the caller cannot say the source of: such a tree is refused here rather than answered from a + /// source the caller did not name, and [`Self::push_raw_at`] is what names one. pub fn push_raw(&mut self, chunk: RawSeriesChunk) -> Result<()> { - self.push_source(NativeChunk::Raw(chunk)) + self.push_source(None, NativeChunk::Raw(chunk)) } - /// Queues one evaluated source chunk. + /// Queues one evaluated source chunk at the tree's only input. pub fn push_evaluated(&mut self, chunk: EvaluatedChunk) -> Result<()> { - self.push_source(NativeChunk::Evaluated(chunk)) + self.push_source(None, NativeChunk::Evaluated(chunk)) + } + + /// Queues one raw source chunk at the input node at `path`. + /// + /// The path is the position the metrics and `EXPLAIN` name the node by, so a caller that reads + /// either can say which of the two inputs a chunk belongs to. + pub fn push_raw_at(&mut self, path: &NodePath, chunk: RawSeriesChunk) -> Result<()> { + self.push_source(Some(path), NativeChunk::Raw(chunk)) + } + + /// Queues one evaluated source chunk at the input node at `path`. + pub fn push_evaluated_at(&mut self, path: &NodePath, chunk: EvaluatedChunk) -> Result<()> { + self.push_source(Some(path), NativeChunk::Evaluated(chunk)) } /// The next chunk the root produces, or `None` when nothing has settled yet. /// - /// Every node takes whole chunks from its input, so a caller that keeps pushing and pulling - /// materialises nothing beyond the chunk in hand -- except below a window that collects its - /// input, which holds that input until [`Self::finish`]. + /// A window and a map take whole chunks from their input, so nothing beyond the chunk in hand + /// is materialised on their edge -- except below a window that collects its input, which holds + /// that input until [`Self::finish`]. A binary node is the other exception: it pairs two whole + /// vectors point by point, so it retains every chunk each operand hands over and reports `None` + /// until [`Self::finish`] ends the input, which is when it computes its result. /// /// A chunk's `is_last` says the series whose data it carries ended. It does not say its label /// set is finished: two source series whose labels were rewritten into one set are two pieces @@ -1517,97 +2944,202 @@ impl NativeExecutor { /// at the root hands over pieces, and a caller that needs one series per label set merges them. pub fn next_chunk(&mut self) -> Result> { self.check_running()?; - // The root is the node the state was built from, which the pass puts first. - let result = self.pull(0).and_then(|chunk| match chunk { - Some(NativeChunk::Evaluated(chunk)) => Ok(Some(chunk)), - // Rejected when the state was built; kept as an error rather than a panic so an - // impossible tree cannot take the process down. - Some(NativeChunk::Raw(_)) => Err(DataFusionError::Execution( - "the native runtime produces evaluated chunks, but its root produced raw samples" - .to_string(), - )), - None => Ok(None), - }); - if let Err(error) = &result { - self.stop(error); + // The end of the input is walked here rather than in one call, so a chunk is handed over as + // soon as the tree settles it: the caller pulls the answer instead of receiving it as one + // collected value, and what it has not pulled yet stays charged to the node holding it. + loop { + // The root is the node the state was built from, which the pass puts first. + let pulled: Option = match self.pull(0) { + Ok(Some(NativeChunk::Evaluated(chunk))) => return Ok(Some(chunk)), + // Rejected when the state was built; kept as an error rather than a panic so an + // impossible tree cannot take the process down. + Ok(Some(NativeChunk::Raw(_))) => { + let error = DataFusionError::Execution( + "the native runtime produces evaluated chunks, but its root produced raw \ + samples" + .to_string(), + ); + self.stop(&error); + return Err(error); + } + Ok(None) => None, + Err(error) => { + self.stop(&error); + return Err(error); + } + }; + let _ = pulled; + // Nothing has settled. While the caller is still pushing, that is a stall and the + // answer is simply not ready; once it has ended the input, each stage below runs on the + // first pull that finds the tree quiet, and the loop looks for what it produced. + if !self.ended { + return Ok(None); + } + if !self.inputs_finished { + // The source queues are empty and every node has consumed what it was given, so a + // series the caller never closed is still open here and nowhere else. It is + // refused before a binary node computes: half a vector is not a vector, so the + // kernel must not allocate a workspace to match one. + if let Err(error) = self.state.unclosed() { + self.stop(&error); + return Err(error); + } + self.inputs_finished = true; + continue; + } + // A window that collects its input answers only once its own input is finished, and + // what a binary node above it reads is that answer. Flushing the deepest ready window + // first is what keeps the two in order: the window produces, the pull that follows + // carries its output to whoever reads it, and only then can a binary node decide + // whether both of its operands are complete. + match self.flush_ready_merges() { + // A window answered: what it queued is pulled on the next turn, and that pull is + // also what carries its answer to a node above it. + Ok(true) => continue, + Ok(false) => {} + Err(error) => { + self.stop(&error); + return Err(error); + } + } + if self.any_merge_pending() { + // A window still holds collected input, so something below it has not finished: + // pulling again is what gives that node its turn. + continue; + } + // Every node has answered everything it can. Closing them is what hands back the + // reservations they were charged, so pulling to exhaustion leaves the pool as it found + // it. + return match self.state.close() { + Ok(()) => { + self.phase = Phase::Finished; + Ok(None) + } + Err(error) => { + self.stop(&error); + Err(error) + } + }; } - result } - /// Ends the input: drains what has settled, merges what the windows that collect their input - /// hold, closes every node and releases every reservation. + /// Ends the input, which is what tells the tree that nothing more will be pushed. /// - /// Every series must have closed by now, in every tree: a window's evaluator reports the series - /// it is still holding, and a tree with no window has its input node report one it handed over - /// without the chunk that ends it. An input that ends mid-series is an error here rather than a - /// series the caller never sees close, and it is refused before any collected input is merged: - /// merging closes what it merges. + /// It hands nothing over: [`Self::next_chunk`] runs the ending stage by stage as the caller + /// pulls, so a chunk reaches the caller as soon as it settles and the chunks not pulled yet + /// stay charged to the node holding them. A caller that wants the whole answer at once calls + /// [`Self::finish`] instead. + pub fn end_of_input(&mut self) -> Result<()> { + if self.ended { + return Err(DataFusionError::Execution( + "the native execution already ended its input".to_string(), + )); + } + self.ended = true; + Ok(()) + } + + /// Ends the input and collects everything the tree answers. /// - /// The merge comes next, deepest window first, and what it hands up is drained as it is - /// produced. What the root hands over is therefore a piece stream: a chunk's `is_last` says the - /// source series it carries ended, and two of them can share one label set. A caller that needs - /// one series per label set from the root merges them with - /// [`crate::grid_series::merge_same_labelset`] as well, exactly as this runtime merges the input - /// of the windows it collects for. + /// It is [`Self::end_of_input`] followed by a drain, kept for callers that want the whole + /// answer in one value. A caller that would rather stream it calls `end_of_input` and then + /// pulls with [`Self::next_chunk`] until it returns `None`, which is also when the execution + /// closes and returns its reservations. pub fn finish(&mut self) -> Result> { + self.end_of_input()?; + self.drain() + } + + /// Pulls what has settled until nothing is left. + fn drain(&mut self) -> Result> { let mut drained = Vec::new(); loop { match self.next_chunk() { Ok(Some(chunk)) => drained.push(chunk), - Ok(None) => break, + Ok(None) => return Ok(drained), Err(error) => return Err(error), } } - // A source series that never ended is refused before anything is merged: the close a merge - // synthesises would make it look like one that did. - if let Some(error) = self.state.truncated() { - self.stop(&error); - return Err(error); - } - if let Err(error) = self.flush_merges(&mut drained) { - self.stop(&error); - return Err(error); - } - match self.state.close() { - Ok(()) => { - self.phase = Phase::Finished; - Ok(drained) - } - Err(error) => { - self.stop(&error); - Err(error) - } - } } /// Merges the collected input of every window that collects it, and drains the root after each /// merged series. /// /// Deeper windows go first: a window above one of them collects the chunks the one below hands - /// up, so flushing the shallow one first would merge an input it has not received yet. The - /// queue of a flushed node is emptied by the root drain that follows each of its merged series, - /// so a chunk it produced never stands beside the fragments it was computed from. - fn flush_merges(&mut self, drained: &mut Vec) -> Result<()> { + /// up, so flushing the shallow one first would merge an input it has not received yet. What a + /// flush queues is handed up by the caller's own pulls, which is why nothing here collects the + /// answer into a value of its own. + fn flush_ready_merges(&mut self) -> Result { + let mut flushed = false; for index in (0..self.state.runtimes.len()).rev() { // A window that collects its input is the one node holding a [`MergeInput`], and the // flush takes it: the same node is not visited twice. if self.state.runtimes[index].merge.is_none() { continue; } - self.flush_merge(index, drained)?; + // Its input has to be finished before it is merged: a node below still holding collected + // input has not answered yet, and merging what it has not sent would answer a series + // from half of its contributions. + let Some(child) = self.state.nodes[index].input else { + continue; + }; + if !self.settled(child) { + continue; + } + self.flush_merge(index)?; + flushed = true; + } + Ok(flushed) + } + + /// Whether any window still holds collected input that has not been merged. + fn any_merge_pending(&self) -> bool { + self.state + .runtimes + .iter() + .any(|runtime| runtime.merge.is_some()) + } + + /// Whether the node at `index` has produced everything it ever will. + /// + /// A pull that finds nothing does not answer it: a collecting window reports nothing until it + /// is flushed, and a binary node reports nothing until both nodes it reads from are finished. + /// Each node therefore answers from its own state and from its children's, which is what keeps + /// a binary node from computing on an operand a window below it has not handed over yet. + fn settled(&self, index: usize) -> bool { + let runtime = &self.state.runtimes[index]; + if !runtime.queued.is_empty() || runtime.merge.is_some() { + return false; + } + match self.state.nodes[index].tag { + NodeTag::Input => true, + NodeTag::Map | NodeTag::Window | NodeTag::Instant => self.state.nodes[index] + .input + .is_none_or(|child| self.settled(child)), + NodeTag::Binary => { + runtime + .binary + .as_ref() + .is_some_and(|binary| binary.computed) + && self.state.nodes[index] + .input + .is_none_or(|child| self.settled(child)) + && self + .state + .right_input(index) + .is_ok_and(|right| self.settled(right)) + } } - Ok(()) } /// Merges the collected input of the node at `index` and evaluates it, one merged series at a /// time. /// /// Each merged series is a whole series: it is handed to the evaluator as one closing series, so - /// the window reports on it once, and its chunk is queued and drained up the tree before the - /// next one is evaluated. That is what keeps the reservation honest: the fragments and the - /// merge's workspace stay charged while the flush runs, and the queue of a node never holds an - /// earlier series beside the fragments of a later one. - fn flush_merge(&mut self, index: usize, drained: &mut Vec) -> Result<()> { + /// the window reports on it once, and its chunk waits in the node's queue at its own estimate. + /// The fragments and the merge's workspace stay charged for the whole flush and go back when it + /// ends; the queued answers stay charged until the caller pulls them. + fn flush_merge(&mut self, index: usize) -> Result<()> { let path = self.state.paths[index].clone(); let Some(merge) = self.state.runtimes[index].merge.take() else { return Ok(()); @@ -1615,7 +3147,7 @@ impl NativeExecutor { if merge.fragments.is_empty() { // Nothing arrived, so there is nothing to merge and nothing to answer: the window's // evaluator never read a series and the charge goes back. - return self.settle_merge(index); + return self.settle_merge(index, merge.bytes); } // The workspace the merge allocates is charged before it runs, from the rows, segments and // fields of the fragments as they were collected. @@ -1658,37 +3190,20 @@ impl NativeExecutor { .resize(retained.saturating_add(emitted).saturating_add(held))?; runtime.enqueue_output(output)?; } - self.drain_root(drained)?; } - self.settle_merge(index) + // The fragments and the merge's workspace go back, and whatever the flush produced stays + // charged in the node's queue until the caller pulls it. + self.settle_merge(index, held) } - /// Sets the reservation of the node at `index` to what it holds once its flush is over. - fn settle_merge(&mut self, index: usize) -> Result<()> { - let runtime = &mut self.state.runtimes[index]; - let retained = runtime - .window - .as_ref() - .map_or(0, RangeEvaluator::retained_bytes); - let emitted = runtime.emitted_bytes(); - runtime.buffer.resize(retained.saturating_add(emitted)) - } - - /// Hands the root's outputs to `drained` until the tree has nothing settled. - fn drain_root(&mut self, drained: &mut Vec) -> Result<()> { - loop { - match self.pull(0)? { - Some(NativeChunk::Evaluated(chunk)) => drained.push(chunk), - Some(NativeChunk::Raw(_)) => { - return Err(DataFusionError::Execution( - "the native runtime produces evaluated chunks, but its root produced raw \ - samples" - .to_string(), - )); - } - None => return Ok(()), - } - } + /// Gives back the `give_back` bytes the flush took, leaving the rest of the node's + /// reservation alone. + /// + /// It must not resize to a figure computed here: the chunks the flush queued are still charged + /// to this node, and they stay charged until the pull that hands each of them up returns its + /// estimate. + fn settle_merge(&mut self, index: usize, give_back: usize) -> Result<()> { + self.state.runtimes[index].buffer.shrink(give_back) } /// The next chunk of the node at `index`. @@ -1729,6 +3244,45 @@ impl NativeExecutor { } } } + NodeTag::Instant => { + let child = input.ok_or_else(|| missing_input(tag))?; + // A selection decides a whole series at once, so every chunk before the one that + // closes it yields nothing and the selection asks its input again. + loop { + let Some(chunk) = self.pull(child)? else { + return Ok(None); + }; + if let Some(output) = self.instant_node(index, chunk)? { + return Ok(Some(NativeChunk::Evaluated(output))); + } + } + } + NodeTag::Binary => { + // The spec names the left operand, the node the build pass reaches next; the right + // one is the input a spec of two fields would have had to carry. + let left = input.ok_or_else(|| missing_input(tag))?; + let right = self.state.right_input(index)?; + // Both operands are read to the end of what they hand over: before the input ends a + // binary node only retains the chunks, because a pair is not decided until both + // sides are whole, and after it ends this is the drain that empties the two. + for (side, child) in [left, right].into_iter().enumerate() { + while let Some(chunk) = self.pull(child)? { + let path = &self.state.paths[index]; + self.state.runtimes[index].retain_binary(path, side, chunk)?; + } + } + // Nothing has settled for a point that has an operand still arriving, and an + // operand below a collecting window has not arrived until that window is flushed. + if !self.inputs_finished || !self.settled(left) || !self.settled(right) { + return Ok(None); + } + let path = &self.state.paths[index]; + let runtime = &mut self.state.runtimes[index]; + runtime.compute_binary(path)?; + // A result holds one value per field, and a field may hold none where another + // does, so its values are counted rather than read as its positions. + runtime.pop_queued(evaluated_values) + } } } @@ -1752,31 +3306,79 @@ impl NativeExecutor { runtime.window(path, chunk) } - /// Queues a source chunk at the tree's input node. - fn push_source(&mut self, chunk: NativeChunk) -> Result<()> { + /// Feeds one chunk to the instant selection at `index`. + fn instant_node(&mut self, index: usize, chunk: NativeChunk) -> Result> { + let path = &self.state.paths[index]; + let runtime = &mut self.state.runtimes[index]; + runtime.instant(path, chunk) + } + + /// Queues a source chunk at the input node `path` names, or at the tree's only one. + fn push_source(&mut self, path: Option<&NodePath>, chunk: NativeChunk) -> Result<()> { self.check_running()?; - let evaluated = matches!(chunk, NativeChunk::Evaluated(_)); - if evaluated != self.state.source_is_evaluated { - let error = DataFusionError::Execution(format!( - "the native source is bound to {}, but an {} chunk was queued at it", - if self.state.source_is_evaluated { - "an evaluated series" - } else { - "raw samples" - }, - if evaluated { "evaluated" } else { "raw" }, - )); - self.stop(&error); - return Err(error); - } - let source = self.state.source; - let result = self.state.runtimes[source].enqueue(chunk); + let result = self.queue_source(path, chunk); if let Err(error) = &result { self.stop(error); } result } + /// Queues a source chunk at one input node, checking it against that input's binding. + fn queue_source(&mut self, path: Option<&NodePath>, chunk: NativeChunk) -> Result<()> { + let source = self.source_index(path)?; + let at = &self.state.paths[source]; + let Some(binding) = self.state.runtimes[source].source_schema.as_ref() else { + return Err(DataFusionError::Execution(format!( + "the input node at {at} does not produce samples" + ))); + }; + let bound = binding.eval_grid.is_some(); + let evaluated = matches!(chunk, NativeChunk::Evaluated(_)); + if evaluated != bound { + return Err(DataFusionError::Execution(format!( + "the native source at {at} is bound to {}, but {} chunk was queued at it", + if bound { + "an evaluated series" + } else { + "raw samples" + }, + if evaluated { "an evaluated" } else { "a raw" }, + ))); + } + self.state.runtimes[source].enqueue(chunk) + } + + /// The input node at `path`, or the tree's only input when the caller named none. + /// + /// A tree with a binary node has two inputs, and a chunk queued at "the input" of such a tree + /// cannot be assigned to either of them: the caller's chunks would be matched as the wrong + /// operand, so the ambiguity is refused instead of answered from the first input found. + fn source_index(&self, path: Option<&NodePath>) -> Result { + let Some(path) = path else { + return match self.state.sources.as_slice() { + [only] => Ok(*only), + _ => Err(DataFusionError::Execution(format!( + "the native execution has {} inputs, so a queued chunk has to name the input it \ + belongs to", + self.state.sources.len() + ))), + }; + }; + let index = *self.state.by_path.get(path).ok_or_else(|| { + DataFusionError::Execution(format!( + "the native tree has no node at {path} to queue a chunk at" + )) + })?; + let tag = self.state.nodes[index].tag; + if tag != NodeTag::Input { + return Err(DataFusionError::Execution(format!( + "the node at {path} is a {} node, and only an input node takes queued chunks", + tag.describe() + ))); + } + Ok(index) + } + /// Refuses to continue an execution that finished or stopped. fn check_running(&self) -> Result<()> { match &self.phase { @@ -1866,6 +3468,18 @@ fn valid_values(chunk: &EvaluatedChunk) -> usize { .sum() } +/// The values a chunk a binary node hands over holds. +/// +/// A binary result is an evaluated chunk, so this is [`valid_values`]: one value per field sample +/// that holds one. A raw chunk cannot reach a binary node's queue, and is answered as its positions +/// so an impossible queue cannot under-count. +fn evaluated_values(chunk: &NativeChunk) -> usize { + match chunk { + NativeChunk::Evaluated(chunk) => valid_values(chunk), + NativeChunk::Raw(chunk) => chunk.time.len(), + } +} + /// The rejection of a node kind this runtime does not execute yet. /// /// It names the kind and the node's position: the position is what the metrics and `EXPLAIN` call @@ -1881,6 +3495,39 @@ fn closed(path: &NodePath) -> DataFusionError { DataFusionError::Execution(format!("the window at {path} is already closed")) } +/// The error for a chunk of another series arriving while one is being selected. +/// +/// [`select_instants`] reads one whole axis, so the buffered chunks have to be one series: a chunk +/// of another series has nowhere to go, and appending it would select its samples as though they +/// were the open series'. +fn series_changed(path: &NodePath) -> DataFusionError { + DataFusionError::Execution(format!( + "the instant selection at {path} combines one series into one axis, and a chunk of another \ + series arrived before the first one ended" + )) +} + +/// The error for a series an instant selection has no labels to report it under. +/// +/// A source bound in label mode carries its identity encoded and no decoded labels, and a chunk +/// that is handed on has to name the series it holds. +fn no_labels(path: &NodePath) -> DataFusionError { + DataFusionError::Execution(format!( + "the instant selection at {path} requires materialized series labels" + )) +} + +/// The error for a source row the selection named but the series does not hold. +/// +/// The selection returns indices into the axis it was given, so a row outside it means the two +/// disagree rather than that a sample is missing. +fn missing_row(path: &NodePath, index: usize) -> DataFusionError { + DataFusionError::Execution(format!( + "the instant selection at {path} selected the source row {index}, which the series it read \ + does not hold" + )) +} + /// The rejection of an input ordering this runtime cannot execute. /// /// It names the input that declares the ordering and the ordering found, so a reader can tell a @@ -1924,6 +3571,24 @@ fn truncated_input(path: &NodePath) -> DataFusionError { )) } +/// The error for a node asked to compute without the runtime its kind holds. +fn no_binary(path: &NodePath) -> DataFusionError { + DataFusionError::Execution(format!("the node at {path} holds no binary operation")) +} + +/// The error for a reservation the platform cannot express. +/// +/// The binary node reserves its retained operands and the kernel's live workspace together, and +/// the kernel reports the second as a size of its own. A sum of the two that does not fit an +/// address space cannot be reserved, so the execution is refused rather than run with a figure +/// that wrapped. +fn reservation_overflow(path: &NodePath) -> DataFusionError { + DataFusionError::Execution(format!( + "the operands and the kernel's workspace of the binary node at {path} do not fit one \ + address space: the bytes it would reserve overflow" + )) +} + /// The error for a node the flattened tree lost its input for. fn missing_input(tag: NodeTag) -> DataFusionError { DataFusionError::Execution(format!( diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 829e79b8802..f31cf86be64 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -21,24 +21,26 @@ use std::sync::Arc; use datafusion::error::DataFusionError; use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool}; use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricValue}; -use datatypes::arrow::array::{Float64Array, UInt32Array}; +use datatypes::arrow::array::{Array, Float64Array, UInt32Array}; use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; use datatypes::series::histogram::{ BucketSideView, CounterResetHint, HistogramBatch, HistogramBatchBuilder, HistogramView, }; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{ - FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, + DenseSamplesRef, FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::{ - Emitted, NativeChunk, NativeExecutionState, NativeExecutor, NodeBuffer, NodeRuntime, - absorb_rebuilds, evaluated_bytes, map_chunk, raw_bytes, + BinaryRuntime, Emitted, NativeChunk, NativeExecutionState, NativeExecutor, NodeBuffer, + NodeRuntime, absorb_rebuilds, evaluated_bytes, grid_end_ms, map_chunk, operand_chunk_bytes, + raw_bytes, }; use crate::evaluated::EvaluatedChunk; use crate::grid_series::merge_same_labelset; +use crate::instant_eval::select_instants; use crate::map::MathOp; use crate::native::metrics::{NodeMetric, NodeMetrics, NodePath}; use crate::native::plan::{ @@ -46,7 +48,10 @@ use crate::native::plan::{ BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, }; use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow}; -use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; +use crate::vector_match::{ + BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, reset_visited_pairs, + visited_pairs, +}; fn grid(start: i64, step: i64, len: u64) -> Arc { Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) @@ -93,11 +98,16 @@ fn metric() -> MetricName { /// The raw source every supported tree starts from. fn input() -> NativeNode { + raw_input_with_ordering(SeriesOrdering::KeyThenTime) +} + +/// The same raw source, declaring `ordering`. +fn raw_input_with_ordering(ordering: SeriesOrdering) -> NativeNode { let output = NativeType::Samples(raw_schema()); NativeNode { expr: NativeExpr::Input(BoundInput { output: output.clone(), - ordering: SeriesOrdering::KeyThenTime, + ordering, }), output, } @@ -193,6 +203,39 @@ fn window_over_fields(count: usize, output_grid: Arc) -> NativeNode { } } +/// A bare selector over `inner`: the last sample at or before each grid point, read within +/// `lookback_ms` and at `offset_ms`. +/// +/// The selection reports one value per input field, so its layout is the input's, just as the +/// compiler builds it. +fn instant( + inner: NativeNode, + lookback_ms: i64, + offset_ms: i64, + output_grid: Arc, +) -> NativeNode { + let fields = inner + .output + .samples() + .expect("a selection reads samples") + .fields + .clone(); + NativeNode { + expr: NativeExpr::Instant { + input: Box::new(inner), + op: BoundInstant { + lookback_ms, + offset_ms, + output_grid: Arc::clone(&output_grid), + }, + }, + output: NativeType::Samples(Arc::new(SeriesSchema { + fields, + eval_grid: Some(output_grid), + })), + } +} + fn map(inner: NativeNode, ops: Vec) -> NativeNode { let output = inner.output.grid().expect("a map needs a grid").clone(); NativeNode { @@ -265,6 +308,34 @@ fn raw_chunk_repeated( .unwrap() } +/// One raw chunk of `series-a` whose fields carry `columns`, one column per field. +/// +/// A `None` is a position that field holds no sample at, which is what a partially filled field +/// looks like at the source. +fn raw_chunk_columns( + schema: &SeriesSchema, + timestamps: &[i64], + columns: Vec>>, + is_last: bool, +) -> RawSeriesChunk { + let fields = SeriesFields::try_from_vec( + columns + .into_iter() + .map(|values| Samples::from_float(Float64Array::from(values))) + .collect(), + ) + .unwrap(); + RawSeriesChunk::try_new( + schema, + Buffer::from_slice_ref(b"series-a"), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from(timestamps.to_vec())).unwrap(), + fields, + is_last, + ) + .unwrap() +} + /// Pushes one native histogram whose positive side is one span of `buckets` buckets of one count /// into `builder`, and returns the index it was filed under. fn push_histogram(builder: &mut HistogramBatchBuilder, buckets: i32) -> u32 { @@ -320,6 +391,59 @@ fn raw_histogram_chunk( .unwrap() } +/// One raw chunk of `series-a` whose one field holds a four-bucket native histogram at each of +/// `timestamps`, each carrying `start_timestamp` as the payload it was read from reports it. +fn raw_histogram_chunk_with_start( + schema: &SeriesSchema, + timestamps: &[i64], + start_timestamp: Option, + is_last: bool, +) -> RawSeriesChunk { + let mut builder = HistogramBatchBuilder::new(); + let offsets = [0]; + let lengths = [4]; + let counts = vec![1.0; 4]; + let indices: UInt32Array = timestamps + .iter() + .map(|_| { + Some( + builder + .push(HistogramView { + schema: 0, + zero_threshold: 0.0, + zero_count: 0.0, + count: 4.0, + sum: 4.0, + reset_hint: CounterResetHint::Unknown, + start_timestamp, + custom_values: &[], + positive: BucketSideView { + span_offsets: &offsets, + span_lengths: &lengths, + buckets: &counts, + }, + negative: BucketSideView { + span_offsets: &[], + span_lengths: &[], + buckets: &[], + }, + }) + .unwrap(), + ) + }) + .collect(); + let samples = Samples::try_from_histogram(indices, builder.finish().unwrap()).unwrap(); + RawSeriesChunk::try_new( + schema, + Buffer::from_slice_ref(b"series-a"), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from(timestamps.to_vec())).unwrap(), + SeriesFields::one(samples), + is_last, + ) + .unwrap() +} + /// One raw chunk of `series-a` whose one field holds the histogram at `index` of `table`. /// /// Two chunks built this way share one `Arc`, which is what makes the allocation @@ -354,14 +478,64 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { pool, ), queued: VecDeque::new(), + instant: None, window: None, map: None, + binary: None, + source_schema: None, emitted: None, merge: None, open_source_series: false, } } +/// A binary node's runtime: both operands bound to `schema` and the reservation they are held for. +fn binary_runtime(pool: &Arc, schema: &Arc) -> NodeRuntime { + NodeRuntime { + buffer: NodeBuffer::new(&NodePath::root(), Arc::new(NodeMetrics::default()), pool), + queued: VecDeque::new(), + instant: None, + window: None, + map: None, + binary: Some(BinaryRuntime::new( + Arc::new(binary_matching(BinaryOp::Add)), + [Arc::clone(schema), Arc::clone(schema)], + )), + source_schema: None, + emitted: None, + merge: None, + open_source_series: false, + } +} + +/// What a binary node holds once it retains `left` and `right`, and what assembling the retained +/// chunks into the series the kernel matches adds on top. +/// +/// Both are read from a runtime of its own, so a pool can be sized from them: the first is what the +/// node reserves for the operands it retains and the second its own bound, and neither is a figure +/// the pool reports. +fn binary_charge( + schema: &Arc, + left: &EvaluatedChunk, + right: &EvaluatedChunk, +) -> (usize, usize) { + let mut runtime = binary_runtime(&pool(), schema); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(left.clone())) + .unwrap(); + runtime + .retain_binary(&NodePath::root(), 1, NativeChunk::Evaluated(right.clone())) + .unwrap(); + let retained = runtime.buffer.reservation.size(); + let assembly = runtime + .binary + .as_ref() + .expect("the runtime holds a binary node") + .assembly_bytes() + .expect("the assembly bound does not overflow"); + (retained, assembly) +} + /// One evaluated chunk of an input series: `values` at `start` and onwards on `schema`'s grid. fn evaluated_chunk( schema: &SeriesSchema, @@ -389,7 +563,21 @@ fn evaluated_chunk_of( values: Vec>, is_last: bool, ) -> EvaluatedChunk { - let samples = Samples::from_float(Float64Array::from(values)); + evaluated_array_chunk_of(schema, metric, start, Float64Array::from(values), is_last) +} + +/// One evaluated chunk of the series `metric` whose one field holds `values`, addressed at `start`. +/// +/// The array is passed in rather than built here so that two chunks can hold sibling slices of one +/// Arrow allocation, which is what a source handing over the chunks of one batch does. +fn evaluated_array_chunk_of( + schema: &SeriesSchema, + metric: MetricName, + start: usize, + values: Float64Array, + is_last: bool, +) -> EvaluatedChunk { + let samples = Samples::from_float(values); let range = GridRange::try_new(schema.eval_grid.clone().unwrap(), start, samples.len()).unwrap(); let series = Series { @@ -400,6 +588,48 @@ fn evaluated_chunk_of( EvaluatedChunk::try_new(series, is_last).unwrap() } +/// One evaluated chunk of the series `metric` whose one field holds `indices` into `table`, +/// addressed at `start` on `schema`'s grid. +/// +/// Two chunks built with one `table` are two slices of one allocation; two built with tables of the +/// same shape hold two allocations of the same size. +fn evaluated_histogram_chunk_of( + schema: &SeriesSchema, + metric: MetricName, + start: usize, + indices: Vec>, + table: &Arc, + is_last: bool, +) -> EvaluatedChunk { + let samples = + Samples::try_from_histogram(UInt32Array::from(indices), Arc::clone(table)).unwrap(); + let range = + GridRange::try_new(schema.eval_grid.clone().unwrap(), start, samples.len()).unwrap(); + let series = Series { + metric, + time: TimeAxis::Grid(range), + fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), + }; + EvaluatedChunk::try_new(series, is_last).unwrap() +} + +/// One histogram table of `histograms` histograms of `buckets` buckets each. +fn histogram_table(histograms: usize, buckets: i32) -> Arc { + let mut builder = HistogramBatchBuilder::new(); + for _ in 0..histograms { + push_histogram(&mut builder, buckets); + } + builder.finish().unwrap() +} + +/// What `table` holds: the batch struct and the arrays its columns view. +/// +/// Written out here rather than read from the runtime, so a test can size its expectations from the +/// table it built instead of from the figure it is checking. +fn histogram_table_bytes(table: &Arc) -> usize { + std::mem::size_of::() + table.as_arrow().get_array_memory_size() +} + /// The series `name{job="job"}`, so two series can share the label a map leaves behind. fn named_metric(name: &str, job: &str) -> MetricName { MetricName::try_new( @@ -458,11 +688,16 @@ fn run(executor: &mut NativeExecutor) -> Vec { } fn sample_values(chunk: &EvaluatedChunk) -> Vec> { + field_values(chunk, 0) +} + +/// The values field `index` carries, one per row the chunk holds. +fn field_values(chunk: &EvaluatedChunk, index: usize) -> Vec> { let field = chunk .series .fields - .get(0) - .expect("these series have one field"); + .get(index) + .unwrap_or_else(|| panic!("the chunk carries no field {index}")); field .iter() .map(|sample| match sample { @@ -472,6 +707,25 @@ fn sample_values(chunk: &EvaluatedChunk) -> Vec> { .collect() } +/// The start timestamp of the histogram at every position of a chunk, in grid order. +/// +/// It is read off the output's own histogram views rather than off a converted value, because the +/// figure under test is the one a later reader sees. +fn histogram_starts(chunk: &EvaluatedChunk) -> Vec> { + let mut cursor = chunk.series.fields.as_slice()[0].cursor(); + chunk + .series + .time + .positions() + .filter_map( + |(_, row)| match cursor.at(row).expect("the axis and the fields are aligned") { + SampleRef::Histogram(view) => Some(view.start_timestamp), + _ => None, + }, + ) + .collect() +} + fn series_start(chunk: &EvaluatedChunk) -> usize { chunk .series @@ -828,23 +1082,6 @@ fn an_unimplemented_node_is_reported_not_panicked() { let statement = || grid(0, 120_000, 2); let scalar_tree = scalar(1.0, statement()); - let instant_tree = { - let out = statement(); - map( - NativeNode { - expr: NativeExpr::Instant { - input: Box::new(input()), - op: BoundInstant { - lookback_ms: 300_000, - offset_ms: 0, - output_grid: Arc::clone(&out), - }, - }, - output: NativeType::Samples(evaluated_schema(out)), - }, - vec![MathOp::Abs], - ) - }; let aggregate_tree = { let out = statement(); NativeNode { @@ -879,7 +1116,6 @@ fn an_unimplemented_node_is_reported_not_panicked() { let cases = [ ("Scalar", "root", scalar_tree), - ("Instant", "root.input", instant_tree), ("Aggregate", "root", aggregate_tree), ("Binary", "root", binary_tree), ]; @@ -2464,6 +2700,68 @@ fn an_interleaved_input_is_refused_without_a_window() { assert!(message.contains("root.input"), "{message}"); } +/// A selection over an interleaved input is refused when the tree is bound, before it can run. +/// +/// The binding is where the ordering is known, and the plan's `Instant` arm refuses an input that +/// declares `Interleaved` for the reason the window arm does: a selection's consumer collects one +/// series' chunks into one buffer, so it reads a series to its last chunk before the next. Nothing +/// about an interleaved input is therefore left to the runtime along a selection, and the tree +/// never reaches [`NativeExecutionState::try_new`]. The ordering check there stays for the shape +/// the binding cannot see through: it only looks at a window's own input, so a window over a map +/// over the source still reads an interleaved stream, which is +/// [`a_window_over_an_interleaved_input_is_rejected`]. The shape with a map above the selection is +/// [`an_interleaved_input_is_refused_under_a_map_over_a_selection`]. +#[test] +fn an_interleaved_input_is_refused_under_a_selection() { + let out_grid = grid(0, 60_000, 2); + let error = NativeTree::try_new(instant( + raw_input_with_ordering(SeriesOrdering::Interleaved), + 60_000, + 0, + Arc::clone(&out_grid), + )) + .expect_err("a selection over an interleaved input must not bind"); + // A rejected tree is a compiler defect rather than a query error, so the binding reports it as + // `Internal`; what this pins is that the refusal names the ordering it came from, since the + // same check refuses a window over the same input. + assert!(matches!(error, DataFusionError::Internal(_)), "{error}"); + let message = error.to_string(); + assert!( + message.contains("interleaved chunks cannot be fed to it"), + "{message}" + ); +} + +/// The same refusal with a map above the selection. +/// +/// The tree here is `Input -> Instant -> Map`: the map sits above the selection, and the selection +/// reads the interleaved input directly. A map between the input and the selection is not a tree +/// this compiler can build at all -- a `Map` produces an evaluated vector while an instant +/// selection requires raw samples, and the plan's `Instant` arm rejects evaluated values -- so what +/// this test pins is the recursion: `validate` descends through the outer map to the selection +/// below it, whose own arm then refuses the input it reads, and the tree is refused at the same +/// point as [`an_interleaved_input_is_refused_under_a_selection`]. +#[test] +fn an_interleaved_input_is_refused_under_a_map_over_a_selection() { + let out_grid = grid(0, 60_000, 2); + let error = NativeTree::try_new(map( + instant( + raw_input_with_ordering(SeriesOrdering::Interleaved), + 60_000, + 0, + Arc::clone(&out_grid), + ), + vec![MathOp::Abs], + )) + .expect_err("a map over a selection over an interleaved input must not bind"); + assert!(matches!(error, DataFusionError::Internal(_)), "{error}"); + let message = error.to_string(); + assert!( + message.contains("interleaved chunks cannot be fed to it"), + "{message}" + ); +} + /// A series that produced values under a label set, followed by one that produced none under the /// same label set, is not a collision: the second contributes no sample, so the answer is just the /// first one's values. @@ -3186,3 +3484,2936 @@ fn a_sparse_series_that_moves_forward_is_appended_to_its_history() { "the merged history is not sorted, disjoint and joined: {runs:?}" ); } + +/// A bare selector stamps the last sample at or before each grid point onto its own grid. +/// +/// The chunk is addressed on the node's output grid, not on the source's timestamps; a grid point +/// may select a row an earlier point already did (the point after the last sample repeats it); and +/// the same samples delivered as one chunk and as three answer the same, because the selection reads +/// a whole axis rather than a chunk. +#[test] +fn a_bare_selector_selects_instants_onto_its_own_grid() { + let out_grid = grid(0, 60_000, 4); + let tree = NativeTree::try_new(instant(input(), 120_000, 0, Arc::clone(&out_grid))).unwrap(); + let schema = raw_schema(); + let whole = raw_chunk( + &schema, + &[0, 30_000, 90_000, 120_000, 200_000], + &[1.0, 2.0, 3.0, 4.0, 5.0], + true, + ); + // The same series as three chunks, so nothing about it is decided by a chunk boundary. + let split = [ + raw_chunk(&schema, &[0, 30_000], &[1.0, 2.0], false), + raw_chunk(&schema, &[90_000], &[3.0], false), + raw_chunk(&schema, &[120_000, 200_000], &[4.0, 5.0], true), + ]; + + let mut once = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + once.push_raw(whole).unwrap(); + let out = run(&mut once); + + let mut piecewise = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let mut in_pieces = Vec::new(); + for chunk in split { + let closing = chunk.is_last; + piecewise.push_raw(chunk).unwrap(); + // Until the series ends nothing is decided for it, so only the closing chunk reports. + let pulled = piecewise.next_chunk().unwrap(); + assert_eq!( + pulled.is_some(), + closing, + "a series reported a chunk before its last one arrived" + ); + in_pieces.extend(pulled); + } + in_pieces.extend(piecewise.finish().unwrap()); + + assert_eq!(out.len(), 1, "one series is one chunk, however it arrived"); + let chunk = &out[0]; + assert!(chunk.is_last, "the only chunk of a series closes it"); + assert!( + Arc::ptr_eq(chunk.series.time.grid().expect("a grid chunk"), &out_grid), + "the chunk is addressed on a grid that is not the selection's output grid" + ); + // 0 -> 0, 60s -> 30s, 120s -> 120s, 180s -> 120s: the row at 90s is never the last one before a + // grid point, and the point past the last sample repeats the row before it. + assert_eq!( + decided(&out), + vec![ + (0, Some(1.0)), + (1, Some(2.0)), + (2, Some(4.0)), + (3, Some(4.0)), + ] + ); + // A selection keeps the labels it read, the metric name included: unlike a range function it + // does not rewrite what the selector named. + assert_eq!(chunk.series.metric, metric()); + assert_eq!( + decided(&in_pieces), + decided(&out), + "the same series split into chunks answered differently" + ); +} + +/// The lookback edge is exclusive: a sample exactly `lookback_ms` before a grid point is not +/// selected, one millisecond later is. +/// +/// This pins what the selection kernel does rather than what Prometheus' documentation suggests: a +/// sample at the point itself is always selected, and the window is `(point - lookback, point]`. +#[test] +fn a_sample_at_the_lookback_edge_is_not_selected() { + // The statement's grid is the single point 1000ms, and the lookback is 200ms. + let out_grid = grid(1000, 100, 1); + let schema = raw_schema(); + let selected = |timestamp: i64| { + let tree = NativeTree::try_new(instant(input(), 200, 0, Arc::clone(&out_grid))).unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_raw(raw_chunk(&schema, &[timestamp], &[1.0], true)) + .unwrap(); + run(&mut execution) + }; + + // 800 is exactly `1000 - 200`, so the edge itself selects nothing. + let edge = selected(800); + assert_eq!(edge.len(), 1, "the series still closes on one chunk"); + assert!(edge[0].is_last); + assert!( + decided(&edge).is_empty(), + "a sample exactly at the lookback edge was selected: {:?}", + decided(&edge) + ); + // One millisecond inside the window is selected; a sample after the grid point never is. + assert_eq!(decided(&selected(801)), vec![(0, Some(1.0))]); + assert!(decided(&selected(1001)).is_empty()); +} + +/// A positive offset reads earlier samples, and a negative one later samples. +#[test] +fn an_offset_reads_a_different_sample_at_each_grid_point() { + let out_grid = grid(0, 60_000, 2); + let schema = raw_schema(); + let values = |offset_ms: i64| { + let tree = NativeTree::try_new(instant(input(), 600_000, offset_ms, Arc::clone(&out_grid))) + .unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_raw(raw_chunk( + &schema, + &[-60_000, 0, 60_000], + &[1.0, 2.0, 3.0], + true, + )) + .unwrap(); + decided(&run(&mut execution)) + }; + + assert_eq!( + values(0), + vec![(0, Some(2.0)), (1, Some(3.0))], + "without an offset a point reads the sample at or before it" + ); + assert_eq!( + values(60_000), + vec![(0, Some(1.0)), (1, Some(2.0))], + "a minute of offset did not read the samples a minute earlier" + ); + // A negative offset reads samples the statement's own range does not reach: both points read + // the sample one minute after them. + assert_eq!( + values(-60_000), + vec![(0, Some(3.0)), (1, Some(3.0))], + "a negative offset did not read the samples a minute later" + ); +} + +/// A series that selects nothing still closes, exactly once, on a chunk that holds no row. +#[test] +fn a_series_with_no_selectable_sample_closes_once() { + // Every sample carries the stale marker, which suppresses the selection at every point. + let stale = f64::from_bits(common_query::prometheus::PROMETHEUS_STALE_NAN_BITS); + let out_grid = grid(0, 60_000, 3); + let tree = NativeTree::try_new(instant(input(), 300_000, 0, Arc::clone(&out_grid))).unwrap(); + let set = ExecutionPlanMetricsSet::new(); + let mut execution = executor(&tree, pool(), &set); + let schema = raw_schema(); + execution + .push_raw(raw_chunk(&schema, &[0, 60_000], &[stale, stale], true)) + .unwrap(); + let out = run(&mut execution); + + assert_eq!(out.len(), 1, "the series has to close exactly once"); + let chunk = &out[0]; + assert!(chunk.is_last); + assert!( + chunk.series.time.is_empty(), + "the closing chunk of a series that selected nothing holds a row" + ); + assert_eq!( + series_start(chunk), + 0, + "the empty chunk is not addressed on the grid" + ); + assert!( + Arc::ptr_eq(chunk.series.time.grid().expect("a grid chunk"), &out_grid), + "the empty chunk is addressed on a grid that is not the selection's output grid" + ); + assert_eq!( + chunk.series.metric, + metric(), + "the series lost its identity" + ); + assert_eq!( + count(&set, &NodePath::root(), NodeMetric::COMPLETED_SERIES), + 1, + "the series did not close exactly once" + ); +} + +/// A row one field fills and another misses stays one row, with a null where the field misses it. +#[test] +fn a_selected_row_keeps_the_fields_that_miss_it_null() { + let out_grid = grid(0, 60_000, 2); + let tree = + NativeTree::try_new(instant(raw_input_of(2), 60_000, 0, Arc::clone(&out_grid))).unwrap(); + let schema = raw_schema_of(field_count(2)); + // Each field holds a value at one of the two rows and none at the other. + let chunk = raw_chunk_columns( + &schema, + &[0, 60_000], + vec![vec![Some(1.0), None], vec![None, Some(4.0)]], + true, + ); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution.push_raw(chunk).unwrap(); + let out = run(&mut execution); + + assert_eq!(out.len(), 1); + let chunk = &out[0]; + assert_eq!( + chunk.series.time.len(), + 2, + "a row no field of which holds a value was written down" + ); + assert_eq!(field_values(chunk, 0), vec![Some(1.0), None]); + assert_eq!(field_values(chunk, 1), vec![None, Some(4.0)]); + assert_eq!( + chunk + .series + .time + .positions() + .map(|(position, _)| position) + .collect::>(), + vec![0, 1] + ); +} + +/// A grid position nobody fills is not a row, and a hole does not close the series early. +/// +/// The samples lie at the first and the last point of the grid with nothing in between, and the +/// lookback is too short to carry either one across: two rows, two runs, and no row per position +/// between them. +#[test] +fn a_position_no_field_fills_is_not_a_row() { + let out_grid = grid(0, 60_000, 5); + let tree = NativeTree::try_new(instant(input(), 1_000, 0, Arc::clone(&out_grid))).unwrap(); + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_raw(raw_chunk(&schema, &[0], &[1.0], false)) + .unwrap(); + // The hole between the two samples decides nothing, and it does not end the series. + assert!( + execution.next_chunk().unwrap().is_none(), + "a hole in the grid closed the series" + ); + assert!( + execution.state().reserved_bytes() > 0, + "the open series is not reserved for" + ); + execution + .push_raw(raw_chunk(&schema, &[240_000], &[5.0], true)) + .unwrap(); + let out = run(&mut execution); + + assert_eq!(out.len(), 1); + let chunk = &out[0]; + assert!(chunk.is_last); + assert_eq!( + chunk + .series + .time + .positions() + .map(|(position, _)| position) + .collect::>(), + vec![0, 4], + "the positions nobody fills were written down as rows" + ); + assert_eq!(decided(&out), vec![(0, Some(1.0)), (4, Some(5.0))]); + assert!( + chunk.range().is_none(), + "a chunk of two runs of positions was addressed as one range" + ); +} + +/// An instant selection selects: the histogram it picks keeps its start timestamp. +/// +/// The sample is read, converted into the histogram type the builder writes back, and written out +/// again, and that type used to have no start timestamp to write: a sample carrying +/// `start_timestamp = Some(1500)` at 2000ms came out `None`. It matters downstream -- a reader +/// detects a counter reset from a start timestamp that falls inside the range it reads -- and it is +/// the difference between selecting a sample and computing a value. +/// +/// One source sample is selected by three grid points here, which is the case a per-row conversion +/// can get wrong twice: applied once and forgotten on the second use, or applied to a value that no +/// longer carries the timestamp. +#[test] +fn a_selected_histogram_keeps_its_start_timestamp() { + let out_grid = grid(2000, 1, 3); + let tree = NativeTree::try_new(instant(input(), 60_000, 0, Arc::clone(&out_grid))).unwrap(); + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_raw(raw_histogram_chunk_with_start( + &schema, + &[2000], + Some(1500), + true, + )) + .unwrap(); + let out = run(&mut execution); + + assert_eq!(out.len(), 1); + assert_eq!( + histogram_starts(&out[0]), + vec![Some(1500), Some(1500), Some(1500)], + "the selected sample lost the start timestamp it was read with" + ); +} + +/// Two series that differ only in an empty-valued label are two series, and both are answered. +/// +/// The label set the runtime's occupancy table compares drops empty values, so a node that recorded +/// what it handed out under one would refuse the second series. A selection keeps the labels it +/// read, empty values included, so it keeps them apart and records nothing. +#[test] +fn two_series_differing_only_in_an_empty_label_are_both_answered() { + let out_grid = grid(0, 60_000, 1); + let tree = NativeTree::try_new(instant(input(), 300_000, 0, Arc::clone(&out_grid))).unwrap(); + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + // `zone=""` against an absent `zone`: one label set to everything that drops empty values. + execution + .push_raw(raw_chunk_of( + &schema, + b"a", + host_metric(Some("")), + &[0], + &[1.0], + true, + )) + .unwrap(); + execution + .push_raw(raw_chunk_of( + &schema, + b"b", + host_metric(None), + &[0], + &[2.0], + true, + )) + .unwrap(); + let out = run(&mut execution); + + assert_eq!(out.len(), 2, "one of the two series was not answered"); + assert_eq!(out[0].series.metric, host_metric(Some(""))); + assert_eq!(out[1].series.metric, host_metric(None)); + assert_eq!(decided(&out[..1]), vec![(0, Some(1.0))]); + assert_eq!(decided(&out[1..]), vec![(0, Some(2.0))]); +} + +/// What a selection reserves is the series it has buffered, measured chunk by chunk. +/// +/// The node holds a whole series, so its reservation grows with the chunks that series arrived in +/// and goes back when the series is answered. Each chunk is measured once, with the same estimate a +/// queued chunk is charged with: an allocation two chunks share is counted once per chunk, which is +/// the over-count a figure that keeps no state across chunks accepts. +/// +/// What this checks is the buffer alone. The workspace the gather of that buffer allocates -- the +/// axis, the selection's two arrays and the rows the builder keeps -- is reserved for while it is +/// live and is not part of this figure, so this test cannot see it, however many bytes it is: +/// [`an_instant_selection_reserves_the_workspace_it_gathers`] is the one that does. +#[test] +fn an_instant_selection_reserves_the_series_it_buffers() { + let out_grid = grid(0, 60_000, 4); + let tree = NativeTree::try_new(instant(input(), 300_000, 0, Arc::clone(&out_grid))).unwrap(); + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let mut previous = 0; + for timestamps in [vec![0, 60_000], vec![120_000], vec![180_000]] { + let values = vec![1.0; timestamps.len()]; + let chunk = raw_chunk(&schema, ×tamps, &values, false); + let bytes = raw_bytes(&chunk); + execution.push_raw(chunk).unwrap(); + assert!( + execution.next_chunk().unwrap().is_none(), + "a series was reported before its last chunk arrived" + ); + let held = execution.state().reserved_bytes(); + assert_eq!( + held, + previous + bytes, + "the buffered series is not what is reserved for: {held} bytes held after {previous} \ + and a chunk of {bytes}" + ); + previous = held; + } + execution + .push_raw(raw_chunk(&schema, &[240_000], &[2.0], true)) + .unwrap(); + let out = run(&mut execution); + assert_eq!(out.len(), 1); + assert_eq!( + execution.state().reserved_bytes(), + 0, + "the series that was answered is still reserved for" + ); +} + +/// The workspace the gather allocates is reserved for before it exists. +/// +/// A selection decides the points of the grid it can be selected at, so its workspace is +/// proportional to those points rather than to the samples of the series: the axis it concatenates, +/// the source row and evaluation timestamp it reports per point, and the rows the builder keeps. +/// The lookback here reaches from the sample to the last point, so this series is decididable at +/// every one of the million points -- the clipped count equals the grid's -- and the two selection +/// arrays alone are 16 MB while the built rows are more, against a series the node holds of one +/// sample of a few hundred bytes. [`a_selection_reserves_the_points_it_decides`] is the other side +/// of the same figure: a series whose samples cover only the start of a long grid reserves for the +/// few points it can decide and is admitted by a pool this one is refused by. +/// +/// The pool here holds 8 KiB, which is enough for the buffered chunk and nothing near the +/// workspace, so the gather is refused instead of being performed. Nothing else refuses a million +/// points, so this is the reservation and not a point limit answering: without it the gather simply +/// runs. +#[test] +fn an_instant_selection_reserves_the_workspace_it_gathers() { + let out_grid = grid(0, 1, 1_000_000); + let tree = NativeTree::try_new(instant(input(), 1_000_000, 0, out_grid)).unwrap(); + let pool = bounded_pool(8 * 1024); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + let schema = raw_schema(); + execution + .push_raw(raw_chunk(&schema, &[0], &[1.0], true)) + .unwrap(); + + let error = execution.next_chunk().unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "the gather's workspace was taken without asking the pool: {error}" + ); + assert!( + !error.to_string().contains("exceed limit"), + "a point limit answered in the pool's place: {error}" + ); + assert_eq!( + pool.reserved(), + 0, + "the stopped execution still holds bytes" + ); + assert_eq!( + execution.state().reserved_bytes(), + 0, + "the workspace of the refused gather is still reserved for" + ); + assert_eq!( + execution.state().nodes_holding_instants(), + 0, + "the stopped execution still holds the buffered series" + ); + // A refused gather stops the execution rather than leaving it to be resumed. + let again = execution.next_chunk().unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); +} + +/// A selection reserves the points it can decide, not the points the grid plans. +/// +/// The review's shape: a seven-day grid at a one-minute step is 10,081 points, and one sample at +/// the start of the series read with a five-minute lookback is decided at five of them. The +/// grid-scaled terms of `InstantRuntime::gather_bytes` at the planned grid -- the selection's two +/// arrays and the doubled builder columns -- are about 504 KB, which the 64 KiB pool here is far +/// below; the handful of points really decided need a few hundred bytes, so this gather has to be +/// admitted. What it hands out is the rows `select_instants` reports for the same series, which is +/// the count the reservation has to agree with. +/// +/// The second half is the other direction: the same grid, the same pool, and a series that spans +/// the grid with a lookback long enough to cover it, so all 10,081 points can be decided. The +/// figure then exceeds the pool and the gather is refused, which is what keeps this from being a +/// reservation of nothing. +#[test] +fn a_selection_reserves_the_points_it_decides() { + let out_grid = grid(0, 60_000, 10_081); + let schema = raw_schema(); + let budget = 64 << 10; + // The two grid-scaled terms of `gather_bytes` at the planned grid: 10,081 points x 16 bytes for + // the selection's arrays, and 10,081 points x (8 + 8 + 1) x 2 for the doubled builder columns. + let full_grid = 10_081 * (8 + 8) + 10_081 * (8 + 8 + 1) * 2; + assert!( + full_grid > budget, + "the pool is not below what the full grid would be reserved: {full_grid} bytes" + ); + + // One sample at the start, read within five minutes: the kernel reports 0s..240s, and the + // candidate bound it sizes its arrays with is 0s..300s. + let tree = NativeTree::try_new(instant(input(), 300_000, 0, Arc::clone(&out_grid))).unwrap(); + let chunk = raw_chunk(&schema, &[0], &[1.0], true); + let (_, timestamps) = select_instants( + &chunk.time, + &chunk.fields, + out_grid.spec().start_ms..=grid_end_ms(out_grid.spec()), + out_grid.spec().step_ms, + 300_000, + 0, + ) + .unwrap(); + assert_eq!( + timestamps.len(), + 5, + "the clipping kernel decides another count" + ); + let mut execution = executor(&tree, bounded_pool(budget), &ExecutionPlanMetricsSet::new()); + execution.push_raw(chunk).unwrap(); + let out = run(&mut execution); + assert_eq!(out.len(), 1); + let expected: Vec<(usize, Option)> = timestamps + .iter() + .map(|timestamp| { + ( + usize::try_from((timestamp - out_grid.spec().start_ms) / out_grid.spec().step_ms) + .unwrap(), + Some(1.0), + ) + }) + .collect(); + assert_eq!( + decided(&out), + expected, + "the gather handed out another set of points than the clipping decides" + ); + + // The same series spans the grid with a lookback that covers it, so every point can be decided + // and the workspace no longer fits the same pool. + let tree = + NativeTree::try_new(instant(input(), 604_800_001, 0, Arc::clone(&out_grid))).unwrap(); + let pool = bounded_pool(budget); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_raw(raw_chunk(&schema, &[0, 604_800_000], &[1.0, 2.0], true)) + .unwrap(); + let error = execution.next_chunk().unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "a series covering the grid was gathered without asking the pool: {error}" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); +} + +/// A grid longer than any point limit is charged for, and the pool is what refuses it. +/// +/// `gather_bytes` used to return zero for a grid this long, so that a point limit inside the +/// kernel stayed the error reported and the workspace of a long gather was never reserved. The +/// estimate now applies to every gather, so the pool is asked before the kernel is and its refusal +/// is the one the caller sees — a bound in bytes, on the path that decides the points, rather than +/// a count that says nothing about what they cost. +#[test] +fn an_oversized_selection_is_refused_by_the_pool() { + // One million and two points over two samples: longer than the short circuit used to allow, + // so the estimate has to cover it rather than return zero. + let out_grid = grid(0, 1, 1_000_002); + let tree = NativeTree::try_new(instant(input(), 1_000_000, 0, out_grid)).unwrap(); + let pool = bounded_pool(8 * 1024); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + let schema = raw_schema(); + execution + .push_raw(raw_chunk(&schema, &[0, 1_000_001], &[1.0, 2.0], true)) + .unwrap(); + + let error = execution.next_chunk().unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "the gather's workspace was taken without asking the pool: {error}" + ); + assert!( + !error.to_string().contains("exceed limit"), + "a point limit answered in the pool's place: {error}" + ); + // Nothing is dropped silently: the execution stops and gives its reservation back. + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(execution.state().nodes_holding_instants(), 0); + let again = execution.next_chunk().unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); +} + +/// An input that ends inside a series is an error, not an empty answer. +/// +/// The selection holds the series and gathers it only on the chunk that closes it, so nothing is +/// answered for it. The node that notices is the input: the chunk it handed over did not say +/// `is_last`, and the tree's close reports that before any collected input is merged. +#[test] +fn an_input_that_ends_inside_a_series_is_reported() { + let tree = NativeTree::try_new(instant(input(), 300_000, 0, grid(0, 60_000, 2))).unwrap(); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + let schema = raw_schema(); + execution + .push_raw(raw_chunk(&schema, &[0], &[1.0], false)) + .unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + + let error = execution.finish().unwrap_err(); + assert!( + error.to_string().contains("ended before the last chunk"), + "{error}" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!( + execution.state().nodes_holding_instants(), + 0, + "the stopped execution still holds the buffered series" + ); +} + +/// A selection combines one series into one axis, so a chunk of another series is refused. +/// +/// The buffered chunks are read as one axis, so a chunk of a second series has nowhere to go: it +/// would be selected as though its samples were the open series'. +#[test] +fn a_chunk_of_another_series_is_refused() { + let tree = NativeTree::try_new(instant(input(), 300_000, 0, grid(0, 60_000, 2))).unwrap(); + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_raw(raw_chunk(&schema, &[0], &[1.0], false)) + .unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + // The second chunk carries another series' key. + execution + .push_raw(raw_chunk_of( + &schema, + b"series-b", + metric(), + &[60_000], + &[2.0], + true, + )) + .unwrap(); + + let error = execution.next_chunk().unwrap_err(); + assert!( + error + .to_string() + .contains("a chunk of another series arrived"), + "{error}" + ); + assert_eq!( + execution.state().reserved_bytes(), + 0, + "the refused series is still reserved for" + ); +} + +// --------------------------------------------------------------------------- +// Vector–vector binary operations, driven through `NativeExecutor`. +// --------------------------------------------------------------------------- + +/// The matching most tests here start from: no label list, one-to-one, no `bool`. +fn binary_matching(op: BinaryOp) -> BinaryMatching { + BinaryMatching { + op, + return_bool: false, + labels: MatchingLabels::Ignoring(Vec::new()), + cardinality: Cardinality::OneToOne, + fill: FillValues::default(), + } +} + +/// A binary node over `left` and `right`, bound the way the compiler binds it: the left side's +/// fields paired by position, on the grid both operands are evaluated on. +fn binary_of(left: NativeNode, right: NativeNode, matching: BinaryMatching) -> NativeNode { + let left_schema = left.output.samples().expect("binary reads samples").clone(); + let right_schema = right + .output + .samples() + .expect("binary reads samples") + .clone(); + let fields = field_count(left_schema.fields.len().min(right_schema.fields.len())); + NativeNode { + expr: NativeExpr::Binary { + left: Box::new(left), + right: Box::new(right), + matching, + }, + output: NativeType::Samples(Arc::new(SeriesSchema { + fields, + eval_grid: Some( + left_schema + .eval_grid + .clone() + .expect("binary reads evaluated samples"), + ), + })), + } +} + +/// A source of evaluated chunks over `count` float fields. +fn evaluated_input_of(count: usize, grid: Arc) -> NativeNode { + let output = NativeType::Samples(Arc::new(SeriesSchema { + fields: field_count(count), + eval_grid: Some(grid), + })); + NativeNode { + expr: NativeExpr::Input(BoundInput { + output: output.clone(), + ordering: SeriesOrdering::KeyThenTime, + }), + output, + } +} + +/// One evaluated chunk of `metric` whose fields carry `columns`, one column per field. +fn evaluated_columns( + schema: &SeriesSchema, + metric: MetricName, + start: usize, + columns: Vec>>, + is_last: bool, +) -> EvaluatedChunk { + let rows = columns.first().map_or(0, Vec::len); + evaluated_on(schema, metric, start, rows, columns, is_last) +} + +/// One evaluated chunk of `metric` addressed on `rows` positions from `start`, carrying `columns`. +/// +/// The axis and the columns are given independently so that a chunk whose two disagree can be built: +/// [`Series`] keeps its fields public, so nothing between a caller and a kernel refuses such a chunk +/// on its way in. +fn evaluated_on( + schema: &SeriesSchema, + metric: MetricName, + start: usize, + rows: usize, + columns: Vec>>, + is_last: bool, +) -> EvaluatedChunk { + let fields = SeriesFields::try_from_vec( + columns + .into_iter() + .map(|values| Samples::from_float(Float64Array::from(values))) + .collect(), + ) + .unwrap(); + let range = GridRange::try_new(schema.eval_grid.clone().unwrap(), start, rows).unwrap(); + EvaluatedChunk::try_new( + Series { + metric, + time: TimeAxis::Grid(range), + fields, + }, + is_last, + ) + .unwrap() +} + +/// One evaluated chunk of `metric` whose one field holds a `buckets`-wide histogram at each of +/// `len` positions from `start`. +fn evaluated_histograms( + schema: &SeriesSchema, + metric: MetricName, + start: usize, + buckets: i32, + len: usize, + is_last: bool, +) -> EvaluatedChunk { + let mut builder = HistogramBatchBuilder::new(); + let indices: UInt32Array = (0..len) + .map(|_| Some(push_histogram(&mut builder, buckets))) + .collect(); + let samples = Samples::try_from_histogram(indices, builder.finish().unwrap()).unwrap(); + let range = GridRange::try_new(schema.eval_grid.clone().unwrap(), start, len).unwrap(); + EvaluatedChunk::try_new( + Series { + metric, + time: TimeAxis::Grid(range), + fields: SeriesFields::one(samples), + }, + is_last, + ) + .unwrap() +} + +/// The `count` of the histogram at every carried row of a chunk. +fn histogram_counts(chunk: &EvaluatedChunk) -> Vec { + let mut cursor = chunk.series.fields.as_slice()[0].cursor(); + chunk + .series + .time + .positions() + .filter_map( + |(_, row)| match cursor.at(row).expect("the axis and the fields align") { + SampleRef::Histogram(view) => Some(view.count), + _ => None, + }, + ) + .collect() +} + +/// A source bound in label mode: `name{job="api",pod="a"}` and the other series here. +fn pod_metric(name: &str, job: &str, pod: &str) -> MetricName { + MetricName::try_new( + Some(name.into()), + vec![ + Label { + name: "job".into(), + value: job.into(), + }, + Label { + name: "pod".into(), + value: pod.into(), + }, + ], + ) + .unwrap() +} + +/// The one side of a `group_left` match: `one{job=...,instance=...}`. +fn one_metric(job: &str, instance: &str) -> MetricName { + MetricName::try_new( + Some("one".into()), + vec![ + Label { + name: "job".into(), + value: job.into(), + }, + Label { + name: "instance".into(), + value: instance.into(), + }, + ], + ) + .unwrap() +} + +/// A tree of two evaluated sources over `points` points under a binary node, with the two paths a +/// caller queues at. +fn binary_tree(op: BinaryOp, points: u64) -> (NativeTree, Arc, NodePath, NodePath) { + let grid = grid(0, 60_000, points); + let root = binary_of( + evaluated_input_of(1, Arc::clone(&grid)), + evaluated_input_of(1, Arc::clone(&grid)), + binary_matching(op), + ); + ( + NativeTree::try_new(root).unwrap(), + grid, + NodePath::root().left(), + NodePath::root().right(), + ) +} + +/// Two evaluated sources under a binary node add the series they match, point by point. +#[test] +fn a_binary_of_two_inputs_adds_the_matched_series() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); + let schema = evaluated_schema(grid); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at( + &left, + evaluated_chunk(&schema, 0, vec![1.0, 2.0, 3.0, 4.0], true), + ) + .unwrap(); + execution + .push_evaluated_at( + &right, + evaluated_chunk(&schema, 0, vec![10.0, 20.0, 30.0, 40.0], true), + ) + .unwrap(); + assert_eq!( + addressed(&run(&mut execution)), + vec![(0, vec![Some(11.0), Some(22.0), Some(33.0), Some(44.0)])] + ); +} + +/// Neither the order the sides arrive in nor the chunk boundaries of one side change the result. +/// +/// A binary node matches whole series, so the two deliveries below are the same vector: one splits +/// the right side over two chunks, the other queues the right side first. `is_last` is the only +/// thing that ends a series, so a chunk boundary carries no meaning of its own. +#[test] +fn a_binary_result_does_not_depend_on_arrival_order_or_chunk_boundaries() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Sub, 4); + let schema = evaluated_schema(Arc::clone(&grid)); + let mut split = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + split + .push_evaluated_at( + &left, + evaluated_chunk(&schema, 0, vec![1.0, 2.0, 3.0, 4.0], true), + ) + .unwrap(); + split + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![10.0, 20.0], false)) + .unwrap(); + split + .push_evaluated_at(&right, evaluated_chunk(&schema, 2, vec![30.0, 40.0], true)) + .unwrap(); + let split = decided(&run(&mut split)); + + let mut reversed = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + reversed + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![10.0, 20.0], false)) + .unwrap(); + reversed + .push_evaluated_at( + &left, + evaluated_chunk(&schema, 0, vec![1.0, 2.0, 3.0, 4.0], true), + ) + .unwrap(); + reversed + .push_evaluated_at(&right, evaluated_chunk(&schema, 2, vec![30.0, 40.0], true)) + .unwrap(); + let reversed = decided(&run(&mut reversed)); + + let expected = vec![ + (0, Some(-9.0)), + (1, Some(-18.0)), + (2, Some(-27.0)), + (3, Some(-36.0)), + ]; + assert_eq!(split, expected); + assert_eq!(reversed, expected); +} + +/// Two series that arrive in separate chunks and hold a value at the same point are refused. +/// +/// Each chunk is a series of its own, closed by its own `is_last`, and the two claim one label set: +/// Prometheus reports the duplicate at the first point both are present at, which no chunk boundary +/// can resolve. Two such series whose positions do not meet are accepted instead, as +/// `a_sparse_binary_keeps_the_shared_positions` shows. +#[test] +fn a_cross_chunk_duplicate_on_one_side_is_refused() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); + let schema = evaluated_schema(grid); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) + .unwrap(); + // The same label set twice on the right, each delivered in the chunk that closes it, and both + // holding values at positions 0 and 1. + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![10.0, 20.0], true)) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![30.0, 40.0], true)) + .unwrap(); + + let error = execution.finish().unwrap_err(); + assert!( + error + .to_string() + .contains("found duplicate series for the match group"), + "{error}" + ); + assert_eq!(pool.reserved(), 0, "the refused operands are still held"); + assert_eq!(execution.state().reserved_bytes(), 0); +} + +/// An operand that closes without a row contributes nothing, and pairing it is not an error. +#[test] +fn an_empty_side_yields_no_series() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); + let schema = evaluated_schema(grid); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + // A closing chunk with no row: the series ends before its first point. + execution + .push_evaluated_at( + &left, + evaluated_chunk_of(&schema, metric(), 0, Vec::new(), true), + ) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) + .unwrap(); + assert!(run(&mut execution).is_empty()); +} + +/// An empty closing chunk after rows is not the series going backwards. +#[test] +fn an_empty_closing_chunk_does_not_rewind_a_series() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); + let schema = evaluated_schema(grid); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0], false)) + .unwrap(); + // The chunk that closes the series holds no row, so where it addresses says nothing. + execution + .push_evaluated_at( + &left, + evaluated_chunk_of(&schema, metric(), 0, Vec::new(), true), + ) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![10.0, 20.0], true)) + .unwrap(); + assert_eq!(decided(&run(&mut execution)), vec![(0, Some(11.0))]); +} + +/// Two sparse operands meet at the positions both carry. +#[test] +fn a_sparse_binary_keeps_the_shared_positions() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); + let schema = evaluated_schema(grid); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + // The left side decides positions 0 and 2 only, in two chunks. + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0], false)) + .unwrap(); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 2, vec![3.0], true)) + .unwrap(); + execution + .push_evaluated_at( + &right, + evaluated_chunk(&schema, 0, vec![10.0, 20.0, 30.0, 40.0], true), + ) + .unwrap(); + assert_eq!( + decided(&run(&mut execution)), + vec![(0, Some(11.0)), (2, Some(33.0))] + ); +} + +/// Fields are paired by position, and a field that misses a position keeps it null. +#[test] +fn a_binary_pairs_the_fields_of_each_operand() { + let grid = grid(0, 60_000, 2); + let root = binary_of( + evaluated_input_of(2, Arc::clone(&grid)), + evaluated_input_of(2, Arc::clone(&grid)), + binary_matching(BinaryOp::Add), + ); + let tree = NativeTree::try_new(root).unwrap(); + let schema = Arc::new(SeriesSchema { + fields: field_count(2), + eval_grid: Some(grid), + }); + let set = ExecutionPlanMetricsSet::new(); + let mut execution = executor(&tree, pool(), &set); + execution + .push_evaluated_at( + &NodePath::root().left(), + evaluated_columns( + &schema, + metric(), + 0, + vec![vec![Some(1.0), None], vec![Some(5.0), Some(6.0)]], + true, + ), + ) + .unwrap(); + execution + .push_evaluated_at( + &NodePath::root().right(), + evaluated_columns( + &schema, + metric(), + 0, + vec![vec![Some(10.0), Some(20.0)], vec![Some(7.0), Some(8.0)]], + true, + ), + ) + .unwrap(); + let out = run(&mut execution); + assert_eq!(out.len(), 1); + // Position 1 holds no left value of field 0, so that field keeps it null while field 1 has one. + assert_eq!(field_values(&out[0], 0), vec![Some(11.0), None]); + assert_eq!(field_values(&out[0], 1), vec![Some(12.0), Some(14.0)]); + // The result decided two positions and holds three values: the two positions are what the node + // evaluated, and a value is what a field sample holds, which is one fewer for the null. + let root_path = NodePath::root(); + assert_eq!( + count(&set, &root_path, NodeMetric::EVALUATED_GRID_POINTS), + 2 + ); + assert_eq!(count(&set, &root_path, NodeMetric::OUTPUT_VALUES), 3); +} + +/// A comparison without `bool` filters the points it does not hold at; with `bool` it reports both. +#[test] +fn a_comparison_filters_and_a_bool_comparison_reports_both_outcomes() { + let grid = grid(0, 60_000, 4); + let schema = evaluated_schema(Arc::clone(&grid)); + for (return_bool, expected) in [ + (false, vec![(2, Some(3.0)), (3, Some(4.0))]), + ( + true, + vec![ + (0, Some(0.0)), + (1, Some(0.0)), + (2, Some(1.0)), + (3, Some(1.0)), + ], + ), + ] { + let matching = BinaryMatching { + op: BinaryOp::Gt, + return_bool, + labels: MatchingLabels::Ignoring(Vec::new()), + cardinality: Cardinality::OneToOne, + fill: FillValues::default(), + }; + let root = binary_of( + evaluated_input_of(1, Arc::clone(&grid)), + evaluated_input_of(1, Arc::clone(&grid)), + matching, + ); + let tree = NativeTree::try_new(root).unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at( + &NodePath::root().left(), + evaluated_chunk(&schema, 0, vec![1.0, 2.0, 3.0, 4.0], true), + ) + .unwrap(); + execution + .push_evaluated_at( + &NodePath::root().right(), + evaluated_chunk(&schema, 0, vec![2.0, 2.0, 2.0, 2.0], true), + ) + .unwrap(); + assert_eq!( + decided(&run(&mut execution)), + expected, + "bool={return_bool}" + ); + } +} + +/// `group_left(instance)` keeps every many-side series and copies the label from its match. +#[test] +fn a_group_modifier_copies_the_one_side_label() { + let grid = grid(0, 60_000, 2); + let matching = BinaryMatching { + op: BinaryOp::Add, + return_bool: false, + labels: MatchingLabels::On(vec![Arc::from("job")]), + cardinality: Cardinality::ManyToOne(vec![Arc::from("instance")]), + fill: FillValues::default(), + }; + let root = binary_of( + evaluated_input_of(1, Arc::clone(&grid)), + evaluated_input_of(1, Arc::clone(&grid)), + matching, + ); + let tree = NativeTree::try_new(root).unwrap(); + let schema = evaluated_schema(Arc::clone(&grid)); + let (left, right) = (NodePath::root().left(), NodePath::root().right()); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for (metric, values) in [ + (pod_metric("a", "api", "p1"), vec![Some(1.0), Some(2.0)]), + (pod_metric("b", "db", "p2"), vec![Some(3.0), Some(4.0)]), + ] { + execution + .push_evaluated_at(&left, evaluated_chunk_of(&schema, metric, 0, values, true)) + .unwrap(); + } + for (metric, values) in [ + (one_metric("api", "i1"), vec![Some(10.0), Some(20.0)]), + (one_metric("db", "i2"), vec![Some(100.0), Some(200.0)]), + ] { + execution + .push_evaluated_at(&right, evaluated_chunk_of(&schema, metric, 0, values, true)) + .unwrap(); + } + + // The result is compared as label sets, so the two series are sorted by the labels they carry: + // the value lists of `f64` have no total order, and none is needed here. + let mut results: Vec<_> = run(&mut execution) + .iter() + .map(|chunk| { + let mut tags: Vec<(String, String)> = chunk + .series + .metric + .tags() + .iter() + .map(|tag| (tag.name.to_string(), tag.value.to_string())) + .collect(); + tags.sort(); + (tags, sample_values(chunk)) + }) + .collect(); + results.sort_by(|left, right| left.0.cmp(&right.0)); + assert_eq!( + results, + vec![ + ( + vec![ + ("instance".to_string(), "i1".to_string()), + ("job".to_string(), "api".to_string()), + ("pod".to_string(), "p1".to_string()), + ], + vec![Some(11.0), Some(22.0)], + ), + ( + vec![ + ("instance".to_string(), "i2".to_string()), + ("job".to_string(), "db".to_string()), + ("pod".to_string(), "p2".to_string()), + ], + vec![Some(103.0), Some(204.0)], + ), + ] + ); +} + +/// Two native histograms are added bucket by bucket. +#[test] +fn a_binary_adds_the_native_histograms_of_both_sides() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); + let schema = evaluated_schema(grid); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at( + &left, + evaluated_histograms(&schema, metric(), 0, 4, 2, true), + ) + .unwrap(); + execution + .push_evaluated_at( + &right, + evaluated_histograms(&schema, metric(), 0, 4, 2, true), + ) + .unwrap(); + let out = run(&mut execution); + assert_eq!(out.len(), 1); + // Each side holds four buckets of one count at each point, so the sum counts eight. + assert_eq!(histogram_counts(&out[0]), vec![8.0, 8.0]); +} + +/// Nothing is decided before the input ends; `finish` is what hands the result over. +#[test] +fn a_binary_yields_nothing_until_the_input_finishes() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); + let schema = evaluated_schema(grid); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![10.0, 20.0], true)) + .unwrap(); + assert!( + execution.next_chunk().unwrap().is_none(), + "a binary node answered before its input ended" + ); + assert_eq!( + addressed(&execution.finish().unwrap()), + vec![(0, vec![Some(11.0), Some(22.0)])] + ); +} + +/// A truncated operand is refused before the kernel is handed anything. +/// +/// The right side also carries a duplicate series, which the kernel would report: the truncation is +/// what comes back, so the kernel never ran over half a vector. +#[test] +fn a_truncated_operand_is_refused_before_the_kernel_runs() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); + let schema = evaluated_schema(grid); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + // The left side holds a duplicate the kernel would report if it were reached. + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) + .unwrap(); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![3.0, 4.0], true)) + .unwrap(); + // The right side never hands over the chunk that closes its series. + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![10.0], false)) + .unwrap(); + + let error = execution.finish().unwrap_err(); + assert!( + error.to_string().contains("ended before the last chunk"), + "{error}" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().nodes_holding_binary(), 0); +} + +/// A workspace the pool cannot hold is refused, and what the node retained is given back with it. +#[test] +fn an_oversized_binary_workspace_is_refused_by_the_pool() { + let points = 100_000; + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, points); + let schema = evaluated_schema(grid); + // Enough for the two one-row operands, far less than the presence arrays the kernel builds. + let pool = bounded_pool(60_000); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0], true)) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![10.0], true)) + .unwrap(); + let error = execution.finish().unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "a point limit answered in the pool's place: {error}" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(execution.state().nodes_holding_binary(), 0); +} + +/// A pool that cannot hold both operands refuses the second one, and the first is given back. +/// +/// Both chunks sit in their input's queue until the input ends, so the reservation covers them at +/// once: the second one is what the pool refuses, and stopping the execution returns what the first +/// one held. +#[test] +fn an_oversized_binary_operand_is_refused_by_the_pool() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 100_000); + let schema = evaluated_schema(grid); + let pool = bounded_pool(60_000); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0], true)) + .unwrap(); + let values: Vec = (0..50_000).map(f64::from).collect(); + let error = execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, values, true)) + .unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "an operand limit answered in the pool's place: {error}" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); +} + +/// A binary operand reserves each chunk it retains before it retains it, and holds exactly what +/// those chunks hold on their own. +/// +/// The figure of a retained chunk is what its rows occupy rather than the allocation they are slices +/// of, so a series delivered in sibling slices of one batch is charged the batch's data once instead +/// of once per chunk. What is refused here is a figure that disagrees with what the operand holds -- +/// a chunk reserved for on top of what the operand already keeps would be refused by a pool sized to +/// the total, and one reserved for less would leave the pool holding less than the node does. +#[test] +fn a_binary_operand_reserves_what_it_retains() { + let grid = grid(0, 60_000, 40_000); + let schema = evaluated_schema(Arc::clone(&grid)); + let batch = Float64Array::from((0..40_000).map(f64::from).collect::>()); + let first = evaluated_array_chunk_of(&schema, metric(), 0, batch.slice(0, 20_000), false); + let second = + evaluated_array_chunk_of(&schema, metric(), 20_000, batch.slice(20_000, 20_000), true); + + // What each chunk holds on its own, and the entry the closing chunk records in the operand's + // boundary list -- the list is storage the operand keeps, and it is charged one entry per closed + // series as it is written. + let boundaries = std::mem::size_of::(); + let (first_alone, second_alone) = ( + operand_chunk_bytes(&first.series), + operand_chunk_bytes(&second.series), + ); + let held = first_alone + second_alone + boundaries; + + // The budget is the figure the operand ends up holding, so a chunk reserved for on top of what + // the operand keeps would be refused and one reserved for less would leave the pool holding less + // than the node does. + let pool = bounded_pool(held); + let mut runtime = binary_runtime(&pool, &schema); + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first)) + .unwrap(); + assert_eq!( + runtime.buffer.reservation.size() - before, + first_alone, + "the first chunk of the operand does not cost what it is estimated at" + ); + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second)) + .unwrap(); + assert_eq!( + runtime.buffer.reservation.size() - before, + second_alone + boundaries, + "the closing chunk of the operand does not cost what it is estimated at, and the end it \ + records" + ); + assert_eq!( + runtime.buffer.reservation.size(), + held, + "the operand does not reserve what it holds" + ); + assert_eq!(pool.reserved(), held); + + // The figure a caller reserves for before retaining a chunk is the one the operand grows by: the + // estimate of the series it carries and the one entry the chunk's end records. + let own = evaluated_chunk(&schema, 0, vec![1.0, 2.0], true); + assert_eq!( + runtime + .binary + .as_ref() + .unwrap() + .pending(&NodePath::root(), 0, &own) + .unwrap(), + operand_chunk_bytes(&own.series) + std::mem::size_of::(), + "the figure reserved for a chunk is not what the operand grows by" + ); + + // Assembling the two chunks keeps the allocation they are slices of: the series the kernel reads + // is made of their descriptors, and no sample is copied into it. + let assembled = runtime + .binary + .as_ref() + .unwrap() + .assemble(&NodePath::root()) + .unwrap(); + assert_eq!( + assembled[0].len(), + 1, + "two chunks of one series are one series" + ); + let field = &assembled[0][0].fields.as_slice()[0]; + assert_eq!( + field.segments().len(), + 2, + "the assembled field is not the chunks it is built from" + ); + for segment in field.segments() { + let Some(DenseSamplesRef::Float(values)) = segment.dense() else { + panic!("a float chunk assembles into float segments"); + }; + assert_eq!( + values.values().inner().data_ptr(), + batch.values().inner().data_ptr(), + "the assembly copied samples instead of sharing the allocation they are slices of" + ); + } +} + +/// Two chunks that are first to reference a histogram table each are billed a table each. +/// +/// A histogram field's samples are a column of indices into a table, and the table is the bulk of +/// what such a chunk costs: the indices are four bytes a row where the table is thousands of bytes +/// of buckets. Two chunks of the same shape hold two tables, so each costs the other, and each +/// costs at least the table it holds -- a figure that charged the column of indices alone would +/// leave both tables outside everything the node reserves. +#[test] +fn a_binary_operand_bills_each_histogram_table_it_retains() { + const BUCKETS: i32 = 4_000; + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let table = histogram_table(2, BUCKETS); + let other = histogram_table(2, BUCKETS); + let bytes = histogram_table_bytes(&table); + assert_eq!( + bytes, + histogram_table_bytes(&other), + "the two tables are not the same shape, so the two chunks are not comparable" + ); + assert!( + bytes > 32 * 1024, + "a table of {bytes} bytes is no bigger than the descriptors of a one-row chunk, so nothing \ + here would tell a billed table from an unbilled one" + ); + let first = evaluated_histogram_chunk_of(&schema, metric(), 0, vec![Some(0)], &table, true); + let second = evaluated_histogram_chunk_of(&schema, metric(), 1, vec![Some(1)], &other, true); + + let pool = pool(); + let mut runtime = binary_runtime(&pool, &schema); + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first)) + .unwrap(); + let first_cost = runtime.buffer.reservation.size() - before; + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second)) + .unwrap(); + let second_cost = runtime.buffer.reservation.size() - before; + + assert_eq!( + first_cost, second_cost, + "two chunks of one shape and one table each cost different figures: {first_cost} and \ + {second_cost}" + ); + for (name, cost) in [("first", first_cost), ("second", second_cost)] { + assert!( + cost >= bytes, + "the {name} chunk costs {cost} bytes, less than the {bytes} its histogram table holds" + ); + assert!( + cost < 2 * bytes, + "the {name} chunk costs {cost} bytes, more than the {bytes} of its table and the rest \ + of a one-row chunk" + ); + } + assert_eq!( + runtime.buffer.reservation.size(), + first_cost + second_cost, + "the operand does not reserve what the two chunks it retains cost" + ); + assert_eq!(pool.reserved(), runtime.buffer.reservation.size()); +} + +/// Two chunks that index one histogram table are billed that table once. +/// +/// A table is one allocation however many chunks of a series index into it, so the second chunk is +/// charged the descriptor, the index and the end it records, and not the table again. The two +/// chunks here are the same shape, so what separates their figures is the table: the pair costs one +/// table plus both chunks' own descriptors, not one table per chunk and not no table at all. +#[test] +fn a_binary_operand_bills_a_shared_histogram_table_once() { + const BUCKETS: i32 = 4_000; + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let table = histogram_table(2, BUCKETS); + let bytes = histogram_table_bytes(&table); + assert!( + bytes > 32 * 1024, + "a table of {bytes} bytes is no bigger than the descriptors of a one-row chunk, so nothing \ + here would tell a shared table from a second one" + ); + let first = evaluated_histogram_chunk_of(&schema, metric(), 0, vec![Some(0)], &table, true); + let second = evaluated_histogram_chunk_of(&schema, metric(), 1, vec![Some(1)], &table, true); + + let pool = pool(); + let mut runtime = binary_runtime(&pool, &schema); + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first)) + .unwrap(); + let first_cost = runtime.buffer.reservation.size() - before; + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second)) + .unwrap(); + let second_cost = runtime.buffer.reservation.size() - before; + + assert!( + first_cost >= bytes, + "the chunk that first references the table costs {first_cost} bytes, less than the {bytes} \ + the table holds" + ); + // The two chunks are the same shape, so the second one is charged its own descriptors and not + // the table: it costs a small fraction of what the table holds, where a second table would cost + // the table again. + assert!( + second_cost * 8 < bytes, + "the second slice of one table costs {second_cost} bytes, comparable to the {bytes} the \ + table itself holds" + ); + // What the pair costs past the second chunk is the table the first one billed, and no more than + // the few bytes that remembering it takes. + let difference = first_cost.saturating_sub(second_cost); + assert!( + difference >= bytes, + "the pair costs {difference} bytes more than its second chunk, less than the {bytes} of the \ + one table between them" + ); + assert!( + difference <= bytes + 64, + "the pair costs {difference} bytes more than its second chunk, past the {bytes} of the one \ + table between them: the table is billed twice" + ); + assert!( + runtime.buffer.reservation.size() < bytes + 2 * second_cost + 64, + "the operand charges the one table of its two chunks twice: {} bytes for {} bytes of table", + runtime.buffer.reservation.size(), + bytes + ); + assert_eq!(pool.reserved(), runtime.buffer.reservation.size()); +} + +/// A pool with room for one histogram table admits one chunk of a table, refuses a second chunk +/// holding another table, and admits a second slice of the table it already holds. +/// +/// This is the figure the reservation is made for: a chunk that is the first to reference a table +/// costs that table, so two of them do not fit in room for one, while a chunk that indexes a table +/// the operand already holds costs its own slice and does. The room beside the first chunk is half a +/// table -- far more than the descriptors of a second chunk and far less than a second table -- and +/// the refused chunk leaves the operand where it was. +#[test] +fn a_pool_that_holds_one_histogram_table_refuses_a_second() { + const BUCKETS: i32 = 4_000; + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let table = histogram_table(2, BUCKETS); + let other = histogram_table(2, BUCKETS); + let bytes = histogram_table_bytes(&table); + assert!( + bytes > 32 * 1024, + "a table of {bytes} bytes is no bigger than the descriptors of a one-row chunk, so the room \ + beside one table would hold a second" + ); + let first = evaluated_histogram_chunk_of(&schema, metric(), 0, vec![Some(0)], &table, true); + let second_own = + evaluated_histogram_chunk_of(&schema, metric(), 0, vec![Some(0)], &other, true); + let second_shared = + evaluated_histogram_chunk_of(&schema, metric(), 1, vec![Some(1)], &table, true); + + // What the operand holds once it retains one chunk of a table, measured where the pool admits + // anything; the pool below is sized from it and half a table. + let mut probe = binary_runtime(&pool(), &schema); + probe + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first.clone())) + .unwrap(); + let one_chunk = probe.buffer.reservation.size(); + let budget = one_chunk + bytes / 2; + + // A second chunk holding a table of its own does not fit: the pool refuses it and the operand + // keeps what it had. + let mut refused = binary_runtime(&bounded_pool(budget), &schema); + refused + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first.clone())) + .unwrap(); + let error = refused + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second_own)) + .unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "a second chunk holding a table of its own was admitted beside the first: {error}" + ); + assert_eq!( + refused.buffer.reservation.size(), + one_chunk, + "the refused chunk moved what the operand reserves" + ); + + // The second slice of the one table the operand holds does fit. + let mut shared = binary_runtime(&bounded_pool(budget), &schema); + shared + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first)) + .unwrap(); + shared + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second_shared)) + .unwrap(); + assert!( + shared.buffer.reservation.size() > one_chunk, + "the second slice of the table was admitted without being charged its own descriptors" + ); + assert!( + shared.buffer.reservation.size() <= budget, + "the operand reserves past the pool it was admitted in" + ); +} + +/// The executor's binary node holds no more than the operands it retains: the peak of its own +/// reservation is what every retained chunk holds on its own, not that plus a chunk it was handed +/// again. +/// +/// The source queue holds one chunk while the node retains the other, so what is read here is the +/// binary node's own figure rather than the pool's: the overlap of the two nodes is a charge of the +/// input and says nothing about what the operand costs. +#[test] +fn a_binary_beneath_the_executor_reserves_what_it_retains() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4_000); + let schema = evaluated_schema(Arc::clone(&grid)); + let batch = Float64Array::from(vec![1.0; 4_000]); + let first = evaluated_array_chunk_of(&schema, metric(), 0, batch.slice(0, 2_000), false); + let second = + evaluated_array_chunk_of(&schema, metric(), 2_000, batch.slice(2_000, 2_000), true); + // What the left operand holds once both chunks are retained: what each chunk holds on its own, + // and the boundary list the closing chunk adds one entry to. + let retained = std::mem::size_of::() + + [&first, &second] + .iter() + .map(|chunk| operand_chunk_bytes(&chunk.series)) + .fold(0usize, usize::saturating_add); + + let set = ExecutionPlanMetricsSet::new(); + let mut execution = executor(&tree, bounded_pool(1 << 22), &set); + execution.push_evaluated_at(&left, first).unwrap(); + execution.push_evaluated_at(&left, second).unwrap(); + // Nothing is queued on the right, so the pull retains both chunks of the left operand and + // nothing else: the kernel has not run and the node holds what it retains. + assert!(execution.next_chunk().unwrap().is_none()); + let peak = NodePath::root().partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, 0); + assert_eq!( + gauge(&set, &peak), + retained, + "the binary node reserved more than the operands it retains" + ); + + // The right operand matches the label set, so the operation answers every point of the grid. + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![2.0; 4_000], true)) + .unwrap(); + assert_eq!( + addressed(&run(&mut execution)), + vec![(0, vec![Some(3.0); 4_000])] + ); +} + +/// A query rooted at a binary node streams its answer after the input ends, one chunk per pull. +/// +/// The kernel needs both whole vectors before it answers anything, so nothing is settled until the +/// caller ends the input. From there the answer is not handed over as one collected value: each pull +/// takes the next chunk out of the node that holds it and gives back what that chunk was charged, +/// and the pull that finds nothing left is where the execution closes. A caller that stops pulling +/// early therefore still holds nothing it did not ask for, and the pool is empty when the last +/// `None` arrives. +#[test] +fn an_ended_input_streams_the_binary_answer_one_chunk_at_a_time() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); + let schema = evaluated_schema(Arc::clone(&grid)); + let pool = bounded_pool(1 << 22); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0; 4], true)) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![2.0; 4], true)) + .unwrap(); + // The operands are whole now, but the kernel has not run: the caller has not ended the input. + assert!(execution.next_chunk().unwrap().is_none()); + + execution + .end_of_input() + .expect("a closed input with two whole operands ends cleanly"); + // Ending the input runs the kernel and leaves its answer in the node that computed it, charged + // there until it is pulled; it does not collect the answer into a value of its own. + let mut chunks = Vec::new(); + while let Some(chunk) = execution.next_chunk().unwrap() { + chunks.push(chunk); + } + assert_eq!(addressed(&chunks), vec![(0, vec![Some(3.0); 4])]); + // The last pull closed the execution and returned everything it reserved. + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + // A finished execution is not pulled again. + let again = execution.next_chunk().unwrap_err(); + assert!(again.to_string().contains("already finished"), "{again}"); +} + +/// `finish` still answers the whole result in one value for a caller that wants it that way. +#[test] +fn finish_collects_what_the_streaming_contract_would_have_pulled() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); + let schema = evaluated_schema(Arc::clone(&grid)); + let pool = bounded_pool(1 << 22); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0; 4], true)) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![2.0; 4], true)) + .unwrap(); + let chunks = execution.finish().expect("the whole answer is collected"); + assert_eq!(addressed(&chunks), vec![(0, vec![Some(3.0); 4])]); + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); +} + +/// A binary node reads an operand a collecting window below it produces only after that window +/// flushes. +/// +/// `Add(LastOverTime(Abs(a)), b)` puts a collecting window under a binary node: the window is above +/// a map, so it collects its whole input and answers at the end of it, while the binary node needs +/// both operands whole before it decides a point. Ending the input therefore has to finish the +/// subtree below each operand before the binary node computes -- flushing the window first and +/// letting the pull that follows carry its answer up. A binary node that computed on the empty +/// left operand would mark itself computed and answer nothing, and the value the window produced +/// afterwards would never be read. +#[test] +fn a_binary_reads_an_operand_a_collecting_window_flushes() { + let grid = grid(0, 60_000, 1); + let schema = evaluated_schema(Arc::clone(&grid)); + // The left operand is a window over a map: the map rewrites the label set, so the window + // collects its input and answers at the end of it. The right operand is a plain source. + let root = binary_of( + window_with( + map(evaluated_input(Arc::clone(&grid)), vec![MathOp::Abs]), + RangeFunction::LastOverTime, + 60_000, + Some(Arc::clone(&grid)), + Arc::clone(&grid), + ), + evaluated_input(Arc::clone(&grid)), + binary_matching(BinaryOp::Add), + ); + let tree = NativeTree::try_new(root).expect("the shape is legal"); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + // One point on each side, in one window: the left is -1, which `abs` makes 1, and the right is + // 10, so the sum is 11. + execution + .push_evaluated_at( + &NodePath::root().left().input().input(), + evaluated_chunk_of(&schema, metric(), 0, vec![Some(-1.0)], true), + ) + .unwrap(); + execution + .push_evaluated_at( + &NodePath::root().right(), + evaluated_chunk_of(&schema, metric(), 0, vec![Some(10.0)], true), + ) + .unwrap(); + + assert_eq!( + decided(&run(&mut execution)), + vec![(0, Some(11.0))], + "the binary node computed before the window below it answered" + ); +} + +/// A series that arrives in ten thousand one-point chunks is one candidate for the kernel, not ten +/// thousand. +/// +/// The kernel matches whole series, so the chunks of a logical series are assembled into the series +/// it reads before it runs: the pairing is over candidates, and a chunk that was a candidate of its +/// own would pair every chunk of one side with every chunk of the other. The same series delivered +/// whole must answer the same result, so the count of pairs the kernel actually visited is what +/// separates the two deliveries rather than their outcome. +#[test] +fn a_series_of_many_chunks_is_one_candidate_for_the_kernel() { + let points = 10_000usize; + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, points as u64); + let schema = evaluated_schema(grid); + let batch = Float64Array::from((0..points).map(|point| point as f64).collect::>()); + // One point per chunk, and only the last of them closes the series: the boundaries of the + // delivery say nothing about the series it carries. + let per_point: Vec = (0..points) + .map(|position| { + evaluated_array_chunk_of( + &schema, + metric(), + position, + batch.slice(position, 1), + position + 1 == points, + ) + }) + .collect(); + + reset_visited_pairs(); + let mut split = executor( + &tree, + bounded_pool(1 << 26), + &ExecutionPlanMetricsSet::new(), + ); + for (position, chunk) in per_point.iter().enumerate() { + split.push_evaluated_at(&left, chunk.clone()).unwrap(); + split.push_evaluated_at(&right, chunk.clone()).unwrap(); + assert!( + split.next_chunk().unwrap().is_none(), + "the binary node answered at position {position} before its input ended" + ); + } + let split = split.finish().unwrap(); + assert_eq!( + visited_pairs(), + 1, + "the chunks of one series were paired instead of the one series they make up" + ); + assert_eq!(split.len(), 1, "one matched label set answers one chunk"); + + reset_visited_pairs(); + let mut whole = executor( + &tree, + bounded_pool(1 << 26), + &ExecutionPlanMetricsSet::new(), + ); + let chunk = evaluated_array_chunk_of(&schema, metric(), 0, batch.clone(), true); + whole.push_evaluated_at(&left, chunk.clone()).unwrap(); + whole.push_evaluated_at(&right, chunk).unwrap(); + assert!(whole.next_chunk().unwrap().is_none()); + let whole = whole.finish().unwrap(); + assert_eq!( + visited_pairs(), + 1, + "a series delivered whole is one candidate as well" + ); + assert_eq!(whole.len(), 1, "one matched label set answers one chunk"); + + assert_eq!( + decided(&split), + decided(&whole), + "the delivery of a series changed the result" + ); + let expected: Vec<(usize, Option)> = (0..points) + .map(|position| (position, Some(2.0 * position as f64))) + .collect(); + assert_eq!(decided(&split), expected); +} + +/// The assembly of the operands into the series the kernel matches is reserved before it allocates. +/// +/// Assembling one series per closed series is metadata on top of the chunks the node retains -- the +/// descriptors the chunks' fields are collected into and the runs the axis is built from -- and the +/// pool is asked for that figure before it exists. A pool a byte short of it refuses the assembly, +/// and nothing of it is left charged: the node holds what it retained while the runtime is still +/// alive. +#[test] +fn an_assembly_the_pool_cannot_hold_is_refused_before_it_allocates() { + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let left = evaluated_chunk(&schema, 0, vec![1.0, 2.0], true); + let right = evaluated_chunk(&schema, 0, vec![10.0, 20.0], true); + let (retained, assembly) = binary_charge(&schema, &left, &right); + assert!( + assembly > 0, + "assembling the operands into series is not charged for" + ); + + // One byte short of the assembly: the assembly is refused rather than run over the budget. + let pool = bounded_pool(retained + assembly - 1); + let mut runtime = binary_runtime(&pool, &schema); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(left.clone())) + .unwrap(); + runtime + .retain_binary(&NodePath::root(), 1, NativeChunk::Evaluated(right.clone())) + .unwrap(); + assert_eq!(runtime.buffer.reservation.size(), retained); + let error = runtime.compute_binary(&NodePath::root()).unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "the assembly was not reserved before it allocated: {error}" + ); + // The assembly never ran, so its charge is gone: what the node holds is what it retained, and + // the pool holds no more than that while the runtime is still alive. + assert_eq!(runtime.buffer.reservation.size(), retained); + assert_eq!(pool.reserved(), retained); + assert_eq!( + runtime.binary.as_ref().unwrap().retained_bytes(), + retained, + "the refused assembly changed what the operand retains" + ); + + // The figure covers the assembly itself: with exactly that much more, the series are built and + // hold the rows the chunks carried. + let pool = bounded_pool(retained + assembly); + let mut runtime = binary_runtime(&pool, &schema); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(left)) + .unwrap(); + runtime + .retain_binary(&NodePath::root(), 1, NativeChunk::Evaluated(right)) + .unwrap(); + let assembled = runtime + .binary + .as_ref() + .unwrap() + .assemble(&NodePath::root()) + .unwrap(); + assert_eq!(assembled[0].len(), 1, "one closed series is one series"); + assert_eq!(assembled[1].len(), 1, "one closed series is one series"); + let built = EvaluatedChunk::try_new(assembled[0][0].clone(), true).unwrap(); + assert_eq!(sample_values(&built), vec![Some(1.0), Some(2.0)]); +} + +/// An assembly the executor's pool cannot hold stops it and leaves it holding nothing. +/// +/// The pool is one byte short of what the node retains plus what assembling the retained chunks +/// allocates, so both operands are retained and the assembly is what the pool refuses. What a caller +/// sees afterwards is a stopped execution that holds nothing: the operand chunks are dropped and the +/// reservation is back at zero while the executor is still alive. +#[test] +fn an_assembly_the_executors_pool_cannot_hold_stops_it() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); + let schema = evaluated_schema(grid); + let (left_chunk, right_chunk) = ( + evaluated_chunk(&schema, 0, vec![1.0, 2.0], true), + evaluated_chunk(&schema, 0, vec![10.0, 20.0], true), + ); + let (retained, assembly) = binary_charge(&schema, &left_chunk, &right_chunk); + let pool = bounded_pool(retained + assembly - 1); + let set = ExecutionPlanMetricsSet::new(); + let mut execution = executor(&tree, Arc::clone(&pool), &set); + execution.push_evaluated_at(&left, left_chunk).unwrap(); + execution.push_evaluated_at(&right, right_chunk).unwrap(); + // Both operands are retained before anything is assembled, and nothing is answered: the refusal + // below is the assembly's and not a chunk's. + assert!(execution.next_chunk().unwrap().is_none()); + assert_eq!( + pool.reserved(), + retained, + "the operands are not what the pool holds" + ); + assert_eq!( + gauge( + &set, + &NodePath::root().partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, 0) + ), + retained, + "the binary node reserved past what it retains" + ); + + let error = execution.finish().unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "the assembly was not reserved before it allocated: {error}" + ); + assert_eq!( + pool.reserved(), + 0, + "the stopped execution kept a reservation" + ); + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!( + execution.state().nodes_holding_binary(), + 0, + "the stopped execution kept the operands it retained" + ); + let stopped = execution.next_chunk().unwrap_err(); + assert!( + stopped + .to_string() + .contains("stopped after an earlier error"), + "a stopped execution answered again: {stopped}" + ); +} + +/// The assembly bound covers the vector a field's descriptors are flattened into, on the shape that +/// grows it the most. +/// +/// One chunk's field can itself hold 1024 segments. Beside a second chunk's one, [`Samples::try_from_chunks`] +/// copies all 1025 descriptors into a vector that doubled to 2048 slots, and then into the +/// `Arc<[Samples]>` it returns, so 3073 slots are live at once: two slots per segment -- 2052 here -- +/// would reserve less than the assembly allocates. The segments are dense slices of one histogram +/// table, which the assembled field keeps sharing rather than copying. +#[test] +fn an_assembly_bound_covers_the_capacity_its_flatten_grows_to() { + let (segments, chunks) = (1025usize, 2usize); + let grid = grid(0, 60_000, segments as u64); + let schema = evaluated_schema(Arc::clone(&grid)); + // One table every segment indexes into, so the assembly has one allocation to share. + let mut builder = HistogramBatchBuilder::new(); + for _ in 0..segments { + push_histogram(&mut builder, 4); + } + let table = builder.finish().unwrap(); + let one = |index: usize| { + let index = u32::try_from(index).unwrap(); + Samples::try_from_histogram(UInt32Array::from(vec![Some(index)]), Arc::clone(&table)) + .unwrap() + }; + // The first chunk's field is itself chunked -- 1024 one-sample segments -- and the second holds + // one, so the two chunks of the one logical series hold 1025 segments in all. + let nested = Samples::try_from_chunks((0..1024).map(one).collect::>()).unwrap(); + assert_eq!( + nested.segments().len(), + 1024, + "the first field is not nested" + ); + let chunk_of = |start: usize, len: usize, samples: Samples, is_last: bool| { + EvaluatedChunk::try_new( + Series { + metric: metric(), + time: TimeAxis::Grid(GridRange::try_new(Arc::clone(&grid), start, len).unwrap()), + fields: SeriesFields::one(samples), + }, + is_last, + ) + .unwrap() + }; + let first = chunk_of(0, 1024, nested, false); + let second = chunk_of(1024, 1, one(1024), true); + + // What the flatten the assembly runs holds at its peak, measured with the operations it makes: + // a chunked field contributes its segments and a dense one contributes itself. + let mut flat: Vec = Vec::new(); + for chunk in [&first, &second] { + let field = &chunk.series.fields.as_slice()[0]; + if field.segments().len() > 1 { + flat.extend(field.segments().iter().cloned()); + } else { + flat.push(field.clone()); + } + } + // The `Arc<[Samples]>` holds one slot per descriptor while the vector they were copied out of is + // still alive, so the peak is that vector's capacity plus the descriptors it held. + let peak = flat.capacity() + flat.len(); + assert_eq!( + flat.len(), + segments, + "the flatten did not meet every segment" + ); + assert!( + flat.capacity() > flat.len(), + "the flatten grew to no more than its descriptors, so this shape proves nothing" + ); + // The bound the assembly is reserved for: one descriptor per chunk per field, three per segment, + // and the four slots a first push allocates. + let allowed = chunks + 3 * segments + 4; + assert!( + peak <= allowed, + "the flatten of {segments} segments in {chunks} chunks holds {peak} slots at its peak, past \ + the {allowed} the assembly bound allows" + ); + + let pool = pool(); + let mut runtime = binary_runtime(&pool, &schema); + for chunk in [first, second.clone()] { + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(chunk)) + .unwrap(); + } + runtime + .retain_binary(&NodePath::root(), 1, NativeChunk::Evaluated(second)) + .unwrap(); + let assembly = runtime.binary.as_ref().unwrap().assembly_bytes().unwrap(); + assert!( + peak * std::mem::size_of::() <= assembly, + "the {assembly} bytes reserved for the assembly do not cover the {peak} slots its flatten \ + holds" + ); + + // The assembled series keeps the segments and the one table they index into. + let assembled = runtime + .binary + .as_ref() + .unwrap() + .assemble(&NodePath::root()) + .unwrap(); + assert_eq!(assembled[0].len(), 1, "one closed series is one series"); + assert_eq!(assembled[0][0].time.len(), segments); + let field = &assembled[0][0].fields.as_slice()[0]; + assert_eq!(field.segments().len(), segments); + for segment in field.segments() { + let Some(DenseSamplesRef::Histogram(histograms)) = segment.dense() else { + panic!("a histogram chunk assembles into histogram segments"); + }; + assert!( + Arc::ptr_eq(histograms.batch(), &table), + "the assembly copied the histogram table instead of sharing it" + ); + } + let built = EvaluatedChunk::try_new(assembled[0][0].clone(), true).unwrap(); + assert_eq!(histogram_counts(&built), vec![4.0; segments]); +} + +/// A mixed operand delivered in two chunks over a sparse axis assembles into one series that keeps +/// its holes, both its fields and the allocations they are slices of. +/// +/// Field 0 holds native histograms and field 1 floats, both chunks index one table, and the +/// positions they decide are 0, 2 and 3 of a four-point grid. The assembly keeps one descriptor per +/// segment instead of copying a sample, so the assembled series reads the same table and the same +/// float buffers the chunks read, and the position neither chunk decided stays a hole. The kernel +/// then answers that series as one candidate, which is what the result below is computed from. +#[test] +fn a_mixed_nested_operand_assembles_into_one_series_with_its_holes() { + let grid = grid(0, 60_000, 4); + let schema = Arc::new(SeriesSchema { + fields: field_count(2), + eval_grid: Some(Arc::clone(&grid)), + }); + // One table both chunks index into. + let mut builder = HistogramBatchBuilder::new(); + for _ in 0..2 { + push_histogram(&mut builder, 4); + } + let table = builder.finish().unwrap(); + let chunk_of = |spans: &[(usize, usize)], + indices: Vec>, + floats: Vec>, + is_last: bool| { + let histograms = + Samples::try_from_histogram(UInt32Array::from(indices), Arc::clone(&table)).unwrap(); + let time = TimeAxis::from_grid_spans( + Arc::clone(&grid), + spans + .iter() + .map(|&(start, len)| GridSpan::new(start, len)) + .collect(), + ) + .unwrap(); + EvaluatedChunk::try_new( + Series { + metric: metric(), + time, + fields: SeriesFields::try_from_vec(vec![ + histograms, + Samples::from_float(Float64Array::from(floats)), + ]) + .unwrap(), + }, + is_last, + ) + .unwrap() + }; + let (left_a, left_b) = ( + chunk_of( + &[(0, 1), (2, 1)], + vec![Some(0), Some(0)], + vec![Some(1.0), None], + false, + ), + chunk_of(&[(3, 1)], vec![Some(1)], vec![Some(4.0)], true), + ); + let (right_a, right_b) = ( + chunk_of( + &[(0, 1), (2, 1)], + vec![Some(1), Some(1)], + vec![Some(10.0), Some(30.0)], + false, + ), + chunk_of(&[(3, 1)], vec![Some(0)], vec![Some(40.0)], true), + ); + + // The two chunks are collected into the one series the kernel matches. + let pool = pool(); + let mut runtime = binary_runtime(&pool, &schema); + for chunk in [&left_a, &left_b] { + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(chunk.clone())) + .unwrap(); + } + let assembled = runtime + .binary + .as_ref() + .unwrap() + .assemble(&NodePath::root()) + .unwrap(); + assert_eq!( + assembled[0].len(), + 1, + "two chunks of one series are not one series" + ); + let series = &assembled[0][0]; + assert_eq!(series.time.len(), 3); + assert_eq!(series.time.first_position(), Some(0)); + assert_eq!(series.time.last_position(), Some(3)); + assert_eq!( + series.time.runs().count(), + 3, + "the assembly filled the hole neither chunk decided" + ); + let histograms = &series.fields.as_slice()[0]; + assert_eq!( + histograms.segments().len(), + 2, + "the chunks' histograms were not collected" + ); + for segment in histograms.segments() { + let Some(DenseSamplesRef::Histogram(samples)) = segment.dense() else { + panic!("a histogram chunk assembles into histogram segments"); + }; + assert!( + Arc::ptr_eq(samples.batch(), &table), + "the assembly copied a histogram table instead of sharing it" + ); + } + let floats = &series.fields.as_slice()[1]; + assert_eq!( + floats.segments().len(), + 2, + "the chunks' floats were not collected" + ); + for (segment, chunk) in floats.segments().iter().zip([&left_a, &left_b]) { + let (Some(DenseSamplesRef::Float(values)), Some(DenseSamplesRef::Float(source))) = + (segment.dense(), chunk.series.fields.as_slice()[1].dense()) + else { + panic!("a float chunk assembles into float segments"); + }; + assert_eq!( + values.values().inner().data_ptr(), + source.values().inner().data_ptr(), + "the assembly copied floats instead of sharing the buffer they are slices of" + ); + } + + // The kernel reads the assembled series, over the two fields and the positions it holds. + let root = binary_of( + evaluated_input_of(2, Arc::clone(&grid)), + evaluated_input_of(2, Arc::clone(&grid)), + binary_matching(BinaryOp::Add), + ); + let tree = NativeTree::try_new(root).unwrap(); + let (left, right) = (NodePath::root().left(), NodePath::root().right()); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + for chunk in [left_a, left_b] { + execution.push_evaluated_at(&left, chunk).unwrap(); + } + for chunk in [right_a, right_b] { + execution.push_evaluated_at(&right, chunk).unwrap(); + } + let out = run(&mut execution); + assert_eq!(out.len(), 1, "one matched label set answers one chunk"); + assert_eq!( + field_values(&out[0], 1), + vec![Some(11.0), None, Some(44.0)], + "the floats of the two chunks are not added at the positions they hold" + ); + assert_eq!( + histogram_counts(&out[0]), + vec![8.0, 8.0, 8.0], + "the histograms of the two chunks are not added at the positions they hold" + ); +} + +/// A kernel error and dropping the execution both give back everything the node reserved. +#[test] +fn a_kernel_error_and_a_drop_release_the_binary_reservation() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); + let schema = evaluated_schema(grid); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) + .unwrap(); + // The same label set twice on the right, both holding a value at position 0. + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![1.0], true)) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![2.0], true)) + .unwrap(); + let error = execution.finish().unwrap_err(); + assert!(error.to_string().contains("duplicate series"), "{error}"); + assert_eq!(pool.reserved(), 0, "the kernel error kept its reservation"); + assert_eq!(execution.state().reserved_bytes(), 0); + + // A dropped execution returns its reservation without being told to. + let mut dropped = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + dropped + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0], true)) + .unwrap(); + assert!(pool.reserved() > 0, "the operand reserved nothing"); + drop(dropped); + assert_eq!(pool.reserved(), 0); +} + +/// A queued chunk of a two-input tree has to name the input it belongs to. +#[test] +fn a_queued_chunk_names_its_input() { + let (tree, grid, left, _right) = binary_tree(BinaryOp::Add, 2); + let schema = evaluated_schema(grid); + let chunk = evaluated_chunk(&schema, 0, vec![1.0, 2.0], true); + + // Unnamed: two inputs make "the input" ambiguous, so nothing is queued at either. + let mut ambiguous = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let error = ambiguous.push_evaluated(chunk.clone()).unwrap_err(); + assert!(error.to_string().contains("has 2 inputs"), "{error}"); + + // A path that names the binary node rather than an input. + let mut wrong_node = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let error = wrong_node + .push_evaluated_at(&NodePath::root(), chunk.clone()) + .unwrap_err(); + assert!(error.to_string().contains("only an input node"), "{error}"); + + // A path that names no node at all. + let mut missing = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let error = missing + .push_evaluated_at(&NodePath::root().right().right(), chunk) + .unwrap_err(); + assert!( + error + .to_string() + .contains("has no node at root.right.right"), + "{error}" + ); + + // An input bound to evaluated samples refuses raw ones, naming the input it was queued at. + let mut fresh = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let error = fresh + .push_raw_at(&left, raw_chunk(&raw_schema(), &[0], &[1.0], true)) + .unwrap_err(); + assert!( + error.to_string().contains(&format!( + "the native source at {left} is bound to an evaluated series" + )), + "{error}" + ); + assert_eq!(left, NodePath::root().left()); +} + +/// A map above a binary, and a window above a binary, pull its result through their own loops. +#[test] +fn a_binary_beneath_a_map_and_a_window_is_pulled_recursively() { + // A map over the binary result: the subtraction is mapped to its magnitude. + let inner_grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + // The map and the window below are the outermost nodes, so the binary node is one step down + // from the root and its two inputs one step below that: `root.input.left` and + // `root.input.right`, not `root.left` and `root.right`. + let (left, right) = ( + NodePath::root().input().left(), + NodePath::root().input().right(), + ); + let root = binary_of( + evaluated_input_of(1, Arc::clone(&inner_grid)), + evaluated_input_of(1, Arc::clone(&inner_grid)), + binary_matching(BinaryOp::Sub), + ); + let mapped = NativeTree::try_new(map(root, vec![MathOp::Abs])).unwrap(); + let mut execution = executor(&mapped, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![4.0, 5.0], true)) + .unwrap(); + assert_eq!( + decided(&run(&mut execution)), + vec![(0, Some(3.0)), (1, Some(3.0))] + ); + + // A window over the binary result, evaluated on its own outer grid. + let outer = grid(0, 60_000, 2); + let root = binary_of( + evaluated_input_of(1, Arc::clone(&inner_grid)), + evaluated_input_of(1, Arc::clone(&inner_grid)), + binary_matching(BinaryOp::Add), + ); + let windowed = NativeTree::try_new(window_with( + root, + RangeFunction::LastOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer), + )) + .unwrap(); + let mut execution = executor(&windowed, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![10.0, 20.0], true)) + .unwrap(); + // The outer window decides each point from the binary result, on its own grid. + assert_eq!( + decided(&run(&mut execution)), + vec![(0, Some(11.0)), (1, Some(22.0))] + ); +} + +/// A binary over two windows reads what each window decided, and over two selections what each +/// selection picked. +#[test] +fn a_binary_over_two_windows_and_selections_is_executed() { + let inner = grid(0, 60_000, 2); + let schema = raw_schema(); + + let root = binary_of( + window_with( + input(), + RangeFunction::LastOverTime, + 60_000, + None, + Arc::clone(&inner), + ), + window_with( + input(), + RangeFunction::LastOverTime, + 60_000, + None, + Arc::clone(&inner), + ), + binary_matching(BinaryOp::Add), + ); + let tree = NativeTree::try_new(root).unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for (path, key, values) in [ + ( + NodePath::root().left().input(), + b"series-a".as_slice(), + [1.0, 2.0], + ), + ( + NodePath::root().right().input(), + b"series-b".as_slice(), + [10.0, 20.0], + ), + ] { + execution + .push_raw_at( + &path, + raw_chunk_of(&schema, key, metric(), &[0, 60_000], &values, true), + ) + .unwrap(); + } + assert_eq!( + decided(&run(&mut execution)), + vec![(0, Some(11.0)), (1, Some(22.0))] + ); + + // The same two grid points, selected from raw samples on each side. + let root = binary_of( + instant(input(), 300_000, 0, Arc::clone(&inner)), + instant(input(), 300_000, 0, Arc::clone(&inner)), + binary_matching(BinaryOp::Add), + ); + let tree = NativeTree::try_new(root).unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for (path, key, value) in [ + (NodePath::root().left().input(), b"series-a".as_slice(), 1.0), + ( + NodePath::root().right().input(), + b"series-b".as_slice(), + 10.0, + ), + ] { + execution + .push_raw_at( + &path, + raw_chunk_of(&schema, key, metric(), &[0], &[value], true), + ) + .unwrap(); + } + // The one sample of each side is the last at or before both grid points. + assert_eq!( + decided(&run(&mut execution)), + vec![(0, Some(11.0)), (1, Some(11.0))] + ); +} + +/// The chain Prometheus evaluates as `abs(instant - last_over_time)`, with the raw samples of each +/// side and the literal rows it decides. +/// +/// The left side is a selection reading back 1001 ms and the right side a 1000 ms window, on a grid +/// of 1000 ms steps: the two report different samples of the two raw series, which is what the +/// subtraction then pairs. +#[test] +fn a_binary_of_a_selection_and_a_window_matches_prometheus() { + let out = grid(0, 1_000, 4); + let left = instant(input(), 1_001, 0, Arc::clone(&out)); + let right = window_with( + input(), + RangeFunction::LastOverTime, + 1_000, + None, + Arc::clone(&out), + ); + let tree = NativeTree::try_new(map( + binary_of(left, right, binary_matching(BinaryOp::Sub)), + vec![MathOp::Abs], + )) + .unwrap(); + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_raw_at( + &NodePath::root().input().left().input(), + raw_chunk_of( + &schema, + b"left_raw", + named_metric("left_raw", "x"), + &[0, 500, 2_000], + &[-2.0, -4.0, -8.0], + true, + ), + ) + .unwrap(); + execution + .push_raw_at( + &NodePath::root().input().right().input(), + raw_chunk_of( + &schema, + b"right_raw", + named_metric("right_raw", "x"), + &[0, 1_000, 2_000, 3_000], + &[1.0, 3.0, 2.0, 4.0], + true, + ), + ) + .unwrap(); + assert_eq!( + decided(&run(&mut execution)), + vec![ + (0, Some(3.0)), + (1, Some(7.0)), + (2, Some(10.0)), + (3, Some(12.0)), + ] + ); +} + +/// An operand chunk whose series changes before it ends is refused, naming the side and the node. +/// +/// A binary node matches whole series, so the pairs of a series that is still open cannot be +/// computed from a chunk of another one: the two are reported instead of being paired as though the +/// second were a continuation of the first. +#[test] +fn a_chunk_of_another_series_on_one_operand_is_refused() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); + let schema = evaluated_schema(grid); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at( + &right, + evaluated_chunk_of(&schema, named_metric("api", "x"), 0, vec![Some(1.0)], false), + ) + .unwrap(); + // The chunk that arrived while `api` is open names another series. + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0], true)) + .unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + + execution + .push_evaluated_at( + &right, + evaluated_chunk_of(&schema, named_metric("db", "x"), 1, vec![Some(2.0)], true), + ) + .unwrap(); + let error = execution.next_chunk().unwrap_err(); + let message = error.to_string(); + assert!( + message.contains("the binary node at root") + && message.contains("its right operand") + && message.contains("before"), + "{message}" + ); + // The execution stopped rather than handing on the pairs it had, and it holds nothing. + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(execution.state().nodes_holding_binary(), 0); + let again = execution.next_chunk().unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); + // No partial answer surfaced through `finish` either. + assert!(execution.finish().is_err()); +} + +/// An operand chunk that starts behind the end of the open series is refused, values or not. +/// +/// The overlap is read off the axes, not off the samples they carry: a chunk whose every sample is +/// missing still occupies the positions its axis places, so a second chunk that reaches back into +/// them is a rewind rather than a continuation. +#[test] +fn an_operand_chunk_that_rewinds_is_refused_with_or_without_values() { + let (tree, grid, left, _right) = binary_tree(BinaryOp::Add, 4); + let schema = evaluated_schema(grid); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + // Two positions that hold no value at all, and a series that did not close on them. + execution + .push_evaluated_at( + &left, + evaluated_chunk_of(&schema, metric(), 0, vec![None, None], false), + ) + .unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + // Position 1 is one of the two the series already placed. + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 1, vec![1.0], true)) + .unwrap(); + + let error = execution.next_chunk().unwrap_err(); + let message = error.to_string(); + assert!( + message.contains("do not continue each other") + && message.contains("the left operand of the binary node at root") + && message.contains("after the series already reached 2"), + "{message}" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().nodes_holding_binary(), 0); +} + +/// A chunk that does not match the layout its operand is bound to is refused before the kernel. +/// +/// Each case is a chunk a caller can build: [`Series`] keeps its fields public, so an axis and the +/// fields beside it can disagree, and a chunk can be addressed on a grid no operand was bound to. +#[test] +fn a_chunk_that_does_not_match_its_operand_is_refused_before_the_kernel() { + let (tree, out_grid, left, _right) = binary_tree(BinaryOp::Add, 4); + let pool = pool(); + // What each operand of `binary_tree` is bound to: one float field on the tree's own grid. + let schema = evaluated_schema(Arc::clone(&out_grid)); + let two_fields = Arc::new(SeriesSchema { + fields: field_count(2), + eval_grid: Some(Arc::clone(&out_grid)), + }); + let elsewhere = grid(1, 60_000, 4); + + let cases: Vec<(&str, EvaluatedChunk)> = vec![ + ( + // An axis on another grid: one step from the one the operand is bound to. + "the other grid", + evaluated_on( + &evaluated_schema(Arc::clone(&elsewhere)), + metric(), + 0, + 2, + vec![vec![Some(1.0), Some(2.0)]], + true, + ), + ), + ( + // Two fields where the operand is bound to one. + "the field count", + evaluated_on( + &two_fields, + metric(), + 0, + 2, + vec![vec![Some(1.0), Some(2.0)], vec![Some(3.0), Some(4.0)]], + true, + ), + ), + ( + // Two rows of axis, one sample of the one field. + "the field length", + evaluated_on(&schema, metric(), 0, 2, vec![vec![Some(1.0)]], true), + ), + ]; + for (case, chunk) in cases { + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution.push_evaluated_at(&left, chunk).unwrap(); + let error = execution.next_chunk().unwrap_err(); + assert!( + error.to_string().contains("rejected its left operand"), + "{case}: {error}" + ); + assert_eq!( + pool.reserved(), + 0, + "{case}: the refused chunk is still held" + ); + assert_eq!(execution.state().reserved_bytes(), 0, "{case}"); + assert_eq!(execution.state().nodes_holding_binary(), 0, "{case}"); + } +} + +/// A series cannot be built with no field at all, which is what keeps a zero-field check honest. +/// +/// The validator's field-count check is not skipped by an empty field list because an empty one +/// cannot exist: [`SeriesFields`] refuses it, so every chunk any caller can build carries at least +/// one field. The boundary is the constructor's, and it is recorded here rather than loosened there. +#[test] +fn a_series_cannot_carry_no_fields() { + let error = + SeriesFields::try_from_vec(Vec::new()).expect_err("a series with no field was accepted"); + assert!(error.to_string().contains("must not be empty"), "{error}"); + // The one-field and many-field shapes a chunk can have are not empty either. + let one = SeriesFields::one(Samples::from_float(Float64Array::from(vec![1.0]))); + assert!(!one.is_empty()); + assert_eq!(one.len(), 1); +} + +/// A binary node with no chunk at all on either side answers nothing, and holds nothing. +/// +/// The input ending without a chunk is a stream that held no series, not a tree that never ran: the +/// kernel is asked about two empty vectors and reports none, so the answer is the empty one. +#[test] +fn an_absent_operand_yields_no_series() { + let (tree, grid, _left, right) = binary_tree(BinaryOp::Add, 2); + let schema = evaluated_schema(grid); + let pool = pool(); + + // Neither side queued a chunk. + let mut empty = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + assert!(empty.finish().unwrap().is_empty()); + assert_eq!(pool.reserved(), 0); + assert_eq!(empty.state().nodes_holding_binary(), 0); + + // Only the right side ran, and it closed: nothing matches a series that is not there. + let mut one_side = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + one_side + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) + .unwrap(); + assert!(one_side.finish().unwrap().is_empty()); + assert_eq!(pool.reserved(), 0); + assert_eq!(one_side.state().nodes_holding_binary(), 0); +} + +/// A binary node counts the series it closes on its output, and does not count an operand chunk +/// that already closed its input series. +#[test] +fn a_binary_counts_each_closed_result_once() { + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); + let schema = evaluated_schema(grid); + let set = ExecutionPlanMetricsSet::new(); + let mut execution = executor(&tree, pool(), &set); + execution + .push_evaluated_at(&left, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) + .unwrap(); + execution + .push_evaluated_at(&right, evaluated_chunk(&schema, 0, vec![10.0, 20.0], true)) + .unwrap(); + let out = run(&mut execution); + assert_eq!(out.len(), 1); + assert!(out[0].is_last, "a result series is handed over closed"); + let root = NodePath::root(); + // One matched result closed, not one per operand chunk and not one per handover of the result. + assert_eq!(count(&set, &root, NodeMetric::COMPLETED_SERIES), 1); + assert_eq!(count(&set, &root, NodeMetric::INPUT_BATCHES), 2); + assert_eq!(count(&set, &root, NodeMetric::OUTPUT_BATCHES), 1); +} + +/// A legitimate empty result over a wide operand finishes in a 4 MiB pool and holds nothing after. +/// +/// A match group of one member collects no points in the duplicate scan, so charging a point per +/// row of an operand reserves memory the kernel never allocates. +#[test] +fn an_empty_result_of_a_wide_operand_fits_its_pool() { + let points = 10_000; + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, points as u64); + let schema = evaluated_schema(grid); + let pool = bounded_pool(4 << 20); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + let series = |job: &str| pod_metric("requests", job, "p"); + execution + .push_evaluated_at( + &left, + evaluated_chunk_of(&schema, series("left"), 0, vec![Some(1.0); points], true), + ) + .unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + for index in 0..32 { + execution + .push_evaluated_at( + &right, + evaluated_chunk_of( + &schema, + series(&format!("r{index:02}")), + 0, + vec![Some(2.0); points], + true, + ), + ) + .unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + } + + let finished = execution.finish(); + assert!( + finished.is_ok(), + "an empty result over {points} points does not fit a 4 MiB pool: {:?}", + finished.as_ref().err() + ); + assert!( + finished.unwrap().is_empty(), + "nothing matches, so nothing is answered" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); +} + +/// A legitimate wide query finishes in a 32 MiB pool, keeping every field's sum and nothing else. +/// +/// A thousand points pair all sixty-four fields of both operands, so the workspace is the rows +/// filed and the tables beside them, not a figure far past either. +#[test] +fn a_dense_wide_result_fits_a_32_mib_pool() { + let (points, width) = (1_000usize, 64usize); + let grid = grid(0, 60_000, points as u64); + let (left_node, right_node) = ( + evaluated_input_of(width, Arc::clone(&grid)), + evaluated_input_of(width, Arc::clone(&grid)), + ); + let schema = left_node + .output + .samples() + .expect("a source of evaluated samples") + .clone(); + let root = binary_of(left_node, right_node, binary_matching(BinaryOp::Add)); + let tree = NativeTree::try_new(root).unwrap(); + let pool = bounded_pool(32 << 20); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + let columns = |value: f64| -> Vec>> { + (0..width).map(|_| vec![Some(value); points]).collect() + }; + let (left, right) = (NodePath::root().left(), NodePath::root().right()); + execution + .push_evaluated_at( + &left, + evaluated_columns(&schema, metric(), 0, columns(1.0), true), + ) + .unwrap(); + execution + .push_evaluated_at( + &right, + evaluated_columns(&schema, metric(), 0, columns(2.0), true), + ) + .unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + + let finished = execution.finish(); + assert!( + finished.is_ok(), + "{width} fields over {points} points do not fit a 32 MiB pool: {:?}", + finished.as_ref().err() + ); + let out = finished.unwrap(); + assert_eq!(out.len(), 1, "one matched label set answers one chunk"); + let chunk = &out[0]; + assert!(chunk.is_last, "a result series is handed over closed"); + assert_eq!(chunk.series.time.len(), points); + assert_eq!(series_start(chunk), 0); + assert_eq!(chunk.series.fields.len(), width); + for field in 0..width { + assert_eq!( + field_values(chunk, field), + vec![Some(3.0); points], + "field {field}" + ); + } + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); +} + +/// An all-missing match group of two right series finishes in a 4 MiB pool and answers nothing. +/// +/// No member carries a sample, so the duplicate scan needs no point buffer. +#[test] +fn an_all_missing_match_group_fits_its_pool() { + let points = 100_000; + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, points as u64); + let schema = evaluated_schema(grid); + let pool = bounded_pool(4 << 20); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated_at( + &left, + evaluated_chunk_of(&schema, metric(), 0, vec![Some(1.0); points], true), + ) + .unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + // Both right chunks close the one label set, so its match group has two members. + for _ in 0..2 { + execution + .push_evaluated_at( + &right, + evaluated_chunk_of(&schema, metric(), 0, vec![None; points], true), + ) + .unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + } + + let finished = execution.finish(); + assert!( + finished.is_ok(), + "an all-missing match group over {points} points does not fit a 4 MiB pool: {:?}", + finished.as_ref().err() + ); + assert!( + finished.unwrap().is_empty(), + "no point holds a value on both sides, so nothing is answered" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); +} diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index 1e5e6488a71..56c830841a0 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -1010,6 +1010,180 @@ fn histogram_chunk(schema: &SeriesSchema, buckets: i32, ts: i64) -> RawSeriesChu .unwrap() } +/// The single histogram sample of [`histogram_chunk`], read with `start_timestamp`. +/// +/// A sample carries the start timestamp a scan read it with, and it is payload rather than a +/// property of the value. +fn histogram_chunk_from( + schema: &SeriesSchema, + buckets: i32, + ts: i64, + start_timestamp: Option, + is_last: bool, +) -> RawSeriesChunk { + let offsets = [0]; + let lengths = [buckets]; + let counts = vec![1.0; usize::try_from(buckets).unwrap()]; + let mut builder = HistogramBatchBuilder::new(); + let index = builder + .push(HistogramView { + schema: 0, + zero_threshold: 0.0, + zero_count: 0.0, + count: f64::from(buckets), + sum: f64::from(buckets), + reset_hint: CounterResetHint::Unknown, + start_timestamp, + custom_values: &[], + positive: BucketSideView { + span_offsets: &offsets, + span_lengths: &lengths, + buckets: &counts, + }, + negative: BucketSideView { + span_offsets: &[], + span_lengths: &[], + buckets: &[], + }, + }) + .unwrap(); + let samples = Samples::try_from_histogram( + UInt32Array::from(vec![Some(index)]), + builder.finish().unwrap(), + ) + .unwrap(); + RawSeriesChunk::try_new( + schema, + Buffer::from(0u64.to_le_bytes().to_vec()), + Some(metric(0)), + RawTimestamps::try_new(ScalarBuffer::from(vec![ts])).unwrap(), + SeriesFields::try_from_vec(vec![samples]).unwrap(), + is_last, + ) + .unwrap() +} + +/// A function that hands back the sample it selected hands back that sample's payload. +/// +/// `last_over_time` and `first_over_time` select a sample instead of computing one, so the +/// histogram that leaves them is the histogram that arrived, start timestamp included. The window +/// here holds two samples that differ in bucket count and in start timestamp, so the count and the +/// timestamp together say which one was selected rather than only that some timestamp survived: +/// the last sample for `last_over_time`, the first one for `first_over_time`. What this pins is +/// that the selection passes the stored payload through; it does not pin a Prometheus result, whose +/// histogram values carry no such field, and it does not claim that a native rate reads the field +/// afterwards. A histogram computed from samples carries none, as +/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one` +/// pins for the operations that build one. +#[test] +fn a_selected_histogram_keeps_its_start_timestamp() { + let schema = raw_schema(1); + let (first_start, last_start): (i64, i64) = (1_500, 2_500); + // One bucket at 0ms and two at 5000ms, each read with its own start timestamp. Both samples + // are inside the window of the second grid point; the first point is decided on the first + // chunk alone, before the second sample has arrived. + let chunks = [ + histogram_chunk_from(&schema, 1, 0, Some(first_start), false), + histogram_chunk_from(&schema, 2, 5_000, Some(last_start), true), + ]; + // The histogram of every row the function hands out, read off the output's own views: the + // bucket count tells the selected sample apart from any other, the start timestamp is the + // payload this test is about. + let selected = |function: RangeFunction| -> Vec<(usize, f64, Option)> { + let mut evaluator = RangeEvaluator::try_new( + &schema, + grid(0, 10_000, 2), + RangeWindow { + range_ms: 20_000, + offset_ms: 0, + anchor_ms: None, + }, + function, + ) + .unwrap(); + let out = collect_chunks(&mut evaluator, &chunks); + assert!(!out.is_empty(), "{function:?} answered no chunk"); + let mut picked = Vec::new(); + for chunk in &out { + let mut cursor = chunk.series.fields.as_slice()[0].cursor(); + for (position, row) in chunk.series.time.positions() { + match cursor.at(row).expect("the axis and the fields are aligned") { + SampleRef::Histogram(view) => { + picked.push((position, view.count, view.start_timestamp)); + } + SampleRef::Float(_) => panic!("{function:?} answered a float for a histogram"), + SampleRef::Missing => { + panic!("{function:?} handed out a row of its own axis without a sample") + } + } + } + } + picked + }; + + assert_eq!( + selected(RangeFunction::LastOverTime), + [(0, 1.0, Some(first_start)), (1, 2.0, Some(last_start))], + "last_over_time did not hand back the sample it selected" + ); + assert_eq!( + selected(RangeFunction::FirstOverTime), + [(0, 1.0, Some(first_start)), (1, 1.0, Some(first_start))], + "first_over_time did not hand back the sample it selected" + ); +} + +/// A histogram computed from a window carries no start timestamp, even when the window holds one. +/// +/// `sum_over_time` computes a histogram rather than selecting one, so the timestamp the sample was +/// read with is not part of the result -- the rule the histogram operations themselves follow, as +/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one` +/// pins. The fold clears the field while adding, so a window holding two histograms already loses +/// it; a window holding one must not depend on that, or whether a result carries the field would +/// say how many samples the window held rather than what the function did. +#[test] +fn a_computed_histogram_drops_its_start_timestamp() { + let schema = raw_schema(1); + let start: i64 = 1_500; + // One histogram sample inside the window of both grid points, so the fold adds nothing to it + // and the single input is the whole result. + let chunks = [histogram_chunk_from(&schema, 1, 0, Some(start), true)]; + let mut evaluator = RangeEvaluator::try_new( + &schema, + grid(0, 10_000, 2), + RangeWindow { + range_ms: 20_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::SumOverTime, + ) + .unwrap(); + let out = collect_chunks(&mut evaluator, &chunks); + let mut computed = Vec::new(); + for chunk in &out { + let mut cursor = chunk.series.fields.as_slice()[0].cursor(); + for (position, row) in chunk.series.time.positions() { + match cursor.at(row).expect("the axis and the fields are aligned") { + SampleRef::Histogram(view) => { + computed.push((position, view.count, view.start_timestamp)); + } + SampleRef::Float(_) => panic!("sum_over_time answered a float for a histogram"), + SampleRef::Missing => { + panic!("sum_over_time handed out a row of its own axis without a sample") + } + } + } + } + // The sum of one histogram is that histogram, so the count says the sample was summed rather + // than passed over; only the start timestamp has to be gone. + assert_eq!( + computed, + [(0, 1.0, None), (1, 1.0, None)], + "sum_over_time kept the start timestamp of the histogram it summed" + ); +} + /// A window retaining a native histogram is charged for the payload it owns, not only the slot. /// /// The histogram sample below stays ahead of the second grid point's window, so the evaluator keeps diff --git a/src/promql/src/select/tests.rs b/src/promql/src/select/tests.rs index 0cc2763bf64..3bac6739214 100644 --- a/src/promql/src/select/tests.rs +++ b/src/promql/src/select/tests.rs @@ -269,6 +269,67 @@ fn limit_operators_keep_histogram_samples() { assert_eq!(kinds(&kept[0], 0), [(1, "histogram")]); } +/// A selection hands back the sample it selected, start timestamp included. +/// +/// `limitk` and `limit_ratio` choose samples rather than compute them, so a histogram that arrives +/// with a start timestamp leaves with it. The count and the sum are compared too, so a computed +/// value that happened to carry a timestamp would not pass for the sample selected. What this pins +/// is that the selection passes the stored payload through, not a Prometheus result and not a +/// downstream rate that reads the field. A histogram computed from samples carries none, as +/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one` +/// pins for the operations that build one. +#[test] +fn limit_operators_keep_the_start_timestamp_of_a_selected_sample() { + let histogram = + OwnedHistogram::parse("0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///"); + let start = 1_500; + // The sample a scan read, which is what a selection hands on. + let stamped = || { + let mut read = FloatHistogram::try_from_view(&histogram.view()).unwrap(); + read.start_timestamp = Some(start); + GridSample::Histogram(Box::new(read)) + }; + // What a limit operator keeps out of one series: the count and sum of the histogram it kept, + // so the sample selected is named, and the start timestamp it kept with it. + let kept = |series: &Series| -> Vec<(usize, f64, f64, Option)> { + let samples = &series.fields.as_slice()[0]; + series + .time + .positions() + .filter_map(|(point, row)| match samples.sample(row) { + SampleRef::Histogram(view) => { + Some((point, view.count, view.sum, view.start_timestamp)) + } + _ => None, + }) + .collect() + }; + let source = histogram.view(); + let expected = |point: usize| (point, source.count, source.sum, Some(start)); + + let schema = schema(3, 1); + let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone())).unwrap(); + builder.push_samples(0, &[Some(stamped())]).unwrap(); + builder.push_samples(2, &[Some(stamped())]).unwrap(); + let series = builder.finish(metric("__name__=a")).unwrap().unwrap(); + + let by_ratio = limit_ratio(1.0, &schema, std::slice::from_ref(&series)).unwrap(); + assert_eq!(by_ratio.len(), 1); + assert_eq!( + kept(&by_ratio[0]), + [expected(0), expected(2)], + "limit_ratio did not hand back the samples it selected" + ); + + let by_count = limitk(1.0, &Grouping::By(Vec::new()), &schema, &[series]).unwrap(); + assert_eq!(by_count.len(), 1); + assert_eq!( + kept(&by_count[0]), + [expected(0), expected(2)], + "limitk did not hand back the samples it selected" + ); +} + fn grouping(kind: &str, labels: &str) -> Grouping { match kind { "without" => Grouping::Without(names(labels)), diff --git a/src/promql/src/vector_match.rs b/src/promql/src/vector_match.rs index eab40a3f64e..83e50a71df2 100644 --- a/src/promql/src/vector_match.rs +++ b/src/promql/src/vector_match.rs @@ -25,9 +25,11 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use datafusion::error::{DataFusionError, Result}; -use datatypes::series::histogram::{CounterResetHint, HistogramView}; -use datatypes::series::samples::{RowCursor, SampleRef, Series, SeriesSchema}; -use datatypes::series::time::{EvalGrid, GridRunPair, TimeAxis}; +use datatypes::series::histogram::{CounterResetHint, HistogramBatchBuilder, HistogramView}; +use datatypes::series::samples::{ + DenseSamplesRef, FieldSpec, RowCursor, SampleRef, Series, SeriesSchema, +}; +use datatypes::series::time::{EvalGrid, GridRunPair, GridSpan, TimeAxis}; use datatypes::series::{Label, MetricName}; use crate::grid_series::{GridSample, GridSeriesBuilder, METADATA_LABELS, external, owned}; @@ -36,6 +38,34 @@ use crate::histogram_eval::float_histogram::FloatHistogram; #[cfg(test)] mod tests; +// How many candidate pairs the binary kernel visited on this thread. +// +// Test-only, and per thread: the pairs a query considers are what says whether a series delivered in +// many chunks is still one candidate, and that is not visible in the result. A thread of its own +// keeps one test's chunks out of another test's figure, and the counter is compiled out of the +// kernel otherwise. +#[cfg(test)] +thread_local! { + static VISITED_PAIRS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Resets the candidate-pair counter of this thread to zero. +#[cfg(test)] +pub(crate) fn reset_visited_pairs() { + VISITED_PAIRS.with(|visited| visited.set(0)); +} + +/// The candidate pairs the binary kernel has visited on this thread since the last +/// [`reset_visited_pairs`]. +/// +/// A pair is visited once per one-side candidate the kernel looks up for a many-side series, before +/// the pairing's label set and axis intersection are built, so the count is what the kernel actually +/// does rather than what its operands' sizes imply it would. +#[cfg(test)] +pub(crate) fn visited_pairs() -> usize { + VISITED_PAIRS.with(std::cell::Cell::get) +} + /// A PromQL binary operator between two instant vectors. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BinaryOp { @@ -166,30 +196,524 @@ pub fn binary_vectors( rhs_schema: &SeriesSchema, rhs: &[Series], ) -> Result> { + binary_vectors_inner(matching, lhs_schema, lhs, rhs_schema, rhs, None) +} + +/// [`binary_vectors`], handing the live workspace it holds to `reserve` as it allocates. +/// +/// What the operation will allocate cannot be known before it allocates: which series match each +/// other, where their axes overlap and which rows the operator keeps all come out of the operands +/// as they are read. So `reserve` receives the **total** live workspace the operation holds, and it +/// is asked at the three granularities [`Budget`] describes: where a long-lived result buffer grows, +/// once per phase, and in the blocks a growing result buffer is reserved in. It is never asked per +/// grid point or per row. A total `reserve` refuses ends the operation with that error, and what it +/// admitted stays the caller's to release. +pub(crate) fn binary_vectors_with_reservation( + matching: &BinaryMatching, + lhs_schema: &SeriesSchema, + lhs: &[Series], + rhs_schema: &SeriesSchema, + rhs: &[Series], + reserve: &mut dyn FnMut(usize) -> Result<()>, +) -> Result> { + let mut budget = Budget::new(reserve); + binary_vectors_inner( + matching, + lhs_schema, + lhs, + rhs_schema, + rhs, + Some(&mut budget), + ) +} + +/// The one binary kernel: one walk, one lookup and one error order, whether or not a caller +/// accounts for the workspace. Every figure is reserved only when `budget` is held. +fn binary_vectors_inner( + matching: &BinaryMatching, + lhs_schema: &SeriesSchema, + lhs: &[Series], + rhs_schema: &SeriesSchema, + rhs: &[Series], + mut budget: Option<&mut Budget<'_>>, +) -> Result> { + // The grid both operands are evaluated on, checked before anything is reserved for them. + let grid = same_grid(lhs_schema, rhs_schema)?; + // The fields paired by position and the descriptors they are handed back in: one result table + // per field, the field list both the results and the output schema keep, and the schema itself. + // The schema is what these bytes cover, so they are reserved before it is built. + let width = lhs_schema.fields.len().min(rhs_schema.fields.len()); + if let Some(budget) = budget.as_deref_mut() { + budget.hold(output_bytes(width))?; + } let output = binary_output_schema(lhs_schema, rhs_schema)?; - let grid = output - .eval_grid - .clone() - .expect("set by binary_output_schema"); let mut errors = Vec::new(); - let mut fields = Vec::with_capacity(output.fields.len()); - for field in 0..output.fields.len() { + let mut fields = Vec::with_capacity(width); + for field in 0..width { let lhs = Operand::try_new(lhs_schema, lhs, field)?; let rhs = Operand::try_new(rhs_schema, rhs, field)?; - fields.push(binary_field(matching, &grid, &lhs, &rhs, &mut errors)?); + let results = binary_field( + matching, + &grid, + &lhs, + &rhs, + &mut errors, + budget.as_deref_mut(), + )?; + // The field's flags, tables and sort are destroyed with its frame, so its phase ends here: + // what the field filed is what stays live, and the next field's phase is charged on its own. + if let Some(budget) = budget.as_deref_mut() { + budget.phase(0)?; + } + fields.push(results); } earliest_error(errors)?; - merge_fields(fields, output) + // The merge is the operation's last phase: it enters its own figure from the results the fields + // filed, which is where every term of it is read. + merge_fields(fields, output, budget) +} + +/// The capacity a fresh `Vec` holds: a first push allocates four entries, and a full one doubles. +const VEC_MIN_CAPACITY: usize = 4; + +/// One label of a match key, charged twice because `group_key` grows its `Vec` by doubling. +const KEY_LABEL_BYTES: usize = 2 * std::mem::size_of::<(Arc, Arc)>(); + +/// One name of [`MatchingLabels`], which `result_metric` collects into a reference vector. The +/// vector is collected from an exact-size iterator, so its buffer holds one `&str` per name. +const MATCHING_NAME_BYTES: usize = std::mem::size_of::<&str>(); + +/// One entry of a match-group table, with the control byte and spare capacity it keeps. +const GROUP_SLOT_BYTES: usize = 2 * std::mem::size_of::<(GroupKey, Vec)>(); + +/// One entry of the one-to-one match set, charged the same way. +const MATCH_SLOT_BYTES: usize = 2 * std::mem::size_of::<(usize, usize)>(); + +/// One entry of a field's result table, charged the same way. +const RESULT_SLOT_BYTES: usize = 2 * std::mem::size_of::<(GroupKey, ResultRows)>(); + +/// One row of a field's results: its point, its match group and its value. The three vectors grow +/// together, so one slot of each is what a row takes, and a block of the vectors is charged a row's +/// bytes per slot it grew by. +const RESULT_ROW_BYTES: usize = + 2 * std::mem::size_of::() + std::mem::size_of::>(); + +/// One row while a label set is sorted: the old and the new copy of its point, group and value +/// vectors, and the row order the sort reads. The sort copies a label set's rows when they are not +/// already in order, so this is what one row costs while it runs. +const SORT_ROW_BYTES: usize = + 4 * std::mem::size_of::() + 2 * std::mem::size_of::>(); + +/// One row of the merge's table, charged the same way. +const MERGE_SLOT_BYTES: usize = + 2 * std::mem::size_of::<(GroupKey, (MetricName, Vec<(usize, usize, GridSample)>))>(); + +/// One row of the builder's histogram table: the scalar columns and the seven list offsets. +const HISTOGRAM_ROW_BYTES: usize = 4 * std::mem::size_of::() + + 2 * std::mem::size_of::() + + std::mem::size_of::() + + 7 * std::mem::size_of::(); + +/// The fixed text of one error message, around the label set it renders. +const ERROR_TEXT_BYTES: usize = 256; + +/// The bytes the operation's own descriptors cost: one result table per paired field, the field +/// list the results and the output schema each keep, and the schema struct. +fn output_bytes(fields: usize) -> usize { + fields + .saturating_mul(std::mem::size_of::() + 2 * std::mem::size_of::()) + .saturating_add(std::mem::size_of::()) +} + +/// The live workspace a binary operation admits as it allocates, at three granularities. +/// +/// A resource limit belongs at an allocation boundary, not at a value: +/// +/// - [`Budget::hold`]: what the results keep until the operation returns -- rows, the label sets they +/// are filed under, the values boxed along them, the messages an error reports. Each is charged +/// where its container grows. +/// - [`Budget::phase`]: one figure for the workspace of one walk, read from the operands before it +/// allocates and replacing the phase before it, so the total is the phase being run beside what is +/// held and never the sum of every phase. +/// - [`Budget::grow`]: a block a container of that phase took when it outgrew what it held. +/// +/// It exists because the caller is handed a *total*, and this turns those figures into that total. +struct Budget<'a> { + /// Admits the live workspace, or refuses it. + reserve: &'a mut dyn FnMut(usize) -> Result<()>, + /// The bytes the results keep until the operation returns. + held: usize, + /// The bytes of the phase being run, beside what is held. + phase: usize, + /// The total handed to `reserve` last, so an unchanged one is not asked for twice. + requested: Option, +} + +impl<'a> Budget<'a> { + fn new(reserve: &'a mut dyn FnMut(usize) -> Result<()>) -> Self { + Self { + reserve, + held: 0, + phase: 0, + requested: None, + } + } + + /// Retains `bytes` of results, which stay live until the operation returns. + fn hold(&mut self, bytes: usize) -> Result<()> { + self.held = self.held.saturating_add(bytes); + self.admit() + } + + /// Admits `bytes` as the whole workspace of the phase being run, replacing the phase before it. + fn phase(&mut self, bytes: usize) -> Result<()> { + self.phase = bytes; + self.admit() + } + + /// Adds `bytes` to the phase for a container of it that has outgrown what was reserved. + fn grow(&mut self, bytes: usize) -> Result<()> { + self.phase = self.phase.saturating_add(bytes); + self.admit() + } + + /// Hands the live total to `reserve` when it differs from the last one. It falls as well as + /// rises, and only a repeated figure is left out. + fn admit(&mut self) -> Result<()> { + let total = self.held.saturating_add(self.phase); + if self.requested != Some(total) { + self.requested = Some(total); + (self.reserve)(total)?; + } + Ok(()) + } +} + +/// The figures one field's phases are charged from, read once from its operands. +#[derive(Default)] +struct FieldMetadata { + /// The presence flags and the one side's match groups. + tables: usize, + /// The allowance for the messages the field can report, which its sort reserves before it knows + /// which of them it appends; only the ones it writes are kept. + errors: usize, + /// The largest key a row of the field is filed under. + largest_key: usize, + /// The widest pairing's label set and the histogram workspace one row of the walk reads. + pairing: usize, +} + +/// The figures one field's phases are charged from. +/// +/// The presence of each side and of the points both are present at are three flags per grid point; +/// the one side's groups are a key, the values `on(...)` matching copies and a member list per +/// series; one series of the many side is looked up by a key of its own; and a field reports at most +/// three messages, each a fixed frame around one rendering. The duplicate scan's list is not part of +/// these tables: a group of one member collects nothing, and a wider group's list is charged by +/// [`overlap`] as it grows. The pairing's own terms are read from the widest series of each side +/// rather than from every pair, since one pairing's label set replaces the one before it. +fn field_metadata_bytes( + matching: &BinaryMatching, + include: &[Arc], + points: usize, + many: &Operand<'_>, + one: &Operand<'_>, +) -> FieldMetadata { + let mut bytes = points.saturating_mul(3); + let mut largest_key = 0usize; + for series in one.series { + bytes = bytes + .saturating_add(match_key_bytes(&series.metric, &matching.labels)) + .saturating_add(2 * std::mem::size_of::()) + .saturating_add(GROUP_SLOT_BYTES) + .saturating_add(2 * std::mem::size_of::<&GroupKey>()) + .saturating_add(2 * std::mem::size_of::<(&GroupKey, usize)>()); + largest_key = largest_key.max(result_key_bytes(&series.metric)); + } + let mut lookup = 0usize; + for series in many.series { + lookup = lookup.max(match_key_bytes(&series.metric, &matching.labels)); + largest_key = largest_key.max(result_key_bytes(&series.metric)); + } + // A result label set carries the many side's labels and the `group_*` ones copied into it, so + // the widest rendering over both operands bounds the text an error writes. + let include_text = include.iter().fold(0usize, |bytes, name| { + bytes.saturating_add(name.len()).saturating_add(6) + }); + let text = many + .series + .iter() + .chain(one.series) + .fold(include_text, |bytes, series| { + bytes.max(label_text_bytes(&series.metric).saturating_add(include_text)) + }); + // The widest series of each side: one pairing's label set replaces the one before it, so the + // widest is what the phase holds at its peak. + let pairing = widest_metric(many) + .zip(widest_metric(one)) + .map_or(0, |(many, one)| pair_bytes(many, one, matching, include)); + FieldMetadata { + tables: bytes.saturating_add(lookup), + errors: 3usize.saturating_mul(ERROR_TEXT_BYTES.saturating_add(text)), + largest_key: largest_key.saturating_add(include.len().saturating_mul(KEY_LABEL_BYTES)), + pairing: pairing.saturating_add(histogram_phase_bytes(many, one)), + } +} + +/// The series of `operand` with the most labels: the widest label set one pairing of its field can +/// build. +fn widest_metric<'a>(operand: &'a Operand<'_>) -> Option<&'a MetricName> { + operand + .series + .iter() + .map(|series| &series.metric) + .max_by_key(|metric| metric.tags().len()) +} + +/// The bytes one pairing allocates before it files a row: the result label set `result_metric` +/// rewrites, the `group_*` labels it copies in, the reference vector it collects the matching label +/// names into, and the key its rows are looked up by. +/// +/// Each rewrite filters the tag list into a `Vec` and turns that into a shared slice, so the list it +/// replaces is alive while two copies of the new one are built, and an included label the many side +/// does not carry is inserted, which costs its descriptor too. The matching names are collected into +/// a reference vector of their own before the rewrite, for `on(...)` and `ignoring(...)` alike and +/// whether or not the series carries them. This is one pairing's scratch: the next pairing replaces +/// it, and a pairing whose axes share no position still pays it, because the label set is built +/// before the axes are intersected. +fn pair_bytes( + many: &MetricName, + one: &MetricName, + matching: &BinaryMatching, + include: &[Arc], +) -> usize { + // The label list each rewrite builds and the one it replaces, then the key `key_of` builds for + // a row: every label with a value and the name, each charged twice for the growth of the key's + // `Vec`, and the name string it copies. + let labels = 3usize + .saturating_mul(many.tags().len().saturating_add(include.len())) + .saturating_mul(std::mem::size_of::