From ed6e32d048c5d1314e316079d092c625bf848674 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:55:29 +0800 Subject: [PATCH 01/33] feat(promql): execute a bound native tree node by node, over sparse evaluated series Ports the native runtime onto the sparse evaluated-series API: a chunk is addressed by a `TimeAxis` that may hold several runs, so a consumer reads positions through the axis instead of assuming `start + row`. The driver and both node kinds move to that API: - `chunk.range().len()` becomes `chunk.series.time.len()`, the compact row count, in every metric and byte estimate. - `occupied_runs` walks `time.positions()` with one field cursor, so a chunk of several runs records each run where it belongs. A run open across a hole now ends where the hole begins; leaving it open to the last row made two runs look like one and refused a series that occupies the hole. - A window keeps the pieces its evaluator decided in a queue: one push can decide several runs, and reporting only what the push returned stranded the rest until the next push. Queued pieces are charged by `retained_bytes`, and the charge is recomputed when one leaves, so a released piece is not held. - `map_chunk` answers `Option`: an operation that empties every position (`clamp` with `max < min`) yields no chunk at all, unless the chunk closes its series -- a closing chunk holding no row is handed over so a consumer can tell "nothing more here" from "no more input". `RangeEvaluator::retained_bytes` is restored with the three byte helpers it reads: a field's buffers, a series' identity and the pending batch's vectors, all by capacity, and still counted as storage rather than as a peak over a push. Tests read absolute positions from the axis (`decided` no longer adds a row number to a start), and two sparse cases cover what the old reading got wrong: a `Window -> Map -> Window` chain over a chunk of two runs, and a series that occupies the hole between another's runs. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 1480 ++++++++++++++++++ src/promql/src/native/execute/tests.rs | 1893 ++++++++++++++++++++++++ src/promql/src/native/mod.rs | 1 + src/promql/src/range_eval.rs | 94 ++ 4 files changed, 3468 insertions(+) create mode 100644 src/promql/src/native/execute.rs create mode 100644 src/promql/src/native/execute/tests.rs diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs new file mode 100644 index 00000000000..8b9e07df75f --- /dev/null +++ b/src/promql/src/native/execute.rs @@ -0,0 +1,1480 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Running a bound tree, node by node. +//! +//! [`NativeExecutionState`] owns the run-time state one execution of a [`NativeTree`] needs, keyed +//! by the position [`metrics::walk`] gives each node. The tree is what the compiler produced and +//! carries no state of its own, so a second execution builds a second state from the same tree and +//! the two never share a buffer, an evaluator or a memory reservation. +//! +//! [`NativeExecutor`] drives that state one chunk at a time. Nodes hand each other +//! [`EvaluatedChunk`]s: a source hands over raw samples, and everything above a window hands over +//! the evaluator's own chunk type. No row batch and no frame is materialised on an internal edge, +//! so a chunk a window produced is fed to the next node as it is. +//! +//! Every window owns a [`RangeEvaluator`], which is what keeps its input grid and its output grid +//! its own: `Window -> Map -> Window` evaluates the inner window on the inner grid and the outer +//! window on the outer grid, and the map in between carries the inner grid through untouched. The +//! outer window reads the inner result as the samples it is, not as something to be resampled onto +//! the outer grid first. +//! +//! 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::hash_map::Entry; +use std::collections::{HashMap, 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::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::grid_series::{LabelSet, label_set}; +use crate::map::{MathOp, drop_metric_name, map_math}; +use crate::native::batch::EvaluatedChunk; +use crate::native::metrics::{self, NodeMetrics, NodePath}; +use crate::native::plan::{BoundWindow, NativeExpr, NativeTree}; +use crate::range_eval::RangeEvaluator; + +#[cfg(test)] +mod tests; + +/// A chunk on an internal edge. +/// +/// Only a source hands over raw samples; everything above a window hands over evaluated chunks. +/// The two cannot be confused once the tree is built, because a window's bound input grid says +/// which one its input produces. +#[derive(Clone, Debug)] +enum NativeChunk { + /// Raw source samples, with their own timestamps. + Raw(RawSeriesChunk), + /// Evaluated values, addressed on their absolute grid positions. + Evaluated(EvaluatedChunk), +} + +impl NativeChunk { + /// The positions this chunk carries: decided grid positions, or raw timestamps. + fn positions(&self) -> usize { + match self { + Self::Raw(chunk) => chunk.time.len(), + Self::Evaluated(chunk) => chunk.series.time.len(), + } + } + + /// Whether this chunk closes its series. + fn is_last(&self) -> bool { + match self { + Self::Raw(chunk) => chunk.is_last, + Self::Evaluated(chunk) => chunk.is_last, + } + } + + /// An estimate of the bytes this chunk holds. + fn bytes(&self) -> usize { + match self { + Self::Raw(chunk) => raw_bytes(chunk), + Self::Evaluated(chunk) => evaluated_bytes(chunk), + } + } +} + +/// An estimate of the bytes a raw chunk holds: its timestamps, one float per field and its +/// identity. +fn raw_bytes(chunk: &RawSeriesChunk) -> usize { + std::mem::size_of::() + + chunk.primary_key.len() + + chunk.time.len() + * (std::mem::size_of::() + chunk.fields.len() * std::mem::size_of::()) +} + +/// An estimate of the bytes an evaluated chunk holds: one float per field and decided position. +/// +/// The grid itself is shared by every chunk addressed on it, so it is not counted per chunk. The +/// figure only has to rank one chunk against another for the memory pool, which is what a +/// reservation is for. +fn evaluated_bytes(chunk: &EvaluatedChunk) -> usize { + std::mem::size_of::() + + chunk.series.time.len() * chunk.series.fields.len() * std::mem::size_of::() +} + +/// Which node kinds the runtime executes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum NodeTag { + /// Forwards the chunks it is given. + Input, + /// Feeds its input to its own [`RangeEvaluator`]. + Window, + /// Applies point-wise operations to its input chunks. + Map, +} + +impl NodeTag { + /// What this tag is called in a rejection. + fn describe(self) -> &'static str { + match self { + Self::Input => "input", + Self::Window => "window", + Self::Map => "map", + } + } +} + +/// The operation a node binds, kept aside until the whole tree has been visited. +/// +/// A window's evaluator needs its input's schema, and the input is visited after the window, so +/// the binding is collected first and the run-time state is built from the complete set. +enum Seed { + Input, + Window(BoundWindow), + Map(Arc<[MathOp]>), +} + +/// One visited node, before its input's position is resolved. +struct PendingNode { + tag: NodeTag, + path: NodePath, + metrics: Arc, + /// What this node produces, when it produces samples. + output_schema: Option>, + seed: Seed, +} + +/// One node of the flattened tree. +#[derive(Clone, Copy, Debug)] +struct NodeSpec { + tag: NodeTag, + /// The position of this node's input, resolved from the tree's own positions. + input: Option, +} + +/// What every node holds: its metric handles and the bytes it reserves. +/// +/// The reservation is the pool's, so a node that buffers input competes with every other operator +/// in the query; the metrics report the same figure so a slow node can be told apart from a wide +/// one. +struct NodeBuffer { + metrics: Arc, + reservation: MemoryReservation, + /// The bytes `reservation` holds, mirrored so a chunk leaving shrinks it exactly. + held: usize, +} + +impl NodeBuffer { + /// Registers a reservation for the node at `path` with `pool`. + fn new(path: &NodePath, metrics: Arc, pool: &Arc) -> Self { + let consumer = MemoryConsumer::new(format!("native.{}", path.as_str())); + Self { + metrics, + reservation: consumer.register(pool), + held: 0, + } + } + + /// Reserves the bytes of a chunk this node starts holding. + fn hold(&mut self, bytes: usize) -> Result<()> { + self.reservation.try_grow(bytes)?; + self.held += bytes; + self.metrics.record_reserved_bytes(self.held); + Ok(()) + } + + /// Returns the bytes of a chunk this node no longer holds. + fn shrink(&mut self, bytes: usize) -> Result<()> { + let held = self.held.saturating_sub(bytes); + self.reservation.try_resize(held)?; + self.held = held; + self.metrics.record_reserved_bytes(held); + 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; + self.reservation.free(); + self.metrics.record_reserved_bytes(0); + } +} + +/// 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, + /// The bytes the entries in `sets` hold, kept as a running total. + /// + /// A node records every label set it has ever handed out and must charge for all of them, so + /// the figure is read after every output. Recomputing it there walks every entry recorded so + /// far, which is quadratic over a series that keeps producing label sets; folding one entry's + /// change in as it happens keeps the read constant. + entries: usize, +} + +/// 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, + /// The bytes this entry's labels and runs hold, kept current by [`Emitted::occupy`]. + bytes: usize, +} + +/// The bytes a label set holds: each label's name and value with the pair that refers to them. +fn label_bytes(labels: &LabelSet) -> usize { + labels + .iter() + .map(|(name, value)| std::mem::size_of::<(Arc, Arc)>() + name.len() + value.len()) + .sum() +} + +/// The bytes a history holds: the entry itself, the per-field vectors and the runs in them. +fn history_bytes(history: &History) -> usize { + std::mem::size_of::() + + history.fields.capacity() * std::mem::size_of::>() + + history + .fields + .iter() + .map(|runs| runs.capacity() * std::mem::size_of::()) + .sum::() +} + +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 occupied: Vec> = chunk + .series + .fields + .iter() + .map(|field| occupied_runs(field, &chunk.series.time)) + .collect(); + // A chunk holding no value records nothing. If the label set is unknown or already closed, + // the series this chunk belongs to contributed no sample at all -- either it is the first + // such series, or a later one that also answers empty -- so there is nothing to report, + // nothing to merge and nothing to refuse. A label set still open is the other case: the + // chunk closes the series that *did* produce the values, so it falls through to close it. + let empty = occupied.iter().all(Vec::is_empty); + if empty && self.sets.get(&labels).is_none_or(|history| history.closed) { + return Ok(()); + } + 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 { + // The stored runs are sorted and disjoint, so only the one holding `run.start` + // or the one just before it can share a position. Scanning them all would make + // a sparse series split across chunks cost a pass over its whole history per + // chunk. + let at = stored.partition_point(|stored| stored.end <= run.start); + let previous = stored.get(at).filter(|stored| stored.overlaps(*run)); + if let Some(previous) = previous { + return Err(occupied_position(path, &labels, index, run, previous)); + } + } + } + } + let fields = chunk.series.fields.len(); + // The change is folded in here rather than recomputed when the figure is read: a node + // keeps every label set it has ever handed out, so a fresh walk after each output costs a + // pass over the whole table for a table that only ever grows. + let history = match self.sets.entry(labels) { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + self.entries += label_bytes(entry.key()); + entry.insert(History::default()) + } + }; + let before = history.bytes; + if history.fields.len() < fields { + history.fields.resize_with(fields, Vec::new); + } + for (index, runs) in occupied.into_iter().enumerate() { + absorb(&mut history.fields[index], &runs); + } + if chunk.is_last { + history.closed = true; + // No later chunk reads these runs: a closed label set refuses every series that would + // use them. Keeping them charges the pool for a series that has already been answered. + history.fields = Vec::new(); + } + let after = history_bytes(history); + history.bytes = after; + self.entries = self.entries - before + after; + 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. + /// + /// The per-entry part is a running total, so reading this after every output does not walk the + /// table: only the entry that changed and the table's own capacity are read here. + fn bytes(&self) -> usize { + self.entries + + self.sets.capacity() + * (std::mem::size_of::() + std::mem::size_of::()) + } + + /// The same figure by walking every entry, used by a test to keep the running total honest. + #[cfg(test)] + fn bytes_recomputed(&self) -> usize { + self.sets + .iter() + .map(|(labels, history)| label_bytes(labels) + history_bytes(history)) + .sum::() + + self.sets.capacity() + * (std::mem::size_of::() + std::mem::size_of::()) + } +} + +/// The runs of positions holding a value in `field`, as the axis `time` places its rows. +/// +/// A missing sample holds no value; a `NaN` and a native histogram do, as they do for a merge. +/// A hole between two rows is not a position either: the axis skips it, so a run open before the +/// hole ends where the hole begins rather than reaching across it. A chunk of several runs is +/// therefore recorded as the runs it holds, and a series that occupies the hole is not refused. +fn occupied_runs(field: &Samples, time: &TimeAxis) -> Vec { + let mut runs: Vec = Vec::new(); + let mut open: Option = None; + let mut previous: Option = None; + let mut cursor = field.cursor(); + for (position, row) in time.positions() { + // The axis names the absolute position of every row, so the hole between two rows is + // visible as a jump in `position` while no row of this chunk sits in it. + if let Some(previous) = previous + && position != previous + 1 + && let Some(start) = open.take() + { + runs.push(Run { + start, + end: previous + 1, + }); + } + let present = !matches!( + cursor.at(row).expect("the axis and the fields are aligned"), + SampleRef::Missing + ); + match (present, open) { + (true, None) => open = Some(position), + (false, Some(start)) => { + runs.push(Run { + start, + end: position, + }); + open = None; + } + _ => {} + } + previous = Some(position); + } + if let Some(start) = open { + // A run still open at the last row ends just past it, not where the field's row count says: + // the rows need not be adjacent to the positions above them. + runs.push(Run { + start, + end: previous.map_or(start, |last| last + 1), + }); + } + runs +} + +/// Merges `incoming` into `stored`, keeping the result in position order and joining the runs that +/// touch. +/// +/// Both sides are sorted and disjoint, so one pass merges them. Adding the runs one at a time and +/// rebuilding the whole array after each would cost the square of the runs a chunk yields: a chunk +/// of one hundred thousand positions alternating between values and nulls yields fifty thousand +/// runs, and re-merging after each is over a billion element moves for a single series. +fn absorb(stored: &mut Vec, incoming: &[Run]) { + if incoming.is_empty() { + return; + } + let mut merged: Vec = Vec::with_capacity(stored.len() + incoming.len()); + let (mut a, mut b) = (0, 0); + while a < stored.len() || b < incoming.len() { + let larger = match (stored.get(a), incoming.get(b)) { + (Some(left), Some(right)) if right.start < left.start => { + b += 1; + *right + } + (Some(left), _) => { + a += 1; + *left + } + (None, Some(right)) => { + b += 1; + *right + } + (None, None) => break, + }; + match merged.last_mut() { + Some(last) if larger.start <= last.end => last.end = last.end.max(larger.end), + _ => merged.push(larger), + } + } + *stored = merged; +} + +/// What a map node applies. +struct MapRuntime { + ops: Arc<[MathOp]>, + /// The schema of what the map produces, which is what its input is checked against. + schema: Arc, +} + +/// What a window node holds. +struct WindowRuntime { + /// This window's own evaluator, with its own input and output grid; `None` once closed. + evaluator: Option, + /// The pieces the evaluator has decided that this node has not handed on yet. + /// + /// One push can decide several runs, and the evaluator hands them out one chunk at a time, so a + /// window that reported only what the push returned would strand the rest until the next push. + /// A piece is charged here from the moment it leaves the evaluator, which no longer holds it. + pending: VecDeque, +} + +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), + pending: VecDeque::new(), + }) + } + + /// 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 { + // A piece leaves the evaluator when it is decided, so from then on only this queue holds + // it. Each piece is counted once: it is either still inside the evaluator or already here. + let queued = self + .pending + .iter() + .map(evaluated_bytes) + .fold(0usize, usize::saturating_add); + self.evaluator + .as_ref() + .map_or(0, RangeEvaluator::retained_bytes) + .saturating_add(queued) + } + + /// 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))?; + let decided = 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: the evaluator carries the window + // state of one series across its chunks and closes it on the chunk that says so. + // Handing each chunk over as it arrives is what lets this window report a 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_series(&chunk.series, chunk.is_last)?, + }; + self.pending.extend(decided); + Ok(self.take_pending()) + } + + /// The next piece this window has decided, if it is holding one. + fn take_pending(&mut self) -> Option { + self.pending.pop_front() + } + + /// Closes this window, reporting an input that ended mid-series. + /// + /// The evaluator is what knows whether a series is still open, for evaluated input as much as + /// for raw: a chunk that did not say `is_last` leaves it holding the series. + fn finish(&mut self) -> Result<()> { + match self.evaluator.take() { + Some(evaluator) => evaluator.finish(), + None => Ok(()), + } + } +} + +/// The per-node run-time state of a node. +struct NodeRuntime { + buffer: NodeBuffer, + /// Source chunks queued by the caller, for an input node. + queued: VecDeque, + /// What a window node holds. + 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 { + /// Queues a source chunk, holding the bytes it needs until it leaves. + fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> { + let (bytes, positions) = (chunk.bytes(), chunk.positions()); + self.buffer.hold(bytes)?; + self.buffer.metrics.record_input(1, positions); + self.queued.push_back(chunk); + Ok(()) + } + + /// Hands over the next queued source chunk, if there is one. + fn pop_source(&mut self) -> Result> { + let Some(chunk) = self.queued.pop_front() else { + return Ok(None); + }; + let metrics = Arc::clone(&self.buffer.metrics); + { + // An input node's own work is handing the chunk over, so its self time covers that and + // nothing its producer did. + let _timer = metrics.timer(); + // The chunk leaves this node, so the pool no longer has to hold it. + self.buffer.shrink(chunk.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. + if let NativeChunk::Evaluated(chunk) = &chunk { + metrics.record_grid_points(chunk.series.time.len()); + } + if chunk.is_last() { + metrics.record_completed_series(1); + } + Ok(Some(chunk)) + } + + /// Maps one evaluated chunk, keeping its axis and its closing. + /// + /// `None` means the operation emptied every position and the chunk does not close its series: + /// there is nothing to hand on, and the input may still decide more. + fn map(&mut self, path: &NodePath, chunk: EvaluatedChunk) -> Result> { + let (bytes, positions, closing) = ( + evaluated_bytes(&chunk), + chunk.series.time.len(), + chunk.is_last, + ); + self.buffer.hold(bytes)?; + 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.map.as_ref() { + Some(map) => map_chunk(&map.schema, &chunk, &map.ops), + None => Err(DataFusionError::Execution(format!( + "the node at {path} holds no map" + ))), + } + }; + metrics.record_input(1, positions); + if closing { + 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.series.time.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)?; + } + 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 = { + let _timer = metrics.timer(); + match self.window.as_mut() { + Some(window) => window.push(path, &chunk), + None => Err(DataFusionError::Execution(format!( + "the node at {path} holds no window" + ))), + } + }; + metrics.record_input(1, positions); + if closing { + // A series closes exactly once, on the chunk carrying `is_last`. A window that decided + // 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.series.time.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)?; + } + // 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(); + } +} + +/// The run-time state of one execution of a bound tree. +/// +/// The state is keyed by tree position: the same positions [`metrics::walk`] derives, so a node's +/// state, its metrics and the name it is shown under cannot drift apart. Because none of it lives +/// on the tree, one compiled tree serves every execution that builds a state from it. +pub struct NativeExecutionState { + /// The tree's structure, flattened in traversal order. + nodes: Vec, + /// The position of each node, in the same order. + paths: Vec, + /// The per-node state, in the same order. + runtimes: Vec, + /// The index of every node, so a caller names a node the way the metrics do. + by_path: HashMap, + /// The index of the root node. + root: usize, + /// 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, +} + +impl NativeExecutionState { + /// Builds the state of one execution of `tree`. + /// + /// Every node registers its metrics in `set` under its position and partition, and every node + /// that buffers input gets its own reservation from `pool`. + pub fn try_new( + tree: &NativeTree, + pool: Arc, + metrics_set: &ExecutionPlanMetricsSet, + partition: usize, + ) -> Result { + // One traversal names and registers every node: the same walk `EXPLAIN` uses, so a node + // 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(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. + NativeExpr::Scalar(_) => { + unsupported.get_or_insert_with(|| not_implemented("Scalar", path)); + None + } + NativeExpr::Instant { .. } => { + unsupported.get_or_insert_with(|| not_implemented("Instant", path)); + None + } + NativeExpr::Aggregate { .. } => { + unsupported.get_or_insert_with(|| not_implemented("Aggregate", path)); + None + } + NativeExpr::Binary { .. } => { + unsupported.get_or_insert_with(|| not_implemented("Binary", path)); + None + } + }; + if let Some((tag, seed)) = plan { + pending.push(PendingNode { + tag, + path: path.clone(), + metrics: handles, + output_schema: node.output.samples().cloned(), + seed, + }); + } + }); + // 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. + if let Some(error) = unsupported { + 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. + let mut by_path = HashMap::with_capacity(pending.len()); + for (index, node) in pending.iter().enumerate() { + by_path.insert(node.path.clone(), index); + } + + let mut nodes = Vec::with_capacity(pending.len()); + let mut paths = Vec::with_capacity(pending.len()); + let mut runtimes = Vec::with_capacity(pending.len()); + for (index, node) in pending.iter().enumerate() { + let input = match node.tag { + NodeTag::Input => None, + NodeTag::Window | NodeTag::Map => { + let path = node.path.input(); + Some(*by_path.get(&path).ok_or_else(|| { + DataFusionError::Execution(format!( + "the native tree has no node at the input of {}", + node.path + )) + })?) + } + }; + let buffer = NodeBuffer::new(&node.path, Arc::clone(&node.metrics), &pool); + let mut runtime = NodeRuntime { + buffer, + queued: VecDeque::new(), + window: None, + map: None, + emitted: None, + }; + match &node.seed { + Seed::Input => {} + Seed::Map(ops) => { + let schema = node.output_schema.clone().ok_or_else(|| { + DataFusionError::Execution(format!( + "the map node at {} does not produce samples", + node.path + )) + })?; + runtime.map = Some(MapRuntime { + 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(|| { + DataFusionError::Execution(format!( + "the window at {} has no input", + node.path + )) + })?; + let input_schema = pending[child].output_schema.clone().ok_or_else(|| { + DataFusionError::Execution(format!( + "the window at {} consumes samples, but its input produces none", + node.path + )) + })?; + 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); + nodes.push(NodeSpec { + tag: node.tag, + input, + }); + paths.push(node.path.clone()); + runtimes.push(runtime); + } + + // The runtime's output is an evaluated chunk. Raw samples have no grid, and a scalar or + // aggregate state is not a query value, so neither can be the tree's answer. + match tree.root().output.samples() { + Some(schema) if schema.eval_grid.is_some() => {} + Some(_) => { + return Err(DataFusionError::Execution( + "the native runtime produces evaluated chunks, but the root of the tree \ + produces raw samples" + .to_string(), + )); + } + None => { + return Err(DataFusionError::Execution( + "the native runtime produces evaluated chunks, but the root of the tree \ + produces a scalar or aggregate state" + .to_string(), + )); + } + } + + // The supported nodes are unary, so a tree of them has exactly one input node; it is where + // the caller's chunks enter. + let root = *by_path.get(&NodePath::root()).ok_or_else(|| { + DataFusionError::Execution("the native tree has no root node".to_string()) + })?; + let source = nodes + .iter() + .position(|node| node.tag == NodeTag::Input) + .ok_or_else(|| { + DataFusionError::Execution("the native tree has no input node".to_string()) + })?; + let source_schema = pending[source].output_schema.clone().ok_or_else(|| { + DataFusionError::Execution(format!( + "the input node at {} does not produce samples", + pending[source].path + )) + })?; + Ok(Self { + nodes, + paths, + runtimes, + by_path, + root, + source, + source_is_evaluated: source_schema.eval_grid.is_some(), + }) + } + + /// The metrics of the node at `path`. + pub fn metrics(&self, path: &NodePath) -> Option<&Arc> { + let index = *self.by_path.get(path)?; + Some(&self.runtimes[index].buffer.metrics) + } + + /// The bytes this execution currently reserves from the pool. + pub fn reserved_bytes(&self) -> usize { + self.runtimes + .iter() + .map(|runtime| runtime.buffer.held) + .sum() + } + + /// The number of nodes this execution runs. + pub fn len(&self) -> usize { + self.nodes.len() + } + + /// Whether the tree this state was built from has no nodes at all. + pub fn is_empty(&self) -> bool { + 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(), + ) + } + + /// The bytes the label sets at `path` charge for, and the same figure walked in full. + /// + /// Test-only: the running total is only correct if folding one entry's change in agrees with + /// recounting the table, so a test compares the two after the table has changed shape. + #[cfg(test)] + fn emitted_charge_pair(&self, path: &NodePath) -> (usize, usize) { + let index = *self + .by_path + .get(path) + .expect("the path names a node of this tree"); + self.runtimes[index] + .emitted + .as_ref() + .map_or((0, 0), |emitted| { + (emitted.bytes(), emitted.bytes_recomputed()) + }) + } + + /// 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 + /// the series, so what is left to do is to check that every series did close, and to return + /// everything the execution reserved. + fn close(&mut self) -> Result<()> { + let mut result = Ok(()); + for runtime in &mut self.runtimes { + if let Some(window) = runtime.window.as_mut() + && let Err(error) = window.finish() + && result.is_ok() + { + result = Err(error); + } + runtime.release(); + } + result + } +} + +/// Drives one execution of a bound tree. +/// +/// The driver owns the state and nothing else: every decision a node makes was bound before the +/// tree existed, so a pull only reads the position and runs the bound operation. +pub struct NativeExecutor { + state: NativeExecutionState, + phase: Phase, +} + +/// Whether the execution can still produce chunks. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Phase { + /// Chunks may still be queued and pulled. + Running, + /// The input ended and every node closed. + Finished, + /// A chunk failed, so the tree stopped: the evaluators must not be reused after an error. + Failed(String), +} + +impl NativeExecutor { + /// Drives `state`, which was built from one execution's tree. + pub fn new(state: NativeExecutionState) -> Self { + Self { + state, + phase: Phase::Running, + } + } + + /// The state this driver runs. + pub fn state(&self) -> &NativeExecutionState { + &self.state + } + + /// Queues one raw source chunk. + pub fn push_raw(&mut self, chunk: RawSeriesChunk) -> Result<()> { + self.push_source(NativeChunk::Raw(chunk)) + } + + /// Queues one evaluated source chunk. + pub fn push_evaluated(&mut self, chunk: EvaluatedChunk) -> Result<()> { + self.push_source(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. + pub fn next_chunk(&mut self) -> Result> { + self.check_running()?; + let root = self.state.root; + let result = self.pull(root).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); + } + result + } + + /// Ends the input: drains what has settled, closes every node and releases every reservation. + pub fn finish(&mut self) -> Result> { + let mut drained = Vec::new(); + loop { + match self.next_chunk() { + Ok(Some(chunk)) => drained.push(chunk), + Ok(None) => break, + Err(error) => return Err(error), + } + } + match self.state.close() { + Ok(()) => { + self.phase = Phase::Finished; + Ok(drained) + } + Err(error) => { + self.stop(&error); + Err(error) + } + } + } + + /// The next chunk of the node at `index`. + fn pull(&mut self, index: usize) -> Result> { + let tag = self.state.nodes[index].tag; + let input = self.state.nodes[index].input; + match tag { + NodeTag::Input => self.state.runtimes[index].pop_source(), + NodeTag::Map => { + let child = input.ok_or_else(|| missing_input(tag))?; + // An operation that empties every position yields no chunk, and the map asks its + // input again rather than reporting a decision it did not make. + loop { + let Some(chunk) = self.pull(child)? else { + return Ok(None); + }; + if let Some(output) = self.map_node(index, chunk)? { + return Ok(Some(output)); + } + } + } + NodeTag::Window => { + let child = input.ok_or_else(|| missing_input(tag))?; + // A piece the window already decided goes out before more input is read, or a + // push that decides several runs would strand all but the first until the next + // push -- and the last of them would never leave at all. + if let Some(output) = self.take_window_output(index)? { + return Ok(Some(output)); + } + loop { + let Some(chunk) = self.pull(child)? else { + return Ok(None); + }; + if let Some(output) = self.window_node(index, chunk)? { + return Ok(Some(NativeChunk::Evaluated(output))); + } + // The push may have decided several pieces without handing one back; they go + // out before this window reads another chunk. + if let Some(output) = self.take_window_output(index)? { + return Ok(Some(output)); + } + } + } + } + } + + /// Maps one chunk the node at `index` pulled from its input. + fn map_node(&mut self, index: usize, chunk: NativeChunk) -> Result> { + let NativeChunk::Evaluated(chunk) = chunk else { + return Err(DataFusionError::Execution(format!( + "the map node at {} consumes an evaluated chunk, not raw samples", + self.state.paths[index] + ))); + }; + let path = &self.state.paths[index]; + let runtime = &mut self.state.runtimes[index]; + Ok(runtime.map(path, chunk)?.map(NativeChunk::Evaluated)) + } + + /// The next piece the window at `index` already decided, if it is holding one. + /// + /// The charge is recomputed here: the piece leaves the queue, so the bytes the node holds drop + /// by exactly that piece, and leaving the old figure in place would hold a reservation for + /// memory nothing is using. + fn take_window_output(&mut self, index: usize) -> Result> { + let path = &self.state.paths[index]; + let runtime = &mut self.state.runtimes[index]; + let Some(output) = runtime + .window + .as_mut() + .and_then(WindowRuntime::take_pending) + else { + return Ok(None); + }; + let metrics = Arc::clone(&runtime.buffer.metrics); + metrics.record_grid_points(output.series.time.len()); + metrics.record_output(1, valid_values(&output)); + runtime.track(path, &output)?; + let retained = runtime + .window + .as_ref() + .map_or(0, WindowRuntime::retained_bytes); + let emitted = runtime.emitted_bytes(); + runtime + .buffer + .hold_exactly(retained.saturating_add(emitted))?; + Ok(Some(NativeChunk::Evaluated(output))) + } + + /// Feeds one chunk to the window at `index`. + fn window_node(&mut self, index: usize, chunk: NativeChunk) -> Result> { + let path = &self.state.paths[index]; + let runtime = &mut self.state.runtimes[index]; + runtime.window(path, chunk) + } + + /// Queues a source chunk at the tree's input node. + fn push_source(&mut self, 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); + if let Err(error) = &result { + self.stop(error); + } + result + } + + /// Refuses to continue an execution that finished or stopped. + fn check_running(&self) -> Result<()> { + match &self.phase { + Phase::Running => Ok(()), + Phase::Finished => Err(DataFusionError::Execution( + "the native execution already finished".to_string(), + )), + Phase::Failed(reason) => Err(DataFusionError::Execution(format!( + "the native execution stopped after an earlier error: {reason}" + ))), + } + } + + /// Stops the execution, returning every byte it reserved to the pool. + /// + /// A stopped execution is not resumed: an evaluator that failed must not be reused, so the + /// chunks it already produced are the only ones the caller will see. + fn stop(&mut self, error: &DataFusionError) { + for runtime in &mut self.state.runtimes { + runtime.release(); + } + self.phase = Phase::Failed(error.to_string()); + } +} + +/// Maps one chunk with `ops`, keeping its axis and its closing. +/// +/// Mapping is point-wise over valued positions, so a chunk whose values survive keeps exactly the +/// rows it came with: a position no field fills is not a row of any chunk, and mapping does not +/// invent one. `None` means the operation emptied every position, which yields no chunk at all +/// unless this chunk closed its series: a closing chunk is still handed over, holding no position, +/// because a consumer tells "nothing more here" from "no more input" by that chunk alone. +fn map_chunk( + schema: &SeriesSchema, + chunk: &EvaluatedChunk, + ops: &[MathOp], +) -> Result> { + let mut series = chunk.series.clone(); + for &op in ops { + series = match map_math(schema, &series, op)? { + Some(mapped) => mapped, + // `clamp` with `max < min` is the empty vector: every position it held was decided and + // holds no value now, so there is no row to hand over. + None => { + return if chunk.is_last { + let empty = no_row_series(schema, &chunk.series)?; + EvaluatedChunk::try_new(empty, true).map(Some) + } else { + Ok(None) + }; + } + }; + } + EvaluatedChunk::try_new(series, chunk.is_last).map(Some) +} + +/// A series carrying the identity of `series` and no row at all. +/// +/// It is what a closing chunk holds when the operation emptied its input: the labels say which +/// series closed, and the axis is empty because no position holds a value. +fn no_row_series(schema: &SeriesSchema, series: &Series) -> Result { + let grid = series.time.grid().ok_or_else(|| { + DataFusionError::Execution("a mapped chunk must be addressed on a grid".to_string()) + })?; + let fields = (0..schema.fields.len()) + .map(|_| Samples::from_float(Float64Array::from(Vec::::new()))) + .collect(); + let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?; + let metric = drop_metric_name(&series.metric)?; + let at = series.time.last_position().map_or(0, |last| last + 1); + let time = GridRange::try_new(Arc::clone(grid), at, 0).map_err(series_error)?; + Series::try_new(schema, metric, TimeAxis::Grid(time), fields).map_err(series_error) +} + +/// The valid values a chunk holds: one per valid field sample. +fn valid_values(chunk: &EvaluatedChunk) -> usize { + chunk + .series + .fields + .iter() + .map(|field| { + field + .iter() + .filter(|sample| !matches!(sample, SampleRef::Missing)) + .count() + }) + .sum() +} + +/// 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 +/// the same node, so a reader can find it in the tree. +fn not_implemented(kind: &str, path: &NodePath) -> DataFusionError { + DataFusionError::NotImplemented(format!( + "the native runtime does not execute {kind} nodes yet: {kind} at {path}" + )) +} + +/// The error for a window whose evaluator this execution already closed. +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!( + "the native tree has no input for a {} node", + tag.describe() + )) +} + +fn series_error(error: datatypes::error::Error) -> DataFusionError { + DataFusionError::External(Box::new(error)) +} diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs new file mode 100644 index 00000000000..33665429bf2 --- /dev/null +++ b/src/promql/src/native/execute/tests.rs @@ -0,0 +1,1893 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! What the runtime has to get right: each layer's grid, per-node accounting, rejection and +//! release. + +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; +use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; +use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; +use datatypes::series::samples::{ + FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, +}; +use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis}; +use datatypes::series::{Label, MetricName, SeriesOrdering}; + +use super::{NativeExecutionState, NativeExecutor, map_chunk}; +use crate::evaluated::EvaluatedChunk; +use crate::map::MathOp; +use crate::native::metrics::{NodeMetric, NodePath}; +use crate::native::plan::{ + AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, + BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, +}; +use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow}; +use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels}; + +fn grid(start: i64, step: i64, len: u64) -> Arc { + Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) +} + +fn fields() -> Arc<[FieldSpec]> { + 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, + eval_grid: None, + }) +} + +fn evaluated_schema(grid: Arc) -> Arc { + Arc::new(SeriesSchema { + fields: fields(), + eval_grid: Some(grid), + }) +} + +fn evaluated(grid: Arc) -> NativeType { + NativeType::Samples(evaluated_schema(grid)) +} + +fn metric() -> MetricName { + MetricName::try_new(Some("requests".into()), Vec::new()).unwrap() +} + +/// The raw source every supported tree starts from. +fn input() -> NativeNode { + let output = NativeType::Samples(raw_schema()); + NativeNode { + expr: NativeExpr::Input(BoundInput { + output: output.clone(), + ordering: SeriesOrdering::KeyThenTime, + }), + output, + } +} + +/// 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(), + ordering: SeriesOrdering::KeyThenTime, + }), + output, + } +} + +/// 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, + RangeFunction::LastOverTime, + 300_000, + None, + output_grid, + ) +} + +fn window_with( + inner: NativeNode, + function: RangeFunction, + range_ms: i64, + input_grid: Option>, + output_grid: Arc, +) -> NativeNode { + NativeNode { + expr: NativeExpr::Window { + input: Box::new(inner), + op: BoundWindow { + function, + window: RangeWindow { + range_ms, + offset_ms: 0, + anchor_ms: None, + }, + input_grid, + output_grid: Arc::clone(&output_grid), + }, + }, + output: evaluated(output_grid), + } +} + +/// 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 { + expr: NativeExpr::Map { + input: Box::new(inner), + op: BoundMap { ops: ops.into() }, + }, + output: evaluated(output), + } +} + +fn scalar(value: f64, grid: Arc) -> NativeNode { + NativeNode { + expr: NativeExpr::Scalar(BoundScalar { value }), + output: NativeType::Scalar(grid), + } +} + +fn raw_chunk( + schema: &SeriesSchema, + timestamps: &[i64], + 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(), + fields, + is_last, + ) + .unwrap() +} + +/// One evaluated chunk of an input series: `values` at `start` and onwards on `schema`'s grid. +fn evaluated_chunk( + schema: &SeriesSchema, + 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, + 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, + set: &ExecutionPlanMetricsSet, +) -> NativeExecutor { + NativeExecutor::new(NativeExecutionState::try_new(tree, pool, set, 0).unwrap()) +} + +/// Pulls until the tree has nothing settled, then closes it. +fn run(executor: &mut NativeExecutor) -> Vec { + let mut out = Vec::new(); + while let Some(chunk) = executor.next_chunk().unwrap() { + out.push(chunk); + } + out.extend(executor.finish().unwrap()); + out +} + +fn sample_values(chunk: &EvaluatedChunk) -> Vec> { + let field = chunk + .series + .fields + .get(0) + .expect("these series have one field"); + field + .iter() + .map(|sample| match sample { + SampleRef::Float(value) => Some(value), + _ => None, + }) + .collect() +} + +fn series_start(chunk: &EvaluatedChunk) -> usize { + chunk + .series + .time + .first_position() + // An empty chunk carries no row, but where it sits is still what it addresses: a closing + // chunk that holds nothing is handed over exactly so the consumer learns it closed. + .or_else(|| chunk.series.time.as_grid_range().map(GridRange::start)) + .expect("every chunk in these tests is addressed on a grid") +} + +/// The absolute start and the values of every chunk, which is what addressing means here. +fn addressed(chunks: &[EvaluatedChunk]) -> Vec<(usize, Vec>)> { + chunks + .iter() + .map(|chunk| (series_start(chunk), sample_values(chunk))) + .collect() +} + +/// Every decided position of a chunk stream with its value, in absolute grid order. +/// +/// Two streams that decided the same positions hold the same result however they were split into +/// chunks, which is what "the same series, delivered differently" means. +/// +/// The positions come from the axis, not from the chunk's start plus a row number: a chunk whose +/// rows form several runs carries them at absolute positions that are not adjacent, so adding the +/// row to the start would name positions the chunk does not hold. +fn decided(chunks: &[EvaluatedChunk]) -> Vec<(usize, Option)> { + chunks + .iter() + .flat_map(|chunk| { + let values = sample_values(chunk); + chunk + .series + .time + .positions() + .map(|(position, row)| { + ( + position, + *values.get(row).expect("one value per carried row"), + ) + }) + .collect::>() + }) + .collect() +} + +fn count(set: &ExecutionPlanMetricsSet, path: &NodePath, metric: &str) -> usize { + let name = path.metric_name(metric); + match set.clone_inner().sum_by_name(&name) { + Some(MetricValue::Count { count, .. }) => count.value(), + other => panic!("no count named {name}: {other:?}"), + } +} + +fn gauge(set: &ExecutionPlanMetricsSet, name: &str) -> usize { + match set.clone_inner().sum_by_name(name) { + Some(MetricValue::Gauge { gauge, .. }) => gauge.value(), + other => panic!("no gauge named {name}: {other:?}"), + } +} + +/// A window over raw input evaluates onto its own output grid, and its values are the evaluator's. +/// +/// The grid is compared by allocation identity, so a window that evaluated on a copy of its +/// output grid — the same timestamps, a different grid — fails here even though every value and +/// every timestamp would still look right. +#[test] +fn a_window_over_raw_input_evaluates_onto_its_own_grid() { + let out_grid = grid(0, 60_000, 4); + let tree = NativeTree::try_new(window(input(), Arc::clone(&out_grid))).unwrap(); + let schema = raw_schema(); + let chunk = raw_chunk( + &schema, + &[0, 60_000, 120_000, 180_000, 240_000], + &[1.0, 2.0, 3.0, 4.0, 5.0], + true, + ); + + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution.push_raw(chunk.clone()).unwrap(); + let out = run(&mut execution); + + // The same samples, evaluated by the evaluator this runtime wraps. + let mut evaluator = RangeEvaluator::try_new( + &schema, + Arc::clone(&out_grid), + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::LastOverTime, + ) + .unwrap(); + let expected: Vec<(usize, Vec>)> = evaluator + .push(&chunk) + .unwrap() + .iter() + .map(|produced| (series_start(produced), sample_values(produced))) + .collect(); + evaluator.finish().unwrap(); + + assert_eq!(out.len(), 1, "one closed series, one chunk"); + for chunk in &out { + 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 window's output grid" + ); + assert_eq!( + chunk.series.time.grid().expect("a grid chunk").spec(), + out_grid.spec() + ); + assert!(chunk.is_last); + } + assert_eq!( + addressed(&out), + vec![(0, vec![Some(1.0), Some(2.0), Some(3.0), Some(4.0)])] + ); + assert_eq!(addressed(&out), expected); +} + +/// `Window -> Map -> Window` keeps the inner grid inside and the outer grid outside. +/// +/// The inner window runs on a 60 s grid and the outer one on a 90 s grid offset by 30 s, so a +/// layer that resampled onto its consumer's grid would change the addressing of every chunk and +/// the values of the last one. +#[test] +fn a_window_map_window_chain_keeps_each_layer_on_its_own_grid() { + let inner_grid = grid(0, 60_000, 5); + let outer_grid = grid(30_000, 90_000, 3); + let inner = || { + window_with( + input(), + RangeFunction::LastOverTime, + 120_000, + None, + Arc::clone(&inner_grid), + ) + }; + let mapped = || map(inner(), vec![MathOp::Abs]); + let chain = || { + window_with( + map(inner(), vec![MathOp::Abs]), + RangeFunction::LastOverTime, + 240_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + ) + }; + let schema = raw_schema(); + let chunk = raw_chunk( + &schema, + &[0, 60_000, 120_000, 180_000, 240_000], + &[-1.0, -2.0, -3.0, -4.0, -5.0], + true, + ); + + // Down to the map, on its own: the map's chunks stay addressed on the inner window's grid. + let map_tree = NativeTree::try_new(mapped()).unwrap(); + let mut map_execution = executor(&map_tree, pool(), &ExecutionPlanMetricsSet::new()); + map_execution.push_raw(chunk.clone()).unwrap(); + let mapped_chunks = run(&mut map_execution); + assert_eq!(mapped_chunks.len(), 1); + for chunk in &mapped_chunks { + assert!( + Arc::ptr_eq(chunk.series.time.grid().expect("a grid chunk"), &inner_grid), + "the map handed over a chunk that is not addressed on the inner grid" + ); + } + assert_eq!(mapped_chunks[0].series.time.len(), 5); + assert_eq!( + addressed(&mapped_chunks), + vec![( + 0, + vec![Some(1.0), Some(2.0), Some(3.0), Some(4.0), Some(5.0)] + )] + ); + + // The whole chain: only the outer window's grid leaves the tree. + let chain_tree = NativeTree::try_new(chain()).unwrap(); + let mut chain_execution = executor(&chain_tree, pool(), &ExecutionPlanMetricsSet::new()); + chain_execution.push_raw(chunk.clone()).unwrap(); + let out = run(&mut chain_execution); + assert_eq!(out.len(), 1); + for chunk in &out { + assert!( + Arc::ptr_eq(chunk.series.time.grid().expect("a grid chunk"), &outer_grid), + "the chain handed over a chunk that is not addressed on the outer grid" + ); + } + assert_eq!(out[0].series.time.len(), 3); + assert_eq!( + addressed(&out), + vec![(0, vec![Some(1.0), Some(3.0), Some(4.0)])] + ); + + // The same chain driven by hand, one kernel at a time. + let mut inner_evaluator = RangeEvaluator::try_new( + &schema, + Arc::clone(&inner_grid), + RangeWindow { + range_ms: 120_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::LastOverTime, + ) + .unwrap(); + let inner_series = inner_evaluator.push(&chunk).unwrap().unwrap(); + inner_evaluator.finish().unwrap(); + let map_schema = evaluated_schema(Arc::clone(&inner_grid)); + let mapped_chunk = map_chunk(&map_schema, &inner_series, &[MathOp::Abs]) + .unwrap() + .expect("`abs` maps every position, so the chunk keeps its rows"); + assert!( + Arc::ptr_eq( + mapped_chunk.series.time.grid().expect("a grid chunk"), + &inner_grid + ), + "the map kernel moved the inner grid" + ); + let mut outer_evaluator = RangeEvaluator::try_new( + &map_schema, + Arc::clone(&outer_grid), + RangeWindow { + range_ms: 240_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::LastOverTime, + ) + .unwrap(); + let outer_series = outer_evaluator + .push_series(&mapped_chunk.series, mapped_chunk.is_last) + .unwrap() + .unwrap(); + outer_evaluator.finish().unwrap(); + assert_eq!( + addressed(&out), + vec![(series_start(&outer_series), sample_values(&outer_series))] + ); +} + +/// A window over an evaluated input reports a decision before its input series has ended. +/// +/// The inner series arrives in two pieces and the window is pulled after the first one, so the +/// outer grid point whose window that piece settled has to come out then. A layer that collected +/// the pieces into a whole series first could not produce anything here: its first answer would +/// only exist once the piece carrying `is_last` had arrived, and the bytes of the whole series +/// would be held until then. +#[test] +fn a_downstream_window_emits_before_its_input_series_ends() { + // 60 s inner grid, 120 s outer grid, so the inner series settles outer points as it arrives. + let inner_grid = grid(0, 60_000, 5); + let outer_grid = grid(0, 120_000, 3); + let tree = NativeTree::try_new(window_with( + evaluated_input(Arc::clone(&inner_grid)), + RangeFunction::LastOverTime, + 240_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + + // The first piece covers inner positions 0..3; the series is still open after it. + let head = evaluated_chunk(&schema, 0, vec![1.0, 2.0, 3.0], false); + let tail = evaluated_chunk(&schema, 3, vec![4.0, 5.0], true); + + let set = ExecutionPlanMetricsSet::new(); + let mut execution = executor(&tree, pool(), &set); + execution.push_evaluated(head).unwrap(); + + let mut early = Vec::new(); + while let Some(chunk) = execution.next_chunk().unwrap() { + early.push(chunk); + } + assert!( + !early.is_empty(), + "the outer window buffered its input: nothing came out before the series ended" + ); + // The piece settled outer points 0 and 1: their windows end inside it, at the inner values + // 1.0 and 3.0. + assert_eq!( + decided(&early), + vec![(0, Some(1.0)), (1, Some(3.0))], + "the outer window did not report the points its input had already settled" + ); + for chunk in &early { + assert!( + !chunk.is_last, + "the series cannot close before its last piece" + ); + } + // The open outer series is still accounted for: the pieces handed over are what it holds. + assert_eq!( + count(&set, &NodePath::root(), NodeMetric::COMPLETED_SERIES), + 0, + "a series closed before its last piece arrived" + ); + + // The closing piece: the rest of the outer grid, and the one chunk that closes the series. + execution.push_evaluated(tail).unwrap(); + let mut out = early; + while let Some(chunk) = execution.next_chunk().unwrap() { + out.push(chunk); + } + out.extend(execution.finish().unwrap()); + assert_eq!( + decided(&out), + vec![(0, Some(1.0)), (1, Some(3.0)), (2, Some(5.0)),] + ); + assert_eq!(out.iter().filter(|chunk| chunk.is_last).count(), 1); + assert!(out.last().unwrap().is_last); + assert_eq!( + count(&set, &NodePath::root(), NodeMetric::COMPLETED_SERIES), + 1, + "the outer series closed once per piece instead of once in total" + ); + + // The same chain with the whole series in one piece answers exactly the same. + let whole_tree = NativeTree::try_new(window_with( + evaluated_input(Arc::clone(&inner_grid)), + RangeFunction::LastOverTime, + 240_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(); + let mut whole = executor(&whole_tree, pool(), &ExecutionPlanMetricsSet::new()); + whole + .push_evaluated(evaluated_chunk( + &schema, + 0, + vec![1.0, 2.0, 3.0, 4.0, 5.0], + true, + )) + .unwrap(); + let whole = run(&mut whole); + assert_eq!(decided(&out), decided(&whole)); + for chunk in &whole { + assert!( + Arc::ptr_eq(chunk.series.time.grid().expect("a grid chunk"), &outer_grid), + "the chain handed over a chunk that is not addressed on the outer grid" + ); + } +} + +/// Every node kind the runtime does not execute is rejected, naming the kind and its position. +#[test] +fn an_unimplemented_node_is_reported_not_panicked() { + // One grid shared by the nodes that validate by allocation identity. + 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 { + expr: NativeExpr::Aggregate { + input: Box::new(window(input(), Arc::clone(&out))), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Grouping::By(Arc::new(["job".into()])), + stage: AggregateStage::Complete, + }, + }, + output: NativeType::Samples(evaluated_schema(out)), + } + }; + let binary_tree = { + let out = statement(); + NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window(input(), Arc::clone(&out))), + right: Box::new(scalar(1.0, Arc::clone(&out))), + matching: BinaryMatching { + op: BinaryOp::Add, + return_bool: false, + labels: MatchingLabels::Ignoring(Vec::new()), + cardinality: Cardinality::OneToOne, + }, + }, + output: NativeType::Samples(evaluated_schema(out)), + } + }; + + let cases = [ + ("Scalar", "root", scalar_tree), + ("Instant", "root.input", instant_tree), + ("Aggregate", "root", aggregate_tree), + ("Binary", "root", binary_tree), + ]; + for (kind, path, root) in cases { + // Legality stays `validate`'s: the plan accepts these trees, the runtime does not run them. + let tree = NativeTree::try_new(root).expect("the bound tree is legal"); + let error = match NativeExecutionState::try_new( + &tree, + pool(), + &ExecutionPlanMetricsSet::new(), + 0, + ) { + Ok(_) => panic!("the runtime accepted a {kind} node"), + Err(error) => error, + }; + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "{kind}: {error}" + ); + let message = error.to_string(); + assert!(message.contains(kind), "{kind}: {message}"); + assert!(message.contains(&format!("at {path}")), "{message}"); + } +} + +/// Each node reports its own chunks, grid points and closed series, at its own position. +/// +/// The two windows decide different traffic — the inner one four grid points of its own grid, the +/// outer one two of its own — so a single total for the tree cannot produce both numbers. They take +/// and hand over the same number of chunks, which is what streaming means here: a node passes on one +/// chunk per chunk it took in, instead of holding its input until a whole series is available. +#[test] +fn each_node_records_its_own_metrics() { + let inner_grid = grid(0, 60_000, 4); + let outer_grid = grid(0, 120_000, 2); + let root = window_with( + window_with( + input(), + RangeFunction::LastOverTime, + 300_000, + None, + Arc::clone(&inner_grid), + ), + RangeFunction::LastOverTime, + 300_000, + Some(inner_grid), + outer_grid, + ); + let tree = NativeTree::try_new(root).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], &[1.0, 2.0], false)) + .unwrap(); + execution + .push_raw(raw_chunk(&schema, &[120_000], &[3.0], false)) + .unwrap(); + execution + .push_raw(raw_chunk(&schema, &[180_000], &[4.0], true)) + .unwrap(); + let out = run(&mut execution); + // The outer window reports each point as the inner one settles it: one chunk per inner chunk, + // and an empty chunk that closes the series. + assert_eq!( + addressed(&out), + vec![(0, vec![Some(1.0)]), (1, vec![Some(3.0)]), (2, Vec::new()),] + ); + assert!(out.last().unwrap().is_last); + + let outer = NodePath::root(); + let inner = outer.input(); + let source = inner.input(); + + // Three source chunks reach the inner window, and the chunks it hands over reach the outer one + // one for one, because neither window buffers. + assert_eq!(count(&set, &source, NodeMetric::INPUT_BATCHES), 3); + assert_eq!(count(&set, &source, NodeMetric::OUTPUT_BATCHES), 3); + assert_eq!(count(&set, &inner, NodeMetric::INPUT_BATCHES), 3); + assert_eq!(count(&set, &outer, NodeMetric::INPUT_BATCHES), 3); + assert_eq!(count(&set, &inner, NodeMetric::OUTPUT_BATCHES), 3); + assert_eq!(count(&set, &outer, NodeMetric::OUTPUT_BATCHES), 3); + // The grid points each window decided, which is its own output range: four on the inner grid + // and two on the outer one, which is the figure that tells the two nodes apart. + assert_eq!(count(&set, &inner, NodeMetric::EVALUATED_GRID_POINTS), 4); + assert_eq!(count(&set, &outer, NodeMetric::EVALUATED_GRID_POINTS), 2); + // The one series closes once, on the chunk carrying `is_last`. + assert_eq!(count(&set, &source, NodeMetric::COMPLETED_SERIES), 1); + assert_eq!(count(&set, &inner, NodeMetric::COMPLETED_SERIES), 1); + assert_eq!(count(&set, &outer, NodeMetric::COMPLETED_SERIES), 1); + // Per node, not one total for the tree. + assert_ne!( + count(&set, &inner, NodeMetric::EVALUATED_GRID_POINTS), + count(&set, &outer, NodeMetric::EVALUATED_GRID_POINTS) + ); +} + +/// An error returns the reservation while the execution is still alive, and a drop returns it too. +#[test] +fn an_error_releases_the_reservation() { + let tree = NativeTree::try_new(window(input(), grid(0, 60_000, 4))).unwrap(); + let pool = pool(); + let set = ExecutionPlanMetricsSet::new(); + let schema = raw_schema(); + + 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(); + assert!( + pool.reserved() > 0, + "the queued chunk has to be reserved for" + ); + // The chunk settles the first grid points, so it comes out; the series it belongs to has not + // ended, so the node still holds what it buffered for it. + let settled = execution.next_chunk().unwrap(); + assert!( + settled.is_some_and(|chunk| !chunk.is_last), + "a chunk that does not close its series was reported as closing it" + ); + let held = pool.reserved(); + assert!(held > 0, "the open series has to be reserved for"); + + // A second chunk of the same series whose timestamps do not increase: the evaluator rejects it + // after the node already held input for it. + execution + .push_raw(raw_chunk(&schema, &[0, 60_000], &[3.0, 4.0], true)) + .unwrap(); + let error = execution.next_chunk().unwrap_err(); + assert!(error.to_string().contains("not increasing"), "{error}"); + // Everything went back to the pool while the execution is alive: waiting for the drop would + // 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); + assert!(gauge(&set, &peak) >= held); + // A stopped execution is not resumed. + let again = execution.next_chunk().unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); + + // Dropping an execution that never finished returns its bytes too. + let mut unfinished = executor(&tree, Arc::clone(&pool), &set); + unfinished + .push_raw(raw_chunk(&schema, &[0], &[1.0], false)) + .unwrap(); + let _ = unfinished.next_chunk().unwrap(); + assert!( + pool.reserved() > 0, + "the open series has to be reserved for" + ); + 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.series.time.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), + )); + // A window directly over an interleaved source is rejected when the tree is bound: the + // binding is where the ordering is known, and refusing there fails before a chunk is read. + let error = tree.expect_err("a window over an interleaved input must not bind"); + let message = error.to_string(); + assert!(message.contains("interleaved"), "{message}"); + assert!(message.contains("window"), "{message}"); + + // A map between them is not caught by the binding, which only looks at a window's own input: + // the map passes chunks through in the order they arrive, so the window still reads an + // interleaved stream. That is what this runtime checks for itself. + let tree = NativeTree::try_new(window_with( + map( + evaluated_input_with_ordering(Arc::clone(&inner_grid), SeriesOrdering::Interleaved), + vec![MathOp::Abs], + ), + RangeFunction::LastOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .expect("the binding accepts a window over a map"); + 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)]), + ] + ); +} + +/// The charge for the label sets a node has handed out does not depend on how it is read. +/// +/// The table only grows, so the figure is folded in as each entry changes rather than walked after +/// every output. Folding it wrong would show up as a running total that drifts from the same figure +/// recounted in full, so both are compared after every chunk: distinct label sets add entries, and +/// later chunks of one set grow its run vectors and the table's own capacity. +#[test] +fn the_emitted_charge_is_the_same_folded_in_as_walked() { + let grid = grid(0, 60_000, 4); + let tree = + NativeTree::try_new(map(evaluated_input(Arc::clone(&grid)), vec![MathOp::Abs])).unwrap(); + let schema = evaluated_schema(Arc::clone(&grid)); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + + let chunks = [ + ("a", "x", 0, vec![Some(-1.0), None, Some(-2.0), None], false), + ("a", "x", 0, vec![None, Some(-3.0), None, None], true), + ("b", "y", 0, vec![None, None, None, Some(-4.0)], true), + ( + "c", + "z", + 0, + vec![Some(-5.0), Some(-6.0), Some(-7.0), Some(-8.0)], + true, + ), + ]; + for (name, job, start, values, is_last) in chunks { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, job), + start, + values, + is_last, + )) + .unwrap(); + while execution.next_chunk().unwrap().is_some() {} + let (folded, walked) = execution.state().emitted_charge_pair(&NodePath::root()); + assert!(folded > 0, "the node handed out nothing to charge for"); + assert_eq!( + folded, walked, + "the folded charge of {folded} bytes is not the {walked} bytes the table holds" + ); + } +} + +/// 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. +/// +/// This is the other order of [`two_series_with_no_result_do_not_collide`], and the one that used to +/// fail: by the time the empty series arrives the label set is already closed, and refusing it +/// failed an execution whose answer was never in doubt. +#[test] +fn a_series_with_no_result_after_a_closed_one_is_passed_over() { + let map_grid = grid(0, 60_000, 1); + 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()); + + // `abs` drops the name, so both series arrive under the same label set. The first holds a + // value; the second holds none at all and has to be passed over rather than refused. + for (name, values) in [("a", vec![Some(-7.0)]), ("b", vec![None])] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, "x"), + 0, + values, + true, + )) + .unwrap(); + } + + let mut handed = Vec::new(); + loop { + match execution.next_chunk() { + Ok(Some(chunk)) => handed.push(decided(&[chunk])), + Ok(None) => break, + Err(error) => panic!("an empty series after a closed one was refused: {error}"), + } + } + assert!( + handed + .iter() + .flatten() + .any(|(_, value)| *value == Some(7.0)), + "the first series' value is missing: {handed:?}" + ); +} + +/// Two series that each produce no value at all are not a collision: both answer empty, and the +/// node hands nothing on rather than refusing the second one. +/// +/// `rate` over a five-minute window with one sample in it has no result, in the single-point and +/// the batch kernel alike. Both series then arrive as a closing chunk of missing values under the +/// same label set -- `rate` drops the name -- but neither holds a sample, so there is nothing to +/// report twice and nothing to merge. +#[test] +fn two_series_with_no_result_do_not_collide() { + let out = grid(0, 60_000, 1); + let tree = NativeTree::try_new(window_with( + input(), + RangeFunction::Rate, + 300_000, + None, + Arc::clone(&out), + )) + .unwrap(); + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + + // One sample each: rate over a 5m window with a single sample has no result. + for name in ["a", "b"] { + execution + .push_raw(raw_chunk_of( + &schema, + name.as_bytes(), + MetricName::try_new(Some(name.into()), vec![]).unwrap(), + &[0], + &[1.0], + true, + )) + .unwrap(); + } + let mut handed = Vec::new(); + loop { + match execution.next_chunk() { + Ok(Some(chunk)) => handed.push(decided(&[chunk])), + Ok(None) => break, + Err(error) => panic!("two empty series were refused: {error}"), + } + } + assert!( + handed.iter().flatten().all(|(_, value)| value.is_none()), + "a series with no result handed a value on: {handed:?}" + ); +} + +/// A chunk of `metric` whose rows are the `spans` of `schema`'s grid, with `values` row by row. +/// +/// This is what a producer that decided only some positions hands over: the rows are absolute grid +/// positions and need not be adjacent, so a consumer that reads them as `start + row` names +/// positions the chunk does not hold. +fn sparse_chunk( + schema: &SeriesSchema, + metric: MetricName, + spans: &[(usize, usize)], + values: Vec, + is_last: bool, +) -> EvaluatedChunk { + let samples = Samples::from_float(Float64Array::from(values)); + let time = TimeAxis::from_grid_spans( + Arc::clone(schema.eval_grid.as_ref().unwrap()), + spans + .iter() + .map(|&(start, len)| GridSpan::new(start, len)) + .collect(), + ) + .unwrap(); + let series = Series { + metric, + time, + fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), + }; + EvaluatedChunk::try_new(series, is_last).unwrap() +} + +#[test] +fn a_sparse_chunk_is_read_at_the_positions_it_holds_through_window_map_window() { + // An inner series that decided positions 0, 1 and 5, 6 of an eight-point grid and left the + // positions between them empty: two runs, not six rows with holes. + let inner_grid = grid(0, 60_000, 8); + let middle_grid = grid(0, 60_000, 8); + let outer_grid = grid(0, 120_000, 4); + let tree = NativeTree::try_new(window_with( + map( + window_with( + evaluated_input(Arc::clone(&inner_grid)), + RangeFunction::LastOverTime, + // One step exactly, so the window is the identity: each point reads the sample at + // its own position and nothing else. + 60_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&middle_grid), + ), + vec![MathOp::Abs], + ), + RangeFunction::LastOverTime, + 240_000, + Some(Arc::clone(&middle_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + let chunk = sparse_chunk( + &schema, + metric(), + &[(0, 2), (5, 2)], + vec![1.0, 2.0, 3.0, 4.0], + true, + ); + + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution.push_evaluated(chunk).unwrap(); + let out = run(&mut execution); + + // The outer window's points: every one of them has a sample in its range, so every one holds + // the last value its window saw. 4.0 sits at 360 s, inside the window that ends there, which + // is why the sparse tail is not lost between the runs. + assert_eq!( + decided(&out), + vec![ + (0, Some(1.0)), + (1, Some(2.0)), + (2, Some(2.0)), + (3, Some(4.0)), + ] + ); + assert_eq!(out.iter().filter(|chunk| chunk.is_last).count(), 1); +} + +#[test] +fn a_sparse_chunk_occupies_only_the_positions_it_holds() { + let map_grid = grid(0, 60_000, 8); + 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()); + // Series a holds positions 0, 1 and 5, 6: two runs with a hole in the middle, not one run + // covering the hole. + execution + .push_evaluated(sparse_chunk( + &schema, + named_metric("a", "x"), + &[(0, 2), (5, 2)], + vec![-1.0, -2.0, -3.0, -4.0], + false, + )) + .unwrap(); + execution + .next_chunk() + .unwrap() + .expect("the first open chunk is handed on as it arrives"); + + // Position 2 sits in the hole, so series b occupies it and collides with nothing a holds. + execution + .push_evaluated(sparse_chunk( + &schema, + named_metric("b", "x"), + &[(2, 1)], + vec![-5.0], + true, + )) + .unwrap(); + execution + .next_chunk() + .unwrap_or_else(|error| panic!("the series in the hole was refused: {error}")) + .expect("the second series is handed on"); +} diff --git a/src/promql/src/native/mod.rs b/src/promql/src/native/mod.rs index e843c0169be..c9545a9fe69 100644 --- a/src/promql/src/native/mod.rs +++ b/src/promql/src/native/mod.rs @@ -29,5 +29,6 @@ pub mod batch; mod display; +pub mod execute; pub mod metrics; pub mod plan; diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index 428f9f0f9af..6b3b7667b03 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -190,6 +190,30 @@ impl PendingBatch { self.eval_ts.is_empty() } + /// The bytes this batch's own vectors hold, by capacity. + fn bytes(&self) -> usize { + let spans = self + .spans + .iter() + .map(|spans| spans.capacity() * std::mem::size_of::>()) + .fold(0usize, usize::saturating_add); + let columns = self + .columns + .iter() + .map(|column| column.capacity() * std::mem::size_of::>()) + .fold(0usize, usize::saturating_add); + self.indices + .capacity() + .saturating_mul(std::mem::size_of::()) + .saturating_add( + self.eval_ts + .capacity() + .saturating_mul(std::mem::size_of::()), + ) + .saturating_add(spans) + .saturating_add(columns) + } + /// Drops the accumulated points, keeping the allocations. fn clear_points(&mut self) { self.indices.clear(); @@ -276,6 +300,27 @@ struct SeriesState { emitted_end: usize, } +impl SeriesState { + /// The bytes this series' identity holds, which the rows handed out do not cover. + fn identity_bytes(&self) -> usize { + let primary_key = self.primary_key.as_ref().map_or(0, |key| key.len()); + let metric: usize = self + .metric + .name() + .map_or(0, |name| name.len()) + .saturating_add( + self.metric + .tags() + .iter() + .map(|tag| tag.name.len() + tag.value.len()) + .fold(0usize, usize::saturating_add), + ); + std::mem::size_of::() + .saturating_add(primary_key) + .saturating_add(metric) + } +} + /// 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 @@ -334,6 +379,28 @@ fn resets_between(resets: &[CounterReset], start: u64, end: u64) -> &[CounterRes } impl FieldSamples { + /// The bytes this field's buffers hold, by capacity. + fn bytes(&self) -> usize { + self.timestamps + .capacity() + .saturating_mul(std::mem::size_of::()) + .saturating_add( + self.values + .capacity() + .saturating_mul(std::mem::size_of::()), + ) + .saturating_add( + self.histograms + .capacity() + .saturating_mul(std::mem::size_of::<(i64, FloatHistogram)>()), + ) + .saturating_add( + self.resets + .capacity() + .saturating_mul(std::mem::size_of::()), + ) + } + fn new(index_resets: bool) -> Self { Self { index_resets, @@ -534,6 +601,33 @@ impl RangeEvaluator { self.batch_calls } + /// An accounted lower bound on the bytes this evaluator keeps between pushes. + /// + /// Counted by capacity, so it is what the storage holds rather than what it uses: the retained + /// samples per field (timestamps, values and native histograms), the reset index, the row a push + /// fills, and the pending batch's own vectors. Left out are the kernel's scratch buffers, this + /// struct's `Vec` headers and the grid, which every chunk addressed on it shares. + /// + /// A push is the only caller that also holds the incoming chunk, and it charges that itself for + /// as long as the call runs; vector growth during a push is neither reserved nor bounded by one + /// doubling, so this is the storage's size, not a peak over the push. The figure must not be + /// per-chunk either: charging every chunk consumed would make the charge grow with the chunk + /// count, so a fixed window over a long series would read as an allocation failure even though + /// the window holds no more samples. + pub(crate) fn retained_bytes(&self) -> usize { + let per_field = self + .fields + .iter() + .map(FieldSamples::bytes) + .fold(0usize, usize::saturating_add); + let row = self.row.capacity() * std::mem::size_of::>(); + let series = self.series.as_ref().map_or(0, SeriesState::identity_bytes); + per_field + .saturating_add(row) + .saturating_add(series) + .saturating_add(self.pending.bytes()) + } + /// Schema of the evaluated series: the input fields on the evaluation grid. pub fn output_schema(&self) -> &Arc { &self.output_schema From e75af676b8ba9030aacc527c28dc0a72c20ea228 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:59:07 +0800 Subject: [PATCH 02/33] refactor(promql): drop the window queue the sparse evaluator never needed `RangeEvaluator::push` and `push_series` each return `Result>`: the evaluator gathers every run it decided into one chunk and hands back at most one. So `pending.extend(decided)` inserted at most one chunk and `take_pending` removed it on the spot, leaving the queue empty after every successful push. That makes the queue dead weight: a `VecDeque` allocation per productive window, an accounting term that is always zero, a second drain site in `pull`, and doc comments claiming a problem the API does not have. The driver's "ask the input again when a window decides nothing" loop was already the whole story. Back to returning the evaluator's own answer, and drop `pending`, `take_pending` and `take_window_output`. Covers the empty-map protocol this port introduces while it is here: an operation that empties every position hands on nothing while its series is open, and one empty chunk when it closes. A non-closing empty chunk would be rejected downstream and a dropped closing one would leave the series unclosed. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 73 +++----------------------- src/promql/src/native/execute/tests.rs | 56 ++++++++++++++++++++ 2 files changed, 62 insertions(+), 67 deletions(-) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 8b9e07df75f..aa68bbdd8b8 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -502,12 +502,6 @@ struct MapRuntime { struct WindowRuntime { /// This window's own evaluator, with its own input and output grid; `None` once closed. evaluator: Option, - /// The pieces the evaluator has decided that this node has not handed on yet. - /// - /// One push can decide several runs, and the evaluator hands them out one chunk at a time, so a - /// window that reported only what the push returned would strand the rest until the next push. - /// A piece is charged here from the moment it leaves the evaluator, which no longer holds it. - pending: VecDeque, } impl WindowRuntime { @@ -519,7 +513,6 @@ impl WindowRuntime { RangeEvaluator::try_new(input, Arc::clone(&op.output_grid), op.window, op.function)?; Ok(Self { evaluator: Some(evaluator), - pending: VecDeque::new(), }) } @@ -546,39 +539,24 @@ impl WindowRuntime { /// 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 { - // A piece leaves the evaluator when it is decided, so from then on only this queue holds - // it. Each piece is counted once: it is either still inside the evaluator or already here. - let queued = self - .pending - .iter() - .map(evaluated_bytes) - .fold(0usize, usize::saturating_add); self.evaluator .as_ref() .map_or(0, RangeEvaluator::retained_bytes) - .saturating_add(queued) } /// 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))?; - let decided = match chunk { + match chunk { // Raw samples are read window by window by the evaluator itself. - NativeChunk::Raw(chunk) => evaluator.push(chunk)?, + NativeChunk::Raw(chunk) => evaluator.push(chunk), // An evaluated input is read as computed samples: the evaluator carries the window // state of one series across its chunks and closes it on the chunk that says so. // Handing each chunk over as it arrives is what lets this window report a 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_series(&chunk.series, chunk.is_last)?, - }; - self.pending.extend(decided); - Ok(self.take_pending()) - } - - /// The next piece this window has decided, if it is holding one. - fn take_pending(&mut self) -> Option { - self.pending.pop_front() + NativeChunk::Evaluated(chunk) => evaluator.push_series(&chunk.series, chunk.is_last), + } } /// Closes this window, reporting an input that ended mid-series. @@ -1210,12 +1188,8 @@ impl NativeExecutor { } NodeTag::Window => { let child = input.ok_or_else(|| missing_input(tag))?; - // A piece the window already decided goes out before more input is read, or a - // push that decides several runs would strand all but the first until the next - // push -- and the last of them would never leave at all. - if let Some(output) = self.take_window_output(index)? { - return Ok(Some(output)); - } + // A window reports on the chunk that closes a series, so a chunk that decides + // nothing yields nothing and the window asks its input again. loop { let Some(chunk) = self.pull(child)? else { return Ok(None); @@ -1223,11 +1197,6 @@ impl NativeExecutor { if let Some(output) = self.window_node(index, chunk)? { return Ok(Some(NativeChunk::Evaluated(output))); } - // The push may have decided several pieces without handing one back; they go - // out before this window reads another chunk. - if let Some(output) = self.take_window_output(index)? { - return Ok(Some(output)); - } } } } @@ -1246,36 +1215,6 @@ impl NativeExecutor { Ok(runtime.map(path, chunk)?.map(NativeChunk::Evaluated)) } - /// The next piece the window at `index` already decided, if it is holding one. - /// - /// The charge is recomputed here: the piece leaves the queue, so the bytes the node holds drop - /// by exactly that piece, and leaving the old figure in place would hold a reservation for - /// memory nothing is using. - fn take_window_output(&mut self, index: usize) -> Result> { - let path = &self.state.paths[index]; - let runtime = &mut self.state.runtimes[index]; - let Some(output) = runtime - .window - .as_mut() - .and_then(WindowRuntime::take_pending) - else { - return Ok(None); - }; - let metrics = Arc::clone(&runtime.buffer.metrics); - metrics.record_grid_points(output.series.time.len()); - metrics.record_output(1, valid_values(&output)); - runtime.track(path, &output)?; - let retained = runtime - .window - .as_ref() - .map_or(0, WindowRuntime::retained_bytes); - let emitted = runtime.emitted_bytes(); - runtime - .buffer - .hold_exactly(retained.saturating_add(emitted))?; - Ok(Some(NativeChunk::Evaluated(output))) - } - /// Feeds one chunk to the window at `index`. fn window_node(&mut self, index: usize, chunk: NativeChunk) -> Result> { let path = &self.state.paths[index]; diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 33665429bf2..35373802ede 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -1891,3 +1891,59 @@ fn a_sparse_chunk_occupies_only_the_positions_it_holds() { .unwrap_or_else(|error| panic!("the series in the hole was refused: {error}")) .expect("the second series is handed on"); } + +/// What an operation that empties every position hands on: nothing while the series is open, and +/// one empty chunk when it closes. +/// +/// The two are not interchangeable. A non-closing empty chunk is rejected by a downstream evaluator +/// (an empty delivery inside a series decides nothing), and dropping the closing one would leave +/// the consumer unable to tell "nothing more here" from "no more input", so the series would never +/// close and `finish` would report an input that ended mid-series. +#[test] +fn an_emptying_operation_hands_on_nothing_until_it_closes_the_series() { + let inner_grid = grid(0, 60_000, 4); + let outer_grid = grid(0, 120_000, 2); + // `clamp` with `max < min` empties every field of every chunk it sees. + let emptying = vec![MathOp::Clamp { min: 1.0, max: 0.0 }]; + let tree = NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), emptying.clone()), + RangeFunction::LastOverTime, + 120_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()); + // An open chunk that maps to nothing yields nothing at all: it is not handed to the window, + // which would refuse an empty delivery inside a series. + execution + .push_evaluated(evaluated_chunk(&schema, 0, vec![5.0, 6.0], false)) + .unwrap(); + assert!( + execution.next_chunk().unwrap().is_none(), + "an emptying map handed on a chunk for a series still open" + ); + + // The closing chunk still closes: one empty chunk reaches the window and closes the series. + execution + .push_evaluated(evaluated_chunk(&schema, 2, vec![7.0, 8.0], true)) + .unwrap(); + let mut out = Vec::new(); + while let Some(chunk) = execution.next_chunk().unwrap() { + out.push(chunk); + } + out.extend(execution.finish().expect("the window closed its series")); + + assert!( + out.iter().all(|chunk| chunk.series.time.is_empty()), + "the outer window produced a value for a series that held none" + ); + assert_eq!( + out.iter().filter(|chunk| chunk.is_last).count(), + 1, + "the series closed a number of times other than once" + ); + assert!(out.last().unwrap().is_last); +} From 9bd5c85a0f15ad47b19d99760c37740c821e0407 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:03:32 +0800 Subject: [PATCH 03/33] test(promql): pin the empty-map output count at one The test checked that every output was empty and that exactly one closed, which a stray extra non-closing empty output would also satisfy. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute/tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 35373802ede..8ffa6f5fc53 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -1936,6 +1936,11 @@ fn an_emptying_operation_hands_on_nothing_until_it_closes_the_series() { } out.extend(execution.finish().expect("the window closed its series")); + assert_eq!( + out.len(), + 1, + "an emptying series handed on more than the one chunk that closes it" + ); assert!( out.iter().all(|chunk| chunk.series.time.is_empty()), "the outer window produced a value for a series that held none" From 922c354b9852f033d9bda4e4629bb212183a40d6 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:29:42 +0800 Subject: [PATCH 04/33] fix(promql): charge the memory the native evaluator actually retains Four omissions made the reservation blind to most of what a window over native histograms keeps, and the existing incremental-equals-recomputed test could not see any of them because both sides used the same formula. - `FloatHistogram` owns four heap allocations -- both bucket lists, the custom bounds, and the span layout -- that `FieldSamples::bytes` never looked at. A retained 4096-bucket sample is tens of kilobytes against a ledger that saw a struct header. `heap_bytes` counts them, and both the retained sample slice and the histograms a row boxes are charged for what they own. - Queued chunks were estimated as one float per field per row, which is not what a histogram field holds: it holds indices into a shared `Arc` and the buffers behind the Arrow arrays. The figure now walks the samples, and counts a shared table or a shared buffer slice once per pass rather than once per chunk that references it. - `history_bytes` included `size_of::()` while the map slot term charged a `History` per entry as well, so every entry paid two headers. The per-entry figure now covers only the heap the entry owns. - The primary key is charged for the allocation its `Buffer` keeps alive rather than the bytes it shows: a scan slices the key out of a decoded dictionary-values buffer, so a short key can pin a batch-sized allocation. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- .../src/histogram_eval/float_histogram.rs | 34 +++ src/promql/src/native/execute.rs | 232 +++++++++++++----- src/promql/src/native/execute/tests.rs | 217 +++++++++++++++- src/promql/src/range_eval.rs | 55 ++++- src/promql/src/range_eval/tests.rs | 87 +++++++ 5 files changed, 564 insertions(+), 61 deletions(-) diff --git a/src/promql/src/histogram_eval/float_histogram.rs b/src/promql/src/histogram_eval/float_histogram.rs index 71f9598bd81..30147d01645 100644 --- a/src/promql/src/histogram_eval/float_histogram.rs +++ b/src/promql/src/histogram_eval/float_histogram.rs @@ -80,6 +80,40 @@ impl FloatHistogram { }) } + /// The bytes this histogram's own heap buffers hold, by capacity. + /// + /// Everything a histogram keeps besides its scalars is on the heap: the bucket lists of both + /// sides, the custom bounds, and the span layout of a histogram read from a view, with the + /// `[Vec; 2]` array that holds the two layout vectors. No scalar of the struct shows any of it: + /// a histogram of 4096 positive buckets is 64 KiB of buckets, and a window that retains one + /// histogram per grid point retains that much per point. + /// + /// The layout array is stored inline in the histogram, so a ledger charging + /// `size_of::()` per slot already pays for those 48 bytes. Counting the whole + /// footprint as one figure here costs a header of over-estimate on a reservation, against a + /// payload of tens of kilobytes that would otherwise be missing from it entirely. + pub(crate) fn heap_bytes(&self) -> usize { + fn buckets(side: &Buckets) -> usize { + side.capacity() * std::mem::size_of::<(i32, f64)>() + } + let layout = self.layout.as_ref().map_or(0, |sides| { + std::mem::size_of::<[Vec<(i32, i32)>; 2]>().saturating_add( + sides + .iter() + .map(|side| side.capacity() * std::mem::size_of::<(i32, i32)>()) + .fold(0, usize::saturating_add), + ) + }); + buckets(&self.positive) + .saturating_add(buckets(&self.negative)) + .saturating_add( + self.custom_values + .capacity() + .saturating_mul(std::mem::size_of::()), + ) + .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 aa68bbdd8b8..f2296252194 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -49,10 +49,14 @@ 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::Float64Array; +use datatypes::arrow::array::{Array, Float64Array}; +use datatypes::arrow::buffer::Buffer; use datatypes::series::SeriesOrdering; +use datatypes::series::histogram::HistogramBatch; use datatypes::series::raw::RawSeriesChunk; -use datatypes::series::samples::{SampleRef, Samples, Series, SeriesFields, SeriesSchema}; +use datatypes::series::samples::{ + DenseSamplesRef, SampleRef, Samples, Series, SeriesFields, SeriesSchema, +}; use datatypes::series::time::{GridRange, TimeAxis}; use crate::grid_series::{LabelSet, label_set}; @@ -95,32 +99,132 @@ impl NativeChunk { } } - /// An estimate of the bytes this chunk holds. - fn bytes(&self) -> usize { + /// The bytes this chunk holds, counting each shared allocation it references that `charged` has + /// not met yet. + fn bytes(&self, charged: &mut ChargedAllocations) -> usize { match self { - Self::Raw(chunk) => raw_bytes(chunk), - Self::Evaluated(chunk) => evaluated_bytes(chunk), + Self::Raw(chunk) => raw_bytes(chunk, charged), + Self::Evaluated(chunk) => evaluated_bytes(chunk, charged), } } } -/// An estimate of the bytes a raw chunk holds: its timestamps, one float per field and its -/// identity. -fn raw_bytes(chunk: &RawSeriesChunk) -> usize { - std::mem::size_of::() - + chunk.primary_key.len() - + chunk.time.len() - * (std::mem::size_of::() + chunk.fields.len() * std::mem::size_of::()) +/// The shared allocations one accounting pass has already counted. +/// +/// A chunk holds very little of what it costs: a field of native histograms holds no floats at all, +/// only indices into an immutable `Arc` table, and both that table and the buffers +/// behind the field's Arrow arrays are batch-wide allocations that a chunk can hold a slice of. Two +/// chunks of one series can share one table by cloning the `Arc`, and both can hold sibling slices +/// of one buffer, so a pass counts an allocation the first time it meets it. Charging it per +/// referencing chunk instead would make the reservation grow with the number of chunks a node holds +/// rather than with the data in them -- the figure the pool has to rank. +/// +/// One pass walks one chunk, or the queue of one node, so the list stays as short as the +/// allocations it met and is dropped with the pass; nothing outlives the call it was made for. +#[derive(Default)] +struct ChargedAllocations { + /// The address of every histogram table this pass has counted. + tables: Vec<*const HistogramBatch>, + /// The address of every Arrow buffer this pass has counted. + buffers: Vec<*const u8>, } -/// An estimate of the bytes an evaluated chunk holds: one float per field and decided position. +impl ChargedAllocations { + /// The bytes `table` holds, or zero when this pass has already counted it. + fn table(&mut self, table: &Arc) -> usize { + let address = Arc::as_ptr(table); + if self.tables.contains(&address) { + return 0; + } + self.tables.push(address); + // The batch struct holds the struct array and the column arrays beside it, which are views + // of that array's children: the array reports the buffers of all of them, once. + std::mem::size_of::() + .saturating_add(table.as_arrow().get_array_memory_size()) + } + + /// The bytes the allocation `buffer` is a slice of, or zero when this pass has already counted + /// it. + /// + /// The capacity is the whole allocation, which is what a slice keeps alive: a key of a few + /// bytes sliced out of a decoded dictionary values buffer pins that buffer. A buffer that owns + /// no memory of its own reports no capacity, and then the bytes it shows are all there is. + fn buffer(&mut self, buffer: &Buffer) -> usize { + let address = buffer.data_ptr().as_ptr().cast_const(); + if self.buffers.contains(&address) { + return 0; + } + self.buffers.push(address); + buffer.capacity().max(buffer.len()) + } + + /// The bytes the buffers of one Arrow array hold. + fn array(&mut self, array: &dyn Array) -> usize { + let data = array.to_data(); + let values = data.buffers().iter().fold(0usize, |total, buffer| { + total.saturating_add(self.buffer(buffer)) + }); + // The validity bitmap is not one of `buffers`: a field of a series with a missing sample + // carries one, and it is an allocation like any other. + let nulls = data + .nulls() + .map_or(0, |nulls| self.buffer(nulls.inner().inner())); + values.saturating_add(nulls) + } +} + +/// The bytes a raw chunk holds: its identity, its timestamps and the Arrow buffers behind its +/// fields. /// -/// The grid itself is shared by every chunk addressed on it, so it is not counted per chunk. The -/// figure only has to rank one chunk against another for the memory pool, which is what a -/// reservation is for. -fn evaluated_bytes(chunk: &EvaluatedChunk) -> usize { +/// The figure is what the chunk keeps alive rather than one float per field and row: a histogram +/// field holds no floats at all, only indices into the table its samples live in. +fn raw_bytes(chunk: &RawSeriesChunk, charged: &mut ChargedAllocations) -> usize { + std::mem::size_of::() + .saturating_add(charged.buffer(&chunk.primary_key)) + .saturating_add(charged.buffer(chunk.time.as_buffer().inner())) + .saturating_add(fields_bytes(&chunk.fields, charged)) +} + +/// The bytes an evaluated chunk holds: its struct and the Arrow buffers behind its fields. +/// +/// The figure is what the chunk keeps alive rather than one float per field and decided position: +/// a histogram field holds no floats at all, only indices into the table its samples live in. The +/// grid itself is shared by every chunk addressed on it, so it is not counted per chunk. +fn evaluated_bytes(chunk: &EvaluatedChunk, charged: &mut ChargedAllocations) -> usize { std::mem::size_of::() - + chunk.series.time.len() * chunk.series.fields.len() * std::mem::size_of::() + .saturating_add(fields_bytes(&chunk.series.fields, charged)) +} + +/// The bytes the fields of a chunk hold: the sample buffers of every segment, and the histogram +/// tables those segments reference. +fn fields_bytes(fields: &SeriesFields, charged: &mut ChargedAllocations) -> usize { + fields + .iter() + .map(|field| { + field + .segments() + .iter() + .map(|segment| segment_bytes(segment, charged)) + .fold(0usize, usize::saturating_add) + }) + .fold(0usize, usize::saturating_add) +} + +/// The bytes one dense segment of samples holds. +fn segment_bytes(segment: &Samples, charged: &mut ChargedAllocations) -> usize { + match segment.dense() { + Some(DenseSamplesRef::Float(values)) => charged.array(values), + Some(DenseSamplesRef::Histogram(histograms)) => charged + .array(histograms.indices()) + .saturating_add(charged.table(histograms.batch())), + Some(DenseSamplesRef::Mixed(mixed)) => charged + .array(mixed.floats()) + .saturating_add(charged.array(mixed.histograms().indices())) + .saturating_add(charged.table(mixed.histograms().batch())), + // `segments` hands out dense segments only, so a nested chunk never reaches here; one that + // somehow did is charged for the descriptor alone rather than for buffers it nests. + None => 0, + } } /// Which node kinds the runtime executes. @@ -181,7 +285,7 @@ struct NodeSpec { struct NodeBuffer { metrics: Arc, reservation: MemoryReservation, - /// The bytes `reservation` holds, mirrored so a chunk leaving shrinks it exactly. + /// The bytes `reservation` holds, mirrored so a chunk leaving returns exactly them. held: usize, } @@ -204,15 +308,6 @@ impl NodeBuffer { Ok(()) } - /// Returns the bytes of a chunk this node no longer holds. - fn shrink(&mut self, bytes: usize) -> Result<()> { - let held = self.held.saturating_sub(bytes); - self.reservation.try_resize(held)?; - self.held = held; - self.metrics.record_reserved_bytes(held); - 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 @@ -277,7 +372,8 @@ struct History { fields: Vec>, /// Whether the series on this label set closed. A second series cannot close it again. closed: bool, - /// The bytes this entry's labels and runs hold, kept current by [`Emitted::occupy`]. + /// The heap this entry owns: the runs its per-field vectors hold, kept current by + /// [`Emitted::occupy`]. The header and the slot it sits in are charged by the table's capacity. bytes: usize, } @@ -289,10 +385,14 @@ fn label_bytes(labels: &LabelSet) -> usize { .sum() } -/// The bytes a history holds: the entry itself, the per-field vectors and the runs in them. +/// The bytes a history holds: the per-field vectors and the runs in them. +/// +/// This is what the entry itself allocates, not the slot it is filed under: the `History` lives in +/// the map's slot, and that slot is what [`Emitted::bytes`] charges with the table's capacity. A +/// `size_of::()` term here billed every entry one header for a value it does not own, +/// once in this figure and again in the slot term beside it. fn history_bytes(history: &History) -> usize { - std::mem::size_of::() - + history.fields.capacity() * std::mem::size_of::>() + history.fields.capacity() * std::mem::size_of::>() + history .fields .iter() @@ -378,10 +478,11 @@ impl Emitted { /// 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. + /// It counts each label's name and value bytes with a tuple per label, the runs a history keeps + /// in its per-field vectors, and the table's capacity at one label-set slot plus one history + /// slot per entry -- which is where a `History` header itself is charged, once, for the entry + /// that lives in it. 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. /// /// The per-entry part is a running total, so reading this after every output does not walk the /// table: only the entry that changed and the table's own capacity are read here. @@ -519,15 +620,15 @@ impl WindowRuntime { /// 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. + /// per field, by capacity, with the payload of every native histogram they retain, the row a + /// push fills with the histograms it boxes, the pending batch's inner vectors, and the identity + /// payload of the series still open -- the allocation behind its primary key, not the bytes the + /// key shows. 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. + /// the inner vectors are counted, not the outer `spans` and `columns` that hold them. /// /// 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 @@ -587,26 +688,42 @@ struct NodeRuntime { impl NodeRuntime { /// Queues a source chunk, holding the bytes it needs until it leaves. + /// + /// What this node holds is its queue and nothing else, so the queue is counted in one pass and + /// the reservation set from that figure: a chunk of a series can share its histogram table with + /// a chunk of the same series beside it, and counting the queue chunk by chunk would charge + /// that one table once per chunk instead of once for the allocation. fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> { - let (bytes, positions) = (chunk.bytes(), chunk.positions()); - self.buffer.hold(bytes)?; - self.buffer.metrics.record_input(1, positions); + let positions = chunk.positions(); self.queued.push_back(chunk); + let bytes = self.queued_bytes(); + self.buffer.hold_exactly(bytes)?; + self.buffer.metrics.record_input(1, positions); Ok(()) } + /// The bytes the chunks this node still queues hold, counted as one accounting pass. + fn queued_bytes(&self) -> usize { + let mut charged = ChargedAllocations::default(); + self.queued + .iter() + .map(|chunk| chunk.bytes(&mut charged)) + .fold(0usize, usize::saturating_add) + } + /// Hands over the next queued source chunk, if there is one. fn pop_source(&mut self) -> Result> { let Some(chunk) = self.queued.pop_front() else { return Ok(None); }; + let bytes = self.queued_bytes(); let metrics = Arc::clone(&self.buffer.metrics); { // An input node's own work is handing the chunk over, so its self time covers that and // nothing its producer did. let _timer = metrics.timer(); // The chunk leaves this node, so the pool no longer has to hold it. - self.buffer.shrink(chunk.bytes())?; + self.buffer.hold_exactly(bytes)?; } metrics.record_output(1, chunk.positions()); // An evaluated source is already addressed on its grid, so its decided positions are grid @@ -626,7 +743,7 @@ impl NodeRuntime { /// there is nothing to hand on, and the input may still decide more. fn map(&mut self, path: &NodePath, chunk: EvaluatedChunk) -> Result> { let (bytes, positions, closing) = ( - evaluated_bytes(&chunk), + evaluated_bytes(&chunk, &mut ChargedAllocations::default()), chunk.series.time.len(), chunk.is_last, ); @@ -662,7 +779,11 @@ impl NodeRuntime { /// 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()); + let (bytes, positions, closing) = ( + chunk.bytes(&mut ChargedAllocations::default()), + 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); @@ -692,13 +813,14 @@ impl NodeRuntime { // 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 evaluator's buffers by capacity -- with the payload of the histograms they retain and + // of the ones the row boxes -- and every label set handed out, leaving out the kernel's + // scratch, this table's map overhead with the `Arc` headers of its strings and the outer + // vectors of the pending batch. 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 diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 8ffa6f5fc53..14a3606d1cc 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -20,8 +20,11 @@ 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; +use datatypes::arrow::array::{Float64Array, UInt32Array}; use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; +use datatypes::series::histogram::{ + BucketSideView, CounterResetHint, HistogramBatchBuilder, HistogramView, +}; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{ FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, @@ -29,8 +32,12 @@ use datatypes::series::samples::{ use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName, SeriesOrdering}; -use super::{NativeExecutionState, NativeExecutor, map_chunk}; +use super::{ + ChargedAllocations, Emitted, History, NativeExecutionState, NativeExecutor, Run, label_bytes, + map_chunk, raw_bytes, +}; use crate::evaluated::EvaluatedChunk; +use crate::grid_series::{LabelSet, label_set}; use crate::map::MathOp; use crate::native::metrics::{NodeMetric, NodePath}; use crate::native::plan::{ @@ -257,6 +264,61 @@ fn raw_chunk_repeated( .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 { + let offsets = [0]; + let lengths = [buckets]; + let counts = vec![1.0; usize::try_from(buckets).unwrap()]; + 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: None, + custom_values: &[], + positive: BucketSideView { + span_offsets: &offsets, + span_lengths: &lengths, + buckets: &counts, + }, + negative: BucketSideView { + span_offsets: &[], + span_lengths: &[], + buckets: &[], + }, + }) + .unwrap() +} + +/// One raw chunk of `series-a` whose one field holds a `buckets`-wide native histogram at each of +/// `timestamps`. +fn raw_histogram_chunk( + schema: &SeriesSchema, + timestamps: &[i64], + buckets: i32, + is_last: bool, +) -> RawSeriesChunk { + let mut builder = HistogramBatchBuilder::new(); + let indices: UInt32Array = timestamps + .iter() + .map(|_| Some(push_histogram(&mut builder, buckets))) + .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 evaluated chunk of an input series: `values` at `start` and onwards on `schema`'s grid. fn evaluated_chunk( schema: &SeriesSchema, @@ -1952,3 +2014,154 @@ fn an_emptying_operation_hands_on_nothing_until_it_closes_the_series() { ); assert!(out.last().unwrap().is_last); } + +/// A window over native histograms reserves what it retains, payload included, and the label-set +/// ledger it charges beside that agrees with a full walk of the table. +/// +/// The chunk accounting walks the samples a chunk holds instead of charging one float per field and +/// row, so a histogram field -- which holds no float at all -- reaches both figures as the table its +/// indices point into. Neither may drift from what the node says it holds: the reservation is the +/// retained bytes plus the emitted ones, and the running total of the emitted table is the same +/// figure recounted in full. +#[test] +fn a_window_over_histograms_reserves_what_it_retains() { + let out = grid(0, 10_000, 2); + let tree = NativeTree::try_new(window_with( + input(), + RangeFunction::LastOverTime, + 20_000, + None, + Arc::clone(&out), + )) + .unwrap(); + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + + for (timestamp, is_last) in [(0, false), (10_000, true)] { + execution + .push_raw(raw_histogram_chunk(&schema, &[timestamp], 2, is_last)) + .unwrap(); + while execution.next_chunk().unwrap().is_some() {} + let (retained, emitted) = execution.state().window_charge(&NodePath::root()); + assert!( + emitted > 0, + "the window handed nothing out, so the ledger below charges for nothing" + ); + assert_eq!( + execution.state().reserved_bytes(), + retained.saturating_add(emitted), + "the reservation is not what the window retains ({retained} bytes) plus what it handed \ + out ({emitted} bytes)", + ); + let (folded, walked) = execution.state().emitted_charge_pair(&NodePath::root()); + assert_eq!( + folded, walked, + "the folded charge of {folded} bytes is not the {walked} bytes the table holds", + ); + } +} + +/// One histogram table is charged once, however many chunks of the series reference it. +/// +/// The chunks of one series can share the immutable table their histogram indices point into, and a +/// node holding both of them holds one table: the source charges its queue as one accounting pass, +/// which counts the table the first time it meets it and the address the `Arc` holds is what makes +/// two clones one table. +#[test] +fn a_histogram_table_is_charged_once_per_pass() { + let schema = raw_schema(); + let mut builder = HistogramBatchBuilder::new(); + let index = push_histogram(&mut builder, 2); + let table = builder.finish().unwrap(); + let chunk = |timestamp: i64, is_last: bool| { + let samples = + Samples::try_from_histogram(UInt32Array::from(vec![Some(index)]), Arc::clone(&table)) + .unwrap(); + RawSeriesChunk::try_new( + &schema, + Buffer::from_slice_ref(b"series-a"), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from(vec![timestamp])).unwrap(), + SeriesFields::one(samples), + is_last, + ) + .unwrap() + }; + let (first, second) = (chunk(0, false), chunk(10_000, true)); + + let mut charged = ChargedAllocations::default(); + let queue = raw_bytes(&first, &mut charged).saturating_add(raw_bytes(&second, &mut charged)); + let alone = raw_bytes(&first, &mut ChargedAllocations::default()) + .saturating_add(raw_bytes(&second, &mut ChargedAllocations::default())); + assert!( + queue < alone, + "a queue of two chunks sharing one table is charged {queue} bytes, no less than the \ + {alone} bytes they are charged apart: the table was counted twice", + ); + + // What the source reserves is exactly that one pass: it holds its queue and nothing else, and + // nothing has been pulled yet. + let tree = NativeTree::try_new(window(input(), grid(0, 10_000, 1))).unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution.push_raw(first).unwrap(); + execution.push_raw(second).unwrap(); + assert_eq!( + execution.state().reserved_bytes(), + queue, + "the queue of two chunks sharing one table was not charged as one pass", + ); +} + +/// One entry's figure is the heap it owns, and its `History` header is charged once, by its slot. +/// +/// The `History` of a label set lives in the map's slot, so a `size_of::()` term in the +/// entry's own figure billed one header twice: once here and once in the capacity term beside it. +/// The two assertions below are the definition of the whole figure -- the labels, the vectors and +/// their runs, and one label-set slot plus one history slot per entry -- so either header counted +/// in the wrong place fails them. +#[test] +fn a_history_entry_is_charged_once_for_its_header() { + let grid = grid(0, 10_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let metric = named_metric("requests", "job"); + let labels = label_set(&metric); + // Not the closing chunk: a closed label set drops its runs, and the runs are what the entry's + // own figure is. + let chunk = evaluated_chunk_of(&schema, metric, 0, vec![Some(1.0), Some(2.0)], false); + + let mut emitted = Emitted::default(); + emitted.occupy(&NodePath::root(), &chunk).unwrap(); + + let history = emitted + .sets + .get(&labels) + .expect("the chunk recorded its label set"); + let entry = label_bytes(&labels) + .saturating_add(history.fields.capacity() * std::mem::size_of::>()) + .saturating_add( + history + .fields + .iter() + .map(|runs| runs.capacity() * std::mem::size_of::()) + .sum::(), + ); + assert!( + history.fields.iter().any(|runs| !runs.is_empty()), + "the entry kept no run, so it has no heap of its own to charge for" + ); + assert_eq!( + emitted.entries, + entry, + "the entry's own bytes are not its labels and runs alone: a `History` header in the figure \ + would add the {} bytes its slot already charges", + std::mem::size_of::(), + ); + assert_eq!( + emitted.bytes(), + entry.saturating_add( + emitted.sets.capacity() + * (std::mem::size_of::() + std::mem::size_of::()) + ), + "the table's capacity is where a label-set slot and one `History` per entry are charged", + ); +} diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index 6b3b7667b03..8575c91260a 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -303,7 +303,20 @@ struct SeriesState { impl SeriesState { /// The bytes this series' identity holds, which the rows handed out do not cover. fn identity_bytes(&self) -> usize { - let primary_key = self.primary_key.as_ref().map_or(0, |key| key.len()); + // A scan slices the primary key out of a decoded dictionary-values buffer, so the bytes the + // key shows are not the bytes it keeps: a key of a few bytes pins the whole buffer it was + // sliced out of, which `capacity` reports for the allocation behind the slice. Charging + // the key's length instead would show a handful of bytes for an allocation the size of a + // decoded batch. (A buffer that does not own its memory reports no capacity, and then the + // bytes it shows are all there is.) + // + // No dedupe is needed against a second slice of the same allocation: one evaluator holds + // one series at a time, and a window over an evaluated input holds no key at all, so a + // pass over this state charges one slice of one allocation rather than one per slice. + let primary_key = self + .primary_key + .as_ref() + .map_or(0, |key| key.capacity().max(key.len())); let metric: usize = self .metric .name() @@ -380,7 +393,17 @@ fn resets_between(resets: &[CounterReset], start: u64, end: u64) -> &[CounterRes impl FieldSamples { /// The bytes this field's buffers hold, by capacity. + /// + /// The histogram term is the slot of every retained sample plus the payload the histogram in + /// that slot owns: a slot is one `(i64, FloatHistogram)` worth of struct, and the buckets the + /// histogram keeps are on the heap behind it, up to tens of kilobytes per sample. Only the + /// retained slice is walked, which is the storage the windows still read; the samples before + /// `head` are gone, their payloads with them. fn bytes(&self) -> usize { + let histograms = self.histograms[self.histogram_head..] + .iter() + .map(|(_, histogram)| histogram.heap_bytes()) + .fold(0usize, usize::saturating_add); self.timestamps .capacity() .saturating_mul(std::mem::size_of::()) @@ -394,6 +417,7 @@ impl FieldSamples { .capacity() .saturating_mul(std::mem::size_of::<(i64, FloatHistogram)>()), ) + .saturating_add(histograms) .saturating_add( self.resets .capacity() @@ -481,6 +505,26 @@ impl FieldSamples { } } +/// The bytes the histograms a row holds box, beyond the slots they sit in. +/// +/// A slot is an `Option`: a pointer and a tag, which is all +/// `size_of::>()` is. A result that is a native histogram does not live in that +/// slot itself: the slot points at a `FloatHistogram` on the heap, which owns its bucket +/// lists in turn, and both are what the row keeps alive between pushes. Only slots that hold a +/// histogram are counted, and only those the last evaluated point left in place: a push clears the +/// row, so the slots past its length hold nothing. +fn boxed_bytes(row: &[Option]) -> usize { + row.iter() + .flatten() + .filter_map(|sample| match sample { + GridSample::Histogram(histogram) => { + Some(std::mem::size_of::().saturating_add(histogram.heap_bytes())) + } + GridSample::Float(_) => None, + }) + .fold(0usize, usize::saturating_add) +} + impl RangeEvaluator { /// Creates an evaluator of `function` for the series of `input` onto `grid`. pub fn try_new( @@ -604,9 +648,10 @@ impl RangeEvaluator { /// An accounted lower bound on the bytes this evaluator keeps between pushes. /// /// Counted by capacity, so it is what the storage holds rather than what it uses: the retained - /// samples per field (timestamps, values and native histograms), the reset index, the row a push - /// fills, and the pending batch's own vectors. Left out are the kernel's scratch buffers, this - /// struct's `Vec` headers and the grid, which every chunk addressed on it shares. + /// samples per field (timestamps, values and the native histograms with the payload each of + /// them owns), the reset index, the row a push fills with the histograms it boxes, and the + /// pending batch's own vectors. Left out are the kernel's scratch buffers, this struct's `Vec` + /// headers and the grid, which every chunk addressed on it shares. /// /// A push is the only caller that also holds the incoming chunk, and it charges that itself for /// as long as the call runs; vector growth during a push is neither reserved nor bounded by one @@ -621,9 +666,11 @@ impl RangeEvaluator { .map(FieldSamples::bytes) .fold(0usize, usize::saturating_add); let row = self.row.capacity() * std::mem::size_of::>(); + let boxed = boxed_bytes(&self.row); let series = self.series.as_ref().map_or(0, SeriesState::identity_bytes); per_field .saturating_add(row) + .saturating_add(boxed) .saturating_add(series) .saturating_add(self.pending.bytes()) } diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index c11af5e3c02..beea2c27a31 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -786,6 +786,93 @@ fn a_chunk_with_histograms_is_not_appended_in_bulk() { assert_eq!(evaluator.bulk_ingest_count(), 0); } +/// One raw chunk of one field holding a single native histogram sample at `ts`, whose positive side +/// is one span of `buckets` buckets of one count each. +fn histogram_chunk(schema: &SeriesSchema, buckets: i32, ts: i64) -> 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: None, + 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(), + false, + ) + .unwrap() +} + +/// A window has to reserve what a native histogram it retains owns, not only the slot it sits in. +/// +/// The histogram sample below stays ahead of the second grid point's window, so the evaluator keeps +/// it, and the two runs differ in nothing but the number of buckets on the positive side: 4 and +/// 4096. Those buckets are `(index, count)` pairs on the heap, which no `size_of` of the struct +/// shows -- 64 KiB for the wider one -- so the bytes the evaluator reports have to grow by at least +/// that payload between the two. A figure counting slots alone would report one number for both. +#[test] +fn a_retained_histogram_is_charged_for_its_buckets() { + let retained = |buckets: i32| -> usize { + let schema = raw_schema(1); + let mut evaluator = RangeEvaluator::try_new( + &schema, + grid(0, 10_000, 2), + // Far longer than the grid: the second point's window still reaches the sample, so the + // push retains it instead of advancing past it. + RangeWindow { + range_ms: 600_000, + offset_ms: 0, + anchor_ms: None, + }, + // A function that counts the histogram, so what the row holds is a float: the two + // figures then differ in the payload of the retained sample alone, not in what the row + // boxes beside it. + RangeFunction::CountOverTime, + ) + .unwrap(); + evaluator + .push(&histogram_chunk(&schema, buckets, 0)) + .unwrap(); + evaluator.retained_bytes() + }; + let (few, many) = (4, 4096); + let payload = usize::try_from(many - few).unwrap() * std::mem::size_of::<(i32, f64)>(); + let (narrow, wide) = (retained(few), retained(many)); + assert!( + wide >= narrow + payload, + "a window retaining one histogram of {many} buckets reports {wide} bytes, not the {narrow} \ + it reports for {few} buckets plus the {payload} bytes of bucket payload between them", + ); +} + /// `rate` over a float-only series takes the batch path. The per-window path produces the same /// output, so a test comparing values alone could not tell which one ran. #[test] From 963b1fe7429cec9d62bb4761c07252092da9f54d Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:36:00 +0800 Subject: [PATCH 05/33] fix(promql): keep the source queue's charge incremental The queue's reservation was recounted by walking every queued chunk on each enqueue and each pop. `push_raw` and `push_evaluated` are public and put no bound on how deep the queue gets, so a caller that queues a whole series before pulling it paid `N(N+1)/2` chunk visits to hold `N` chunks -- the same shape of defect this branch fixes in `absorb`. `QueuedCharge` keeps a reference count and the bytes behind each shared allocation: a table or buffer is charged when the first queued chunk reaches it and given back when the last one leaves, so an operation walks the one chunk it names. The count is per chunk rather than per field, because a pop re-walks the same chunk with the same dedupe and must remove exactly the references that were added. A chunk's own struct bytes are counted per chunk (`own_bytes`); only the allocations behind its fields are counted by address, since a struct has no address to dedupe on. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 230 ++++++++++++++-- src/promql/src/native/execute/tests.rs | 354 ++++++++++++++++++++++++- 2 files changed, 560 insertions(+), 24 deletions(-) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index f2296252194..6578ab3b7ec 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -107,6 +107,18 @@ impl NativeChunk { Self::Evaluated(chunk) => evaluated_bytes(chunk, charged), } } + + /// The bytes this chunk occupies on its own, which no other chunk holds a reference to. + /// + /// It is the struct term of [`Self::bytes`] and nothing else: everything beside it is a buffer or + /// a histogram table, which a sibling chunk of the series can share and which the queue counts + /// per allocation rather than per chunk. + fn own_bytes(&self) -> usize { + match self { + Self::Raw(_) => std::mem::size_of::(), + Self::Evaluated(_) => std::mem::size_of::(), + } + } } /// The shared allocations one accounting pass has already counted. @@ -119,28 +131,31 @@ impl NativeChunk { /// referencing chunk instead would make the reservation grow with the number of chunks a node holds /// rather than with the data in them -- the figure the pool has to rank. /// -/// One pass walks one chunk, or the queue of one node, so the list stays as short as the -/// allocations it met and is dropped with the pass; nothing outlives the call it was made for. +/// One pass walks one chunk, so the list stays as short as the allocations that chunk met and is +/// dropped with the pass; nothing outlives the call it was made for. The queue of one node is not +/// recounted by such a pass: [`QueuedCharge`] folds a chunk in as it enters and out as it leaves, +/// carrying the same dedupe across the queue. #[derive(Default)] struct ChargedAllocations { - /// The address of every histogram table this pass has counted. - tables: Vec<*const HistogramBatch>, - /// The address of every Arrow buffer this pass has counted. - buffers: Vec<*const u8>, + /// The address of every histogram table this pass has counted, with the bytes it contributes. + tables: Vec<(*const HistogramBatch, usize)>, + /// The address of every Arrow buffer this pass has counted, with the bytes it contributes. + buffers: Vec<(*const u8, usize)>, } impl ChargedAllocations { /// The bytes `table` holds, or zero when this pass has already counted it. fn table(&mut self, table: &Arc) -> usize { let address = Arc::as_ptr(table); - if self.tables.contains(&address) { + if self.tables.iter().any(|(counted, _)| *counted == address) { return 0; } - self.tables.push(address); // The batch struct holds the struct array and the column arrays beside it, which are views // of that array's children: the array reports the buffers of all of them, once. - std::mem::size_of::() - .saturating_add(table.as_arrow().get_array_memory_size()) + let bytes = std::mem::size_of::() + .saturating_add(table.as_arrow().get_array_memory_size()); + self.tables.push((address, bytes)); + bytes } /// The bytes the allocation `buffer` is a slice of, or zero when this pass has already counted @@ -151,11 +166,12 @@ impl ChargedAllocations { /// no memory of its own reports no capacity, and then the bytes it shows are all there is. fn buffer(&mut self, buffer: &Buffer) -> usize { let address = buffer.data_ptr().as_ptr().cast_const(); - if self.buffers.contains(&address) { + if self.buffers.iter().any(|(counted, _)| *counted == address) { return 0; } - self.buffers.push(address); - buffer.capacity().max(buffer.len()) + let bytes = buffer.capacity().max(buffer.len()); + self.buffers.push((address, bytes)); + bytes } /// The bytes the buffers of one Arrow array hold. @@ -173,6 +189,144 @@ impl ChargedAllocations { } } +/// The bytes the chunks one node queues hold, kept as chunks enter and leave the queue. +/// +/// A node is asked for its queue's figure on every enqueue and every pop, and the queue can hold a +/// whole series at once, for a caller that pushes a series before pulling it. Recounting the queue +/// with a [`ChargedAllocations`] pass each time is one pass over every queued chunk per operation, +/// which is quadratic in the chunks that caller queues. What is kept here instead is a count per +/// shared allocation, with the bytes that allocation contributes and the running total they add up +/// to, so an operation walks only the allocations of the one chunk it names. +/// +/// The dedupe is the one [`ChargedAllocations`] makes inside a chunk, carried across the queue. It +/// is per queued chunk that references an allocation, not per field or per segment that does: the +/// chunk is walked with one pass, so a chunk whose two fields index one table is one reference to +/// it, and the walk a pop makes of the same chunk meets the same references. A chunk is therefore +/// charged its own struct once, and an allocation once for as long as at least one queued chunk +/// references it -- the figure a whole-queue pass would give, without the pass. +#[derive(Default)] +struct QueuedCharge { + /// Every histogram table the queued chunks reference, by address, with how many queued chunks + /// reference it and the bytes it contributes to the total while at least one does. + tables: HashMap, + /// Every Arrow buffer the queued chunks reference, likewise: two chunks of one series hold + /// sibling slices of one buffer, and the address of the allocation is what makes them one. + buffers: HashMap, + /// What the queued chunks hold: their own structs, and the allocations above added once each. + /// This is what the node reserves for its queue. + bytes: usize, + /// How many chunks the accounting has walked, test-only. + /// + /// An enqueue or a pop walks the chunk it names, so this grows by one per operation whatever + /// the queue holds. A figure recounted from the whole queue would grow with the depth of the + /// queue, which is what a test refuses. + #[cfg(test)] + walked: usize, +} + +/// How many queued chunks reference one shared allocation, and the bytes it contributes while at +/// least one of them does. +#[derive(Clone, Copy)] +struct Counted { + chunks: usize, + bytes: usize, +} + +impl QueuedCharge { + /// Counts the allocations `chunk` references, as that chunk enters the queue, and returns the + /// queue's new total. + fn enqueue(&mut self, chunk: &NativeChunk) -> usize { + let charged = self.walk(chunk); + // The struct a chunk is held by is its own; only what it points at can be shared. + self.bytes = self.bytes.saturating_add(chunk.own_bytes()); + for &(table, bytes) in &charged.tables { + count_reference(&mut self.tables, &mut self.bytes, table as usize, bytes); + } + for &(buffer, bytes) in &charged.buffers { + count_reference(&mut self.buffers, &mut self.bytes, buffer as usize, bytes); + } + self.bytes + } + + /// Gives the allocations `chunk` references back, as that chunk leaves the queue, and returns + /// the queue's new total. + /// + /// An allocation another queued chunk still references stays charged: only the last reference + /// takes its bytes out, which is what keeps a shared table counted once for as long as the + /// queue holds it. + fn pop(&mut self, chunk: &NativeChunk) -> usize { + let charged = self.walk(chunk); + self.bytes = self.bytes.saturating_sub(chunk.own_bytes()); + for &(table, _) in &charged.tables { + drop_reference(&mut self.tables, &mut self.bytes, table as usize); + } + for &(buffer, _) in &charged.buffers { + drop_reference(&mut self.buffers, &mut self.bytes, buffer as usize); + } + self.bytes + } + + /// The shared allocations one chunk references, each met once. + /// + /// The pass is over `chunk` alone: what the queue holds is folded in from the allocations the + /// pass met rather than recounted by walking the queue. The same chunk walked again meets the + /// same addresses, which is what makes the subtraction on the way out match the addition on the + /// way in. + fn walk(&mut self, chunk: &NativeChunk) -> ChargedAllocations { + let mut charged = ChargedAllocations::default(); + // The figure this sums is the chunk's own; the queue needs the allocations behind it, which + // `charged` now holds. + let _ = chunk.bytes(&mut charged); + #[cfg(test)] + { + self.walked += 1; + } + charged + } +} + +/// Counts one more reference to the allocation at `address`, which contributes `bytes`, and adds +/// those bytes to `total` when the queue did not already hold it. +fn count_reference( + counts: &mut HashMap, + total: &mut usize, + address: usize, + bytes: usize, +) { + let entry = counts + .entry(address) + .or_insert(Counted { chunks: 0, bytes }); + if entry.chunks == 0 { + // The first chunk to meet the allocation is what makes the queue pay for it: a chunk + // sharing it afterwards adds a reference, not bytes. + *total = total.saturating_add(entry.bytes); + } + entry.chunks += 1; +} + +/// Gives one reference to the allocation at `address` back, and takes its bytes out of `total` when +/// it was the last one, so a queue that emptied leaves no entry and no bytes behind. +fn drop_reference(counts: &mut HashMap, total: &mut usize, address: usize) { + let last = match counts.get_mut(&address) { + // The chunk entered the queue before it left it, so one leaving cannot reach zero while + // another chunk of the queue still references the allocation. + Some(entry) if entry.chunks > 1 => { + entry.chunks -= 1; + false + } + Some(_) => true, + // Every chunk that leaves was queued, so its allocations were counted on the way in. An + // address missing here is exactly the asymmetry that would leak or undercharge silently. + None => { + debug_assert!(false, "the queue released an allocation it never counted"); + false + } + }; + if last && let Some(entry) = counts.remove(&address) { + *total = total.saturating_sub(entry.bytes); + } +} + /// The bytes a raw chunk holds: its identity, its timestamps and the Arrow buffers behind its /// fields. /// @@ -677,6 +831,8 @@ struct NodeRuntime { buffer: NodeBuffer, /// Source chunks queued by the caller, for an input node. queued: VecDeque, + /// What `queued` holds, folded in as chunks enter and out as they leave. + queued_charge: QueuedCharge, /// What a window node holds. window: Option, /// What a map node applies. @@ -689,21 +845,30 @@ struct NodeRuntime { impl NodeRuntime { /// Queues a source chunk, holding the bytes it needs until it leaves. /// - /// What this node holds is its queue and nothing else, so the queue is counted in one pass and - /// the reservation set from that figure: a chunk of a series can share its histogram table with - /// a chunk of the same series beside it, and counting the queue chunk by chunk would charge - /// that one table once per chunk instead of once for the allocation. + /// What this node holds is its queue and nothing else, so the reservation is the queue's + /// running total: a chunk of a series can share its histogram table with a chunk of the same + /// series beside it, and counting the queue chunk by chunk would charge that one table once per + /// chunk instead of once for the allocation. + /// + /// The total is kept incrementally rather than recounted from the queue: recomputing it here + /// costs a pass over every queued chunk per chunk queued, so a caller that queues a whole series + /// before pulling it pays quadratically in the chunks it holds. What this costs instead is one + /// pass over the chunk entering, and the same on the way out. fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> { let positions = chunk.positions(); + let bytes = self.queued_charge.enqueue(&chunk); self.queued.push_back(chunk); - let bytes = self.queued_bytes(); self.buffer.hold_exactly(bytes)?; self.buffer.metrics.record_input(1, positions); Ok(()) } /// The bytes the chunks this node still queues hold, counted as one accounting pass. - fn queued_bytes(&self) -> usize { + /// + /// Test-only: what the node reserves for its queue is the running total of [`QueuedCharge`], so + /// this walk is the figure that total is checked against rather than the figure it is read from. + #[cfg(test)] + fn queued_bytes_recomputed(&self) -> usize { let mut charged = ChargedAllocations::default(); self.queued .iter() @@ -716,7 +881,9 @@ impl NodeRuntime { let Some(chunk) = self.queued.pop_front() else { return Ok(None); }; - let bytes = self.queued_bytes(); + // The leaving chunk gives back only what it alone held: an allocation a chunk still in the + // queue references stays charged, and no chunk left behind is walked to find that out. + let bytes = self.queued_charge.pop(&chunk); let metrics = Arc::clone(&self.buffer.metrics); { // An input node's own work is handing the chunk over, so its self time covers that and @@ -869,6 +1036,10 @@ impl NodeRuntime { self.emitted = None; self.queued.clear(); self.queued.shrink_to_fit(); + // The queue's counts go with the queue: they are what a later chunk would be folded onto, + // and a chunk that is dropped is a chunk the pool no longer has to hold. The reservation is + // returned below, once, for everything this node still held. + self.queued_charge = QueuedCharge::default(); self.buffer.release(); } } @@ -1006,6 +1177,7 @@ impl NativeExecutionState { let mut runtime = NodeRuntime { buffer, queued: VecDeque::new(), + queued_charge: QueuedCharge::default(), window: None, map: None, emitted: None, @@ -1167,6 +1339,24 @@ impl NativeExecutionState { }) } + /// The bytes the queue at `path` charges for, and the same figure recounted by walking it. + /// + /// Test-only: the queue's running total is only correct if folding one chunk in as it enters and + /// out as it leaves agrees with one pass over what is left, so a test compares the two after the + /// queue has changed shape. + #[cfg(test)] + fn queued_charge_pair(&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.queued_charge.bytes, + runtime.queued_bytes_recomputed(), + ) + } + /// 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 diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 14a3606d1cc..3c93cdc09ad 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -15,6 +15,7 @@ //! What the runtime has to get right: each layer's grid, per-node accounting, rejection and //! release. +use std::collections::VecDeque; use std::sync::Arc; use datafusion::error::DataFusionError; @@ -23,7 +24,7 @@ use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricValue}; use datatypes::arrow::array::{Float64Array, UInt32Array}; use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; use datatypes::series::histogram::{ - BucketSideView, CounterResetHint, HistogramBatchBuilder, HistogramView, + BucketSideView, CounterResetHint, HistogramBatch, HistogramBatchBuilder, HistogramView, }; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{ @@ -33,13 +34,13 @@ use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis} use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::{ - ChargedAllocations, Emitted, History, NativeExecutionState, NativeExecutor, Run, label_bytes, - map_chunk, raw_bytes, + ChargedAllocations, Emitted, History, NativeChunk, NativeExecutionState, NativeExecutor, + NodeBuffer, NodeRuntime, QueuedCharge, Run, label_bytes, map_chunk, raw_bytes, }; use crate::evaluated::EvaluatedChunk; use crate::grid_series::{LabelSet, label_set}; use crate::map::MathOp; -use crate::native::metrics::{NodeMetric, NodePath}; +use crate::native::metrics::{NodeMetric, NodeMetrics, NodePath}; use crate::native::plan::{ AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, @@ -319,6 +320,47 @@ fn raw_histogram_chunk( .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 +/// one table for accounting even though each chunk carries its own indices into it. +fn raw_shared_histogram_chunk( + schema: &SeriesSchema, + table: &Arc, + index: u32, + timestamp: i64, + is_last: bool, +) -> RawSeriesChunk { + let samples = + Samples::try_from_histogram(UInt32Array::from(vec![Some(index)]), Arc::clone(table)) + .unwrap(); + RawSeriesChunk::try_new( + schema, + Buffer::from_slice_ref(b"series-a"), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from(vec![timestamp])).unwrap(), + SeriesFields::one(samples), + is_last, + ) + .unwrap() +} + +/// A source node's runtime: the queue, its accounting and the reservation the two are held for. +fn source_runtime(pool: &Arc) -> NodeRuntime { + NodeRuntime { + buffer: NodeBuffer::new( + &NodePath::root().input(), + Arc::new(NodeMetrics::default()), + pool, + ), + queued: VecDeque::new(), + queued_charge: QueuedCharge::default(), + window: None, + map: None, + emitted: None, + } +} + /// One evaluated chunk of an input series: `values` at `start` and onwards on `schema`'s grid. fn evaluated_chunk( schema: &SeriesSchema, @@ -2112,6 +2154,310 @@ fn a_histogram_table_is_charged_once_per_pass() { ); } +/// A queue of two chunks that share one table charges it once, and the running total is what one +/// pass over the queue counts. +/// +/// The figure the node reserves while both chunks are queued is the incremental one: the table is +/// met by the first chunk that references it and is not charged again by the second. Charging it +/// per chunk fails the record check, and recounting the queue per enqueue fails the count of +/// chunks walked in the test below. +#[test] +fn a_queued_allocation_is_charged_once() { + let pool = pool(); + let mut source = source_runtime(&pool); + let schema = raw_schema(); + let mut builder = HistogramBatchBuilder::new(); + let index = push_histogram(&mut builder, 2); + let table = builder.finish().unwrap(); + let chunk = |timestamp: i64, is_last: bool| { + raw_shared_histogram_chunk(&schema, &table, index, timestamp, is_last) + }; + let (first, second) = (chunk(0, false), chunk(10_000, true)); + + // What the two chunks cost charged apart, and what the second one costs on its own: the + // difference between the two is what the shared table is worth. + let apart = raw_bytes(&first, &mut ChargedAllocations::default()) + .saturating_add(raw_bytes(&second, &mut ChargedAllocations::default())); + let second_alone = raw_bytes(&second, &mut ChargedAllocations::default()); + + source.enqueue(NativeChunk::Raw(first)).unwrap(); + let one = source.queued_charge.bytes; + assert_eq!( + one, + source.queued_bytes_recomputed(), + "one queued chunk is not charged what one pass over it counts" + ); + assert_eq!( + source.buffer.held, one, + "the reservation is not the queue's figure" + ); + assert_eq!(pool.reserved(), one); + + source.enqueue(NativeChunk::Raw(second)).unwrap(); + let two = source.queued_charge.bytes; + let counted = *source + .queued_charge + .tables + .get(&(Arc::as_ptr(&table) as usize)) + .expect("the queue did not count the table both chunks index into"); + assert_eq!( + counted.chunks, 2, + "two queued chunks reference the table, but the queue counts {}", + counted.chunks + ); + assert_eq!( + two, + source.queued_bytes_recomputed(), + "the running total is not what one pass over the queue counts" + ); + assert_eq!( + two - one, + second_alone - counted.bytes, + "the chunk that entered charged the shared table a second time" + ); + assert!( + two < apart, + "a queue of two chunks sharing one table is charged {two} bytes, no less than the {apart} \ + bytes they are charged apart: the table was counted twice", + ); + assert_eq!(source.buffer.held, two); + assert_eq!(pool.reserved(), two); +} + +/// A shared table is given back with the last queued chunk that references it, not the first. +/// +/// A leak here shows as a reservation that never returns: the first pop takes one reference away +/// and the table stays charged, the second takes the last one and the table goes with it. +#[test] +fn a_queued_allocation_is_given_back_with_its_last_chunk() { + let pool = pool(); + let mut source = source_runtime(&pool); + let schema = raw_schema(); + let mut builder = HistogramBatchBuilder::new(); + let index = push_histogram(&mut builder, 2); + let table = builder.finish().unwrap(); + let address = Arc::as_ptr(&table) as usize; + let chunk = |timestamp: i64, is_last: bool| { + raw_shared_histogram_chunk(&schema, &table, index, timestamp, is_last) + }; + + source.enqueue(NativeChunk::Raw(chunk(0, false))).unwrap(); + source + .enqueue(NativeChunk::Raw(chunk(10_000, true))) + .unwrap(); + assert_eq!(source.queued_charge.tables[&address].chunks, 2); + + let first = source + .pop_source() + .unwrap() + .expect("the queue held two chunks"); + assert!(!first.is_last()); + assert_eq!( + source.queued_charge.tables[&address].chunks, 1, + "the chunk left in the queue still references the table, so it is still charged" + ); + assert!( + source.queued_charge.bytes > 0, + "the queue still holds a chunk, but charges for nothing" + ); + assert_eq!( + source.queued_charge.bytes, + source.queued_bytes_recomputed(), + "the pop did not leave the running total at one pass over the queue" + ); + assert_eq!(source.buffer.held, source.queued_charge.bytes); + + source + .pop_source() + .unwrap() + .expect("the queue held two chunks"); + assert!( + !source.queued_charge.tables.contains_key(&address), + "the last chunk referencing the table left, but the queue still counts it" + ); + assert!( + source.queued_charge.buffers.is_empty(), + "a buffer outlived the chunks that referenced it" + ); + assert_eq!( + source.queued_charge.bytes, 0, + "the queue is empty, but it is still charged for" + ); + assert_eq!( + source.buffer.held, 0, + "the reservation did not come back with the queue" + ); + assert_eq!(pool.reserved(), 0); + assert!(source.pop_source().unwrap().is_none()); +} + +/// Queueing a chunk accounts for that chunk alone, however deep the queue is. +/// +/// The figure is the number of chunks the accounting walked, not wall time: `N` enqueues have to +/// walk `N` chunks and `N` pops another `N`, whatever the queue held. Recounting the queue per +/// operation -- the defect this refuses -- walks `N * (N + 1) / 2` chunks for the enqueues alone. +#[test] +fn queueing_a_chunk_walks_one_chunk() { + let pool = pool(); + let mut source = source_runtime(&pool); + let schema = raw_schema(); + let chunks = 64; + for index in 0..chunks { + let timestamp = i64::try_from(index).unwrap() * 10_000; + let chunk = raw_chunk(&schema, &[timestamp], &[1.0], index + 1 == chunks); + source.enqueue(NativeChunk::Raw(chunk)).unwrap(); + } + assert_eq!( + source.queued_charge.walked, chunks, + "queueing {chunks} chunks walked {} chunk(s): the figure is recounted from the queue", + source.queued_charge.walked, + ); + assert_eq!( + source.queued_charge.bytes, + source.queued_bytes_recomputed(), + "the running total is not what one pass over the queue counts" + ); + + let mut popped = 0; + while source.pop_source().unwrap().is_some() { + popped += 1; + } + assert_eq!(popped, chunks, "the queue did not hand back every chunk"); + assert_eq!( + source.queued_charge.walked, + 2 * chunks, + "popping {chunks} chunks walked {} chunk(s): the figure is recounted from the queue", + source.queued_charge.walked, + ); + assert_eq!(source.queued_charge.bytes, 0); +} + +/// A mixed sequence of pushes and pulls leaves the queue's figure equal to one pass over what is +/// left in it, and the reservation equal to that figure. +/// +/// The chunks mix ones that share a table with ones that share nothing, so an allocation is +/// referenced by one, two or no queued chunk as the sequence runs. Both the node's own reservation +/// and the pool's are checked, so a total that drifts from the queue is caught by the figure the +/// memory pool actually holds. +#[test] +fn a_queue_figure_survives_a_mixed_push_and_pull_sequence() { + let pool = pool(); + let mut source = source_runtime(&pool); + let schema = raw_schema(); + let mut builder = HistogramBatchBuilder::new(); + let index = push_histogram(&mut builder, 2); + let table = builder.finish().unwrap(); + + for round in 0..6i64 { + for step in 0..2 { + let chunk = + raw_shared_histogram_chunk(&schema, &table, index, round * 10_000 + step, false); + source.enqueue(NativeChunk::Raw(chunk)).unwrap(); + } + let chunk = raw_chunk(&schema, &[round * 10_000 + 2], &[1.0], false); + source.enqueue(NativeChunk::Raw(chunk)).unwrap(); + let folded = source.queued_charge.bytes; + assert_eq!( + folded, + source.queued_bytes_recomputed(), + "round {round}: the running total is not one pass over the queue" + ); + assert_eq!(source.buffer.held, folded); + assert_eq!(pool.reserved(), folded); + + for _ in 0..2 { + if source.pop_source().unwrap().is_none() { + break; + } + } + let folded = source.queued_charge.bytes; + assert_eq!( + folded, + source.queued_bytes_recomputed(), + "round {round}: the running total is not one pass over what is left" + ); + assert_eq!(source.buffer.held, folded); + assert_eq!(pool.reserved(), folded); + } + + while source.pop_source().unwrap().is_some() {} + assert_eq!(source.queued_charge.bytes, 0); + assert!( + source.queued_charge.tables.is_empty(), + "a table outlived the chunks that referenced it" + ); + assert!( + source.queued_charge.buffers.is_empty(), + "a buffer outlived the chunks that referenced it" + ); + assert_eq!(source.buffer.held, 0); + assert_eq!(pool.reserved(), 0); +} + +/// What a source reserves through the executor is the figure one pass over its queue counts. +#[test] +fn the_executor_reserves_what_one_pass_over_the_queue_counts() { + let tree = NativeTree::try_new(window(input(), grid(0, 10_000, 4))).unwrap(); + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for step in 0..3 { + let chunk = raw_chunk(&schema, &[step * 10_000], &[1.0], false); + execution.push_raw(chunk).unwrap(); + } + let (folded, walked) = execution + .state() + .queued_charge_pair(&NodePath::root().input()); + assert_eq!( + folded, walked, + "the executor's queue is not charged what one pass over it counts" + ); + assert_eq!( + execution.state().reserved_bytes(), + folded, + "the source's reservation is not its queue's figure" + ); +} + +/// Releasing a node drops the queue's counts with the queue and returns the reservation once. +/// +/// A count left behind would be folded onto by the next chunk the node queues, and the reservation +/// shown as returned while the counts still hold the bytes is the leak this refuses. +#[test] +fn releasing_a_node_drops_the_queue_and_its_counts() { + let pool = pool(); + let mut source = source_runtime(&pool); + let schema = raw_schema(); + let mut builder = HistogramBatchBuilder::new(); + let index = push_histogram(&mut builder, 2); + let table = builder.finish().unwrap(); + source + .enqueue(NativeChunk::Raw(raw_shared_histogram_chunk( + &schema, &table, index, 0, false, + ))) + .unwrap(); + source + .enqueue(NativeChunk::Raw(raw_shared_histogram_chunk( + &schema, &table, index, 10_000, true, + ))) + .unwrap(); + assert_eq!(pool.reserved(), source.queued_charge.bytes); + + source.release(); + assert!(source.queued.is_empty(), "the queue outlived its release"); + assert!( + source.queued_charge.tables.is_empty(), + "the queue's table counts outlived the queue" + ); + assert!( + source.queued_charge.buffers.is_empty(), + "the queue's buffer counts outlived the queue" + ); + assert_eq!(source.queued_charge.bytes, 0); + assert_eq!(source.buffer.held, 0); + assert_eq!(pool.reserved(), 0, "the reservation was not returned"); + assert!(source.pop_source().unwrap().is_none()); +} + /// One entry's figure is the heap it owns, and its `History` header is charged once, by its slot. /// /// The `History` of a label set lives in the map's slot, so a `size_of::()` term in the From 0e4ff30dd21f56d1c9ca2ce62e3bb2004c2c657f Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:27:07 +0800 Subject: [PATCH 06/33] perf(promql): append a forward-moving chunk to the emitted history `absorb` rebuilt the whole stored run array on every non-empty chunk. Legal input made that quadratic across chunks with no label collision: one series in `K` chunks, chunk `i` occupying only grid position `2*i`, stores one more run per chunk and moves `K(K+1)/2` of them -- about five billion for a hundred thousand rows. A chunk that starts at or past the end of the last stored run only ever adds to the end, so its runs are appended and the boundary run is joined where it touches. One that can interleave or reach backwards still takes the full one-pass merge, which can split a run. Both leave the runs sorted, disjoint and joined, which is what `Emitted::occupy` looks a position up by. The test records the chunks through `Emitted::occupy` itself and reads the history back from it, covering the forward case, the touching boundary, a hole that has to join both neighbours, and a position before everything stored. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 74 +++++++++++- src/promql/src/native/execute/tests.rs | 160 ++++++++++++++++++++++++- 2 files changed, 229 insertions(+), 5 deletions(-) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 6578ab3b7ec..9500be2f82b 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -709,17 +709,83 @@ fn occupied_runs(field: &Samples, time: &TimeAxis) -> Vec { runs } +// How many times `absorb` rebuilt the stored runs instead of appending to them. +// +// Test-only, and per thread: the runs stored afterwards are the same either way, so a rebuild shows +// only in what it costs, and a test that reads its own thread's figure is not disturbed by another +// test's chunks. +#[cfg(test)] +thread_local! { + static ABSORB_REBUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times this thread's [`absorb`] rebuilt the stored runs. +#[cfg(test)] +fn absorb_rebuilds() -> usize { + ABSORB_REBUILDS.with(std::cell::Cell::get) +} + /// Merges `incoming` into `stored`, keeping the result in position order and joining the runs that /// touch. /// -/// Both sides are sorted and disjoint, so one pass merges them. Adding the runs one at a time and -/// rebuilding the whole array after each would cost the square of the runs a chunk yields: a chunk -/// of one hundred thousand positions alternating between values and nulls yields fifty thousand -/// runs, and re-merging after each is over a billion element moves for a single series. +/// Within a chunk one pass over both sides is what keeps this linear, since each side is sorted and +/// disjoint. Adding the runs one at a time and rebuilding the array after each would cost the square +/// of the runs a chunk yields: a chunk of one hundred thousand positions alternating between values +/// and nulls yields fifty thousand runs, and re-merging after each is over a billion element moves +/// for a single series. +/// +/// One pass per chunk is still a pass over everything the series has stored so far, so it is not +/// free once the *history* grows across chunks: a series split into `K` chunks of one position each, +/// a hole apart, stores one more run per chunk and moves `K(K+1)/2` of them, with no label collision +/// and no illegal input anywhere. A chunk that starts no earlier than the end of the last stored run +/// only ever adds to the end — the stored runs are sorted and disjoint, so every one of them ends +/// before anything this chunk holds — and it is appended instead, which is amortised constant per +/// run. That is the shape a scan hands over as its positions move forward chunk after chunk. A chunk +/// that starts before the last stored run can split a run or reach back past it, so it still costs +/// the full merge. +/// +/// Either way the result is sorted, disjoint, and has the runs that touch joined, which is what +/// [`Emitted::occupy`] looks a position up by. fn absorb(stored: &mut Vec, incoming: &[Run]) { if incoming.is_empty() { return; } + if stored + .last() + .is_none_or(|last| incoming[0].start >= last.end) + { + append_runs(stored, incoming); + } else { + merge_runs(stored, incoming); + } +} + +/// Appends `incoming` to `stored`, all of which lies past the last stored run. +/// +/// Nothing already stored has to be placed again: the two sides are each in position order and +/// nothing `incoming` holds can reach back into what is stored, so its runs are pushed on the end and +/// the vector's own growth is the only move — amortised over the runs appended. Where its first run +/// touches the end of the last stored run the two are one run, as they are after a merge, so it is +/// joined rather than left beside it. +fn append_runs(stored: &mut Vec, incoming: &[Run]) { + let mut incoming = incoming; + if let Some(last) = stored.last_mut() + && let Some(first) = incoming.first() + && first.start <= last.end + { + last.end = last.end.max(first.end); + incoming = &incoming[1..]; + } + stored.extend_from_slice(incoming); +} + +/// Merges `incoming` into `stored`, where the two can interleave. +/// +/// One pass is enough because each side is sorted and disjoint: whichever run starts first is +/// placed, and it joins the run before it where the two touch. +fn merge_runs(stored: &mut Vec, incoming: &[Run]) { + #[cfg(test)] + ABSORB_REBUILDS.with(|rebuilds| rebuilds.set(rebuilds.get() + 1)); let mut merged: Vec = Vec::with_capacity(stored.len() + incoming.len()); let (mut a, mut b) = (0, 0); while a < stored.len() || b < incoming.len() { diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 3c93cdc09ad..56bc886014b 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -35,7 +35,7 @@ use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::{ ChargedAllocations, Emitted, History, NativeChunk, NativeExecutionState, NativeExecutor, - NodeBuffer, NodeRuntime, QueuedCharge, Run, label_bytes, map_chunk, raw_bytes, + NodeBuffer, NodeRuntime, QueuedCharge, Run, absorb_rebuilds, label_bytes, map_chunk, raw_bytes, }; use crate::evaluated::EvaluatedChunk; use crate::grid_series::{LabelSet, label_set}; @@ -2511,3 +2511,161 @@ fn a_history_entry_is_charged_once_for_its_header() { "the table's capacity is where a label-set slot and one `History` per entry are charged", ); } + +/// A sparse series that only ever moves forward is appended to its history, not merged into it again +/// chunk after chunk. +/// +/// One legal series arrives as eight chunks of one position each, every position a hole apart from +/// the last: no label set is reached twice, no position of a field is occupied twice, and this is +/// what a scan produces as its positions advance. The stored runs still grow by one per chunk, so +/// rebuilding the array after each chunk moves `K(K+1)/2` runs to hold `K` rows of real data, which +/// is the cost this asserts away. +/// +/// The chunks go through [`super::Emitted::occupy`], the helper the runtime records an output with, +/// so what is checked is the history that helper keeps. Three shapes are pushed: chunks landing past +/// every stored run, which have to be appended to; a chunk starting where the last stored run ends, +/// which has to be joined to it rather than left beside it; and chunks landing before what is +/// stored, which cannot be appended to and have to go through the full merge while still leaving the +/// history sorted and disjoint. +#[test] +fn a_sparse_series_that_moves_forward_is_appended_to_its_history() { + let map_grid = grid(0, 60_000, 21); + let schema = evaluated_schema(Arc::clone(&map_grid)); + let path = NodePath::root(); + let mut emitted = Emitted::default(); + + // One row at `position`, which is one run of one position: the same series every time, since a + // map dropping the name leaves them all one label set. + let push = |emitted: &mut Emitted, position: usize| { + let chunk = sparse_chunk( + &schema, + named_metric("a", "x"), + &[(position, 1)], + vec![-1.0], + false, + ); + emitted + .occupy(&path, &chunk) + .unwrap_or_else(|error| panic!("position {position} was refused: {error}")); + }; + // The runs stored under the one label set, which is what `absorb` keeps in position order. + let stored = |emitted: &Emitted| -> Vec<(usize, usize)> { + emitted + .sets + .values() + .next() + .expect("the chunk was recorded under one label set") + .fields + .first() + .expect("the series has one field") + .iter() + .map(|run| (run.start, run.end)) + .collect() + }; + let ordered = |runs: &[(usize, usize)]| { + runs.iter().all(|(start, end)| start < end) + && runs.windows(2).all(|pair| pair[0].1 < pair[1].0) + }; + + // Eight chunks, one position each, a hole between them. + let positions = [4, 6, 8, 10, 12, 14, 16, 18]; + let before = absorb_rebuilds(); + for position in positions { + push(&mut emitted, position); + } + assert_eq!( + stored(&emitted), + vec![ + (4, 5), + (6, 7), + (8, 9), + (10, 11), + (12, 13), + (14, 15), + (16, 17), + (18, 19), + ], + "a sparse series was not stored as the one run each of its chunks occupies" + ); + assert_eq!( + absorb_rebuilds() - before, + 0, + "the {} chunks of a series moving forward rebuilt its history instead of appending to it", + positions.len() + ); + + // A chunk that starts where the last stored run ends touches it, and the two are one run: the + // fast path appends, and the boundary is the part it has to join. + let before = absorb_rebuilds(); + push(&mut emitted, 19); + assert_eq!( + stored(&emitted), + vec![ + (4, 5), + (6, 7), + (8, 9), + (10, 11), + (12, 13), + (14, 15), + (16, 17), + (18, 20), + ], + "a chunk touching the last stored run was left beside it rather than joined to it" + ); + assert_eq!( + absorb_rebuilds() - before, + 0, + "a chunk touching the last stored run was merged rather than appended to it" + ); + + // A chunk landing in a hole before the last stored run cannot be appended to: it joins the runs + // on both sides of it, so it goes through the full merge, which has to join them all the same. + let before = absorb_rebuilds(); + push(&mut emitted, 5); + assert_eq!( + stored(&emitted), + vec![ + (4, 7), + (8, 9), + (10, 11), + (12, 13), + (14, 15), + (16, 17), + (18, 20), + ], + "a chunk in a hole did not join the runs on either side of it" + ); + assert_eq!( + absorb_rebuilds() - before, + 1, + "a chunk landing before the last stored run was appended rather than merged" + ); + + // A chunk before every stored run is the other shape the fast path cannot take. + let before = absorb_rebuilds(); + push(&mut emitted, 1); + let runs = stored(&emitted); + assert_eq!( + runs, + vec![ + (1, 2), + (4, 7), + (8, 9), + (10, 11), + (12, 13), + (14, 15), + (16, 17), + (18, 20), + ], + "a chunk before every stored run did not land in front of them" + ); + assert_eq!( + absorb_rebuilds() - before, + 1, + "a chunk landing before every stored run was appended rather than merged" + ); + assert!( + ordered(&runs), + "the merged history is not sorted, disjoint and joined: {runs:?}" + ); +} From 42ea525cc8e8f2c222c02edb4994692f2816a5c7 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:29:30 +0800 Subject: [PATCH 07/33] fix(promql): report a truncated input from a tree with no window `close` only asked windows whether a series was still open, so a tree of an input alone, or of a map over one, accepted a final chunk without `is_last` and handed the consumer a series that never closed. The input node now follows the series of the chunk it last handed over, and closing such a tree reports the truncation against it, which is the same refusal a window makes for the input it reads. `occupied_runs` read a row the axis names with `expect`, which panics on a `Series` whose fields are shorter than its axis; the fields are public, so that chunk is constructible by a caller. It now returns the misalignment as an error naming the node, the field and both lengths. The chunk protocol says one series closes once, which reads as one close per label set. State that it is per input series: a node that rewrites labels can hand two series over under one label set and both of them close. Also say in `Emitted`'s doc that the table is one node's own, so a label set costs its bytes again in every node that keeps one. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/batch.rs | 7 +- src/promql/src/native/execute.rs | 109 ++++++++++++++++++++++--- src/promql/src/native/execute/tests.rs | 80 ++++++++++++++++++ 3 files changed, 184 insertions(+), 12 deletions(-) diff --git a/src/promql/src/native/batch.rs b/src/promql/src/native/batch.rs index f3982a0115e..0137bbef658 100644 --- a/src/promql/src/native/batch.rs +++ b/src/promql/src/native/batch.rs @@ -23,7 +23,12 @@ //! one, and an inner grid is never addressed with an outer grid's index. //! - A series closes exactly once, on the chunk that carries [`EvaluatedChunk::is_last`]. A closed //! prefix still has to be followed by a final chunk even when that chunk holds no values, so a -//! consumer can tell "nothing more here" from "no more input". +//! consumer can tell "nothing more here" from "no more input". This is per input series, not per +//! label set: a node that rewrites labels can hand two input series over under one label set, and +//! each of them still closes on its own chunk, so a label set may be closed more than once. A +//! series that produced values closes it, and a later input series with no result at all closes it +//! again on the chunk that ends it; a node that can merge two inputs into one series must not read +//! the second close as a defect. //! //! The chunk type itself is [`crate::evaluated::EvaluatedChunk`]: one chunk protocol serves both the diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 9500be2f82b..4f9853b6b2d 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -507,6 +507,10 @@ impl Run { /// 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`]. +/// +/// The table is one node's own: a node knows what it has handed out itself and sees nothing of what +/// the node below kept, so a label set costs its bytes again in every node that keeps a table, and +/// what is deduplicated here is one node's history rather than a plan's. #[derive(Default)] struct Emitted { sets: HashMap, @@ -570,8 +574,9 @@ impl Emitted { .series .fields .iter() - .map(|field| occupied_runs(field, &chunk.series.time)) - .collect(); + .enumerate() + .map(|(index, field)| occupied_runs(path, index, field, &chunk.series.time)) + .collect::>()?; // A chunk holding no value records nothing. If the label set is unknown or already closed, // the series this chunk belongs to contributed no sample at all -- either it is the first // such series, or a later one that also answers empty -- so there is nothing to report, @@ -658,13 +663,22 @@ impl Emitted { } } -/// The runs of positions holding a value in `field`, as the axis `time` places its rows. +/// The runs of positions holding a value in field `index`, as the axis `time` places its rows. /// /// A missing sample holds no value; a `NaN` and a native histogram do, as they do for a merge. /// A hole between two rows is not a position either: the axis skips it, so a run open before the /// hole ends where the hole begins rather than reaching across it. A chunk of several runs is /// therefore recorded as the runs it holds, and a series that occupies the hole is not refused. -fn occupied_runs(field: &Samples, time: &TimeAxis) -> Vec { +/// +/// The axis is what says how many rows there are, so every field it reads has to hold one sample per +/// row. [`Series`] keeps its fields public, so a chunk built by struct literal can carry fewer, and +/// that is refused here rather than read past the end of the field. +fn occupied_runs( + path: &NodePath, + index: usize, + field: &Samples, + time: &TimeAxis, +) -> Result> { let mut runs: Vec = Vec::new(); let mut open: Option = None; let mut previous: Option = None; @@ -681,10 +695,10 @@ fn occupied_runs(field: &Samples, time: &TimeAxis) -> Vec { end: previous + 1, }); } - let present = !matches!( - cursor.at(row).expect("the axis and the fields are aligned"), - SampleRef::Missing - ); + let sample = cursor + .at(row) + .ok_or_else(|| misaligned_field(path, index, time, field))?; + let present = !matches!(sample, SampleRef::Missing); match (present, open) { (true, None) => open = Some(position), (false, Some(start)) => { @@ -706,7 +720,27 @@ fn occupied_runs(field: &Samples, time: &TimeAxis) -> Vec { end: previous.map_or(start, |last| last + 1), }); } - runs + Ok(runs) +} + +/// The rejection of a series whose axis and fields disagree on how many rows there are. +/// +/// [`Series`] keeps its fields public, so a chunk built by struct literal — by a caller of this crate +/// as much as by a mistake here — can carry fewer samples than the axis places rows, and then the row +/// the axis names has nothing to read. +fn misaligned_field( + path: &NodePath, + index: usize, + time: &TimeAxis, + field: &Samples, +) -> DataFusionError { + DataFusionError::Execution(format!( + "the node at {path} was handed a series whose axis and fields are misaligned: the axis \ + places {} rows, but field {index} holds {} samples, so the axis names a row the field does \ + not have", + time.len(), + field.len(), + )) } // How many times `absorb` rebuilt the stored runs instead of appending to them. @@ -906,6 +940,23 @@ struct NodeRuntime { /// 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, + /// Whether the series the last chunk handed over belongs to is still open. + /// + /// Only an input node ever sets this, because its queue is the one the caller fills; the flag is + /// what reports a truncated input to a tree that has no window, since nothing else in such a + /// tree holds a series and so nothing else could notice one that never ended. It is assigned on + /// every handover -- `false` when that chunk carried `is_last`, `true` when it did not -- and + /// cleared when the node is released, so a true flag says exactly one thing: the last chunk the + /// consumer saw did not close its series, and no chunk came after it. Nothing else writes it, so + /// it cannot report a truncation that did not happen. + /// + /// One flag is enough under the `Contiguous` and `KeyThenTime` orderings, which keep the chunks + /// of a series together: only the series last handed over can be open, and one that closed + /// cannot resume. An `Interleaved` input does reach a tree with no window above it -- that + /// ordering is refused only where a window reads a series at a time -- and there an earlier + /// series left open behind another one's chunk is not reported. The flag under-reports such a + /// stream; it never over-reports one. + open_source_series: bool, } impl NodeRuntime { @@ -943,6 +994,10 @@ impl NodeRuntime { } /// 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. fn pop_source(&mut self) -> Result> { let Some(chunk) = self.queued.pop_front() else { return Ok(None); @@ -964,6 +1019,9 @@ impl NodeRuntime { if let NativeChunk::Evaluated(chunk) = &chunk { metrics.record_grid_points(chunk.series.time.len()); } + // 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); } @@ -1100,6 +1158,10 @@ impl NodeRuntime { // caller keeps the stopped executor alive. The label sets this node handed out go with it. self.window = None; self.emitted = None; + // A node that holds no chunk holds no series either, so nothing it handed over is still + // open for it: the flag is what closing the execution reads, and it must not survive the + // state that could have kept a series alive. + self.open_source_series = false; self.queued.clear(); self.queued.shrink_to_fit(); // The queue's counts go with the queue: they are what a later chunk would be folded onto, @@ -1247,6 +1309,7 @@ impl NativeExecutionState { window: None, map: None, emitted: None, + open_source_series: false, }; match &node.seed { Seed::Input => {} @@ -1440,16 +1503,23 @@ impl NativeExecutionState { /// /// A drain finds nothing left to emit: a window reports its results on the chunk that closes /// the series, so what is left to do is to check that every series did close, and to return - /// everything the execution reserved. + /// everything the execution reserved. A window's evaluator is what holds a series and so + /// notices one that never ended; a tree with no window has none, so there the input node answers + /// the same question from [`NodeRuntime::open_source_series`], which follows what it handed over. + /// The first error found is the one reported, and the nodes are walked from the root down, so a + /// window above the input reports its own truncation as it always did. fn close(&mut self) -> Result<()> { let mut result = Ok(()); - for runtime in &mut self.runtimes { + for (path, runtime) in self.paths.iter().zip(self.runtimes.iter_mut()) { if let Some(window) = runtime.window.as_mut() && let Err(error) = window.finish() && result.is_ok() { result = Err(error); } + if runtime.open_source_series && result.is_ok() { + result = Err(truncated_input(path)); + } runtime.release(); } result @@ -1524,6 +1594,11 @@ impl NativeExecutor { } /// Ends the input: drains what has settled, closes every node and releases every reservation. + /// + /// 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. pub fn finish(&mut self) -> Result> { let mut drained = Vec::new(); loop { @@ -1784,6 +1859,18 @@ fn occupied_position( )) } +/// The rejection of an input that ended without the chunk closing its series. +/// +/// It is what a window's evaluator reports for the input it reads, said by the node that handed the +/// chunks over instead: a tree with no window has no evaluator to hold the series, so the input node +/// is the one node left that can tell a series that ended from one that was cut off. +fn truncated_input(path: &NodePath) -> DataFusionError { + DataFusionError::Execution(format!( + "the input at {path} ended before the last chunk of a series: the last chunk it handed over \ + did not say `is_last`" + )) +} + /// 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 56bc886014b..ddb96a57444 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -358,6 +358,7 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { window: None, map: None, emitted: None, + open_source_series: false, } } @@ -2057,6 +2058,53 @@ fn an_emptying_operation_hands_on_nothing_until_it_closes_the_series() { assert!(out.last().unwrap().is_last); } +/// A tree with no window reports an input that ended mid-series as a truncated input. +/// +/// A window's evaluator is what knows a series has not closed: it holds the series until the chunk +/// carrying `is_last`, so closing the execution over what is left reports the input that never +/// delivered it. A tree of an input alone, or of a map over one, has no evaluator at all, so +/// without the input node saying so the series would reach the consumer open and never close. The +/// input node is the only place that sees every chunk the caller queued, so the truncation is +/// reported against it, for a tree of one node and for one with a map above it alike. +#[test] +fn an_input_that_ends_mid_series_is_reported_without_a_window() { + let map_grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&map_grid)); + let shapes = [ + // The input alone, and the same input under a map: neither has a window above it. + ("an input", evaluated_input(Arc::clone(&map_grid))), + ( + "a map over an input", + map(evaluated_input(Arc::clone(&map_grid)), vec![MathOp::Abs]), + ), + ]; + for (what, root) in shapes { + let tree = NativeTree::try_new(root).unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + // A chunk that does not close its series: the chunk carrying `is_last` never arrives. + execution + .push_evaluated(evaluated_chunk(&schema, 0, vec![-1.0, -2.0], false)) + .unwrap(); + let handed = execution + .next_chunk() + .unwrap() + .expect("a chunk of a series still open is handed on as it arrives"); + assert!( + !handed.is_last, + "{what} handed on a chunk that closed a series it never closed" + ); + let error = execution + .finish() + .expect_err("an input that ended mid-series was accepted"); + assert!( + error + .to_string() + .contains("ended before the last chunk of a series"), + "{what} reported {error} instead of a truncated input" + ); + } +} + /// A window over native histograms reserves what it retains, payload included, and the label-set /// ledger it charges beside that agrees with a full walk of the table. /// @@ -2458,6 +2506,38 @@ fn releasing_a_node_drops_the_queue_and_its_counts() { assert!(source.pop_source().unwrap().is_none()); } +/// A chunk whose axis and fields disagree is refused, not read past the end of a field. +/// +/// [`Series`] keeps its fields public, so a chunk built by struct literal -- by a caller of this +/// crate as much as by a mistake here -- can carry fewer samples than the axis places rows. The +/// label-set ledger reads every row the axis names, so it is where such a chunk would be read out of +/// bounds; it reports the misalignment against the node that was handed it instead. +#[test] +fn a_series_whose_axis_and_fields_disagree_is_rejected() { + let grid = grid(0, 60_000, 4); + // Two samples placed on a four-row axis: the third row the axis names has nothing to read. + let samples = Samples::from_float(Float64Array::from(vec![1.0, 2.0])); + let time = TimeAxis::Grid(GridRange::try_new(Arc::clone(&grid), 0, 4).unwrap()); + let series = Series { + metric: named_metric("requests", "job"), + time, + fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), + }; + let chunk = EvaluatedChunk::try_new(series, false).expect("the axis is addressed on a grid"); + + let mut emitted = Emitted::default(); + let error = emitted + .occupy(&NodePath::root(), &chunk) + .expect_err("a field with fewer samples than the axis places rows was accepted"); + let message = error.to_string(); + assert!( + message.contains("misaligned") + && message.contains("4 rows") + && message.contains("2 samples"), + "the rejection does not name what the axis places against what the field holds: {message}" + ); +} + /// One entry's figure is the heap it owns, and its `History` header is charged once, by its slot. /// /// The `History` of a label set lives in the map's slot, so a `size_of::()` term in the From 73760651f763753be321dbb49412743e04574539 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:51:20 +0800 Subject: [PATCH 08/33] feat(promql): execute an instant selection as a tree node The tree could not run `NativeExpr::Instant`: the state builder recorded `not_implemented` and refused the whole tree before reading a chunk, while the compiler already produced the node for a bare selector. A query the plan and the compiler both accept therefore had no runtime path at all. `InstantRuntime` buffers one series to its `is_last` chunk -- the selection kernel reads a complete axis -- then calls the shared `select_instants` once and gathers the rows it picked onto the binding's own grid. Positions come from the grid lattice the kernel was asked for, and a timestamp off that lattice is an error rather than a skipped row. A series that selects nothing still closes, with an empty chunk on the grid; an input that ends inside a series is reported on `finish()`. The node does not record label-set occupancy: it keeps the metric verbatim, so it cannot map two series onto one label set, and the occupancy key drops empty-valued tags -- two genuinely distinct series would be refused as a collision. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 491 ++++++++++++++++++++-- src/promql/src/native/execute/tests.rs | 546 ++++++++++++++++++++++++- 2 files changed, 994 insertions(+), 43 deletions(-) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 4f9853b6b2d..45a897d9db7 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -30,6 +30,12 @@ //! 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 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. @@ -50,20 +56,22 @@ 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::SeriesOrdering; +use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; use datatypes::series::histogram::HistogramBatch; -use datatypes::series::raw::RawSeriesChunk; +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, GridSpec, TimeAxis}; +use datatypes::series::{MetricName, SeriesOrdering}; -use crate::grid_series::{LabelSet, label_set}; +use crate::grid_series::{GridSample, GridSeriesBuilder, LabelSet, label_set}; +use crate::histogram_eval::float_histogram::FloatHistogram; +use crate::instant_eval::select_instants; use crate::map::{MathOp, drop_metric_name, map_math}; use crate::native::batch::EvaluatedChunk; use crate::native::metrics::{self, NodeMetrics, NodePath}; -use crate::native::plan::{BoundWindow, NativeExpr, NativeTree}; +use crate::native::plan::{BoundInstant, BoundWindow, NativeExpr, NativeTree}; use crate::range_eval::RangeEvaluator; #[cfg(test)] @@ -237,8 +245,26 @@ impl QueuedCharge { /// queue's new total. fn enqueue(&mut self, chunk: &NativeChunk) -> usize { let charged = self.walk(chunk); + self.add(chunk.own_bytes(), &charged) + } + + /// Counts the allocations a raw chunk references as a node buffers it, and returns the new + /// total. + /// + /// It is the same fold [`Self::enqueue`] makes, for a node that buffers the chunks of one series + /// itself rather than queueing the chunks it is handed: its chunks can share a histogram table + /// or an Arrow buffer just as queued ones can, and counting them chunk by chunk would charge one + /// allocation once per chunk of the series instead of once for the allocation. + fn enqueue_raw(&mut self, chunk: &RawSeriesChunk) -> usize { + let mut charged = ChargedAllocations::default(); + let _ = raw_bytes(chunk, &mut charged); // The struct a chunk is held by is its own; only what it points at can be shared. - self.bytes = self.bytes.saturating_add(chunk.own_bytes()); + self.add(std::mem::size_of::(), &charged) + } + + /// Adds one chunk's own struct and the allocations it references to the total. + fn add(&mut self, own_bytes: usize, charged: &ChargedAllocations) -> usize { + self.bytes = self.bytes.saturating_add(own_bytes); for &(table, bytes) in &charged.tables { count_reference(&mut self.tables, &mut self.bytes, table as usize, bytes); } @@ -386,6 +412,8 @@ fn segment_bytes(segment: &Samples, charged: &mut ChargedAllocations) -> 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. @@ -397,6 +425,7 @@ impl NodeTag { fn describe(self) -> &'static str { match self { Self::Input => "input", + Self::Instant => "instant selection", Self::Window => "window", Self::Map => "map", } @@ -409,6 +438,7 @@ impl NodeTag { /// the binding is collected first and the run-time state is built from the complete set. enum Seed { Input, + Instant(BoundInstant), Window(BoundWindow), Map(Arc<[MathOp]>), } @@ -926,6 +956,242 @@ impl WindowRuntime { } } +/// 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, folded in as chunks arrive and given back when the series is gathered. + held: QueuedCharge, +} + +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: QueuedCharge::default(), + }) + } + + /// The bytes the buffered chunks of the open series hold. + fn buffered_bytes(&self) -> usize { + self.held.bytes + } + + /// 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.enqueue_raw(&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 = QueuedCharge::default(); + 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 = grid_sample(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), + } + } + + /// Reports an input that ended inside a series this node was gathering. + fn finish(&self, path: &NodePath) -> Result<()> { + if self.chunks.is_empty() { + Ok(()) + } else { + Err(unfinished_series(path)) + } + } +} + +/// 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 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) +} + +/// The value a grid series holds for `sample`, or `None` when the sample is missing. +/// +/// It is the mapping every kernel applies when it turns a source sample into a grid value: a float +/// stays the float it is -- a `NaN` that is not the stale marker included -- a native histogram is +/// read out of the table it indexes, and a missing sample holds no value. +fn grid_sample(sample: SampleRef<'_>) -> Result> { + Ok(match sample { + SampleRef::Missing => None, + SampleRef::Float(value) => Some(GridSample::Float(value)), + SampleRef::Histogram(view) => Some(GridSample::Histogram(Box::new( + FloatHistogram::try_from_view(&view)?, + ))), + }) +} + +/// 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, @@ -933,6 +1199,8 @@ struct NodeRuntime { queued: VecDeque, /// What `queued` holds, folded in as chunks enter and out as they leave. queued_charge: QueuedCharge, + /// What an instant node holds. + instant: Option, /// What a window node holds. window: Option, /// What a map node applies. @@ -1129,6 +1397,58 @@ impl NodeRuntime { Ok(output) } + /// Buffers one chunk for 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 (bytes, positions, closing) = ( + chunk.bytes(&mut ChargedAllocations::default()), + chunk.positions(), + chunk.is_last(), + ); + // The chunk is held for as long as it enters the buffer. + self.buffer.hold(bytes)?; + 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(), chunk) { + (Some(instant), NativeChunk::Raw(chunk)) => 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. + (Some(_), NativeChunk::Evaluated(_)) => Err(DataFusionError::Execution(format!( + "the instant selection at {path} consumes raw samples, not an evaluated chunk" + ))), + (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); + } + // 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.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. + let buffered = self + .instant + .as_ref() + .map_or(0, InstantRuntime::buffered_bytes); + self.buffer.hold_exactly(buffered)?; + 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 @@ -1152,11 +1472,13 @@ 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 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 go with it. self.window = None; + self.instant = None; self.emitted = None; // A node that holds no chunk holds no series either, so nothing it handed over is still // open for it: the flag is what closing the execution reads, and it must not survive the @@ -1226,6 +1548,9 @@ impl NativeExecutionState { first_window.get_or_insert_with(|| path.clone()); Some((NodeTag::Window, Seed::Window(op.clone()))) } + NativeExpr::Instant { op, .. } => { + Some((NodeTag::Instant, Seed::Instant(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. @@ -1233,10 +1558,6 @@ impl NativeExecutionState { unsupported.get_or_insert_with(|| not_implemented("Scalar", path)); None } - NativeExpr::Instant { .. } => { - unsupported.get_or_insert_with(|| not_implemented("Instant", path)); - None - } NativeExpr::Aggregate { .. } => { unsupported.get_or_insert_with(|| not_implemented("Aggregate", path)); None @@ -1291,7 +1612,7 @@ impl NativeExecutionState { for (index, node) in pending.iter().enumerate() { let input = match node.tag { NodeTag::Input => None, - NodeTag::Window | NodeTag::Map => { + NodeTag::Instant | NodeTag::Window | NodeTag::Map => { let path = node.path.input(); Some(*by_path.get(&path).ok_or_else(|| { DataFusionError::Execution(format!( @@ -1306,6 +1627,7 @@ impl NativeExecutionState { buffer, queued: VecDeque::new(), queued_charge: QueuedCharge::default(), + instant: None, window: None, map: None, emitted: None, @@ -1313,6 +1635,26 @@ impl NativeExecutionState { }; match &node.seed { Seed::Input => {} + Seed::Instant(instant) => { + let child = input.ok_or_else(|| { + DataFusionError::Execution(format!( + "the instant selection at {} has no input", + node.path + )) + })?; + let input_schema = pending[child].output_schema.clone().ok_or_else(|| { + DataFusionError::Execution(format!( + "the instant selection at {} consumes samples, but its input produces \ + none", + node.path + )) + })?; + runtime.instant = Some(InstantRuntime::try_new(&input_schema, instant)?); + // 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. + } Seed::Map(ops) => { let schema = node.output_schema.clone().ok_or_else(|| { DataFusionError::Execution(format!( @@ -1499,15 +1841,52 @@ 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 their accounting. + #[cfg(test)] + pub(crate) fn nodes_holding_instants(&self) -> usize { + self.runtimes + .iter() + .filter(|runtime| runtime.instant.is_some()) + .count() + } + + /// The bytes the buffered series at `path` charges for, and the same figure walked in full. + /// + /// Test-only: a selection holds a whole series, so what it reserves is the sum over the chunks + /// it holds, with an allocation two chunks share counted once. The running total the node keeps + /// is only correct if it agrees with one pass over the buffer. + #[cfg(test)] + fn instant_charge_pair(&self, path: &NodePath) -> (usize, usize) { + let index = *self + .by_path + .get(path) + .expect("the path names a node of this tree"); + let instant = self.runtimes[index] + .instant + .as_ref() + .expect("the path names an instant selection"); + let mut charged = ChargedAllocations::default(); + let walked = instant + .chunks + .iter() + .map(|chunk| raw_bytes(chunk, &mut charged)) + .fold(0usize, usize::saturating_add); + (instant.buffered_bytes(), walked) + } + /// 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 - /// the series, so what is left to do is to check that every series did close, and to return - /// everything the execution reserved. A window's evaluator is what holds a series and so - /// notices one that never ended; a tree with no window has none, so there the input node answers - /// the same question from [`NodeRuntime::open_source_series`], which follows what it handed over. - /// The first error found is the one reported, and the nodes are walked from the root down, so a - /// window above the input reports its own truncation as it always did. + /// the series and a selection gathers the whole series on it, so what is left to do is to check + /// that every series did close, and to return everything the execution reserved. A window's + /// evaluator and a selection's buffer are what hold a series and so notice one that never + /// ended; a tree with neither has nothing holding one, so there the input node answers the same + /// question from [`NodeRuntime::open_source_series`], which follows what it handed over. The + /// first error found is the one reported, and the nodes are walked from the root down, so a + /// window or a selection above the input reports its own truncation as it always did. fn close(&mut self) -> Result<()> { let mut result = Ok(()); for (path, runtime) in self.paths.iter().zip(self.runtimes.iter_mut()) { @@ -1517,6 +1896,12 @@ impl NativeExecutionState { { result = Err(error); } + if let Some(instant) = runtime.instant.as_ref() + && let Err(error) = instant.finish(path) + && result.is_ok() + { + result = Err(error); + } if runtime.open_source_series && result.is_ok() { result = Err(truncated_input(path)); } @@ -1652,6 +2037,19 @@ 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))); + } + } + } } } @@ -1675,6 +2073,13 @@ impl NativeExecutor { runtime.window(path, chunk) } + /// 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 tree's input node. fn push_source(&mut self, chunk: NativeChunk) -> Result<()> { self.check_running()?; @@ -1804,6 +2209,46 @@ 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 an input that ended inside a series an instant selection was gathering. +fn unfinished_series(path: &NodePath) -> DataFusionError { + DataFusionError::Execution(format!( + "the input of the instant selection at {path} ended before the last chunk of a series" + )) +} + +/// 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 under a window. /// /// It names the window that needs contiguity, the input that does not keep it, and the ordering diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index ddb96a57444..5b05818736b 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -193,6 +193,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 +298,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 { @@ -355,6 +416,7 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { ), queued: VecDeque::new(), queued_charge: QueuedCharge::default(), + instant: None, window: None, map: None, emitted: None, @@ -458,11 +520,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 { @@ -828,23 +895,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 { @@ -878,7 +928,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), ]; @@ -2749,3 +2798,460 @@ 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" + ); +} + +/// 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, folded 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. The figure is the one the queue of a source keeps: an +/// allocation two chunks share is counted once, which is what one pass over the buffer counts. +#[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()]; + execution + .push_raw(raw_chunk(&schema, ×tamps, &values, false)) + .unwrap(); + assert!( + execution.next_chunk().unwrap().is_none(), + "a series was reported before its last chunk arrived" + ); + let held = execution.state().reserved_bytes(); + let (folded, walked) = execution.state().instant_charge_pair(&NodePath::root()); + assert_eq!( + folded, walked, + "the reservation is not what one pass over the buffered series counts" + ); + assert_eq!( + held, folded, + "the buffered series is not what is reserved for" + ); + assert!( + held > previous, + "the chunk was not reserved for: {held} bytes held after {previous}" + ); + 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 selection's own limits are reported as its error, and an error stops the execution. +#[test] +fn an_oversized_selection_is_reported_as_its_error() { + // One million and two grid points over two samples: more points than the kernel will decide. + 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 = pool(); + 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!( + error.to_string().contains("exceed limit"), + "the selection's own limit was not the error reported: {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. +#[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" + ); +} From 3630ba0488d7cdb32900f9d2fec6c37175f8f5fb Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:54:11 +0800 Subject: [PATCH 09/33] fix(promql): refuse an interleaved input, and close a label set only for its owner Two series-level identity holes, both reported against `42ea525`. The truncation flag followed the last chunk handed over, which is the same as "is a series open" only while at most one series can be open. A tree with no window still accepted `Interleaved`, and `a` open, `b` closed, end of input then passed while `a` never closed. Tracking the open set would need an identity that a raw chunk in bound-label mode does not have (`metric` is `None`, the key holds it), so the ordering is refused when the state is built instead, for every tree shape and not only under a window. The flag's doc now says what it means and why that is the whole answer. `History` closed on any series' `is_last`, so with `abs` dropping the metric name a series that contributed nothing could close a label set another series was still filling: `a{job="x"}` value, `b{job="x"}` empty close, `a{job="x"}` continuation was refused with "already closed the label set". Contiguous input hands over exactly that sequence, so it was not an interleaving artefact. A history now remembers the series that filled it and closes only for that series' closing chunk; a series that produced nothing under an open set is passed over, as it already was under a closed one. The owner is charged as part of the entry. The ordering check also reads every input node rather than only the first: a tree with two inputs would otherwise have its second declaration read and dropped. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 226 +++++++++++++++++-------- src/promql/src/native/execute/tests.rs | 187 +++++++++++++++----- 2 files changed, 297 insertions(+), 116 deletions(-) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 4f9853b6b2d..b1e2afe9a28 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -51,13 +51,13 @@ use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReser use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet; use datatypes::arrow::array::{Array, Float64Array}; use datatypes::arrow::buffer::Buffer; -use datatypes::series::SeriesOrdering; use datatypes::series::histogram::HistogramBatch; use datatypes::series::raw::RawSeriesChunk; use datatypes::series::samples::{ DenseSamplesRef, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; use datatypes::series::time::{GridRange, TimeAxis}; +use datatypes::series::{MetricName, SeriesOrdering}; use crate::grid_series::{LabelSet, label_set}; use crate::map::{MathOp, drop_metric_name, map_math}; @@ -99,6 +99,17 @@ impl NativeChunk { } } + /// The identity of the series this chunk belongs to, when the chunk names it. + /// + /// A raw chunk in bound-label mode carries its identity in its key and no metric name, so there + /// is nothing to compare; an evaluated chunk always names the series it holds. + fn metric(&self) -> Option<&MetricName> { + match self { + Self::Raw(chunk) => chunk.metric.as_ref(), + Self::Evaluated(chunk) => Some(&chunk.series.metric), + } + } + /// The bytes this chunk holds, counting each shared allocation it references that `charged` has /// not met yet. fn bytes(&self, charged: &mut ChargedAllocations) -> usize { @@ -528,13 +539,37 @@ struct Emitted { struct History { /// The occupied runs of each field, in position order and disjoint. fields: Vec>, + /// The source series that filled this label set, when the chunk that did named it. + /// + /// A chunk holding no value is handed over to close a series, never to fill a label set, so it + /// closes this one only when it belongs to the series that filled it: a second series that + /// produced nothing here is a series this label set never saw, and closing on its `is_last` + /// would leave the series that did produce the values unable to finish. `None` is a set filled + /// by chunks that named no series, where there is nothing to compare a closing chunk against. + owner: Option, /// Whether the series on this label set closed. A second series cannot close it again. closed: bool, - /// The heap this entry owns: the runs its per-field vectors hold, kept current by - /// [`Emitted::occupy`]. The header and the slot it sits in are charged by the table's capacity. + /// The heap this entry owns: the runs its per-field vectors hold and the owner's name and tags, + /// kept current by [`Emitted::occupy`]. The header and the slot it sits in are charged by the + /// table's capacity. bytes: usize, } +impl History { + /// Whether a chunk of `source` holding no value is the one that closes this label set. + /// + /// Only the series that filled it can: a series that produced nothing here is one this label + /// set never saw, so closing on its `is_last` would take the close away from the series that + /// did fill it. A chunk naming no series is compared with nothing and closes the set, which is + /// what every chunk did before the owner was kept. + fn closed_by(&self, source: Option<&MetricName>) -> bool { + match (self.owner.as_ref(), source) { + (Some(owner), Some(source)) => owner == source, + _ => true, + } + } +} + /// The bytes a label set holds: each label's name and value with the pair that refers to them. fn label_bytes(labels: &LabelSet) -> usize { labels @@ -543,7 +578,23 @@ fn label_bytes(labels: &LabelSet) -> usize { .sum() } -/// The bytes a history holds: the per-field vectors and the runs in them. +/// The bytes a metric name holds: its name and each tag's name and value, with the tags that refer +/// to them. +/// +/// This is the convention [`label_bytes`] keeps: the payload of the shared strings and one row per +/// label. The `Option` a [`History`] keeps its owner in is not counted here, being part +/// of the header that entry's slot is charged for. +fn metric_bytes(metric: &MetricName) -> usize { + metric.name().map_or(0, |name| name.len()) + + std::mem::size_of_val(metric.tags()) + + metric + .tags() + .iter() + .map(|tag| tag.name.len() + tag.value.len()) + .sum::() +} + +/// The bytes a history holds: the per-field vectors, the runs in them and its owner. /// /// This is what the entry itself allocates, not the slot it is filed under: the `History` lives in /// the map's slot, and that slot is what [`Emitted::bytes`] charges with the table's capacity. A @@ -556,11 +607,16 @@ fn history_bytes(history: &History) -> usize { .iter() .map(|runs| runs.capacity() * std::mem::size_of::()) .sum::() + + history.owner.as_ref().map_or(0, metric_bytes) } impl Emitted { /// Records what `chunk` occupies, rejecting it against what this node already handed out. /// + /// `source` is the identity of the input series `chunk` came from, when the chunk names one: a + /// label set is filled by the series that contributes its values, and it is that series whose + /// closing chunk closes it (see [`History::owner`]). + /// /// 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 @@ -568,7 +624,12 @@ impl Emitted { /// 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<()> { + fn occupy( + &mut self, + path: &NodePath, + source: Option<&MetricName>, + chunk: &EvaluatedChunk, + ) -> Result<()> { let labels = label_set(&chunk.series.metric); let occupied: Vec> = chunk .series @@ -577,18 +638,18 @@ impl Emitted { .enumerate() .map(|(index, field)| occupied_runs(path, index, field, &chunk.series.time)) .collect::>()?; - // A chunk holding no value records nothing. If the label set is unknown or already closed, - // the series this chunk belongs to contributed no sample at all -- either it is the first - // such series, or a later one that also answers empty -- so there is nothing to report, - // nothing to merge and nothing to refuse. A label set still open is the other case: the - // chunk closes the series that *did* produce the values, so it falls through to close it. let empty = occupied.iter().all(Vec::is_empty); - if empty && self.sets.get(&labels).is_none_or(|history| history.closed) { - return Ok(()); - } - if let Some(history) = self.sets.get(&labels) { + let recorded = self.sets.get(&labels); + if let Some(history) = recorded { if history.closed { - return Err(closed_label_set(path, &labels)); + // A series that produced nothing under a closed label set contributes no sample, so + // there is nothing to report, nothing to merge and nothing to refuse. One that did + // produce values is the second series this set cannot take. + return if empty { + Ok(()) + } else { + Err(closed_label_set(path, &labels)) + }; } for (index, runs) in occupied.iter().enumerate() { let stored = history.fields.get(index).map_or(&[][..], Vec::as_slice); @@ -604,6 +665,17 @@ impl Emitted { } } } + // A chunk holding no value records nothing. Past a closed set the same series is the + // one that answered empty, and on an open set it is the close of the series that filled + // it -- but only of that series: a different one closes a label set it never wrote to, + // which would leave the series that did write to it unable to finish. + if empty && !(chunk.is_last && history.closed_by(source)) { + return Ok(()); + } + } else if empty { + // The first chunk onto a label set holds no value: a series that answered empty, with + // nothing to record, nothing to close and nothing to merge. + return Ok(()); } let fields = chunk.series.fields.len(); // The change is folded in here rather than recomputed when the figure is read: a node @@ -617,6 +689,14 @@ impl Emitted { } }; let before = history.bytes; + // The series that contributes the values is the one that owns the label set, so a chunk of + // another one cannot close it later on. + if !empty + && let Some(source) = source + && history.owner.as_ref() != Some(source) + { + history.owner = Some(source.clone()); + } if history.fields.len() < fields { history.fields.resize_with(fields, Vec::new); } @@ -638,10 +718,11 @@ impl Emitted { /// 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, the runs a history keeps - /// in its per-field vectors, and the table's capacity at one label-set slot plus one history - /// slot per entry -- which is where a `History` header itself is charged, once, for the entry - /// that lives in it. 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. + /// in its per-field vectors, the owner each entry keeps with its name and tags, and the table's + /// capacity at one label-set slot plus one history slot per entry -- which is where a `History` + /// header itself is charged, once, for the entry that lives in it. 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. /// /// The per-entry part is a running total, so reading this after every output does not walk the /// table: only the entry that changed and the table's own capacity are read here. @@ -950,12 +1031,10 @@ struct NodeRuntime { /// consumer saw did not close its series, and no chunk came after it. Nothing else writes it, so /// it cannot report a truncation that did not happen. /// - /// One flag is enough under the `Contiguous` and `KeyThenTime` orderings, which keep the chunks - /// of a series together: only the series last handed over can be open, and one that closed - /// cannot resume. An `Interleaved` input does reach a tree with no window above it -- that - /// ordering is refused only where a window reads a series at a time -- and there an earlier - /// series left open behind another one's chunk is not reported. The flag under-reports such a - /// stream; it never over-reports one. + /// "The series of the last chunk handed over" is the whole answer because no more than one + /// series can be open here: [`NativeExecutionState::try_new`] refuses an input declaring + /// `SeriesOrdering::Interleaved`, so the chunks of a series arrive together and the series last + /// handed over is the only one that could still be open. open_source_series: bool, } @@ -1060,8 +1139,10 @@ impl NodeRuntime { if let Some(output) = &output { metrics.record_grid_points(output.series.time.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)?; + // What it handed out is what the label sets of this node now hold. The identity is the + // input's: `map_chunk` has already rewritten the output's label set, and a series is + // the one that arrived. + self.track(path, Some(&chunk.series.metric), output)?; } let bytes = self.emitted_bytes(); self.buffer.hold_exactly(bytes)?; @@ -1075,6 +1156,12 @@ impl NodeRuntime { chunk.positions(), chunk.is_last(), ); + // Which series this chunk came from, for the label-set table below. A window consumes one + // series to its `is_last` before the next, so the chunk that closes an output label set is + // the one of the series that produced its values, which is what lets the table accept a + // closing chunk of a series that wrote to it. A raw chunk in bound-label mode names no + // series, so there is nothing to pass on. + let source = chunk.metric(); // The chunk is held for as long as the evaluator consumes it. self.buffer.hold(bytes)?; let metrics = Arc::clone(&self.buffer.metrics); @@ -1098,8 +1185,9 @@ impl NodeRuntime { if let Some(output) = &output { metrics.record_grid_points(output.series.time.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)?; + // What it handed out is what the label sets of this node now hold, and the series that + // filled one is the series its chunks came from. + self.track(path, source, output)?; } // 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 @@ -1131,13 +1219,20 @@ impl NodeRuntime { /// 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<()> { + /// `source` is the identity of the input series the chunk came from, when there is one: a node + /// that rewrites labels is where two input series become indistinguishable, so this is where + /// the second one is refused, and it is also the only place that knows which series filled the + /// label set a chunk closes. A 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, + source: Option<&MetricName>, + output: &EvaluatedChunk, + ) -> Result<()> { match self.emitted.as_mut() { - Some(emitted) => emitted.occupy(path, output), + Some(emitted) => emitted.occupy(path, source, output), // A node that keeps its input's labels cannot make two series one. None => Ok(()), } @@ -1209,23 +1304,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; + // The first input whose declared order this runtime cannot execute, and where it says so. + // Every node here reads one series at a time, so an input that interleaves them is one this + // runtime cannot execute. Recorded per input rather than kept from the first one seen: a + // tree with two inputs would otherwise have its second declaration read and dropped. + let mut unsupported_ordering_found: Option<(SeriesOrdering, NodePath)> = 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(bound) => { - ordering.get_or_insert_with(|| (bound.ordering, path.clone())); + if bound.ordering == SeriesOrdering::Interleaved { + unsupported_ordering_found + .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::Window { op, .. } => 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. @@ -1262,19 +1357,16 @@ 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)); - } - } + // 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 `is_last`, and an input + // node keeps one flag for the series it handed over, which is what reports one that never + // closed. An input that declares `Interleaved` can leave a series open across another + // series' chunks, which either of those would misread, so the tree is refused here rather + // than run. That is a precondition of the runtime, not a limitation to document: the tree + // stays free to declare the ordering -- the compiler's job is not narrowed here -- and no + // tree this runtime executes declares it. + if let Some((ordering, source)) = &unsupported_ordering_found { + return Err(unsupported_ordering(*ordering, source)); } // A node's input is the node at the same position extended by the step the traversal took, @@ -1804,19 +1896,15 @@ 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. +/// The rejection of an input ordering this runtime cannot execute. /// -/// 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 { +/// It names the input that declares the ordering and the ordering found, so a reader can tell a +/// tree this runtime cannot run from one it cannot run correctly. +fn unsupported_ordering(ordering: SeriesOrdering, 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 native runtime does not execute {ordering:?} input yet: the nodes here read one series \ + at a time, and the input at {input} is {ordering:?}, so the chunks of two of them can \ + arrive interleaved" )) } diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index ddb96a57444..93f810f83e7 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -1349,9 +1349,13 @@ fn a_merge_across_a_closed_series_is_not_implemented() { /// 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. +/// drops the name. Neither piece says it is the last chunk of its series, so the second one arrives +/// while the first is still open. 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. +/// +/// The ordering is contiguous because that is the only ordering this runtime executes: the stream +/// below is not one a scan produces, since it never closes `a`, and what is checked here is the +/// occupancy the check reads rather than a delivery order. /// /// 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 @@ -1361,10 +1365,10 @@ fn a_merge_across_a_closed_series_is_not_implemented() { 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), + evaluated_input_with_ordering(Arc::clone(&map_grid), SeriesOrdering::Contiguous), vec![MathOp::Abs], )) - .expect("a map-only tree is legal over an interleaved input"); + .expect("a map-only tree is legal over a contiguous input"); let schema = evaluated_schema(Arc::clone(&map_grid)); let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); @@ -1645,6 +1649,12 @@ fn a_chunk_with_no_output_keeps_charging_the_emitted_table() { } /// A window cannot run over an interleaved input, and the runtime says so before reading a chunk. +/// +/// The binding refuses a window whose own input declares the ordering, and the runtime refuses the +/// ordering itself -- which is what catches a window over a map over the source, where the binding +/// only sees the map. A tree with no window above the source is refused by the same check, since +/// every node here reads one series at a time; [`an_interleaved_input_is_refused_without_a_window`] +/// is that case on its own. #[test] fn a_window_over_an_interleaved_input_is_rejected() { let inner_grid = grid(0, 60_000, 2); @@ -1688,44 +1698,37 @@ fn a_window_over_an_interleaved_input_is_rejected() { ); 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); +/// An interleaved input is refused with no window above it to notice it. +/// +/// A map over an input has no evaluator, so nothing in the tree reads one series to its `is_last`. +/// The sequence the input node cannot tell from a whole one is `a{job="x"}` open, `b{job="y"}` +/// closed, and the end of the input: the flag that reports a series left open would say the last +/// chunk closed its series and `finish` would accept an input whose first series never closed. The +/// runtime therefore refuses the ordering when the state is built, before a chunk is read, instead +/// of reporting a truncation it cannot see. +#[test] +fn an_interleaved_input_is_refused_without_a_window() { + let map_grid = grid(0, 60_000, 2); 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)]), - ] + .expect("the binding accepts a map over an interleaved input"); + let error = + match NativeExecutionState::try_new(&tree, pool(), &ExecutionPlanMetricsSet::new(), 0) { + Ok(_) => panic!("the runtime accepted an interleaved input with no window above it"), + Err(error) => error, + }; + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "{error}" ); + let message = error.to_string(); + assert!(message.contains("Interleaved"), "{message}"); + assert!(message.contains("root.input"), "{message}"); } /// The charge for the label sets a node has handed out does not depend on how it is read. @@ -1781,6 +1784,11 @@ fn the_emitted_charge_is_the_same_folded_in_as_walked() { /// This is the other order of [`two_series_with_no_result_do_not_collide`], and the one that used to /// fail: by the time the empty series arrives the label set is already closed, and refusing it /// failed an execution whose answer was never in doubt. +/// +/// The set is closed here, which is what makes the empty series a later one that also answers +/// empty. Its mirror image -- an empty closing chunk that arrives while the set is still open -- is +/// [`an_empty_closing_chunk_of_another_series_does_not_close_a_label_set`], where the same series +/// is not a harmless extra but would take the close away from the series that filled the set. #[test] fn a_series_with_no_result_after_a_closed_one_is_passed_over() { let map_grid = grid(0, 60_000, 1); @@ -1823,6 +1831,68 @@ fn a_series_with_no_result_after_a_closed_one_is_passed_over() { ); } +/// An empty closing chunk of one series does not close a label set another series is still filling. +/// +/// `abs` drops the metric name, so `a{job="x"}` and `b{job="x"}` are one label set to the map. `b` +/// holds no row at all: its closing chunk closes a series that contributed nothing, so it must not +/// close the set `a` opened, or `a`'s continuation would be refused for a label set that `a` itself +/// never closed. Two series back to back are what contiguous input hands over, so this is a stream +/// the runtime executes rather than an ordering it refuses. +#[test] +fn an_empty_closing_chunk_of_another_series_does_not_close_a_label_set() { + 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()); + + // `a` opens the label set and has not closed it when `b` closes an empty series onto it, and the + // chunk that closes `a` itself comes last. + let chunks = [ + evaluated_chunk_of(&schema, named_metric("a", "x"), 0, vec![Some(-1.0)], false), + evaluated_chunk_of(&schema, named_metric("b", "x"), 0, vec![], true), + evaluated_chunk_of(&schema, named_metric("a", "x"), 1, vec![Some(-2.0)], true), + ]; + let steps = chunks.len(); + let mut handed = Vec::new(); + for (step, chunk) in chunks.into_iter().enumerate() { + execution.push_evaluated(chunk).unwrap(); + while let Some(chunk) = execution + .next_chunk() + .unwrap_or_else(|error| panic!("step {step} was refused: {error}")) + { + handed.push(chunk); + } + } + assert_eq!( + handed.len(), + steps, + "the map did not consume all {steps} chunks it was given: {:?}", + decided(&handed) + ); + let last = handed.last().expect("the map handed nothing on"); + assert!(last.is_last, "the final output does not close its series"); + // `abs` drops the metric name, so the label set the output closes is `{job="x"}`. + let mut mapped = named_metric("a", "x"); + mapped.remove("__name__"); + assert_eq!( + last.series.metric, mapped, + "the final output closes a label set other than the one `abs` leaves of `a{{job=\"x\"}}`" + ); + assert_eq!( + (series_start(last), sample_values(last)), + (1, vec![Some(2.0)]), + "the value `a` held at position 1 did not survive" + ); + assert!( + execution.finish().unwrap().is_empty(), + "the map still held a chunk when the input ended" + ); +} + /// Two series that each produce no value at all are not a collision: both answer empty, and the /// node hands nothing on rather than refusing the second one. /// @@ -1958,10 +2028,10 @@ fn a_sparse_chunk_is_read_at_the_positions_it_holds_through_window_map_window() fn a_sparse_chunk_occupies_only_the_positions_it_holds() { let map_grid = grid(0, 60_000, 8); let tree = NativeTree::try_new(map( - evaluated_input_with_ordering(Arc::clone(&map_grid), SeriesOrdering::Interleaved), + evaluated_input(Arc::clone(&map_grid)), vec![MathOp::Abs], )) - .expect("a map-only tree is legal over an interleaved input"); + .unwrap(); let schema = evaluated_schema(Arc::clone(&map_grid)); let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); @@ -2527,7 +2597,7 @@ fn a_series_whose_axis_and_fields_disagree_is_rejected() { let mut emitted = Emitted::default(); let error = emitted - .occupy(&NodePath::root(), &chunk) + .occupy(&NodePath::root(), Some(&chunk.series.metric), &chunk) .expect_err("a field with fewer samples than the axis places rows was accepted"); let message = error.to_string(); assert!( @@ -2543,8 +2613,8 @@ fn a_series_whose_axis_and_fields_disagree_is_rejected() { /// The `History` of a label set lives in the map's slot, so a `size_of::()` term in the /// entry's own figure billed one header twice: once here and once in the capacity term beside it. /// The two assertions below are the definition of the whole figure -- the labels, the vectors and -/// their runs, and one label-set slot plus one history slot per entry -- so either header counted -/// in the wrong place fails them. +/// their runs, the owner's name and tags, and one label-set slot plus one history slot per entry -- +/// so either header counted in the wrong place fails them. #[test] fn a_history_entry_is_charged_once_for_its_header() { let grid = grid(0, 10_000, 2); @@ -2553,15 +2623,32 @@ fn a_history_entry_is_charged_once_for_its_header() { let labels = label_set(&metric); // Not the closing chunk: a closed label set drops its runs, and the runs are what the entry's // own figure is. - let chunk = evaluated_chunk_of(&schema, metric, 0, vec![Some(1.0), Some(2.0)], false); + let chunk = evaluated_chunk_of( + &schema, + metric.clone(), + 0, + vec![Some(1.0), Some(2.0)], + false, + ); let mut emitted = Emitted::default(); - emitted.occupy(&NodePath::root(), &chunk).unwrap(); + emitted + .occupy(&NodePath::root(), Some(&metric), &chunk) + .unwrap(); let history = emitted .sets .get(&labels) .expect("the chunk recorded its label set"); + // The owner the entry keeps is the series that filled it, so its name and each tag cost the + // same bytes the label set of the chunk did. + let owner = metric.name().map_or(0, |name| name.len()) + + std::mem::size_of_val(metric.tags()) + + metric + .tags() + .iter() + .map(|tag| tag.name.len() + tag.value.len()) + .sum::(); let entry = label_bytes(&labels) .saturating_add(history.fields.capacity() * std::mem::size_of::>()) .saturating_add( @@ -2570,7 +2657,13 @@ fn a_history_entry_is_charged_once_for_its_header() { .iter() .map(|runs| runs.capacity() * std::mem::size_of::()) .sum::(), - ); + ) + .saturating_add(owner); + assert_eq!( + history.owner.as_ref(), + Some(&metric), + "the entry does not name the series that filled it" + ); assert!( history.fields.iter().any(|runs| !runs.is_empty()), "the entry kept no run, so it has no heap of its own to charge for" @@ -2578,8 +2671,8 @@ fn a_history_entry_is_charged_once_for_its_header() { assert_eq!( emitted.entries, entry, - "the entry's own bytes are not its labels and runs alone: a `History` header in the figure \ - would add the {} bytes its slot already charges", + "the entry's own bytes are not its labels, its runs and its owner: a `History` header in \ + the figure would add the {} bytes its slot already charges", std::mem::size_of::(), ); assert_eq!( @@ -2625,7 +2718,7 @@ fn a_sparse_series_that_moves_forward_is_appended_to_its_history() { false, ); emitted - .occupy(&path, &chunk) + .occupy(&path, Some(&chunk.series.metric), &chunk) .unwrap_or_else(|error| panic!("position {position} was refused: {error}")); }; // The runs stored under the one label set, which is what `absorb` keeps in position order. From 8b8e3cc66a39785361b8357f6870b4a1cce81ae9 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 00:06:26 +0800 Subject: [PATCH 10/33] fix(promql): reserve the instant gather's workspace and keep the histogram start Two findings from the review of the instant node. The gather allocates after the last chunk arrives: the concatenated axis, the descriptors that read it, the two arrays the selection returns, and the rows the builder keeps. Nothing asked the pool for any of it, so with one sample selected by every point of a million-point grid the node took tens of megabytes while its reservation fell to the buffered chunks' size -- nothing at all, on the chunk that ends the series. `gather_bytes` now derives a bound from the values in hand (rows, chunks, segments, fields, points, and the widest histogram row per field, since one row can be selected by every point), and the reservation grows by it before the gather runs. It shrinks back on both the success and the error path, so the workspace never outlives the call. A selection reads an existing sample, so it has to carry that sample's payload. `FloatHistogram` had no `start_timestamp` and `push_to` wrote `None`, which lost it for any histogram that had one: `detect_start_timestamp_reset` reads that field to spot a counter reset, so a window over this output would mis-detect resets. The field is now carried through a view and written back; the kernels that compute a histogram instead of reading one leave it `None`, which is what they produced before. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- .../src/histogram_eval/float_histogram.rs | 36 ++- src/promql/src/histogram_eval/tests.rs | 72 +++++ src/promql/src/native/execute.rs | 204 +++++++++++++- src/promql/src/native/execute/tests.rs | 262 +++++++++++++++++- 4 files changed, 559 insertions(+), 15 deletions(-) diff --git a/src/promql/src/histogram_eval/float_histogram.rs b/src/promql/src/histogram_eval/float_histogram.rs index 30147d01645..1d067b1758f 100644 --- a/src/promql/src/histogram_eval/float_histogram.rs +++ b/src/promql/src/histogram_eval/float_histogram.rs @@ -35,6 +35,19 @@ 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 payload rather than a property of a computed value: [`Self::try_from_view`] carries + /// it because the sample it reads has one 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`] and [`Self::copy_to_schema`], with the + /// constructors beside them -- leaves it `None`, as Go's `FloatHistogram`, which has no such + /// field, does. [`Self::equals`] does not compare it for the same reason. + /// + /// It is not cosmetic: a reader detects a counter reset from a start timestamp that falls + /// inside the range it reads, so a sample handed on without one is a sample whose reset cannot + /// be told from its bucket counts alone. + pub(crate) start_timestamp: Option, pub(crate) schema: i32, pub(crate) zero_threshold: f64, pub(crate) zero_count: f64, @@ -62,6 +75,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, @@ -138,7 +152,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, @@ -159,6 +173,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, @@ -177,6 +192,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; @@ -190,6 +207,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; @@ -223,6 +242,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; @@ -231,13 +252,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, @@ -263,6 +290,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, @@ -331,6 +360,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, @@ -418,6 +449,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..32c7d44f13d 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}; @@ -385,6 +388,75 @@ fn histogram_points(series: &Series) -> BTreeMap { /// `histogram_quantile` drops all metadata labels; the single-histogram functions drop only /// `__name__`, as Prometheus does. +/// The start timestamp is payload of a histogram that was read, and not of one that was computed. +/// +/// It 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; +/// every operation that derives a value from its input leaves it `None`, as Go's `FloatHistogram`, +/// which has no such field, does. 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)); +} + #[test] fn histogram_functions_drop_metadata_labels() { let grid = Arc::new( diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index c3f2f1dae35..675a3e7063c 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -57,7 +57,7 @@ use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReser use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet; use datatypes::arrow::array::{Array, Float64Array}; use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; -use datatypes::series::histogram::HistogramBatch; +use datatypes::series::histogram::{HistogramBatch, HistogramView}; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{ DenseSamplesRef, RowCursor, SampleRef, Samples, Series, SeriesFields, SeriesSchema, @@ -1080,6 +1080,101 @@ impl InstantRuntime { self.held.bytes } + /// 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 its + /// bound grid decides, 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 of the grid, 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 grid 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 + /// a grid decides are reserved for whatever their number is. + fn gather_bytes(&self, closing: &RawSeriesChunk) -> usize { + // The bound grid validated that its length fits a `usize`. + let points = usize::try_from(self.selection.output_grid.spec().len).unwrap_or(usize::MAX); + 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 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 point of the grid 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 @@ -1209,6 +1304,67 @@ fn buffered_fields(chunks: &[RawSeriesChunk], fields: usize) -> Result 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 [`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. @@ -1497,6 +1653,22 @@ impl NodeRuntime { ); // The chunk is held for as long as it enters the buffer. self.buffer.hold(bytes)?; + // 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. + if let (NativeChunk::Raw(raw), true) = (&chunk, closing) { + let scratch = self + .instant + .as_ref() + .map_or(0, |instant| instant.gather_bytes(raw)); + self.buffer.hold(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 @@ -1520,21 +1692,41 @@ impl NodeRuntime { // the whole series on it, so it is counted here rather than on the chunk handed out. metrics.record_completed_series(1); } - // An error leaves the reservation to the driver, which releases every node when it stops. - let output = outcome?; + // 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. What stays + // reserved is the buffered series the node still holds, which is what `hold_buffered` + // counts. Shrinking asks the pool for nothing, so it cannot fail for want of capacity. + let output = match outcome { + Ok(output) => output, + Err(error) => { + self.hold_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. + // 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.hold_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 hold_buffered(&mut self) -> Result<()> { let buffered = self .instant .as_ref() .map_or(0, InstantRuntime::buffered_bytes); - self.buffer.hold_exactly(buffered)?; - Ok(output) + self.buffer.hold_exactly(buffered) } /// Records what this node hands out under its output label set. diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 193ddf6991a..b9061ee0318 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -93,11 +93,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, } @@ -381,6 +386,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 @@ -539,6 +597,25 @@ fn field_values(chunk: &EvaluatedChunk, index: usize) -> 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 @@ -1780,6 +1857,74 @@ 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 execution is built, not run. +/// +/// The binding accepts this tree: the plan's `Instant` arm has no ordering check yet -- #9785 adds +/// one to `validate`, so that half of the refusal arrives in a separate change. The tree can +/// therefore be *built* here and cannot be *executed*, which is exactly the split this runtime +/// keeps: an instant selection reads one series to its `is_last` and holds no cross-series state, +/// but the input node's flag -- and every node above it -- assumes the chunks of a series arrive +/// together, so an input declaring `Interleaved` is refused before a chunk is read. The shape with +/// a map between the input and 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 tree = NativeTree::try_new(instant( + raw_input_with_ordering(SeriesOrdering::Interleaved), + 60_000, + 0, + Arc::clone(&out_grid), + )) + .expect("the binding accepts a selection over an interleaved input"); + let error = + match NativeExecutionState::try_new(&tree, pool(), &ExecutionPlanMetricsSet::new(), 0) { + Ok(_) => panic!("the runtime accepted an interleaved input under a selection"), + Err(error) => error, + }; + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "{error}" + ); + let message = error.to_string(); + assert!(message.contains("Interleaved"), "{message}"); + assert!(message.contains("root.input"), "{message}"); +} + +/// The same refusal with a map between the input and the selection. +/// +/// A map passes chunks through in the order they arrive, so the selection still reads an +/// interleaved stream even though the node below it is a map: the ordering is a property of the +/// input, and the runtime records it there rather than at the node that reads it. +#[test] +fn an_interleaved_input_is_refused_under_a_map_over_a_selection() { + let out_grid = grid(0, 60_000, 2); + let tree = NativeTree::try_new(map( + instant( + raw_input_with_ordering(SeriesOrdering::Interleaved), + 60_000, + 0, + Arc::clone(&out_grid), + ), + vec![MathOp::Abs], + )) + .expect("the binding accepts a map over a selection over an interleaved input"); + let error = + match NativeExecutionState::try_new(&tree, pool(), &ExecutionPlanMetricsSet::new(), 0) { + Ok(_) => { + panic!("the runtime accepted an interleaved input under a map and a selection") + } + Err(error) => error, + }; + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "{error}" + ); + let message = error.to_string(); + assert!(message.contains("Interleaved"), "{message}"); + assert!(message.contains("root.input.input"), "{message}"); +} + /// The charge for the label sets a node has handed out does not depend on how it is read. /// /// The table only grows, so the figure is folded in as each entry changes rather than walked after @@ -3165,6 +3310,41 @@ fn a_position_no_field_fills_is_not_a_row() { ); } +/// 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 @@ -3211,6 +3391,11 @@ fn two_series_differing_only_in_an_empty_label_are_both_answered() { /// 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. The figure is the one the queue of a source keeps: an /// allocation two chunks share is counted once, which is what one pass over the buffer counts. +/// +/// 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); @@ -3255,13 +3440,72 @@ fn an_instant_selection_reserves_the_series_it_buffers() { ); } -/// The selection's own limits are reported as its error, and an error stops the execution. +/// The workspace the gather allocates is reserved for before it exists. +/// +/// A selection decides its whole grid at once, so its workspace is proportional to the points of +/// the grid 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. One sample selected +/// by a million points is the review's case: the two selection arrays alone are 16 MB and the built +/// rows are more, while the series the node holds is one sample of a few hundred bytes. +/// +/// 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_oversized_selection_is_reported_as_its_error() { - // One million and two grid points over two samples: more points than the kernel will decide. +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 grid past the removed point limit is refused by the pool, not by a count of its own. +/// +/// `gather_bytes` used to return zero for a grid this long, so that the kernel's own point limit +/// stayed the error reported. The kernel has no limit now, so the estimate applies to every gather +/// and what refuses this one is the pool, exactly as it refuses a grid under the limit. +#[test] +fn an_oversized_selection_is_refused_by_the_pool() { + // One million and two points over two samples: more points than the removed limit allowed. 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 = pool(); + let pool = bounded_pool(8 * 1024); let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); let schema = raw_schema(); execution @@ -3270,8 +3514,12 @@ fn an_oversized_selection_is_reported_as_its_error() { let error = execution.next_chunk().unwrap_err(); assert!( - error.to_string().contains("exceed limit"), - "the selection's own limit was not the error reported: {error}" + 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); From fc2189f4c4d5aa5e98c7219d21bd0717a50f6913 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 00:08:44 +0800 Subject: [PATCH 11/33] docs(promql): describe the gather test by what this branch does The doc on `an_oversized_selection_is_refused_by_the_pool` said the kernel has no point limit any more. It does on this branch: the limit is removed on its own branch, which this one does not carry, so the comment described a state that has not arrived. What is true here is the order: the estimate now applies to every gather, so the pool is asked before the kernel is, and the pool's refusal is the one the caller sees. That is worth saying on its own -- a bound in bytes on the path that decides the points, rather than a count that says nothing about what they cost -- and it stays true after the limit goes. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute/tests.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index b9061ee0318..bd9e0e57dc2 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -3495,14 +3495,17 @@ fn an_instant_selection_reserves_the_workspace_it_gathers() { ); } -/// A grid past the removed point limit is refused by the pool, not by a count of its own. +/// 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 the kernel's own point limit -/// stayed the error reported. The kernel has no limit now, so the estimate applies to every gather -/// and what refuses this one is the pool, exactly as it refuses a grid under the limit. +/// `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: more points than the removed limit allowed. + // 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); From 1c77715c9a1983242d1704c74821761d5ca19174 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 02:18:18 +0800 Subject: [PATCH 12/33] feat(promql): execute vector binary nodes in the native runtime Checkpoint the vector-vector runtime and single shared matching kernel. Keep addressed input delivery, whole-input buffering, nested composition and error cleanup together. The existing arithmetic/comparison implementation remains the only computation path. Local review checkpoint only, not ready for publication: all-targets check passes; the current run has three new fixture failures. Independent review requires current-live workspace resizing, field-local matched storage and kept-value merge budgeting before approval. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 790 ++++++++++++-- src/promql/src/native/execute/tests.rs | 1346 +++++++++++++++++++++++- src/promql/src/vector_match.rs | 587 ++++++++++- src/promql/src/vector_match/tests.rs | 691 +++++++++++- src/promql/tests/native_binary.rs | 250 +++++ 5 files changed, 3536 insertions(+), 128 deletions(-) create mode 100644 src/promql/tests/native_binary.rs diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 675a3e7063c..d62a072b1f3 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -36,6 +36,10 @@ //! 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. +//! //! 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. @@ -73,6 +77,9 @@ use crate::native::batch::EvaluatedChunk; use crate::native::metrics::{self, NodeMetrics, NodePath}; use crate::native::plan::{BoundInstant, BoundWindow, NativeExpr, NativeTree}; use crate::range_eval::RangeEvaluator; +use crate::vector_match::{ + BinaryMatching, binary_vectors_with_reservation, validate_binary_operand, +}; #[cfg(test)] mod tests; @@ -285,6 +292,29 @@ impl QueuedCharge { self.bytes } + /// What [`Self::add`] would add to the total for a chunk whose own struct is `own_bytes` and + /// which references `charged`, without adding it. + /// + /// It is the figure a caller reserves before it takes the chunk: the own struct and the + /// allocations the ledger does not already count, which is one allocation the first time a + /// chunk references it and nothing for the chunks that share it afterwards. An entry is only + /// present while at least one chunk references the allocation, so a key being absent is what + /// says those bytes are not charged yet. + fn increment(&self, own_bytes: usize, charged: &ChargedAllocations) -> usize { + let mut bytes = own_bytes; + for &(table, table_bytes) in &charged.tables { + if !self.tables.contains_key(&(table as usize)) { + bytes = bytes.saturating_add(table_bytes); + } + } + for &(buffer, buffer_bytes) in &charged.buffers { + if !self.buffers.contains_key(&(buffer as usize)) { + bytes = bytes.saturating_add(buffer_bytes); + } + } + bytes + } + /// Gives the allocations `chunk` references back, as that chunk leaves the queue, and returns /// the queue's new total. /// @@ -429,6 +459,8 @@ enum NodeTag { 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 { @@ -439,6 +471,7 @@ impl NodeTag { Self::Instant => "instant selection", Self::Window => "window", Self::Map => "map", + Self::Binary => "binary", } } } @@ -452,6 +485,12 @@ enum Seed { Instant(BoundInstant), Window(BoundWindow), Map(Arc<[MathOp]>), + /// A binary operation: its matching rules and the layout each operand is bound to. + Binary { + matching: Arc, + left: Arc, + right: Arc, + }, } /// One visited node, before its input's position is resolved. @@ -468,8 +507,20 @@ struct PendingNode { #[derive(Clone, Copy, Debug)] struct NodeSpec { tag: NodeTag, - /// The position of this node's input, resolved from the tree's own positions. - input: Option, + /// The positions of this node's inputs, resolved from the tree's own positions: the one input + /// of a unary node, the left and right operand of a binary node, and none for an input node. + inputs: [Option; 2], +} + +impl NodeSpec { + /// The position of input `slot`, which the tree has to have resolved. + fn input(&self, slot: usize) -> Result { + self.inputs + .get(slot) + .copied() + .flatten() + .ok_or_else(|| missing_input(self.tag)) + } } /// What every node holds: its metric handles and the bytes it reserves. @@ -1273,6 +1324,248 @@ impl InstantRuntime { } } +/// 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: the kernel groups +/// and matches whole series by label set and reads each one where its own axis places it, so the +/// chunks of a series are handed over as separate series entries and no row is copied to join them. +#[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 series this operand handed over, in arrival order. + series: Vec, + /// The bytes `series` hold, folded in as chunks arrive: two chunks of one series can share an + /// Arrow buffer or a histogram table, and the dedupe of [`QueuedCharge`] is what keeps one + /// allocation counted once for the whole operand. + held: QueuedCharge, +} + +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: the descriptor the operand takes for + /// it, and only those allocations the chunks it already holds do not reference. The figure is + /// what a caller reserves before it retains the chunk, so an allocation two chunks of one + /// series share is paid for once rather than once per chunk. + fn pending(&self, chunk: &EvaluatedChunk) -> usize { + let mut charged = ChargedAllocations::default(); + let _ = fields_bytes(&chunk.series.fields, &mut charged); + self.held.increment(std::mem::size_of::(), &charged) + } + + /// Retains one chunk, folding the allocations it references into what the operand holds. + fn enqueue(&mut self, chunk: EvaluatedChunk) { + let mut charged = ChargedAllocations::default(); + let _ = fields_bytes(&chunk.series.fields, &mut charged); + self.series.push(chunk.series); + self.held.add(std::mem::size_of::(), &charged); + } + + /// Drops the retained series, giving back what they hold. + fn release(&mut self) { + self.open = None; + self.series.clear(); + self.series.shrink_to_fit(); + self.held = QueuedCharge::default(); + } +} + +/// 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 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.bytes) + .fold(0usize, usize::saturating_add) + } + + /// The bytes the chunk of `side` would add to that operand's retention. + /// + /// It is read from the operand's own ledger before the chunk is retained, so the figure is the + /// one the operand grows by and not the chunk's own: a chunk holding a slice of an allocation + /// the operand already references costs the descriptor and nothing more. + 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 kernel allocates its matching tables, its per-point presence arrays and its result rows + /// before it can report anything it finds wrong with the operands, so it is handed a way to + /// reserve each figure before it allocates it: the callback receives the total workspace the + /// kernel is about to hold, and the reservation becomes the retained operands plus that + /// workspace. Nothing is estimated on the kernel's behalf -- the figure that is reserved is the + /// one the kernel itself derived, so the reservation is asked for before the allocation exists + /// and covers it for as long as it is alive. The reservation keeps covering what the kernel + /// returned until the caller queues it. + 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_operand, right_operand] = &self.operands; + let [left_schema, right_schema] = &self.schemas; + let (left, right) = (&left_operand.series, &right_operand.series); + let retained = self.retained_bytes(); + // The operands are still held while the kernel runs, so what this node holds is both the + // operands and the workspace the kernel reports; the callback resizes the reservation to + // that sum each time the kernel is about to grow. + 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(workspace) + .ok_or_else(|| reservation_overflow(path))?; + buffer.hold_exactly(bytes) + }, + ) + }; + // The operands 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?; + // Both operands have been read: what this node holds from here on is what the kernel + // returned, so the pool is not charged for a vector nothing reads again. + 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 @@ -1442,6 +1735,13 @@ struct NodeRuntime { 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, @@ -1496,12 +1796,14 @@ impl NodeRuntime { .fold(0usize, usize::saturating_add) } - /// Hands over the next queued source chunk, if there is one. + /// Hands over the next queued chunk, if there is one, charging the queue for what it held. /// - /// 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) = self.queued.pop_front() else { return Ok(None); }; @@ -1510,23 +1812,37 @@ impl NodeRuntime { let bytes = self.queued_charge.pop(&chunk); let metrics = Arc::clone(&self.buffer.metrics); { - // An input node's own work is handing the chunk over, so its self time covers that and + // This node's own work is handing the chunk over, so its self time covers that and // nothing its producer did. let _timer = metrics.timer(); // The chunk leaves this node, so the pool no longer has to hold it. self.buffer.hold_exactly(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)) } @@ -1641,6 +1957,78 @@ 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 series it retained, counted allocation + /// by allocation, and the reservation is set to that figure rather than grown per chunk: two + /// chunks of one series can share a histogram table or an Arrow buffer, and charging it per + /// chunk would make the reservation grow with the chunk count instead of with the data. + /// + /// The chunk is therefore reserved for by the increment it makes to the operand, not by what + /// it costs on its own: a chunk holding a slice of an allocation the operand already retains + /// adds its descriptor and nothing else. Reserving the whole chunk on top of the operand would + /// charge that allocation twice for as long as the call runs, and a pool holding what the node + /// really retains would refuse a chunk of an allocation the operand has already paid for. + 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 increment is read from the operand's ledger 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.hold(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.hold_exactly(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)?); + self.queued_charge.enqueue(&chunk); + self.queued.push_back(chunk); + 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: the interval between the two is the + // kernel's output being moved, and it is covered by the larger of the two figures. + self.buffer.hold_exactly(self.queued_charge.bytes) + } + /// Buffers one chunk for this node's instant selection. /// /// `None` means the series this chunk belongs to has not ended: the selection reads one whole @@ -1766,6 +2154,8 @@ impl NodeRuntime { // handed out go with it. self.window = None; self.instant = None; + self.binary = None; + self.source_schema = None; self.emitted = None; // A node that holds no chunk holds no series either, so nothing it handed over is still // open for it: the flag is what closing the execution reads, and it must not survive the @@ -1797,10 +2187,8 @@ pub struct NativeExecutionState { by_path: HashMap, /// The index of the root node. root: usize, - /// 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 input node, in traversal order: where a caller's chunks enter. + sources: Vec, } impl NativeExecutionState { @@ -1840,7 +2228,9 @@ impl NativeExecutionState { } 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. + // that; this runtime simply does not execute them yet. A binary node is the one + // kind the arm below narrows further: legality is a wider set of operand types than + // the kernel takes. NativeExpr::Scalar(_) => { unsupported.get_or_insert_with(|| not_implemented("Scalar", path)); None @@ -1849,9 +2239,34 @@ impl NativeExecutionState { unsupported.get_or_insert_with(|| not_implemented("Aggregate", path)); None } - NativeExpr::Binary { .. } => { - unsupported.get_or_insert_with(|| not_implemented("Binary", path)); - None + 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 walk 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() => + { + Some(( + NodeTag::Binary, + Seed::Binary { + matching: Arc::new(matching.clone()), + left: Arc::clone(left), + right: Arc::clone(right), + }, + )) + } + _ => { + unsupported.get_or_insert_with(|| not_implemented("Binary", path)); + None + } + } } }; if let Some((tag, seed)) = plan { @@ -1894,17 +2309,25 @@ impl NativeExecutionState { let mut paths = Vec::with_capacity(pending.len()); let mut runtimes = Vec::with_capacity(pending.len()); for (index, node) in pending.iter().enumerate() { - let input = match node.tag { - NodeTag::Input => None, + // The child of a node is the node at the position its own input extends to, so the + // structure is read off the positions instead of a second traversal. + let child = |path: NodePath| -> Result { + by_path.get(&path).copied().ok_or_else(|| { + DataFusionError::Execution(format!( + "the native tree has no node at the input of {}", + node.path + )) + }) + }; + let inputs = match node.tag { + NodeTag::Input => [None, None], NodeTag::Instant | NodeTag::Window | NodeTag::Map => { - let path = node.path.input(); - Some(*by_path.get(&path).ok_or_else(|| { - DataFusionError::Execution(format!( - "the native tree has no node at the input of {}", - node.path - )) - })?) + [Some(child(node.path.input())?), None] } + NodeTag::Binary => [ + Some(child(node.path.left())?), + Some(child(node.path.right())?), + ], }; let buffer = NodeBuffer::new(&node.path, Arc::clone(&node.metrics), &pool); let mut runtime = NodeRuntime { @@ -1914,13 +2337,19 @@ impl NativeExecutionState { instant: None, window: None, map: None, + binary: None, + source_schema: None, emitted: None, open_source_series: false, }; match &node.seed { - Seed::Input => {} + Seed::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_schema.clone(); + } Seed::Instant(instant) => { - let child = input.ok_or_else(|| { + let child = inputs[0].ok_or_else(|| { DataFusionError::Execution(format!( "the instant selection at {} has no input", node.path @@ -1955,7 +2384,7 @@ impl NativeExecutionState { runtime.emitted = Some(Emitted::default()); } Seed::Window(window) => { - let child = input.ok_or_else(|| { + let child = inputs[0].ok_or_else(|| { DataFusionError::Execution(format!( "the window at {} has no input", node.path @@ -1973,11 +2402,27 @@ impl NativeExecutionState { // from two series. runtime.emitted = Some(Emitted::default()); } + Seed::Binary { + matching, + left, + right, + } => { + // Both operand positions are resolved above, and each operand's layout is the + // one its own child produces: the walk only built this node when both produce + // evaluated samples. + runtime.binary = Some(BinaryRuntime::new( + Arc::clone(matching), + [Arc::clone(left), Arc::clone(right)], + )); + // 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. + } } debug_assert_eq!(nodes.len(), index); nodes.push(NodeSpec { tag: node.tag, - input, + inputs, }); paths.push(node.path.clone()); runtimes.push(runtime); @@ -2003,31 +2448,41 @@ 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 root = *by_path.get(&NodePath::root()).ok_or_else(|| { DataFusionError::Execution("the native tree has no root node".to_string()) })?; - let source = nodes + // 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() - .position(|node| node.tag == NodeTag::Input) - .ok_or_else(|| { - DataFusionError::Execution("the native tree has no input node".to_string()) - })?; - let source_schema = pending[source].output_schema.clone().ok_or_else(|| { - DataFusionError::Execution(format!( - "the input node at {} does not produce samples", - pending[source].path - )) - })?; + .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, by_path, root, - source, - source_is_evaluated: source_schema.eval_grid.is_some(), + sources, }) } @@ -2137,6 +2592,19 @@ impl NativeExecutionState { .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 bytes the buffered series at `path` charges for, and the same figure walked in full. /// /// Test-only: a selection holds a whole series, so what it reserves is the sum over the chunks @@ -2161,6 +2629,26 @@ impl NativeExecutionState { (instant.buffered_bytes(), walked) } + /// 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<()> { + for (path, runtime) in self.paths.iter().zip(&self.runtimes) { + if runtime.open_source_series { + return Err(truncated_input(path)); + } + 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 @@ -2202,6 +2690,14 @@ 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 execution can still produce chunks. @@ -2221,6 +2717,7 @@ impl NativeExecutor { Self { state, phase: Phase::Running, + inputs_finished: false, } } @@ -2229,20 +2726,39 @@ 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. + /// A window and a map take whole chunks from their input, so nothing beyond the chunk in hand + /// is materialised on their edge. A binary node is the 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. pub fn next_chunk(&mut self) -> Result> { self.check_running()?; let root = self.state.root; @@ -2269,14 +2785,17 @@ impl NativeExecutor { /// 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. pub fn finish(&mut self) -> Result> { - let mut drained = Vec::new(); - loop { - match self.next_chunk() { - Ok(Some(chunk)) => drained.push(chunk), - Ok(None) => break, - Err(error) => return Err(error), - } + let mut drained = self.drain()?; + // A stream that ended mid-series 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); } + // Every source has ended. A binary node can answer its result now, and a binary node + // beneath another one answers in turn, so the drain runs to quiescence again. + self.inputs_finished = true; + drained.extend(self.drain()?); match self.state.close() { Ok(()) => { self.phase = Phase::Finished; @@ -2289,14 +2808,26 @@ impl NativeExecutor { } } + /// 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) => return Ok(drained), + Err(error) => return Err(error), + } + } + } + /// The next chunk of the node at `index`. fn pull(&mut self, index: usize) -> Result> { let tag = self.state.nodes[index].tag; - let input = self.state.nodes[index].input; + let spec = self.state.nodes[index]; match tag { NodeTag::Input => self.state.runtimes[index].pop_source(), NodeTag::Map => { - let child = input.ok_or_else(|| missing_input(tag))?; + let child = spec.input(0)?; // An operation that empties every position yields no chunk, and the map asks its // input again rather than reporting a decision it did not make. loop { @@ -2309,7 +2840,7 @@ impl NativeExecutor { } } NodeTag::Window => { - let child = input.ok_or_else(|| missing_input(tag))?; + let child = spec.input(0)?; // A window reports on the chunk that closes a series, so a chunk that decides // nothing yields nothing and the window asks its input again. loop { @@ -2322,7 +2853,7 @@ impl NativeExecutor { } } NodeTag::Instant => { - let child = input.ok_or_else(|| missing_input(tag))?; + let child = spec.input(0)?; // 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 { @@ -2334,6 +2865,28 @@ impl NativeExecutor { } } } + NodeTag::Binary => { + let (left, right) = (spec.input(0)?, spec.input(1)?); + // 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)?; + } + } + if !self.inputs_finished { + // Nothing has settled for a point that has an operand still arriving. + 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) + } } } @@ -2364,31 +2917,72 @@ impl NativeExecutor { runtime.instant(path, chunk) } - /// Queues a source chunk at the tree's input node. - fn push_source(&mut self, chunk: NativeChunk) -> Result<()> { + /// 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 { @@ -2478,6 +3072,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 @@ -2596,6 +3202,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 bd9e0e57dc2..e32f351eeee 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -34,8 +34,9 @@ use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis} use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::{ - ChargedAllocations, Emitted, History, NativeChunk, NativeExecutionState, NativeExecutor, - NodeBuffer, NodeRuntime, QueuedCharge, Run, absorb_rebuilds, label_bytes, map_chunk, raw_bytes, + BinaryRuntime, ChargedAllocations, Emitted, History, NativeChunk, NativeExecutionState, + NativeExecutor, NodeBuffer, NodeRuntime, QueuedCharge, Run, absorb_rebuilds, fields_bytes, + label_bytes, map_chunk, raw_bytes, }; use crate::evaluated::EvaluatedChunk; use crate::grid_series::{LabelSet, label_set}; @@ -477,6 +478,27 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { instant: None, window: None, map: None, + binary: None, + source_schema: None, + emitted: 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(), + queued_charge: QueuedCharge::default(), + 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, open_source_series: false, } @@ -509,7 +531,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 { @@ -3599,3 +3635,1307 @@ fn a_chunk_of_another_series_is_refused() { "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, + } +} + +/// 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, + }; + 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")]), + }; + 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<(Vec<(String, String)>, 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); +} + +/// Two chunks of one series that share one Arrow allocation are charged for it once, and the pool +/// is asked for the increment rather than for the chunk. +/// +/// A source hands over sibling slices of one batch, so both chunks reference one allocation: the +/// second costs the operand the descriptor that refers to it and nothing else. The budget here is +/// exactly what the operand holds, so a chunk reserved for on top of the allocation it shares would +/// be refused even though the node never holds more than it reserved. +#[test] +fn a_binary_operand_is_charged_the_increment_of_a_shared_allocation() { + 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 one chunk costs the operand on its own: the descriptor and the allocation, because a + // pass over one chunk does not know what the operand already holds. + let alone = |chunk: &EvaluatedChunk| { + let mut charged = ChargedAllocations::default(); + std::mem::size_of::() + fields_bytes(&chunk.series.fields, &mut charged) + }; + let (first_alone, second_alone) = (alone(&first), alone(&second)); + // What both cost together: the one allocation they are slices of, and a descriptor each. + let mut charged = ChargedAllocations::default(); + let held = [&first, &second] + .iter() + .map(|chunk| { + std::mem::size_of::() + fields_bytes(&chunk.series.fields, &mut charged) + }) + .fold(0usize, usize::saturating_add); + assert!( + first_alone + second_alone > held, + "the two chunks are not slices of one allocation: {first_alone} and {second_alone} bytes \ + add up to no more than the {held} they are charged together, so nothing would be charged \ + twice" + ); + + // The budget is the figure the operand holds, which a chunk reserved for on top of the + // allocation it shares would not fit into. + let pool = bounded_pool(held); + let mut runtime = binary_runtime(&pool, &schema); + let before = runtime.buffer.held; + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first)) + .unwrap(); + assert_eq!( + runtime.buffer.held - before, + first_alone, + "the first chunk of an allocation does not cost the descriptor and the allocation" + ); + let before = runtime.buffer.held; + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second)) + .unwrap(); + assert_eq!( + runtime.buffer.held - before, + std::mem::size_of::(), + "a chunk of the allocation the operand already retains cost more than its descriptor" + ); + assert_eq!( + runtime.buffer.held, held, + "the operand does not reserve what it holds" + ); + assert_eq!(pool.reserved(), held); + + // An allocation the operand does not hold yet is still charged: the increment is the descriptor + // and the new allocation, not the descriptor alone. + 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(), + alone(&own), + "a chunk of an allocation the operand does not hold is not charged for it" + ); +} + +/// The executor's binary node never reserves a chunk on top of the allocation it shares: the peak +/// of its own reservation is the operand it retains, not that plus the chunk it was handed. +/// +/// 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_does_not_reserve_a_shared_chunk_on_top() { + 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, counted the way its ledger counts: + // the one allocation the chunks are slices of, and one descriptor per chunk. + let mut charged = ChargedAllocations::default(); + let retained = [&first, &second] + .iter() + .map(|chunk| { + std::mem::size_of::() + fields_bytes(&chunk.series.fields, &mut charged) + }) + .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 the chunk it was handed on top of the allocation 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 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); +} diff --git a/src/promql/src/vector_match.rs b/src/promql/src/vector_match.rs index 5e49080fb87..2521167a082 100644 --- a/src/promql/src/vector_match.rs +++ b/src/promql/src/vector_match.rs @@ -25,10 +25,10 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use datafusion::error::{DataFusionError, Result}; -use datatypes::series::MetricName; -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::{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}; use crate::histogram_eval::float_histogram::FloatHistogram; @@ -136,29 +136,460 @@ pub fn binary_output_schema(lhs: &SeriesSchema, rhs: &SeriesSchema) -> Result Result> { + binary_vectors_with_reservation( + matching, + lhs_schema, + lhs, + rhs_schema, + rhs, + &mut |_: usize| -> Result<()> { Ok(()) }, + ) +} + +/// [`binary_vectors`], handing the workspace it needs 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** additional live workspace the operation +/// needs, never an increment: the first call covers what the operands' metadata bounds, and every +/// later call only grows it, because the rows the results keep are added as they are filed while a +/// step's scratch replaces the scratch of the step before it. 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 output = binary_output_schema(lhs_schema, rhs_schema)?; let grid = output .eval_grid .clone() .expect("set by binary_output_schema"); + let mut budget = Budget::new(reserve); + // The output schema's field list, one result table per field and the vector holding them. + let descriptors = output + .fields + .len() + .saturating_mul(std::mem::size_of::() + 2 * std::mem::size_of::()) + .saturating_add(std::mem::size_of::()); + budget.retain(descriptors)?; let mut errors = Vec::new(); let mut fields = Vec::with_capacity(output.fields.len()); for field in 0..output.fields.len() { 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)?); + fields.push(binary_field( + matching, + &grid, + &lhs, + &rhs, + &mut errors, + &mut budget, + )?); } earliest_error(errors)?; + // The merge holds every field's results at once: the triples it files, the table it files them + // in and the builder writing the series out are the last scratch of the operation. + let sets = fields + .iter() + .map(|results| results.series.len()) + .fold(0usize, usize::saturating_add); + let merge = merge_bytes( + budget.rows, + sets, + output.fields.len(), + budget.histograms, + budget.histogram_heap, + ); + budget.drop_scratch(); + budget.step(merge)?; merge_fields(fields, output) } +/// 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 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, charged twice for the +/// capacity each of the three vectors ends at. +const RESULT_ROW_BYTES: usize = + 2 * (2 * std::mem::size_of::() + 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 workspace a binary operation admits as it allocates. +/// +/// What the results retain -- rows, the label sets they are filed under, their histograms -- only +/// grows, while the scratch of a step replaces the scratch of the step before it. So the total +/// handed to the caller is the live peak: the retained bytes plus the largest scratch beside them, +/// never the sum of everything the operation allocated along the way. +struct Budget<'a> { + /// Admits a total of additional live workspace, or refuses it. + reserve: &'a mut dyn FnMut(usize) -> Result<()>, + /// The bytes the results keep until the operation returns. + retained: usize, + /// The largest scratch needed beside them by the step being run. + scratch: usize, + /// The largest total admitted so far. + total: usize, + /// The result rows filed, which the merge holds until it writes them out. + rows: usize, + /// The result rows holding a histogram, and the heap those histograms hold. + histograms: usize, + histogram_heap: usize, +} + +impl<'a> Budget<'a> { + fn new(reserve: &'a mut dyn FnMut(usize) -> Result<()>) -> Self { + Self { + reserve, + retained: 0, + scratch: 0, + total: 0, + rows: 0, + histograms: 0, + histogram_heap: 0, + } + } + + /// Retains `bytes` of results and admits the total covering them. + fn retain(&mut self, bytes: usize) -> Result<()> { + self.retained = self.retained.saturating_add(bytes); + self.admit() + } + + /// Admits a step needing `bytes` beside what is retained, replacing the previous step's + /// scratch. + fn step(&mut self, bytes: usize) -> Result<()> { + self.scratch = self.scratch.max(bytes); + self.admit() + } + + /// Forgets the last step's scratch: its tables and buffers are gone. + fn drop_scratch(&mut self) { + self.scratch = 0; + } + + /// Retains one histogram result row: the value it boxes and the heap its buckets hold. + fn retain_histogram(&mut self, heap: usize) -> Result<()> { + self.histograms = self.histograms.saturating_add(1); + self.histogram_heap = self.histogram_heap.saturating_add(heap); + self.retain(std::mem::size_of::().saturating_add(heap)) + } + + /// Hands the live total to `reserve` once it has grown. It never shrinks, so the caller never + /// gives back what a later step no longer needs. + fn admit(&mut self) -> Result<()> { + let total = self.retained.saturating_add(self.scratch); + if total > self.total { + self.total = total; + (self.reserve)(total)?; + } + Ok(()) + } +} + +/// What one field's tables, flags and messages cost before it pairs anything, with the largest +/// label-set key it can file a row under. +/// +/// 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 with the table holding them and the references indexing them; the duplicate scan +/// collects that side's present points; 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. +/// Nothing here counts the pairing the field walks: which series match and where their axes +/// overlap is only known as the walk reaches them. +fn field_metadata_bytes( + matching: &BinaryMatching, + include: &[Arc], + points: usize, + many: &Operand<'_>, + one: &Operand<'_>, +) -> (usize, usize) { + 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)>()) + // The duplicate scan's point list, one point per row the side carries at most. + .saturating_add(2 * std::mem::size_of::() * series.time.len()); + 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)) + }); + let errors = 3usize.saturating_mul(ERROR_TEXT_BYTES.saturating_add(text)); + ( + bytes.saturating_add(lookup).saturating_add(errors), + largest_key.saturating_add(include.len().saturating_mul(KEY_LABEL_BYTES)), + ) +} + +/// The bytes one pairing allocates before it files a row: the result label set `result_metric` +/// rewrites, the `group_*` labels it copies in, 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. 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, 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::