From 7d2d9a8d4e7977a47401afc9f4086e53ff04267d Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:10:45 +0800 Subject: [PATCH] fix(promql): match binary operands by logical series Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 266 ++++++++++++++++++++++--- src/promql/src/native/execute/tests.rs | 239 ++++++++++++++++++++-- src/promql/src/vector_match.rs | 33 +++ 3 files changed, 490 insertions(+), 48 deletions(-) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index f3c40542f84..8b33d369f7c 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -39,6 +39,8 @@ //! A vector–vector binary node is the one kind that reads two inputs: it retains the chunks of both //! operands and runs the matching kernel once the input has ended, because the operation pairs two //! whole vectors point by point and nothing is decided for a point until both sides are complete. +//! The chunks of one logical series are assembled into the single series the kernel matches before it +//! runs, so a series that arrived in many chunks is one candidate, not one per chunk. //! //! A node kind this runtime does not execute yet is rejected when the execution is built, naming //! the kind and its position. An unsupported tree therefore never starts, rather than answering @@ -66,7 +68,7 @@ use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{ DenseSamplesRef, RowCursor, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; -use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; +use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis}; use datatypes::series::{MetricName, SeriesOrdering}; use crate::grid_series::{GridSample, GridSeriesBuilder, LabelSet, label_set}; @@ -1326,9 +1328,15 @@ 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. +/// What is kept is the series each chunk carries, not a concatenation of them: a chunk is retained +/// as it arrives and nothing is copied on the way in, because the chunks of a series can share an +/// allocation and the figure the operand charges for is the data it holds rather than a running copy +/// of it. +/// +/// The kernel matches whole series by label set, so the chunks are assembled into one series per +/// logical series once the input has ended: a series that arrived in a thousand chunks is otherwise +/// a thousand candidates on this side for every candidate of the other, and its own rows would be +/// paired a chunk at a time. #[derive(Default)] struct BinaryOperand { /// The series whose last chunk did not close it, with the position after its last row. @@ -1338,11 +1346,18 @@ struct BinaryOperand { /// 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. + /// The chunks 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. + /// The chunk count at which each logical series closed, exclusive, in arrival order. + /// + /// The chunks `start..end` of one entry are one logical series: a label set that closes and + /// starts again is two of them, so a list of ends is what keeps the two apart where a label set + /// alone would read them as one. Only a chunk carrying `is_last` records an end, and it does so + /// whether or not it carries a row. + ends: Vec, + /// The bytes `series` and `ends` 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, } @@ -1350,28 +1365,175 @@ 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. + /// it, the room a chunk that closes its series needs in the boundary list, 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) + self.held + .increment(std::mem::size_of::(), &charged) + .saturating_add(self.ends_growth(chunk.is_last)) } /// Retains one chunk, folding the allocations it references into what the operand holds. fn enqueue(&mut self, chunk: EvaluatedChunk) { + let closing = chunk.is_last; + // The boundary list is storage the operand keeps, and it grows before the chunk is recorded + // in it: an end is charged for before it exists, the same figure `pending` reported. + self.held.bytes = self.held.bytes.saturating_add(self.ends_growth(closing)); 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); + if closing { + self.ends.push(self.series.len()); + } } - /// Drops the retained series, giving back what they hold. + /// The bytes the boundary list grows by when a chunk that ends its series `closing` is recorded + /// in it. + /// + /// The list holds one `usize` per closed logical series and grows by doubling from a first + /// allocation of four entries, so a record costs nothing while the capacity it has holds it and + /// otherwise costs the new capacity. + fn ends_growth(&self, closing: bool) -> usize { + let needed = self.ends.len() + 1; + if !closing || needed <= self.ends.capacity() { + return 0; + } + let capacity = (2 * self.ends.capacity()).max(4).max(needed); + (capacity - self.ends.capacity()) * std::mem::size_of::() + } + + /// The chunk ranges of the logical series this operand closed, in arrival order. + /// + /// Read after the input ended: a series that is still open has no end, and + /// [`BinaryRuntime::closed`] refuses such an input before anything is assembled. + fn boundaries(&self) -> impl Iterator> + '_ { + self.ends.iter().scan(0, |start, &end| { + let range = *start..end; + *start = end; + Some(range) + }) + } + + /// The bytes assembling this operand's chunks into logical series allocates, before it does. + /// + /// One series per closed logical series, on `schema`'s grid, and nothing that copies a sample: + /// the descriptors the chunks' fields are made of are collected and shared. What is counted is + /// therefore metadata only -- the entry in the assembled vector, the field list of the series, + /// and for each field the chunk descriptors it is collected into, the list + /// [`Samples::try_from_chunks`] flattens them into and the `Arc` it hands them over in, which is + /// one list of each per field per boundary. The axis adds the runs the boundary covers in the + /// vector they are collected in, and, from two runs on, the span and row-offset arrays + /// [`TimeAxis::from_grid_spans`] copies them into; a single run becomes a [`GridRange`] and + /// allocates neither. + fn assembly_bytes(&self, schema: &SeriesSchema) -> Option { + let samples = std::mem::size_of::(); + let grids = std::mem::size_of::(); + let width = schema.fields.len(); + let mut bytes = 0usize; + for boundary in self.boundaries() { + let chunks = &self.series[boundary]; + // The runs the boundary covers, and the dense segments its fields hold: a chunk's field + // can itself be chunked, and flattening it copies one descriptor per segment. + let mut runs = 0usize; + let mut segments = 0usize; + for chunk in chunks { + runs = runs.checked_add(chunk.time.runs().count())?; + for field in chunk.fields.iter() { + segments = segments.checked_add(field.segments().len())?; + } + } + let descriptors = chunks + .len() + .checked_mul(width)? + .checked_add(segments.checked_mul(2)?)?; + let collected = runs.checked_mul(grids)?; + let ranges = if runs > 1 { + runs.checked_mul(grids.checked_add(std::mem::size_of::())?)? + } else { + 0 + }; + bytes = bytes + .checked_add(std::mem::size_of::())? + .checked_add(width.checked_mul(samples)?)? + .checked_add(descriptors.checked_mul(samples)?)? + .checked_add(collected)? + .checked_add(ranges)?; + } + Some(bytes) + } + + /// The logical series this operand closed, each as one series on `schema`'s grid. + /// + /// The chunks of a logical series are collected, not concatenated: the fields keep one + /// descriptor per segment of every chunk, the axis keeps the runs the chunks cover, and the + /// buffers behind both are shared with the chunks this operand still holds. The series is what + /// the kernel matches and reads, so it must be on the schema's grid and hold as many rows as its + /// axis places, which is what [`Series::try_new`] checks. What it allocates is + /// [`Self::assembly_bytes`], which a caller reserves before this runs. + fn assemble(&self, schema: &SeriesSchema, path: &NodePath, side: usize) -> Result> { + let grid = schema.eval_grid.clone().ok_or_else(|| { + DataFusionError::Execution(format!( + "the binary node at {path} assembles its {} operand on an evaluation grid, and the \ + operand's schema names none", + side_name(side) + )) + })?; + let mut assembled = Vec::with_capacity(self.ends.len()); + for boundary in self.boundaries() { + let chunks = &self.series[boundary]; + let metric = chunks.first().map(|chunk| chunk.metric.clone()).ok_or_else(|| { + DataFusionError::Execution(format!( + "the binary node at {path} closed a logical series of its {} operand without a \ + chunk to assemble", + side_name(side) + )) + })?; + let runs = chunks + .iter() + .map(|chunk| chunk.time.runs().count()) + .fold(0usize, usize::saturating_add); + let mut spans = Vec::with_capacity(runs); + for chunk in chunks { + for run in chunk.time.runs() { + spans.push(GridSpan::new(run.position, run.len)); + } + } + let mut fields = Vec::with_capacity(schema.fields.len()); + for index in 0..schema.fields.len() { + let mut segments = Vec::with_capacity(chunks.len()); + for chunk in chunks { + let field = chunk.fields.get(index).ok_or_else(|| { + DataFusionError::Execution(format!( + "the binary node at {path} cannot assemble its {} operand: a chunk of \ + it carries {} fields, not {}", + side_name(side), + chunk.fields.len(), + schema.fields.len() + )) + })?; + segments.push(field.clone()); + } + fields.push(Samples::try_from_chunks(segments).map_err(series_error)?); + } + let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?; + let time = TimeAxis::from_grid_spans(grid.clone(), spans).map_err(series_error)?; + assembled.push(Series::try_new(schema, metric, time, fields).map_err(series_error)?); + } + Ok(assembled) + } + + /// Drops the retained chunks, giving back what they hold. fn release(&mut self) { self.open = None; self.series.clear(); self.series.shrink_to_fit(); + self.ends.clear(); + self.ends.shrink_to_fit(); self.held = QueuedCharge::default(); } } @@ -1379,9 +1541,10 @@ impl BinaryOperand { /// 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. +/// in hand the way a map does: it retains every chunk each operand hands over, assembles the chunks +/// of each logical series into the one series the kernel matches, and runs the kernel once, after the +/// input has ended and both operands closed. The chunks it produces are queued in the node's own +/// output queue and handed over from there. struct BinaryRuntime { /// The operation and its modifiers, bound by the compiler. matching: Arc, @@ -1421,6 +1584,24 @@ impl BinaryRuntime { .fold(0usize, usize::saturating_add) } + /// The bytes assembling both operands into logical series allocates, before it does. + fn assembly_bytes(&self) -> Option { + let [left, right] = &self.operands; + let [left_schema, right_schema] = &self.schemas; + left.assembly_bytes(left_schema)? + .checked_add(right.assembly_bytes(right_schema)?) + } + + /// The logical series both operands closed, ready for the kernel to match. + fn assemble(&self, path: &NodePath) -> Result<[Vec; 2]> { + let [left, right] = &self.operands; + let [left_schema, right_schema] = &self.schemas; + Ok([ + left.assemble(left_schema, path, 0)?, + right.assemble(right_schema, path, 1)?, + ]) + } + /// The bytes the chunk of `side` would add to that operand's retention. /// /// It is read from the operand's own ledger before the chunk is retained, so the figure is the @@ -1510,10 +1691,15 @@ impl BinaryRuntime { /// Runs the kernel over both operands and returns the series it produced. /// + /// The chunks of each operand are assembled into the logical series they make up first, because + /// the kernel matches whole series by label set: a series that arrived in many chunks would + /// otherwise be a candidate per chunk on its own side and be paired with every candidate of the + /// other, which is quadratic in the chunk count of one series rather than in the series count. + /// /// The kernel requests a conservative live-workspace budget before allocating its matching - /// tables, per-point presence arrays and results. The reservation covers the retained operands - /// plus that workspace, and resizes as temporary storage is released. It keeps covering the - /// returned results until the caller queues them. + /// tables, per-point presence arrays and results. The reservation covers the retained chunks, + /// the assembled series the kernel reads and that workspace, and resizes as temporary storage is + /// released. It keeps covering the returned results until the caller queues them. fn compute(&mut self, path: &NodePath, buffer: &mut NodeBuffer) -> Result>> { // The kernel reads the operands once and drops them, so a second call has nothing to read // and nothing left to produce: what it produced the first time is in the node's queue, and @@ -1522,13 +1708,30 @@ impl BinaryRuntime { 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 as the live workspace changes. + // The assembled series are live while the kernel reads them and share the buffers the + // retained chunks hold, so what they add is metadata, and it is reserved before it exists: + // the assembly allocates as it goes, and a figure read from it afterwards would be a figure + // the pool never admitted. + let assembly = self + .assembly_bytes() + .ok_or_else(|| reservation_overflow(path))?; + buffer.hold(assembly)?; + let assembled = match self.assemble(path) { + Ok(assembled) => assembled, + Err(error) => { + // Nothing the assembly allocated outlives this call, so the node falls back to what + // it still holds. A failure of that resize is the pool's to report; the driver stops + // the execution either way and releases every node. + buffer.hold_exactly(retained)?; + return Err(error); + } + }; + let [left, right] = &assembled; + // The operands are still held while the kernel runs, so what this node holds is the operands, + // the assembled series and the workspace the kernel reports; the callback resizes the + // reservation to that sum as the live workspace changes. let metrics = Arc::clone(&buffer.metrics); let output = { // The timer covers this node's own work only: it is dropped before the driver polls @@ -1542,18 +1745,21 @@ impl BinaryRuntime { right, &mut |workspace| { let bytes = retained - .checked_add(workspace) + .checked_add(assembly) + .and_then(|held| held.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. + // The operands and the assembled series have been handed to the kernel and the reservation + // covers the workspace it allocated past them, so a failure is the driver's to release: it + // stops the execution and every node with it. let output = output?; - // 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. + // The assembled series were the kernel's input and are read by nothing after it, so they go + // before the chunks they share their buffers with: what this node holds from here on is what + // the kernel returned, and the pool is not charged for a vector nothing reads again. + drop(assembled); for operand in &mut self.operands { operand.release(); } diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 3b197d251ef..31a42c530fa 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -28,7 +28,7 @@ use datatypes::series::histogram::{ }; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{ - FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, + DenseSamplesRef, FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName, SeriesOrdering}; @@ -47,7 +47,9 @@ use crate::native::plan::{ BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, }; use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow}; -use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels}; +use crate::vector_match::{ + BinaryMatching, BinaryOp, Cardinality, MatchingLabels, reset_visited_pairs, visited_pairs, +}; fn grid(start: i64, step: i64, len: u64) -> Arc { Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) @@ -4339,14 +4341,18 @@ fn a_binary_operand_is_charged_the_increment_of_a_shared_allocation() { 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. + // What both cost together: the one allocation they are slices of, a descriptor each, and the + // room the closing chunk's end takes in the operand's boundary list -- the list is storage the + // operand keeps, and its first end allocates room for four. + let boundaries = 4 * std::mem::size_of::(); 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); + let held = boundaries + + [&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 \ @@ -4373,8 +4379,9 @@ fn a_binary_operand_is_charged_the_increment_of_a_shared_allocation() { .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" + std::mem::size_of::() + boundaries, + "a chunk of the allocation the operand already retains cost more than its descriptor and \ + the end it records" ); assert_eq!( runtime.buffer.held, held, @@ -4395,6 +4402,36 @@ fn a_binary_operand_is_charged_the_increment_of_a_shared_allocation() { alone(&own), "a chunk of an allocation the operand does not hold is not charged for it" ); + + // Assembling the two chunks keeps the allocation they are slices of: the series the kernel reads + // is made of their descriptors, and no sample is copied into it. + let assembled = runtime + .binary + .as_ref() + .unwrap() + .assemble(&NodePath::root()) + .unwrap(); + assert_eq!( + assembled[0].len(), + 1, + "two chunks of one series are one series" + ); + let field = &assembled[0][0].fields.as_slice()[0]; + assert_eq!( + field.segments().len(), + 2, + "the assembled field is not the chunks it is built from" + ); + for segment in field.segments() { + let Some(DenseSamplesRef::Float(values)) = segment.dense() else { + panic!("a float chunk assembles into float segments"); + }; + assert_eq!( + values.values().inner().data_ptr(), + batch.values().inner().data_ptr(), + "the assembly copied samples instead of sharing the allocation they are slices of" + ); + } } /// The executor's binary node never reserves a chunk on top of the allocation it shares: the peak @@ -4412,14 +4449,16 @@ fn a_binary_beneath_the_executor_does_not_reserve_a_shared_chunk_on_top() { 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. + // the one allocation the chunks are slices of, one descriptor per chunk, and the boundary list + // the closing chunk adds its end to. 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 retained = 4 * std::mem::size_of::() + + [&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); @@ -4445,6 +4484,170 @@ fn a_binary_beneath_the_executor_does_not_reserve_a_shared_chunk_on_top() { ); } +/// A series that arrives in ten thousand one-point chunks is one candidate for the kernel, not ten +/// thousand. +/// +/// The kernel matches whole series, so the chunks of a logical series are assembled into the series +/// it reads before it runs: the pairing is over candidates, and a chunk that was a candidate of its +/// own would pair every chunk of one side with every chunk of the other. The same series delivered +/// whole must answer the same result, so the count of pairs the kernel actually visited is what +/// separates the two deliveries rather than their outcome. +#[test] +fn a_series_of_many_chunks_is_one_candidate_for_the_kernel() { + let points = 10_000usize; + let (tree, grid, left, right) = binary_tree(BinaryOp::Add, points as u64); + let schema = evaluated_schema(grid); + let batch = Float64Array::from((0..points).map(|point| point as f64).collect::>()); + // One point per chunk, and only the last of them closes the series: the boundaries of the + // delivery say nothing about the series it carries. + let per_point: Vec = (0..points) + .map(|position| { + evaluated_array_chunk_of( + &schema, + metric(), + position, + batch.slice(position, 1), + position + 1 == points, + ) + }) + .collect(); + + reset_visited_pairs(); + let mut split = executor( + &tree, + bounded_pool(1 << 26), + &ExecutionPlanMetricsSet::new(), + ); + for (position, chunk) in per_point.iter().enumerate() { + split.push_evaluated_at(&left, chunk.clone()).unwrap(); + split.push_evaluated_at(&right, chunk.clone()).unwrap(); + assert!( + split.next_chunk().unwrap().is_none(), + "the binary node answered at position {position} before its input ended" + ); + } + let split = split.finish().unwrap(); + assert_eq!( + visited_pairs(), + 1, + "the chunks of one series were paired instead of the one series they make up" + ); + assert_eq!(split.len(), 1, "one matched label set answers one chunk"); + + reset_visited_pairs(); + let mut whole = executor( + &tree, + bounded_pool(1 << 26), + &ExecutionPlanMetricsSet::new(), + ); + let chunk = evaluated_array_chunk_of(&schema, metric(), 0, batch.clone(), true); + whole.push_evaluated_at(&left, chunk.clone()).unwrap(); + whole.push_evaluated_at(&right, chunk).unwrap(); + assert!(whole.next_chunk().unwrap().is_none()); + let whole = whole.finish().unwrap(); + assert_eq!( + visited_pairs(), + 1, + "a series delivered whole is one candidate as well" + ); + assert_eq!(whole.len(), 1, "one matched label set answers one chunk"); + + assert_eq!( + decided(&split), + decided(&whole), + "the delivery of a series changed the result" + ); + let expected: Vec<(usize, Option)> = (0..points) + .map(|position| (position, Some(2.0 * position as f64))) + .collect(); + assert_eq!(decided(&split), expected); +} + +/// The assembly of the operands into the series the kernel matches is reserved before it allocates. +/// +/// Assembling one series per closed series is metadata on top of the chunks the node retains -- the +/// descriptors the chunks' fields are collected into and the runs the axis is built from -- and the +/// pool is asked for that figure before it exists. A pool a byte short of it refuses the assembly, +/// and nothing of it is left charged: the node holds what it retained while the runtime is still +/// alive. +#[test] +fn an_assembly_the_pool_cannot_hold_is_refused_before_it_allocates() { + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let left = evaluated_chunk(&schema, 0, vec![1.0, 2.0], true); + let right = evaluated_chunk(&schema, 0, vec![10.0, 20.0], true); + + // What the node holds once both operands are retained, and what assembling them into the one + // series each of them is adds. + let (retained, assembly) = { + let pool = pool(); + let mut runtime = binary_runtime(&pool, &schema); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(left.clone())) + .unwrap(); + runtime + .retain_binary(&NodePath::root(), 1, NativeChunk::Evaluated(right.clone())) + .unwrap(); + let retained = runtime.buffer.held; + let assembly = runtime.binary.as_ref().unwrap().assembly_bytes().unwrap(); + (retained, assembly) + }; + assert!( + assembly > 0, + "assembling the operands into series is not charged for" + ); + + // One byte short of the assembly: the assembly is refused rather than run over the budget. + let pool = bounded_pool(retained + assembly - 1); + let mut runtime = binary_runtime(&pool, &schema); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(left.clone())) + .unwrap(); + runtime + .retain_binary(&NodePath::root(), 1, NativeChunk::Evaluated(right)) + .unwrap(); + assert_eq!(runtime.buffer.held, retained); + let error = runtime.compute_binary(&NodePath::root()).unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "the assembly was not reserved before it allocated: {error}" + ); + // The assembly never ran, so its charge is gone: what the node holds is what it retained, and + // the pool holds no more than that while the runtime is still alive. + assert_eq!(runtime.buffer.held, retained); + assert_eq!(pool.reserved(), retained); + assert_eq!( + runtime.binary.as_ref().unwrap().retained_bytes(), + retained, + "the refused assembly changed what the operand retains" + ); + + // The figure covers the assembly itself: with exactly that much more, the series are built and + // hold the rows the chunks carried. + let pool = bounded_pool(retained + assembly); + let mut runtime = binary_runtime(&pool, &schema); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(left)) + .unwrap(); + runtime + .retain_binary( + &NodePath::root(), + 1, + NativeChunk::Evaluated(evaluated_chunk(&schema, 0, vec![10.0, 20.0], true)), + ) + .unwrap(); + let assembled = runtime + .binary + .as_ref() + .unwrap() + .assemble(&NodePath::root()) + .unwrap(); + assert_eq!(assembled[0].len(), 1, "one closed series is one series"); + assert_eq!(assembled[1].len(), 1, "one closed series is one series"); + let built = EvaluatedChunk::try_new(assembled[0][0].clone(), true).unwrap(); + assert_eq!(sample_values(&built), vec![Some(1.0), Some(2.0)]); +} + /// 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() { diff --git a/src/promql/src/vector_match.rs b/src/promql/src/vector_match.rs index 8f4e49ab250..ec3bc578d60 100644 --- a/src/promql/src/vector_match.rs +++ b/src/promql/src/vector_match.rs @@ -36,6 +36,34 @@ use crate::histogram_eval::float_histogram::FloatHistogram; #[cfg(test)] mod tests; +// How many candidate pairs the binary kernel visited on this thread. +// +// Test-only, and per thread: the pairs a query considers are what says whether a series delivered in +// many chunks is still one candidate, and that is not visible in the result. A thread of its own +// keeps one test's chunks out of another test's figure, and the counter is compiled out of the +// kernel otherwise. +#[cfg(test)] +thread_local! { + static VISITED_PAIRS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Resets the candidate-pair counter of this thread to zero. +#[cfg(test)] +pub(crate) fn reset_visited_pairs() { + VISITED_PAIRS.with(|visited| visited.set(0)); +} + +/// The candidate pairs the binary kernel has visited on this thread since the last +/// [`reset_visited_pairs`]. +/// +/// A pair is visited once per one-side candidate the kernel looks up for a many-side series, before +/// the pairing's label set and axis intersection are built, so the count is what the kernel actually +/// does rather than what its operands' sizes imply it would. +#[cfg(test)] +pub(crate) fn visited_pairs() -> usize { + VISITED_PAIRS.with(std::cell::Cell::get) +} + /// A PromQL binary operator between two instant vectors. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BinaryOp { @@ -785,6 +813,11 @@ fn binary_field( }; let group_id = group_ids[&key]; for &one_index in candidates { + // One candidate of the one side is paired with this series, whether or not the pairing + // turns out to hold a row: the visit is what the test-only counter reports, before the + // pairing's label set and axis intersection are built. + #[cfg(test)] + VISITED_PAIRS.with(|visited| visited.set(visited.get() + 1)); // One pairing's label set is built before the axes are intersected, so it is reserved // first and the next pairing replaces it. let mut pairing = 0usize;