From 1874ece5f2ffb85ba8f4b596450de761b7df8b88 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:34:01 +0800 Subject: [PATCH] fix(promql): refuse a second series under one label set, and charge what a window keeps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A label-rewriting node could hand on two series under one label set: a window drops the metric name and empty-valued labels, so two inputs that differ only in those leave as one label set, and the consumer then reports one series twice or folds two series into one answer. Each such node now records the positions it has emitted per label set and per field, and refuses a second series whose occupied positions overlap. Adjacency and disjoint positions are allowed, so one series in several pieces still runs. A series that closed is refused a second time, which is a limitation of a streaming evaluator rather than a PromQL collision: the pair does merge in Prometheus, but the per-series state above it is already closed. The reservation a window holds now follows what its evaluator keeps instead of what it consumed, so a long input under a short range does not grow without bound. The figure is the evaluator's own storage by capacity — per field, the row, the pending batch's inner vectors and the open series' identity — plus the label sets handed out. It is a lower bound, not a measurement: kernel scratch is a constant factor of the counted samples, and the map overhead, Arc headers, outer pending vectors and a sliced buffer's backing are left out. Releasing a stopped executor also drops its window and its emitted table instead of only returning the reservation, and a window over an interleaved input is refused before the first chunk is read. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- .../src/histogram_eval/float_histogram.rs | 25 + src/promql/src/native/execute.rs | 445 +++++++++- src/promql/src/native/execute/tests.rs | 833 +++++++++++++++++- src/promql/src/range_eval.rs | 123 +++ src/promql/src/range_eval/tests.rs | 233 +++++ 5 files changed, 1627 insertions(+), 32 deletions(-) diff --git a/src/promql/src/histogram_eval/float_histogram.rs b/src/promql/src/histogram_eval/float_histogram.rs index 71f9598bd81..ad9068e1970 100644 --- a/src/promql/src/histogram_eval/float_histogram.rs +++ b/src/promql/src/histogram_eval/float_histogram.rs @@ -80,6 +80,31 @@ impl FloatHistogram { }) } + /// The bytes this histogram owns outside its own `size_of`, from the vectors it holds. + /// + /// Capacity, not length: a bucket list that was drained keeps its buffer, so what the + /// reservation has to cover is what the vector still holds. Saturating, because the figure + /// goes into a memory reservation, which must never wrap to a small number. + pub(crate) fn heap_bytes(&self) -> usize { + let buckets = self + .positive + .capacity() + .saturating_add(self.negative.capacity()) + .saturating_mul(std::mem::size_of::<(i32, f64)>()); + let custom = self + .custom_values + .capacity() + .saturating_mul(std::mem::size_of::()); + // Only a histogram read from a view keeps its span layout; a derived one holds none. + let layout = self.layout.as_ref().map_or(0, |[positive, negative]| { + positive + .capacity() + .saturating_add(negative.capacity()) + .saturating_mul(std::mem::size_of::<(i32, i32)>()) + }); + buckets.saturating_add(custom).saturating_add(layout) + } + /// The spans of each side. fn spans(&self) -> [Vec<(i32, i32)>; 2] { self.layout diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 213d66c0ffa..2b87ec7ec0a 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -33,6 +33,14 @@ //! 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. +//! +//! A node that rewrites labels — a window drops the metric name and the empty-valued labels, a map +//! drops the name — can turn two distinct series into one label set, and each of them still closes +//! on its own chunk. The node that did the rewriting is where the second one is refused, before the +//! node above evaluates it: a label set that has closed cannot be produced again, and a chunk that +//! holds a value where the same field already holds one cannot be merged without holding whole +//! series. A chunk that continues a label set where it ended, or that fills positions the set has +//! not occupied, is handed on. use std::collections::{HashMap, VecDeque}; use std::sync::Arc; @@ -41,14 +49,16 @@ use datafusion::error::{DataFusionError, Result}; use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation}; use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet; use datatypes::arrow::array::Float64Array; +use datatypes::series::SeriesOrdering; use datatypes::series::raw::RawSeriesChunk; use datatypes::series::samples::{SampleRef, Samples, Series, SeriesFields, SeriesSchema}; use datatypes::series::time::{GridRange, TimeAxis}; -use crate::map::{MathOp, map_math}; use crate::native::batch::EvaluatedChunk; use crate::native::metrics::{self, NodeMetrics, NodePath}; use crate::native::plan::{BoundWindow, NativeExpr, NativeTree}; +use crate::grid_series::{LabelSet, label_set}; +use crate::map::{MathOp, map_math}; use crate::range_eval::RangeEvaluator; #[cfg(test)] @@ -202,6 +212,18 @@ impl NodeBuffer { Ok(()) } + /// Reserves exactly `bytes`, which is what this node holds from now on. + /// + /// A node that consumes its input chunk by chunk what it holds afterwards is not the sum of + /// what it consumed, so the reservation is set from the state that is left rather than grown + /// per chunk. + fn hold_exactly(&mut self, bytes: usize) -> Result<()> { + self.reservation.try_resize(bytes)?; + self.held = bytes; + self.metrics.record_reserved_bytes(bytes); + Ok(()) + } + /// Returns every byte this node holds to the pool. fn release(&mut self) { self.held = 0; @@ -210,6 +232,172 @@ impl NodeBuffer { } } +/// One run of grid positions, half-open, that hold a value in one field. +#[derive(Clone, Copy, Debug)] +struct Run { + start: usize, + end: usize, +} + +impl Run { + /// Whether two runs share a position. + fn overlaps(self, other: Self) -> bool { + self.start < other.end && other.start < self.end + } +} + +/// The positions one node has handed out, per output label set and field. +/// +/// A node that rewrites labels — a `Map` dropping the metric name, a `Window` dropping the name +/// and the empty-valued labels — can turn two input series into one label set, and the node above +/// reads the two chunks as one series. What is kept here is which positions of each field were +/// already handed out under each label set, so a second series onto a set can be refused before +/// the node above evaluates it. +/// +/// Occupancy is per field and per position, not per chunk range: a chunk reports the positions it +/// decided, which include the ones holding no value, and series that share a decided range while +/// sharing no sample merge cleanly, as they do in [`crate::grid_series::merge_same_labelset`]. +#[derive(Default)] +struct Emitted { + sets: HashMap, +} + +/// What one node has handed out under one output label set. +#[derive(Default)] +struct History { + /// The occupied runs of each field, in position order and disjoint. + fields: Vec>, + /// Whether the series on this label set closed. A second series cannot close it again. + closed: bool, +} + +impl Emitted { + /// Records what `chunk` occupies, rejecting it against what this node already handed out. + /// + /// A label set that has closed cannot be reached by a second series: the node would hand on two + /// chunks that its consumer cannot tell apart, and the merge the caller wants spans the first + /// series, whose state the evaluator above has already closed. Such a pair does merge in + /// Prometheus, so this is a limitation of the streaming evaluator rather than a collision; it is + /// refused instead of being answered wrongly (see [`closed_label_set`]). A chunk of a set still + /// open is refused only where it holds a value at a position that same field already holds one + /// at, which is the case no merge can resolve. + fn occupy(&mut self, path: &NodePath, chunk: &EvaluatedChunk) -> Result<()> { + let labels = label_set(&chunk.series.metric); + let base = chunk.range().start(); + let occupied: Vec> = chunk + .series + .fields + .iter() + .map(|field| occupied_runs(field, base)) + .collect(); + if let Some(history) = self.sets.get(&labels) { + if history.closed { + return Err(closed_label_set(path, &labels)); + } + for (index, runs) in occupied.iter().enumerate() { + let stored = history.fields.get(index).map_or(&[][..], Vec::as_slice); + for run in runs { + if let Some(previous) = stored.iter().find(|stored| stored.overlaps(*run)) { + return Err(occupied_position(path, &labels, index, run, previous)); + } + } + } + } + let fields = chunk.series.fields.len(); + let history = self.sets.entry(labels).or_default(); + if history.fields.len() < fields { + history.fields.resize_with(fields, Vec::new); + } + for (index, runs) in occupied.into_iter().enumerate() { + for run in runs { + absorb(&mut history.fields[index], run); + } + } + if chunk.is_last { + history.closed = true; + } + Ok(()) + } + + /// An estimate of the bytes this table holds, which the node reserves for. + /// + /// It counts each label's name and value bytes with a tuple per label, a history with its runs, + /// and the table's capacity at a label-set slot plus a history per entry. It leaves out the + /// map's buckets and the `Arc` headers of the strings it shares, so it is a lower bound rather + /// than a measurement. + fn bytes(&self) -> usize { + let sets = self + .sets + .iter() + .map(|(labels, history)| { + labels + .iter() + .map(|(name, value)| { + std::mem::size_of::<(std::sync::Arc, std::sync::Arc)>() + + name.len() + + value.len() + }) + .sum::() + + std::mem::size_of::() + + history.fields.capacity() * std::mem::size_of::>() + + history + .fields + .iter() + .map(|runs| runs.capacity() * std::mem::size_of::()) + .sum::() + }) + .sum::(); + sets + self.sets.capacity() + * (std::mem::size_of::() + std::mem::size_of::()) + } +} + +/// The runs of positions holding a value in `field`, whose first position is `base`, in order. +/// +/// A missing sample holds no value; a `NaN` and a native histogram do, as they do for a merge. +fn occupied_runs(field: &Samples, base: usize) -> Vec { + let mut runs: Vec = Vec::new(); + let mut open: Option = None; + for (offset, sample) in field.iter().enumerate() { + let position = base + offset; + match (!matches!(sample, SampleRef::Missing), open) { + (true, None) => open = Some(position), + (false, Some(start)) => { + runs.push(Run { + start, + end: position, + }); + open = None; + } + _ => {} + } + } + if let Some(start) = open { + runs.push(Run { + start, + end: base + field.len(), + }); + } + runs +} + +/// Adds `run` to `runs`, keeping them in position order and joining the ones that touch. +/// +/// `runs` never holds two that overlap, so only adjacency is joined; joining is what keeps one +/// series arriving in many chunks from costing one run per chunk. +fn absorb(runs: &mut Vec, run: Run) { + let at = runs.partition_point(|stored| stored.start < run.start); + runs.insert(at, run); + let mut merged: Vec = Vec::with_capacity(runs.len()); + for run in runs.drain(..) { + match merged.last_mut() { + Some(last) if run.start <= last.end => last.end = last.end.max(run.end), + _ => merged.push(run), + } + } + *runs = merged; +} + /// What a map node applies. struct MapRuntime { ops: Arc<[MathOp]>, @@ -224,10 +412,49 @@ struct WindowRuntime { } impl WindowRuntime { + /// The run-time state of the window `op`, reading the samples of `input`. + fn try_new(input: &SeriesSchema, op: &BoundWindow) -> Result { + // One evaluator per window, with the grids the node was bound to: the output grid is the + // node's own grid, which is also the grid its chunks are addressed on. + let evaluator = + RangeEvaluator::try_new(input, Arc::clone(&op.output_grid), op.window, op.function)?; + Ok(Self { + evaluator: Some(evaluator), + }) + } + + /// The bytes this window's charge accounts for, as its evaluator's storage stands now. + /// + /// Between pushes this is the accounted retained size: the sample buffers the evaluator keeps + /// per field, by capacity, the row a push fills, the pending batch's inner vectors, and the + /// identity payload of the series still open. It is a lower bound on what is held, not a + /// measurement of it. + /// + /// The kernel's scratch is left out, being a constant factor of the window samples already + /// counted. The `Emitted` table's own map overhead and the `Arc` headers of the strings it + /// shares are charged for beside this figure rather than inside it. Of the pending batch only + /// the inner vectors are counted, not the outer `spans` and `columns` that hold them. And a + /// sliced buffer's backing can be larger than the bytes its primary key shows. + /// + /// During a push the evaluator also holds the incoming chunk, which the caller charges while + /// the call runs; vector growth during a push is not reserved at all, and is not bounded by one + /// doubling either, since a bulk append can allocate more than twice the previous capacity and + /// several vectors can grow at once. So this is the storage's current size, not a peak over a + /// push. + /// + /// The evaluator is the only one that knows: it keeps samples per field, each field with its + /// own timestamps, values, reset index and native histograms, and it drops them by its own + /// rule. Mirroring that rule here would be a second copy of it, free to drift from the first. + fn retained_bytes(&self) -> usize { + self.evaluator + .as_ref() + .map_or(0, RangeEvaluator::retained_bytes) + } + /// Feeds one input chunk to the evaluator and returns the chunk it yields, if any. fn push(&mut self, path: &NodePath, chunk: &NativeChunk) -> Result> { let evaluator = self.evaluator.as_mut().ok_or_else(|| closed(path))?; - match chunk { + let output = match chunk { // Raw samples are read window by window by the evaluator itself. NativeChunk::Raw(chunk) => evaluator.push(chunk), // An evaluated input is read as computed samples, one chunk at a time: the evaluator @@ -236,7 +463,8 @@ impl WindowRuntime { // decision before its input series has ended; buffering the chunks into a whole series // first would hold the input's bytes and delay every result to the end of the series. NativeChunk::Evaluated(chunk) => evaluator.push_evaluated(chunk), - } + }?; + Ok(output) } /// Closes this window, reporting an input that ended mid-series. @@ -260,6 +488,9 @@ struct NodeRuntime { window: Option, /// What a map node applies. map: 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, } impl NodeRuntime { @@ -322,14 +553,18 @@ impl NodeRuntime { let output = outcome?; metrics.record_grid_points(output.range().len()); metrics.record_output(1, valid_values(&output)); - // A map holds one chunk for as long as it maps it. - self.buffer.release(); + // A map holds one chunk for as long as it maps it, and the label sets it has handed out + // from then on. + self.track(path, &output)?; + let bytes = self.emitted_bytes(); + self.buffer.hold_exactly(bytes)?; Ok(output) } /// Feeds one chunk to this node's window. fn window(&mut self, path: &NodePath, chunk: NativeChunk) -> Result> { let (bytes, positions, closing) = (chunk.bytes(), chunk.positions(), chunk.is_last()); + // The chunk is held for as long as the evaluator consumes it. self.buffer.hold(bytes)?; let metrics = Arc::clone(&self.buffer.metrics); let outcome = { @@ -347,22 +582,72 @@ impl NodeRuntime { // nothing for it still closed it, so it is counted here rather than on its output. metrics.record_completed_series(1); } + // An error leaves the reservation to the driver, which releases every node when it stops. let output = outcome?; if let Some(output) = &output { metrics.record_grid_points(output.range().len()); metrics.record_output(1, valid_values(output)); + // What it handed out is what the label sets of this node now hold. + self.track(path, output)?; } - if closing { - // The evaluator dropped what it retained for the series, so this node holds nothing - // more of it; a series that has not closed is still buffered and stays reserved. - self.buffer.release(); - } + // The chunk has been consumed: what this node still holds is what the evaluator kept of it + // and the label sets it has already handed out. Between pushes the charge for both is the + // accounted size of that storage, a lower bound on what is held rather than a measurement: + // the evaluator's buffers by capacity and every label set handed out, leaving out the + // kernel's scratch, this table's map overhead with the `Arc` headers of its strings, the + // outer vectors of the pending batch and a sliced buffer's extra backing. During one push + // the evaluator additionally holds the incoming chunk, charged by `hold` above for as long + // as the call runs, and vector growth is not reserved and not bounded by one doubling — + // a bulk append can allocate more than twice the previous capacity, and several vectors can + // grow at once — so this figure is what the storage stands at, not a peak over the push. + // + // The reason the figure must not be per-chunk: charging every chunk consumed makes the + // reservation grow with the chunk count, so a fixed window over a long series reads as an + // allocation failure even though the window holds no more samples. + // + // Both terms are charged whether or not this chunk produced one: a chunk that yields + // nothing leaves the evaluator's samples and every earlier series' history exactly where + // they were, so dropping the charge here would release memory this node still holds. + let retained = self + .window + .as_ref() + .map_or(0, WindowRuntime::retained_bytes); + let emitted = self.emitted_bytes(); + self.buffer.hold_exactly(retained.saturating_add(emitted))?; Ok(output) } + /// Records what this node hands out under its output label set. + /// + /// A node that rewrites labels is where two input series become indistinguishable, so this is + /// where the second one is refused: the node above reads what this one hands over, and a window + /// above would evaluate the two as two series and report both. Checking at the root would be + /// too late for that — the answer would already have been computed. + fn track(&mut self, path: &NodePath, output: &EvaluatedChunk) -> Result<()> { + match self.emitted.as_mut() { + Some(emitted) => emitted.occupy(path, output), + // A node that keeps its input's labels cannot make two series one. + None => Ok(()), + } + } + + /// The bytes the label sets this node has handed out hold. + /// + /// Zero for a node that keeps its input's labels, which keeps no such table. + fn emitted_bytes(&self) -> usize { + self.emitted.as_ref().map_or(0, Emitted::bytes) + } + /// 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 go with it. + self.window = None; + self.emitted = None; self.queued.clear(); + self.queued.shrink_to_fit(); self.buffer.release(); } } @@ -404,12 +689,23 @@ impl NativeExecutionState { // cannot be shown at one position and registered at another. let mut pending: Vec = Vec::new(); let mut unsupported: Option = None; + // The order the source streams its series in, and where it says so: a window evaluates one + // series at a time, so it is only executable over an input that keeps each series + // contiguous. + let mut ordering: Option<(SeriesOrdering, NodePath)> = None; + let mut first_window: Option = None; metrics::walk(tree.root(), &mut |node, path| { let handles = Arc::new(NodeMetrics::default()); handles.register(path, metrics_set, partition); let plan = match &node.expr { - NativeExpr::Input(_) => Some((NodeTag::Input, Seed::Input)), - NativeExpr::Window { op, .. } => Some((NodeTag::Window, Seed::Window(op.clone()))), + NativeExpr::Input(bound) => { + ordering.get_or_insert_with(|| (bound.ordering, path.clone())); + Some((NodeTag::Input, Seed::Input)) + } + NativeExpr::Window { op, .. } => { + first_window.get_or_insert_with(|| path.clone()); + Some((NodeTag::Window, Seed::Window(op.clone()))) + } NativeExpr::Map { op, .. } => Some((NodeTag::Map, Seed::Map(Arc::clone(&op.ops)))), // The kinds below are legal in a bound tree, and `validate` stays the authority on // that; this runtime simply does not execute them yet. @@ -446,6 +742,21 @@ impl NativeExecutionState { return Err(error); } + // A window feeds one series at a time to its evaluator, so it can only run over an input + // that keeps each series contiguous. The tree stays free to say `Interleaved` -- the + // compiler's job is not narrowed here -- but this runtime says so up front instead of + // failing on the second series of a chunk stream it advertised a chunk at a time. + if let Some(window) = &first_window + && let Some((ordering, source)) = &ordering + { + match ordering { + SeriesOrdering::Contiguous | SeriesOrdering::KeyThenTime => {} + SeriesOrdering::Interleaved => { + return Err(unsupported_ordering(*ordering, window, source)); + } + } + } + // A node's input is the node at the same position extended by the step the traversal took, // so the structure is read off the positions instead of a second traversal that could // disagree with the first. @@ -476,6 +787,7 @@ impl NativeExecutionState { queued: VecDeque::new(), window: None, map: None, + emitted: None, }; match &node.seed { Seed::Input => {} @@ -490,6 +802,9 @@ impl NativeExecutionState { ops: Arc::clone(ops), schema, }); + // A map drops the metric name, so it is one of the nodes that can turn two + // series into one label set. + runtime.emitted = Some(Emitted::default()); } Seed::Window(window) => { let child = input.ok_or_else(|| { @@ -504,18 +819,11 @@ impl NativeExecutionState { node.path )) })?; - // One evaluator per window, with the grids the node was bound to: the output - // grid is the node's own grid, which is also the grid its chunks are - // addressed on. - let evaluator = RangeEvaluator::try_new( - &input_schema, - Arc::clone(&window.output_grid), - window.window, - window.function, - )?; - runtime.window = Some(WindowRuntime { - evaluator: Some(evaluator), - }); + runtime.window = Some(WindowRuntime::try_new(&input_schema, window)?); + // A window drops the metric name and the empty-valued labels, so a `rate` over + // a series whose tag is empty and one where it is absent produces one label set + // from two series. + runtime.emitted = Some(Emitted::default()); } } debug_assert_eq!(nodes.len(), index); @@ -599,6 +907,40 @@ impl NativeExecutionState { self.nodes.is_empty() } + /// What the node at `path` charges for: the bytes its window's evaluator retains and the bytes + /// of the label sets it has handed out. + /// + /// Test-only: a window's reservation has to be exactly these two numbers, so a test compares + /// the reservation against them rather than against a figure the runtime keeps on the side. + #[cfg(test)] + fn window_charge(&self, path: &NodePath) -> (usize, usize) { + let index = *self + .by_path + .get(path) + .expect("the path names a node of this tree"); + let runtime = &self.runtimes[index]; + ( + runtime + .window + .as_ref() + .map_or(0, WindowRuntime::retained_bytes), + runtime.emitted_bytes(), + ) + } + + /// How many nodes still hold the state a window buffers into. + /// + /// Test-only: releasing a stopped execution has to drop the evaluators and their sample + /// buffers, not only the numbers that say how many bytes they were reserved for, and that is + /// not observable from the pool. + #[cfg(test)] + pub(crate) fn nodes_holding_windows(&self) -> usize { + self.runtimes + .iter() + .filter(|runtime| runtime.window.is_some()) + .count() + } + /// 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 @@ -870,6 +1212,61 @@ fn closed(path: &NodePath) -> DataFusionError { DataFusionError::Execution(format!("the window at {path} is already closed")) } +/// The rejection of an input ordering this runtime cannot execute under a window. +/// +/// It names the window that needs contiguity, the input that does not keep it, and the ordering +/// that was found, so a reader can tell a tree this runtime cannot run from one it cannot run +/// correctly. +fn unsupported_ordering( + ordering: SeriesOrdering, + window: &NodePath, + input: &NodePath, +) -> DataFusionError { + DataFusionError::NotImplemented(format!( + "the native runtime does not execute windows over {ordering:?} input yet: the window at \ + {window} reads one series at a time, but the input at {input} is {ordering:?}" + )) +} + +/// The rejection of a second series onto a label set the node already closed. +/// +/// This is a limitation of this streaming evaluator, not a PromQL collision. Two series whose +/// distinct label sets were rewritten into one do merge when they hold values in different places: +/// [`crate::grid_series::merge_same_labelset`] accepts exactly that, rejecting only two values of +/// one field at one position. What this runtime cannot do is merge across a series that has already +/// closed, because the evaluator closes its per-series state on the chunk carrying `is_last`: +/// nothing is left to merge the second series into, and the node hands chunks on as it produces +/// them, so it cannot hold the first series back until it knows whether a second one follows. +/// +/// The case is therefore refused rather than answered wrongly: reporting the two as one series, or +/// the first series twice, would both be a claim this layer cannot stand behind. +fn closed_label_set(path: &NodePath, labels: &LabelSet) -> DataFusionError { + DataFusionError::Execution(format!( + "the node at {path} already closed the label set {labels:?}, and a second input series \ + produces it: answering would report one series twice, and merging the two would need \ + whole series" + )) +} + +/// The rejection of a chunk holding a value where the same field already holds one. +/// +/// No merge resolves this one: at `position`, field `field` of the label set `labels` would carry +/// two values, which is what Prometheus rejects for two series whose label sets became equal. +fn occupied_position( + path: &NodePath, + labels: &LabelSet, + field: usize, + run: &Run, + previous: &Run, +) -> DataFusionError { + DataFusionError::Execution(format!( + "the node at {path} produces two series under the label set {labels:?} that both hold a \ + value of field {field} at position {position}: one occupies {previous:?} and another \ + {run:?}. Merging them would need whole series, which this layer does not hold", + position = run.start.max(previous.start), + )) +} + /// 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 1a8eae108c0..94ffe1d7408 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -27,7 +27,7 @@ use datatypes::series::samples::{ FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; -use datatypes::series::{MetricName, SeriesOrdering}; +use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::{NativeExecutionState, NativeExecutor, map_chunk}; use crate::evaluated::EvaluatedChunk; @@ -45,12 +45,25 @@ fn grid(start: i64, step: i64, len: u64) -> Arc { } fn fields() -> Arc<[FieldSpec]> { - Arc::from([FieldSpec { name: "v0".into() }]) + field_count(1) +} + +/// `count` float fields named `v0`, `v1`, ... +fn field_count(count: usize) -> Arc<[FieldSpec]> { + (0..count) + .map(|index| FieldSpec { + name: format!("v{index}").into(), + }) + .collect() } fn raw_schema() -> Arc { + raw_schema_of(fields()) +} + +fn raw_schema_of(fields: Arc<[FieldSpec]>) -> Arc { Arc::new(SeriesSchema { - fields: fields(), + fields, eval_grid: None, }) } @@ -82,9 +95,9 @@ fn input() -> NativeNode { } } -/// A source whose chunks are already evaluated, such as the inner result of a subquery. -fn evaluated_input(grid: Arc) -> NativeNode { - let output = evaluated(grid); +/// The same source over `count` float fields, which one input chunk has to carry all of. +fn raw_input_of(count: usize) -> NativeNode { + let output = NativeType::Samples(raw_schema_of(field_count(count))); NativeNode { expr: NativeExpr::Input(BoundInput { output: output.clone(), @@ -94,6 +107,23 @@ fn evaluated_input(grid: Arc) -> NativeNode { } } +/// A source whose chunks are already evaluated, such as the inner result of a subquery. +fn evaluated_input(grid: Arc) -> NativeNode { + evaluated_input_with_ordering(grid, SeriesOrdering::KeyThenTime) +} + +/// A source of evaluated chunks that guarantees `ordering`. +fn evaluated_input_with_ordering(grid: Arc, ordering: SeriesOrdering) -> NativeNode { + let output = evaluated(grid); + NativeNode { + expr: NativeExpr::Input(BoundInput { + output: output.clone(), + ordering, + }), + output, + } +} + fn window(inner: NativeNode, output_grid: Arc) -> NativeNode { window_with( inner, @@ -129,6 +159,32 @@ fn window_with( } } +/// A 1 ms `last_over_time` window over `count` float fields, whose output carries them all. +/// +/// Every other window here is over `fields`; this one is what a test of per-field retention needs. +fn window_over_fields(count: usize, output_grid: Arc) -> NativeNode { + let fields = field_count(count); + NativeNode { + expr: NativeExpr::Window { + input: Box::new(raw_input_of(count)), + op: BoundWindow { + function: RangeFunction::LastOverTime, + window: RangeWindow { + range_ms: 1, + offset_ms: 0, + anchor_ms: None, + }, + input_grid: None, + 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 { @@ -153,12 +209,49 @@ fn raw_chunk( values: &[f64], is_last: bool, ) -> RawSeriesChunk { + raw_chunk_of(schema, b"series-a", metric(), timestamps, values, is_last) +} + +/// One raw chunk of the series named by `key` and `metric`. +fn raw_chunk_of( + schema: &SeriesSchema, + key: &[u8], + metric: MetricName, + timestamps: &[i64], + values: &[f64], + is_last: bool, +) -> RawSeriesChunk { + RawSeriesChunk::try_new( + schema, + Buffer::from_slice_ref(key), + Some(metric), + RawTimestamps::try_new(ScalarBuffer::from(timestamps.to_vec())).unwrap(), + SeriesFields::one(Samples::from_float(Float64Array::from(values.to_vec()))), + is_last, + ) + .unwrap() +} + +/// One raw chunk of `series-a` whose every field carries `values`, so one input can be pushed to a +/// schema of more than one field. +fn raw_chunk_repeated( + schema: &SeriesSchema, + timestamps: &[i64], + values: &[f64], + is_last: bool, +) -> RawSeriesChunk { + let fields = SeriesFields::try_from_vec( + (0..schema.fields.len()) + .map(|_| Samples::from_float(Float64Array::from(values.to_vec()))) + .collect(), + ) + .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::from_float(Float64Array::from(values.to_vec()))), + fields, is_last, ) .unwrap() @@ -170,22 +263,77 @@ fn evaluated_chunk( start: usize, values: Vec, is_last: bool, +) -> EvaluatedChunk { + evaluated_chunk_of( + schema, + metric(), + start, + values.into_iter().map(Some).collect(), + is_last, + ) +} + +/// One evaluated chunk of the series `metric`, `values` at `start` and onwards on `schema`'s grid. +/// +/// A `None` value is a position the series decided to hold no sample, which is what an inner +/// evaluated result carries where it had nothing to report. +fn evaluated_chunk_of( + schema: &SeriesSchema, + metric: MetricName, + start: usize, + values: Vec>, + is_last: bool, ) -> EvaluatedChunk { let samples = Samples::from_float(Float64Array::from(values)); let range = GridRange::try_new(schema.eval_grid.clone().unwrap(), start, samples.len()).unwrap(); let series = Series { - metric: metric(), + metric, time: TimeAxis::Grid(range), fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), }; EvaluatedChunk::try_new(series, is_last).unwrap() } +/// 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( + Some(name.into()), + vec![Label { + name: "job".into(), + value: job.into(), + }], + ) + .unwrap() +} + +/// `requests{host="web-1"}` with `zone` either present and empty or absent. +/// +/// The two are distinct series to a scan — an empty tag value is a present label, an absent one is +/// not — and the same label set to everything that drops empty-valued labels, as Prometheus does. +fn host_metric(zone: Option<&str>) -> MetricName { + let mut tags = vec![Label { + name: "host".into(), + value: "web-1".into(), + }]; + if let Some(zone) = zone { + tags.push(Label { + name: "zone".into(), + value: zone.into(), + }); + } + MetricName::try_new(Some("requests".into()), tags).unwrap() +} + fn pool() -> Arc { Arc::new(GreedyMemoryPool::new(1 << 20)) } +/// A pool with a fixed budget, so a reservation that grows with the input fails here. +fn bounded_pool(bytes: usize) -> Arc { + Arc::new(GreedyMemoryPool::new(bytes)) +} + fn executor( tree: &NativeTree, pool: Arc, @@ -707,6 +855,11 @@ fn an_error_releases_the_reservation() { let mut execution = executor(&tree, Arc::clone(&pool), &set); assert_eq!(pool.reserved(), 0); + assert_eq!( + execution.state().nodes_holding_windows(), + 1, + "a window that has not been released is what the drop below has to give back" + ); execution .push_raw(raw_chunk(&schema, &[0, 60_000], &[1.0, 2.0], false)) .unwrap(); @@ -735,6 +888,14 @@ fn an_error_releases_the_reservation() { // keep the query's bytes in use for as long as the caller holds the executor. assert_eq!(pool.reserved(), 0); assert_eq!(execution.state().reserved_bytes(), 0); + // The numbers above only say the reservation was returned. The state the bytes were taken for + // has to be gone too, or the executor keeps the evaluator's sample buffers alive while the pool + // reports them as free: the window is dropped, not only its accounting. + assert_eq!( + execution.state().nodes_holding_windows(), + 0, + "the stopped execution still holds a window's samples while its reservation reads zero" + ); let current = NodePath::root().metric_name(NodeMetric::CURRENT_RESERVED_BYTES); assert_eq!(gauge(&set, ¤t), 0); let peak = NodePath::root().partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, 0); @@ -759,3 +920,659 @@ fn an_error_releases_the_reservation() { drop(unfinished); assert_eq!(pool.reserved(), 0); } + +/// A map that drops the metric name cannot hand two series on under one label set. +/// +/// `a{job="x"}` and `b{job="x"}` arrive whole, so each says it is the last chunk of its own series, +/// and `abs` drops the name, so both become `{job="x"}`. A window above the map reads chunks as +/// they arrive, so it would take them for two series and answer once per series; the only answer +/// the data has is the merged series, which this layer does not hold. The map refuses the second +/// one before the window above evaluates it. +#[test] +fn two_series_onto_one_label_set_after_a_map_are_rejected() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let tree = || { + NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::AvgOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap() + }; + let schema = evaluated_schema(Arc::clone(&inner_grid)); + + // The first series closes, so its window answer comes out on its own. + let mut execution = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + vec![Some(1.0), None], + true, + )) + .unwrap(); + let first = execution + .next_chunk() + .unwrap() + .expect("the first series settles the outer point"); + assert_eq!(sample_values(&first), vec![Some(1.0)]); + assert!(first.is_last); + + // The second one maps onto the label set the first one closed. Answering would produce a second + // chunk with the same labels at the same point. + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("b", "x"), + 0, + vec![None, Some(3.0)], + true, + )) + .unwrap(); + let error = match execution.next_chunk() { + Ok(None) => panic!("the second series settled nothing at all"), + Ok(Some(chunk)) => panic!( + "the map handed a second series on at the label set the first one closed: {:?}", + decided(&[chunk]) + ), + Err(error) => error, + }; + let message = error.to_string(); + assert!( + message.contains("job"), + "the rejection does not name the label set: {message}" + ); + assert!( + message.contains("closed"), + "the rejection does not say the label set was already closed: {message}" + ); + + // What the rejection protects: one series carrying both samples averages to 2 at that point, + // which is the answer neither of the two separate series can produce. + let mut merged = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); + merged + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("c", "x"), + 0, + vec![Some(1.0), Some(3.0)], + true, + )) + .unwrap(); + let answer = merged + .next_chunk() + .unwrap() + .expect("the merged series settles the outer point"); + assert_eq!(sample_values(&answer), vec![Some(2.0)]); +} + +/// A window that drops empty-valued labels cannot hand two series on under one label set either. +/// +/// `{host="web-1", zone=""}` and `{host="web-1"}` are two series to the scan: an empty tag value is +/// a present label, an absent one is not. `rate` drops the metric name and the empty-valued labels, +/// so both become `{host="web-1"}` and each covers the same grid; answering would hand the whole +/// grid out twice under the same labels and the same timestamps. No map is involved, so the +/// rejection has to be the node's own — a check at the root would be too late, because the window +/// above would already have evaluated the two as two series. +#[test] +fn two_series_onto_one_label_set_after_a_window_are_rejected() { + let out_grid = grid(0, 60_000, 5); + let tree = NativeTree::try_new(window_with( + input(), + RangeFunction::Rate, + 300_000, + None, + Arc::clone(&out_grid), + )) + .unwrap(); + let schema = raw_schema(); + let counter = [0, 60_000, 120_000, 180_000, 240_000]; + + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_raw(raw_chunk_of( + &schema, + b"series-a", + host_metric(Some("")), + &counter, + &[1.0, 2.0, 3.0, 4.0, 5.0], + true, + )) + .unwrap(); + let first = execution + .next_chunk() + .unwrap() + .expect("the first series settles the grid"); + assert!(!first.range().is_empty()); + assert!(first.is_last); + + // The second series is a different one to the scan and the same one to `rate`. + execution + .push_raw(raw_chunk_of( + &schema, + b"series-b", + host_metric(None), + &counter, + &[6.0, 7.0, 8.0, 9.0, 10.0], + true, + )) + .unwrap(); + let error = match execution.next_chunk() { + Ok(None) => panic!("the second series settled nothing at all"), + Ok(Some(chunk)) => panic!( + "a second series left the window under the first one's label set: {:?}", + decided(&[chunk]) + ), + Err(error) => error, + }; + let message = error.to_string(); + assert!(message.contains("host"), "{message}"); + assert!(message.contains("web-1"), "{message}"); + assert!(message.contains("closed"), "{message}"); + + // Two series carrying different hosts stay distinct, which is what a rate over a label that + // survives the rewrite looks like. + let mut distinct = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + distinct + .push_raw(raw_chunk_of( + &schema, + b"series-a", + host_metric(Some("")), + &counter, + &[1.0, 2.0, 3.0, 4.0, 5.0], + true, + )) + .unwrap(); + distinct + .push_raw(raw_chunk_of( + &schema, + b"series-b", + MetricName::try_new( + Some("requests".into()), + vec![Label { + name: "host".into(), + value: "web-2".into(), + }], + ) + .unwrap(), + &counter, + &[6.0, 7.0, 8.0, 9.0, 10.0], + true, + )) + .unwrap(); + let out = run(&mut distinct); + assert_eq!(out.len(), 2, "two series over two hosts are two series"); +} + +/// A chunk that holds a value where the same field already holds one is rejected. +/// +/// Neither piece closes its series, so this is not a closed label set: the refusal is about the +/// positions themselves. `v0` would carry two values at position 0 under one label set, which no +/// merge can resolve, so the node refuses rather than picking one. +#[test] +fn two_series_holding_a_value_at_one_position_are_rejected() { + let map_grid = grid(0, 60_000, 2); + let tree = NativeTree::try_new(map( + evaluated_input(Arc::clone(&map_grid)), + vec![MathOp::Abs], + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&map_grid)); + + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for (name, values) in [ + ("a", vec![Some(-1.0), Some(-2.0)]), + ("b", vec![Some(-3.0), Some(-4.0)]), + ] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, "x"), + 0, + values, + false, + )) + .unwrap(); + } + // The first piece is fine on its own: nothing has occupied any position yet. + let first = execution + .next_chunk() + .unwrap() + .expect("the first piece is handed on as it arrives"); + assert_eq!(sample_values(&first), vec![Some(1.0), Some(2.0)]); + // The second one puts a second value of the same field at position 0. + let error = match execution.next_chunk() { + Ok(None) => panic!("the map produced no chunk at all"), + Ok(Some(chunk)) => panic!( + "a second series holding a value at the same position was handed on: {:?}", + decided(&[chunk]) + ), + Err(error) => error, + }; + let message = error.to_string(); + assert!(message.contains("job"), "{message}"); + assert!(message.contains("field 0"), "{message}"); + assert!(message.contains("position 0"), "{message}"); +} + +/// Two closed series that hold no position of the same field in common still cannot be handed on: +/// merging across a closed series is not implemented by this streaming evaluator, so the pair is +/// refused rather than answered wrongly. +/// +/// Neither piece holds a value where the other does — each has a missing value where the other holds +/// one — so the two do merge in Prometheus, and [`crate::grid_series::merge_same_labelset`] accepts +/// exactly this. What refuses it is the label set having closed on the piece carrying `is_last`: the +/// evaluator above has already closed its per-series state for it, so the node cannot hold the first +/// series back until it knows whether a second one follows. The refusal has to say so; a test that +/// passed both pieces as open chunks would be proving a merge the runtime never performs. +#[test] +fn a_merge_across_a_closed_series_is_not_implemented() { + let map_grid = grid(0, 60_000, 2); + let tree = NativeTree::try_new(map( + evaluated_input(Arc::clone(&map_grid)), + vec![MathOp::Abs], + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&map_grid)); + + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + // Each source series is closed properly: the pieces hold disjoint positions of field 0 and both + // end their series. + for (name, values) in [("a", vec![Some(-1.0), None]), ("b", vec![None, Some(-3.0)])] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, "x"), + 0, + values, + true, + )) + .unwrap(); + } + let first = execution + .next_chunk() + .unwrap() + .expect("the first closed series is handed on before the second one arrives"); + assert_eq!(sample_values(&first), vec![Some(1.0), None]); + // The second one would merge with it, which this runtime does not do across a closed series. + let error = match execution.next_chunk() { + Ok(None) => panic!("the map produced no chunk for the closed label set"), + Ok(Some(chunk)) => panic!( + "a merge across a closed series was handed on instead of refused: {:?}", + decided(&[chunk]) + ), + Err(error) => error, + }; + let message = error.to_string(); + assert!(message.contains("job"), "{message}"); + assert!( + message.contains("already closed the label set"), + "{message}" + ); +} + +/// Two open chunks that share a label set are accepted where no position of a field collides. +/// +/// `a{job="x"}` and `b{job="x"}` are two series to the input and one label set to `abs`, which +/// drops the name. The source is interleaved, so the second one is pushed while the first is still +/// open, and neither says it is the last chunk of its series. The two occupy disjoint positions of +/// field 0 — a value at 0 and a value at 3 — so the label-set check hands both on. +/// +/// This is acceptance by that check, and it is not a merge: this layer passes every chunk through +/// as it arrives and keeps no sample state that would combine two series. Merging two series under +/// one label set is [`crate::grid_series::merge_same_labelset`]'s job, and nothing here performs +/// it. +#[test] +fn two_open_series_that_share_a_label_set_are_accepted_when_no_position_collides() { + let map_grid = grid(0, 60_000, 4); + let tree = NativeTree::try_new(map( + evaluated_input_with_ordering(Arc::clone(&map_grid), SeriesOrdering::Interleaved), + vec![MathOp::Abs], + )) + .expect("a map-only tree is legal over an interleaved input"); + let schema = evaluated_schema(Arc::clone(&map_grid)); + + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + vec![Some(-1.0), None], + false, + )) + .unwrap(); + let first = execution + .next_chunk() + .unwrap() + .expect("the first open chunk is handed on as it arrives"); + assert_eq!(sample_values(&first), vec![Some(1.0), None]); + assert_eq!(series_start(&first), 0); + + // Positions 2 and 3 of field 0, holding a value at 3 only: no position of the field is + // occupied twice, so nothing the check looks at is claimed by both series. + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("b", "x"), + 2, + vec![None, Some(-3.0)], + false, + )) + .unwrap(); + let second = execution + .next_chunk() + .unwrap_or_else(|error| panic!("the second open chunk was refused: {error}")) + .expect("the second open chunk is handed on too"); + assert_eq!(sample_values(&second), vec![None, Some(3.0)]); + assert_eq!(series_start(&second), 2); + assert!( + execution.next_chunk().unwrap().is_none(), + "the map handed on more than the two chunks it was given" + ); +} + +/// One series arriving in pieces is not two series: a chunk that continues where its label set +/// ended is handed on. +/// +/// The map is passed twice for one label set, and the window above it reports the whole series once +/// the piece carrying `is_last` arrives. +#[test] +fn a_series_that_continues_where_it_ended_is_not_a_second_series() { + let inner_grid = grid(0, 60_000, 4); + let outer_grid = grid(180_000, 60_000, 1); + let tree = NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::AvgOverTime, + 360_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + vec![Some(-1.0), None], + false, + )) + .unwrap(); + while let Some(chunk) = execution.next_chunk().unwrap() { + assert!( + !chunk.is_last, + "the series cannot close before its last chunk" + ); + } + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 2, + vec![None, Some(-3.0)], + true, + )) + .unwrap(); + let out = run(&mut execution); + assert_eq!( + decided(&out), + vec![(0, Some(2.0))], + "the two chunks of one series are one series to the window above the map" + ); + assert!(out.last().unwrap().is_last); +} + +/// A window reserves what it retains, not what it has consumed. +/// +/// A long series is fed one sample per chunk to a pool with a fixed budget, pulling and dropping +/// the result of every chunk and closing only on the last one. The same one-sample-per-chunk input +/// leaves the evaluator's storage at the same size however many chunks it arrives in, so the +/// reservation reaches the same figure whether the data is split into 64 chunks or into 1024. +/// +/// What the reservation has to be is not left to a constant: after every pull it is compared with +/// what the same window's evaluator says it retains and what the label sets it handed out hold. A +/// figure that merely did not grow with the chunk count would fail that, as would one that let the +/// emitted table go. +#[test] +fn a_window_reserves_what_it_retains_not_what_it_consumed() { + // A 1 ms window on a 1 ms grid, so every chunk's sample is out of the window of the next one. + let tree = || { + NativeTree::try_new(window_with( + input(), + RangeFunction::LastOverTime, + 1, + None, + grid(0, 1, 1024), + )) + .unwrap() + }; + let schema = raw_schema(); + + let peak = |count: usize| { + let pool = bounded_pool(32 << 10); + let mut execution = executor(&tree(), Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + let mut peak = 0; + for index in 0..count { + execution + .push_raw(raw_chunk( + &schema, + &[index as i64], + &[index as f64], + index + 1 == count, + )) + .unwrap_or_else(|error| { + panic!("chunk {index} of the {count}-chunk series did not fit: {error}") + }); + // The output of every chunk is dropped: a consumer reading the series as it arrives + // never holds it, and neither may the node. + let pulled = execution.next_chunk().unwrap_or_else(|error| { + panic!("chunk {index} of the {count}-chunk series did not fit: {error}") + }); + drop(pulled); + let held = execution.state().reserved_bytes(); + let (retained, emitted) = execution.state().window_charge(&NodePath::root()); + assert_eq!( + held, + retained.saturating_add(emitted), + "chunk {index} of {count} holds {held} bytes, but the window retains {retained} \ + and handed out {emitted}" + ); + assert!( + held <= (4 << 10), + "chunk {index} of {count} holds {held} bytes of a 1 ms window over one sample" + ); + peak = peak.max(held).max(pool.reserved()); + } + peak + }; + let short = peak(64); + let long = peak(1024); + assert_eq!( + short, long, + "the reservation grew with the number of chunks the same series arrived in" + ); +} + +/// A window's retention is per field, as the evaluator's storage is. +/// +/// The same one-sample-per-chunk input goes to a window over one float field, over two and over +/// three, and the reservation is compared with what each window retains after every pull. Every +/// field costs its own timestamps, values and row slot, so the figure grows by the same amount per +/// field; a figure counting one timestamp and one float per row would not. The widths are compared +/// by their increments rather than as a multiple of one: the identity of the open series is part of +/// the reservation and is counted once however many fields the series carries. +#[test] +fn a_window_retains_the_samples_of_every_field() { + // The most the window ever retained, over the same input and the same short window. + let peak = |width: usize| -> usize { + let tree = NativeTree::try_new(window_over_fields(width, grid(0, 1, 1024))).unwrap(); + let schema = raw_schema_of(field_count(width)); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let (count, mut peak) = (8, 0); + for index in 0..count { + execution + .push_raw(raw_chunk_repeated( + &schema, + &[index as i64], + &[index as f64], + index + 1 == count, + )) + .unwrap(); + drop(execution.next_chunk().unwrap()); + let (retained, emitted) = execution.state().window_charge(&NodePath::root()); + let held = execution.state().reserved_bytes(); + assert_eq!( + held, + retained.saturating_add(emitted), + "{width} field(s), chunk {index} of {count}: {held} bytes reserved, but the \ + window retains {retained} and handed out {emitted}" + ); + peak = peak.max(retained); + } + peak + }; + let (one, two, three) = (peak(1), peak(2), peak(3)); + assert!( + two > one, + "a window over two fields retained {two} bytes, no more than the {one} bytes a window over \ + one field retains" + ); + assert_eq!( + two - one, + three - two, + "a third field costs {} bytes where a second cost {}: the retention is not one field's \ + storage per field", + three - two, + two - one + ); +} + +/// A chunk that produces nothing still leaves the table this node emitted into in its hands. +/// +/// The first chunk decided both grid points and the window handed them out, so the table holds a +/// label set and its runs. The second chunk decides nothing — every point was already decided — so +/// the window yields no chunk, but it has given none of that history back: the reservation has to +/// keep covering the table, not drop it. +#[test] +fn a_chunk_with_no_output_keeps_charging_the_emitted_table() { + let tree = NativeTree::try_new(window_with( + input(), + RangeFunction::LastOverTime, + 1, + None, + 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, 60_000], &[1.0, 2.0], false)) + .unwrap(); + let first = execution + .next_chunk() + .unwrap() + .expect("the first chunk decided both points"); + assert_eq!(sample_values(&first), vec![Some(1.0), Some(2.0)]); + drop(first); + let (retained, emitted) = execution.state().window_charge(&NodePath::root()); + assert!( + emitted > 0, + "the window handed out a position, which it has to hold" + ); + assert_eq!( + execution.state().reserved_bytes(), + retained.saturating_add(emitted), + "the reservation does not cover the {emitted} bytes the window handed out" + ); + + // Both points are decided, so this chunk decides nothing and the window yields no chunk. + execution + .push_raw(raw_chunk(&schema, &[120_000], &[3.0], false)) + .unwrap(); + assert!( + execution.next_chunk().unwrap().is_none(), + "a chunk after every point was decided produced a chunk" + ); + let (retained, emitted) = execution.state().window_charge(&NodePath::root()); + assert!( + emitted > 0, + "the window's emitted table emptied itself between chunks" + ); + assert_eq!( + execution.state().reserved_bytes(), + retained.saturating_add(emitted), + "a chunk with no output released the {emitted} bytes the emitted table still holds" + ); +} + +/// A window cannot run over an interleaved input, and the runtime says so before reading a chunk. +#[test] +fn a_window_over_an_interleaved_input_is_rejected() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(0, 120_000, 1); + let tree = NativeTree::try_new(window_with( + evaluated_input_with_ordering(Arc::clone(&inner_grid), SeriesOrdering::Interleaved), + RangeFunction::LastOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .expect("the bound tree is legal"); + let error = + match NativeExecutionState::try_new(&tree, pool(), &ExecutionPlanMetricsSet::new(), 0) { + Ok(_) => panic!("the runtime accepted an interleaved input under a window"), + Err(error) => error, + }; + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "{error}" + ); + let message = error.to_string(); + assert!(message.contains("Interleaved"), "{message}"); + assert!(message.contains("at root "), "{message}"); + assert!(message.contains("root.input"), "{message}"); + + // A map needs no ordering: it holds one chunk at a time, so the series of an interleaved stream + // never have to be contiguous. `A1, B1, A2, B2` runs here as it arrives. + let map_grid = grid(0, 60_000, 4); + let tree = NativeTree::try_new(map( + evaluated_input_with_ordering(Arc::clone(&map_grid), SeriesOrdering::Interleaved), + vec![MathOp::Abs], + )) + .expect("a map-only tree is legal over an interleaved input"); + let schema = evaluated_schema(Arc::clone(&map_grid)); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for (name, job, start, values, is_last) in [ + ("a", "x", 0, vec![Some(-1.0), Some(-2.0)], false), + ("b", "y", 0, vec![Some(-3.0), Some(-4.0)], false), + ("a", "x", 2, vec![Some(-5.0), Some(-6.0)], true), + ("b", "y", 2, vec![Some(-7.0), Some(-8.0)], true), + ] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, job), + start, + values, + is_last, + )) + .unwrap(); + } + assert_eq!( + addressed(&run(&mut execution)), + vec![ + (0, vec![Some(1.0), Some(2.0)]), + (0, vec![Some(3.0), Some(4.0)]), + (2, vec![Some(5.0), Some(6.0)]), + (2, vec![Some(7.0), Some(8.0)]), + ] + ); +} diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index 8ca3436b011..28ca7f22341 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -197,6 +197,37 @@ impl PendingBatch { spans.clear(); } } + + /// The bytes the accumulated points hold in the vectors themselves, by capacity, because + /// clearing a batch keeps its allocation for the next one. Saturating, since the figure goes + /// into a memory reservation that must never wrap to a small number. + /// + /// The outer `spans` and `columns` vectors are not counted, only the buffers they hold, so this + /// is a lower bound on what the batch retains. + fn bytes(&self) -> usize { + self.indices + .capacity() + .saturating_mul(std::mem::size_of::()) + .saturating_add( + self.eval_ts + .capacity() + .saturating_mul(std::mem::size_of::()), + ) + .saturating_add(self.spans.iter().fold(0usize, |bytes, spans| { + bytes.saturating_add( + spans + .capacity() + .saturating_mul(std::mem::size_of::>()), + ) + })) + .saturating_add(self.columns.iter().fold(0usize, |bytes, column| { + bytes.saturating_add( + column + .capacity() + .saturating_mul(std::mem::size_of::>()), + ) + })) + } } /// Records one point for the next batch call: its evaluation timestamp and, per field, the range @@ -281,6 +312,28 @@ struct SeriesState { emitted_end: usize, } +impl SeriesState { + /// The bytes this identity holds once the input chunk it came from is gone: the primary key + /// buffer and the metric's name and label strings. Saturating, because the figure goes into a + /// memory reservation. + /// + /// `Buffer::len` is the buffer's visible byte length, so the key term is those bytes; a buffer + /// sliced from a larger allocation leaves the backing beyond them uncounted. Neither the metric + /// nor its labels has a byte-length accessor, so the string contents are measured directly: + /// that counts every byte of every name and value, and leaves out the `Arc` headers and the + /// label slice they sit in, which are a small fixed amount per label rather than per byte. + fn identity_bytes(&self) -> usize { + let key = self.primary_key.as_ref().map_or(0, Buffer::len); + let name = self.metric.name().map_or(0, str::len); + let labels = self.metric.tags().iter().fold(0usize, |bytes, label| { + bytes + .saturating_add(label.name.len()) + .saturating_add(label.value.len()) + }); + key.saturating_add(name).saturating_add(labels) + } +} + /// How the windows of an `@`-anchored selector map to the grid. /// /// Like Prometheus, an anchored selector is read once, as the window of the first grid point @@ -544,6 +597,76 @@ impl RangeEvaluator { &self.output_schema } + /// The bytes this evaluator's storage is accounted at, as its buffers stand now: their + /// capacity, not the number of samples live in them, because a drained vector keeps its buffer. + /// + /// Counted, and this is what a window reserves for: the samples retained per field — each with + /// its own timestamps, values, reset index and native histograms, the histograms with the heap + /// they own beyond their slot — the row a push fills, the points accumulated for the next batch + /// call, and the identity the open series keeps once the input chunk it came from is gone. + /// Between pushes this total is what those buffers are accounted at, a lower bound on what they + /// hold; during one, it is what they stood at before the push, and the caller in + /// `native::execute` says what a push holds on top. Saturating throughout, so a pathological + /// input cannot wrap the figure to a small one. + /// + /// Two things are deliberately left out. The kernel's scratch — quantile's sorted copy, MAD's + /// two vectors — lives inside the closures behind [`WindowKernel`], which offer no accessor to + /// it; it is bounded by the retained samples of the one window being evaluated, which is the + /// quantity already counted above, so it is a constant factor of that storage rather than a term + /// growing with anything else. And `output` with `batch` holds nothing between pushes: + /// `GridSeriesBuilder::finish` moves its fields out into the series it returns, and the batch + /// kernels are plain functions capturing no state. + pub(crate) fn retained_bytes(&self) -> usize { + let fields = self.fields.iter().fold(0usize, |bytes, field| { + let slot = std::mem::size_of::<(i64, FloatHistogram)>(); + // What each native histogram holds beyond the slot it occupies. + let payload = field + .histograms + .iter() + .fold(0usize, |held, (_, histogram)| { + held.saturating_add(histogram.heap_bytes()) + }); + bytes + .saturating_add( + field + .timestamps + .capacity() + .saturating_mul(std::mem::size_of::()), + ) + .saturating_add( + field + .values + .capacity() + .saturating_mul(std::mem::size_of::()), + ) + .saturating_add( + field + .resets + .capacity() + .saturating_mul(std::mem::size_of::()), + ) + .saturating_add(field.histograms.capacity().saturating_mul(slot)) + .saturating_add(payload) + }); + // The row a push fills, one slot per field, and the boxed payload each buffered native + // histogram owns beyond the pointer its slot holds. + let row = self + .row + .capacity() + .saturating_mul(std::mem::size_of::>()); + let row_payload = self.row.iter().fold(0usize, |held, sample| match sample { + Some(GridSample::Histogram(histogram)) => held + .saturating_add(std::mem::size_of::()) + .saturating_add(histogram.heap_bytes()), + _ => held, + }); + fields + .saturating_add(row) + .saturating_add(row_payload) + .saturating_add(self.pending.bytes()) + .saturating_add(self.series.as_ref().map_or(0, SeriesState::identity_bytes)) + } + /// Consumes the next chunk of the current series, or starts a new series. /// /// Returns the grid points this chunk decided, as one chunk whose range is absolute on the diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index 6f8482b2fb8..2a761ae615a 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -579,6 +579,239 @@ fn functions_match_range_udfs() { } } +/// The retention figure of `evaluator` with the pending-batch and field-histogram terms left out, +/// every remaining term added up here from the evaluator's own vectors: the capacity of each +/// field's timestamps, values and reset index, the row a push fills with the heap of the histograms +/// it holds, and the identity of the series still open. +/// +/// The two terms left out are pinned by their own tests below, since neither is live in every +/// evaluator. +fn hand_summed_retention_without_batch_or_histograms(evaluator: &RangeEvaluator) -> usize { + let mut expected = 0; + for field in &evaluator.fields { + expected += field.timestamps.capacity() * std::mem::size_of::(); + expected += field.values.capacity() * std::mem::size_of::(); + expected += field.resets.capacity() * std::mem::size_of::(); + } + expected += evaluator.row.capacity() * std::mem::size_of::>(); + // The payload a histogram in the row owns beyond the slot the row holds it in. + expected += evaluator + .row + .iter() + .fold(0usize, |held, sample| match sample { + Some(GridSample::Histogram(histogram)) => { + held + std::mem::size_of::() + histogram.heap_bytes() + } + _ => held, + }); + // The identity of the open series: `chunk` holds the host it was built for as a `u64`, so the + // primary key is 8 bytes, and the metric is `http_requests` with the one label `host="h0"`. + expected + 8 + "http_requests".len() + "host".len() + "h0".len() +} + +/// The bytes the native histograms the fields retain are worth, added up here from the evaluator's +/// own vectors: the slot each occupies and the heap it owns beyond it. +fn hand_summed_field_histograms(evaluator: &RangeEvaluator) -> usize { + evaluator + .fields + .iter() + .map(|field| { + field.histograms.capacity() * std::mem::size_of::<(i64, FloatHistogram)>() + + field + .histograms + .iter() + .map(|(_, histogram)| histogram.heap_bytes()) + .sum::() + }) + .sum() +} + +/// The per-field float vectors and the reset index of an open series are pinned here, hand-summed. +/// +/// The expectation is built from the evaluator's own vectors rather than from the routine under +/// test: each term is a capacity read directly and multiplied by the size of what the vector holds. +/// The kernel indexes counter resets, so the reset term is proven non-zero below rather than being +/// zero by accident. +/// +/// This evaluator keeps no histogram and no pending batch, so those terms are zero here and are +/// pinned by `the_retained_bytes_of_an_evaluator_include_its_pending_batch` and +/// `the_retained_bytes_of_an_evaluator_include_its_histograms` instead. +#[test] +fn the_retained_bytes_of_an_open_series_are_hand_summed() { + let mut evaluator = probe_evaluator( + 2, + grid(0, 1, 2_000), + RangeWindow { + range_ms: 1_000, + offset_ms: 0, + anchor_ms: None, + }, + ); + // A counter resetting in both fields, sampled every 100 ms: the last decided point's window + // still holds every sample, so nothing is released before the figure is read. + let rows: Vec = [1.0, 2.0, 3.0, 0.5, 1.5, 2.5, 0.25, 1.0, 2.0, 3.0] + .into_iter() + .enumerate() + .map(|(index, value)| (index as i64 * 100, vec![Some(value), Some(value * 10.0)])) + .collect(); + evaluator.push(&chunk(&rows, 2, 0, false)).unwrap(); + assert!( + evaluator + .fields + .iter() + .all(|field| field.values.len() == rows.len()), + "the evaluator released samples the window still needs" + ); + + // The sum, one term at a time: no term of it comes from the accounting routine. + let expected = hand_summed_retention_without_batch_or_histograms(&evaluator); + // The batch buffer of this evaluator is never filled, since the probe kernel has no batch + // form, so its term is zero and the sum above has to be the whole figure. + assert!(evaluator.pending.is_empty()); + assert_eq!(evaluator.pending.bytes(), 0); + // The probe keeps floats only, so no histogram is retained and no histogram term is live here. + assert_eq!(hand_summed_field_histograms(&evaluator), 0); + + let resets: usize = evaluator + .fields + .iter() + .map(|field| field.resets.capacity() * std::mem::size_of::()) + .sum(); + assert!( + resets > 0, + "a counter-indexing kernel kept no reset, so dropping the reset term would pass" + ); + assert_eq!( + evaluator.retained_bytes(), + expected, + "the retention figure is not the hand sum of the buffers it is made of" + ); + let live: usize = evaluator + .fields + .iter() + .map(|field| field.values.len() * std::mem::size_of::()) + .sum(); + assert!(live > 0, "the evaluator retained no float sample"); + assert!( + evaluator.retained_bytes() > live, + "the figure is no larger than the samples alone, so it counts no buffer" + ); +} + +/// The bytes the pending batch keeps between pushes are part of the retention figure. +/// +/// A batchable function accumulates its points during a push and always flushes them before the +/// push returns, so the batch holds no point here; but every vector it filled keeps the allocation +/// for the next batch, and that allocation is what the reservation has to cover. The total is +/// checked against the hand sum of the other terms plus this one, so dropping the term leaves the +/// figure too small. +#[test] +fn the_retained_bytes_of_an_evaluator_include_its_pending_batch() { + let mut evaluator = RangeEvaluator::try_new( + &raw_schema(1), + grid(0, 1, 2_000), + RangeWindow { + range_ms: 1_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + ) + .unwrap(); + // Sampled every 100 ms over a 1 s window: hundreds of points reach the batch in this one push. + let rows: Vec = (0..10) + .map(|index| (index as i64 * 100, vec![Some(index as f64 + 1.0)])) + .collect(); + evaluator.push(&chunk(&rows, 1, 0, false)).unwrap(); + assert!( + evaluator.pending.is_empty(), + "the batch still held points between pushes, so this test no longer describes one" + ); + let pending = evaluator.pending.bytes(); + assert!( + pending > 0, + "the batch grew no buffer, so the pending term is zero and nothing is pinned" + ); + + let other = hand_summed_retention_without_batch_or_histograms(&evaluator) + + hand_summed_field_histograms(&evaluator); + assert_eq!( + evaluator.retained_bytes(), + other + pending, + "the retention figure does not include the bytes of the pending batch" + ); +} + +/// The slots and heap of the retained native histograms are part of the retention figure. +/// +/// One histogram sample, with a float behind it, pushed as a chunk that does not close the series. +/// The grid reaches one step past the last sample, so the push stops before it evaluates the whole +/// grid and neither the closing chunk nor the release past the last window drops the histogram +/// before the figure is read. The total is strictly larger than the hand sum without the histogram +/// terms, and equals that sum plus them. +#[test] +fn the_retained_bytes_of_an_evaluator_include_its_histograms() { + let histogram = "0/0/0/4014000000000000/4014000000000000/1/0_1/4014000000000000///"; + let mut builder = HistogramBatchBuilder::new(); + let index = builder + .push(OwnedHistogram::parse(histogram).view()) + .unwrap(); + let histograms = HistogramSamples::try_new( + UInt32Array::from(vec![Some(index), None]), + builder.finish().unwrap(), + ) + .unwrap(); + let samples = + Samples::try_from_mixed(Float64Array::from(vec![None, Some(2.0)]), histograms).unwrap(); + let chunk = RawSeriesChunk::try_new( + &raw_schema(1), + Buffer::from(0u64.to_le_bytes().to_vec()), + Some(metric(0)), + RawTimestamps::try_new(ScalarBuffer::from(vec![10_000, 20_000])).unwrap(), + SeriesFields::try_from_vec(vec![samples]).unwrap(), + false, + ) + .unwrap(); + let mut evaluator = RangeEvaluator::try_new( + &raw_schema(1), + grid(0, 10_000, 4), + RangeWindow { + range_ms: 30_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + ) + .unwrap(); + evaluator.push(&chunk).unwrap(); + + assert!( + !evaluator.fields[0].histograms.is_empty(), + "the evaluator dropped the histogram, so every histogram term would be zero" + ); + let payload: usize = evaluator.fields[0] + .histograms + .iter() + .map(|(_, histogram)| histogram.heap_bytes()) + .sum(); + assert!( + payload > 0, + "no retained histogram owns heap beyond its slot, so only the slot term is pinned" + ); + let histogram_bytes = hand_summed_field_histograms(&evaluator); + let without = + hand_summed_retention_without_batch_or_histograms(&evaluator) + evaluator.pending.bytes(); + assert!( + evaluator.retained_bytes() > without, + "the retention figure is what it is without the histograms, so it counts neither term" + ); + assert_eq!( + evaluator.retained_bytes(), + without + histogram_bytes, + "the retention figure does not add up to the histograms' slots and heap" + ); +} + /// A chunk of entirely present float columns is appended in bulk, and that is the path the test /// asserts: the per-sample loop produces the same output, so comparing values alone could not /// tell whether the bulk path ran.