diff --git a/src/promql/src/aggregate/tests.rs b/src/promql/src/aggregate/tests.rs index f37d30c8244..2bb20247349 100644 --- a/src/promql/src/aggregate/tests.rs +++ b/src/promql/src/aggregate/tests.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::collections::BTreeMap; + use datatypes::arrow::array::{Float64Array, UInt32Array}; use datatypes::series::Label; use datatypes::series::histogram::HistogramBatchBuilder; @@ -23,6 +25,12 @@ use crate::golden::{assert_result, cases}; const CASES: &str = include_str!("prometheus_cases.txt"); +/// A label set as name/value pairs, the way the fixture names one. +type LabelKey = Vec<(Arc, Arc)>; + +/// The valued positions of one label set, by grid index. +type Positions = Vec<(usize, u64)>; + const OPS: [AggregateOp; 6] = [ AggregateOp::Sum, AggregateOp::Count, @@ -93,6 +101,29 @@ fn input( .unwrap() } +/// Every valued position of `pieces`, stitched into one dense vector over the grid. +/// +/// `aggregate_float` returns one piece per run of consecutive positions that hold a result, so a +/// group whose values are interrupted arrives as several pieces; the first position and the +/// value vector are what the assertions here compare. +fn values_of(pieces: &[Series], field: usize, grid_len: usize) -> (usize, Vec>) { + let mut dense = vec![None; grid_len]; + let mut start = usize::MAX; + for piece in pieces { + let (piece_start, piece_values) = values(piece, field); + start = start.min(piece_start); + for (offset, value) in piece_values.into_iter().enumerate() { + if value.is_some() { + assert!(dense[piece_start + offset].is_none(), "two pieces overlap"); + dense[piece_start + offset] = value; + } + } + } + let first = dense.iter().position(Option::is_some).unwrap_or(0); + let last = dense.iter().rposition(Option::is_some).map_or(0, |i| i + 1); + (first, dense[first..last.max(first)].to_vec()) +} + fn values(series: &Series, field: usize) -> (usize, Vec>) { let TimeAxis::Grid(range) = &series.time else { panic!("lost grid") @@ -313,33 +344,41 @@ fn fields_are_aggregated_independently() { let output = aggregate_float(&multi, &series, op, grouping).unwrap(); for field in [0, 1] { let expected = aggregate_float(&single, &project(field), op, grouping).unwrap(); - let expected = expected - .iter() - .map(|s| (s.metric.clone(), values(s, 0))) - .collect::>(); - for actual in &output { - let (start, actual_values) = values(actual, field); - let present = actual_values - .iter() - .enumerate() - .filter_map(|(i, v)| v.map(|v| (start + i, v.to_bits()))) - .collect::>(); - let reference = expected - .iter() - .find(|(metric, _)| metric == &actual.metric) - .map_or_else(Vec::new, |(_, (start, v))| { - v.iter() + // The multi-field result is cut into pieces where its values are interrupted, so + // the comparison is over the dense values of each label set, not over pieces. + let grid_len = multi.eval_grid.as_ref().unwrap().timestamps().len(); + let grouped = |pieces: &[Series], field: usize| { + let mut by_metric: BTreeMap = BTreeMap::new(); + for piece in pieces { + let same: Vec = pieces + .iter() + .filter(|other| other.metric == piece.metric) + .cloned() + .collect(); + let (start, values) = values_of(&same, field, grid_len); + let mut key: LabelKey = piece + .metric + .tags() + .iter() + .map(|tag| (tag.name.clone(), tag.value.clone())) + .collect(); + if let Some(name) = piece.metric.name() { + key.insert(0, (Arc::from("__name__"), Arc::from(name))); + } + by_metric.insert( + key, + values + .into_iter() .enumerate() .filter_map(|(i, v)| v.map(|v| (start + i, v.to_bits()))) - .collect() - }); - assert_eq!(present, reference, "{op:?} {grouping:?} field {field}"); - } - assert!( - expected - .iter() - .all(|(m, _)| output.iter().any(|s| &s.metric == m)) - ); + .collect(), + ); + } + by_metric + }; + let actual = grouped(&output, field); + let expected = grouped(&expected, 0); + assert_eq!(actual, expected, "{op:?} {grouping:?} field {field}"); } } } @@ -389,7 +428,9 @@ fn state_blocks_keep_absolute_indices_across_boundaries_and_gaps() { ), ]; let output = aggregate_float(&schema, &inputs, AggregateOp::Sum, Grouping::By(&[])).unwrap(); - assert_eq!(output.len(), 1); + // One group, and its values are interrupted by empty blocks, so it arrives as several pieces + // of the same label set. What must hold is the dense values, not the piece count. + assert!(output.iter().all(|piece| piece.metric == output[0].metric)); let mut a = vec![None; 452]; let mut b = vec![None; 452]; for i in 60..68 { @@ -402,8 +443,8 @@ fn state_blocks_keep_absolute_indices_across_boundaries_and_gaps() { a[i - 60] = Some(4.0); b[i - 60] = Some(6.0); } - assert_eq!(values(&output[0], 0), (60, a)); - assert_eq!(values(&output[0], 1), (60, b)); + assert_eq!(values_of(&output, 0, 512), (60, a)); + assert_eq!(values_of(&output, 1, 512), (60, b)); } #[test] diff --git a/src/promql/src/evaluated.rs b/src/promql/src/evaluated.rs index fd7888c6ae5..ff2a4a59751 100644 --- a/src/promql/src/evaluated.rs +++ b/src/promql/src/evaluated.rs @@ -18,21 +18,21 @@ use datafusion::error::{DataFusionError, Result}; use datatypes::series::samples::Series; use datatypes::series::time::{GridRange, TimeAxis}; -/// One slice of one evaluated series. +/// One slice of one evaluated series: a run of consecutive positions that hold a value. /// -/// The series' [`TimeAxis::Grid`] covers the positions this chunk decided, whether they hold a -/// value or not. Those positions are absolute on the grid: a consumer that concatenates the chunks -/// of a series never reorders them, and never has to translate a chunk-local row number into a -/// grid position. +/// The series' [`TimeAxis::Grid`] covers the positions this chunk holds, and those positions are +/// absolute on the grid: a consumer that concatenates the chunks of a series never reorders them, +/// and never has to translate a chunk-local row number into a grid position. /// -/// The range reports progress, not values: a decided position without a result is a missing value -/// inside the range, and the positions after it have not been decided yet. That is why a chunk can -/// span positions holding no value at all -- dropping them would leave a consumer waiting for -/// input that has already settled them. +/// A decided position without a result is not a row of any chunk. It lies between two chunks, and +/// the positions after the last one handed out have not been decided yet, so the chunks of a +/// series may leave gaps -- a chunk never spans a position that holds no value. That is what keeps +/// a sparse series from costing a row per empty position. A single field may still hold a null at +/// a position another field fills, since the fields of one chunk are row-aligned. /// -/// A series closes exactly once, on the chunk that carries `is_last`. A closed prefix is always -/// followed by a closing chunk, even when that chunk holds no values, so a consumer can tell -/// "nothing more here" from "no more input". +/// A series closes exactly once, on the chunk that carries `is_last`. A closed prefix is followed +/// by a closing chunk when nothing is left, even when that chunk holds no values, so a consumer +/// can tell "nothing more here" from "no more input". #[derive(Clone, Debug)] pub struct EvaluatedChunk { /// The evaluated values, addressed on their absolute grid positions. diff --git a/src/promql/src/golden.rs b/src/promql/src/golden.rs index 0c502c0281d..499214049cb 100644 --- a/src/promql/src/golden.rs +++ b/src/promql/src/golden.rs @@ -151,11 +151,16 @@ fn grid_series(schema: &SeriesSchema, metric: MetricName, points: &Points) -> Op } /// Compares labels and the trimmed absolute range exactly, and values with [`close`]. -pub(crate) fn assert_result(case: &Case, mut actual: Vec) { +/// +/// An operator hands out one piece per run of consecutive positions that hold a value, so one +/// label set can arrive as several pieces. They are folded back together here, in label order, +/// before the comparison: the values are what a fixture pins down, not how the result was cut. +pub(crate) fn assert_result(case: &Case, actual: Vec) { + let context = || format!("{} ({})", case.expr, case.header.join(" ")); + let mut actual = fold_pieces(actual); actual.sort_by_key(|series| label_key(&series.metric)); let mut expected = case.result.iter().collect::>(); expected.sort_by_key(|(metric, _)| label_key(metric)); - let context = || format!("{} ({})", case.expr, case.header.join(" ")); assert_eq!(actual.len(), expected.len(), "{}", context()); for (actual, (metric, points)) in actual.iter().zip(expected) { assert_eq!(&actual.metric, metric, "{}", context()); @@ -192,6 +197,88 @@ pub(crate) fn assert_result(case: &Case, mut actual: Vec) { } } +/// Joins the pieces of each label set into one dense series, with a null where no piece held a +/// value. One piece sets stay as they are. +pub(crate) fn fold_pieces(pieces: Vec) -> Vec { + let mut groups: Vec<(LabelKey, Vec)> = Vec::new(); + for piece in pieces { + let key = label_key(&piece.metric); + match groups.iter_mut().find(|(group, _)| *group == key) { + Some((_, members)) => members.push(piece), + None => groups.push((key, vec![piece])), + } + } + groups + .into_iter() + .map(|(_, members)| { + if members.len() == 1 { + return members.into_iter().next().unwrap(); + } + fold_one(members) + }) + .collect() +} + +/// Folds one label set's pieces into one series over the span they cover. +fn fold_one(pieces: Vec) -> Series { + let metric = pieces[0].metric.clone(); + let fields = pieces[0].fields.len(); + let grid = match &pieces[0].time { + TimeAxis::Grid(range) => range.grid().clone(), + other => panic!("expected a grid series, got {other:?}"), + }; + let mut rows: Vec>>> = + (0..grid.timestamps().len()).map(|_| None).collect(); + for piece in &pieces { + let TimeAxis::Grid(range) = &piece.time else { + panic!("expected a grid series, got {:?}", piece.time); + }; + for row in 0..range.len() { + let values: Vec> = piece + .fields + .iter() + .map(|field| match field.sample(row) { + SampleRef::Float(value) => Some(value), + SampleRef::Missing => None, + _ => panic!("a fixture only pins float outputs"), + }) + .collect(); + if values.iter().any(Option::is_some) { + assert!( + rows[range.start() + row].is_none(), + "two pieces hold a value at position {}", + range.start() + row + ); + rows[range.start() + row] = Some(values); + } + } + } + let first = rows.iter().position(Option::is_some).unwrap_or(0); + let last = rows.iter().rposition(Option::is_some).map_or(0, |i| i + 1); + let rows = &rows[first..last.max(first)]; + let fields = (0..fields) + .map(|field| { + let values: Float64Array = rows + .iter() + .map(|row| row.as_ref().and_then(|row| row[field])) + .collect(); + Samples::from_float(values) + }) + .collect::>(); + let fields = SeriesFields::try_from_vec(fields).unwrap(); + let time = GridRange::try_new(grid.clone(), first, rows.len()).unwrap(); + let schema = SeriesSchema { + fields: (0..pieces[0].fields.len()) + .map(|index| FieldSpec { + name: Arc::from(format!("f{index}")), + }) + .collect::>() + .into(), + eval_grid: Some(grid), + }; + Series::try_new(&schema, metric, TimeAxis::Grid(time), fields).unwrap() +} + /// Prometheus `almost.Equal` with relative tolerance 1e-10, treating results below 1e-10 as /// equal and any NaN as equal to NaN, as promql-compat compares engines. pub(crate) fn close(a: f64, b: f64) -> bool { @@ -211,7 +298,10 @@ pub(crate) fn close(a: f64, b: f64) -> bool { equal || (a.abs() < EPSILON && b.abs() < EPSILON) } -fn label_key(metric: &MetricName) -> Vec<(String, String)> { +/// A label set as name/value pairs, the way the fixtures name one. +type LabelKey = Vec<(String, String)>; + +fn label_key(metric: &MetricName) -> LabelKey { let mut key = metric .tags() .iter() diff --git a/src/promql/src/grid_series.rs b/src/promql/src/grid_series.rs index f3ad72ac1ad..881f800110e 100644 --- a/src/promql/src/grid_series.rs +++ b/src/promql/src/grid_series.rs @@ -14,8 +14,8 @@ //! Building evaluated series that cover only their result range on a shared grid. -use std::collections::HashMap; use std::collections::hash_map::Entry; +use std::collections::{HashMap, VecDeque}; use std::sync::Arc; use datafusion::arrow::array::builder::NullBufferBuilder; @@ -35,24 +35,49 @@ pub(crate) mod reference; #[cfg(test)] mod tests; -/// Builds one series on the schema's evaluation grid from rows pushed at absolute grid indices. +/// Builds grid series from rows pushed at absolute grid indices, one piece per run of +/// consecutive positions that hold a value. /// -/// The output starts at the first row with a valid value in any field and ends at the last such -/// row, so a short-lived series never holds values for the whole grid. Missing rows between -/// valid ones become nulls; NaN is a valid value. A caller that has decided positions hold no -/// value widens the span with [`GridSeriesBuilder::cover_from`] and -/// [`GridSeriesBuilder::cover_through`], which is how a decided-but-empty position reaches a -/// consumer instead of being trimmed away. +/// A push names one position and the value each field holds there. Rows are accumulated +/// compactly: a row is kept only when at least one field holds a value at that position, so an +/// empty stretch costs one skipped push and no storage at all. Fields stay row-aligned, so a field +/// with no value at a retained row still gets a null there; the Arrow layout needs one row per +/// retained position, and the position does hold a value. +/// +/// [`GridSeriesBuilder::finish`] cuts the accumulated rows into maximal runs of consecutive +/// positions and returns one [`Series`] per run, each a slice sharing the one buffer per field. pub struct GridSeriesBuilder { schema: Arc, grid: Arc, - /// Absolute index of the first valid row. - start: Option, /// Smallest index the next push may use. next: usize, - /// Index after the last valid row; rows from here to the next valid row are pending nulls. - valid_end: usize, + /// Grid index of each retained row, ascending. + /// + /// This vector is the only record of where the gaps are, and it says only where rows sit: + /// with `V` entries, `F` fields and `k` runs (`k <= V`) the whole series costs `8*F*V` value + /// bytes plus validity bits, one `usize` per retained row and `O(k)` run descriptors. Nothing + /// is proportional to the positions holding no value. + indices: Vec, + /// One row per retained row, per field; empty when nothing is buffered. fields: Vec, + /// The buffered rows finalized into shared buffers, with the runs still to hand out. + finished: Option, +} + +/// Retained rows turned into field buffers a run can be sliced out of. +struct Finished { + fields: SeriesFields, + /// Absolute start, compact offset and length of each run, in grid order. + runs: VecDeque, +} + +/// A maximal run of consecutive retained positions. +struct Run { + /// Absolute grid index of the run's first row. + start: usize, + /// Where the run begins in the compact buffers. + offset: usize, + len: usize, } struct FieldBuilder { @@ -85,16 +110,16 @@ impl GridSeriesBuilder { Ok(Self { schema, grid, - start: None, next: 0, - valid_end: 0, + indices: Vec::new(), fields: Vec::new(), + finished: None, }) } /// Pushes the field values at absolute grid `index`; `None` is a missing value. /// - /// Indices must be strictly increasing; skipped indices are missing rows. + /// Indices must be strictly increasing; skipped indices are positions that hold no value. pub fn push(&mut self, index: usize, values: &[Option]) -> Result<()> { if !self.start_row(index, values.len(), values.iter().all(Option::is_none))? { return Ok(()); @@ -133,7 +158,7 @@ impl GridSeriesBuilder { Ok(()) } - /// Checks the row and pads the gap before it; returns whether the row has a value to write. + /// Validates the row and retains it; returns whether it holds a value to write. fn start_row(&mut self, index: usize, len: usize, empty: bool) -> Result { if len != self.schema.fields.len() { return Err(DataFusionError::Execution(format!( @@ -149,99 +174,97 @@ impl GridSeriesBuilder { } self.next = index + 1; if empty { + // A position holding no value anywhere is not a row: an index absent from `indices` + // already says exactly that, so writing it down would only cost storage. return Ok(false); } - - if self.start.is_none() { - self.start = Some(index); - self.fields = (0..len) - .map(|_| FieldBuilder { - values: Vec::new(), - nulls: NullBufferBuilder::new(0), - histograms: None, - }) - .collect(); - } else { - let gap = index - self.valid_end; - for field in &mut self.fields { - field.values.resize(field.values.len() + gap, 0.0); - field.nulls.append_n_nulls(gap); - if let Some(column) = &mut field.histograms { - column.indices.resize(column.indices.len() + gap, None); - } - } + if self.fields.is_empty() { + self.fields = (0..len).map(|_| FieldBuilder::new()).collect(); } - self.valid_end = index + 1; + self.indices.push(index); Ok(true) } - /// Declares that the output span begins at `index`, before any value is pushed for it. - /// - /// A caller that has already decided the positions before its first value hold no value uses - /// this, so the span covers them: a span beginning at the first value would report those - /// positions as ones nothing is known about, and a consumer would never learn they were - /// decided. Positions must still be pushed in increasing order from here. - pub fn cover_from(&mut self, index: usize) -> Result<()> { - if self.start.is_some() || index == self.grid.timestamps().len() { - return Ok(()); - } - if index < self.next { - return Err(DataFusionError::Execution(format!( - "grid series cannot begin its span at {index}, behind the next row {}", - self.next - ))); - } - self.start = Some(index); - self.valid_end = index; - self.next = index; - self.fields = (0..self.schema.fields.len()) - .map(|_| FieldBuilder { - values: Vec::new(), - nulls: NullBufferBuilder::new(0), - histograms: None, - }) - .collect(); - Ok(()) + /// Whether rows have been pushed that no caller has taken yet. + pub fn has_pending(&self) -> bool { + !self.indices.is_empty() + || self + .finished + .as_ref() + .is_some_and(|finished| !finished.runs.is_empty()) } - /// Extends the output span to `end`, writing a missing value for every position in between. + /// Starts the series the following pushes belong to. /// - /// The counterpart of [`Self::cover_from`] for positions decided after the last value. - pub fn cover_through(&mut self, end: usize) -> Result<()> { - if self.start.is_none() { - return Ok(()); - } - if end < self.valid_end { - return Err(DataFusionError::Execution(format!( - "grid series cannot cover through {end}, behind its last row {}", - self.valid_end - ))); - } - let gap = end - self.valid_end; - for field in &mut self.fields { - field.values.resize(field.values.len() + gap, 0.0); - field.nulls.append_n_nulls(gap); - if let Some(column) = &mut field.histograms { - column.indices.resize(column.indices.len() + gap, None); - } - } - self.valid_end = end; - self.next = end; - Ok(()) - } - - /// Finishes the current series and resets the builder for the next one. + /// A caller that takes pieces one at a time never reaches [`Self::finish`], so this is what + /// releases the series before: rows are pushed in increasing order, but the next series may + /// begin before the previous one ended, since a piece covers only the positions holding a + /// value. /// - /// Returns `None` when no pushed row had a valid value. - pub fn finish(&mut self, metric: MetricName) -> Result> { - let start = self.start.take(); - let fields = std::mem::take(&mut self.fields); - let valid_end = std::mem::take(&mut self.valid_end); + /// Panics in debug builds when rows are still pending, which means the previous series was + /// left unread. + pub fn begin_series(&mut self) { + debug_assert!( + !self.has_pending(), + "a new series starts with rows of the previous one still pending" + ); self.next = 0; - let Some(start) = start else { + self.indices.clear(); + self.fields.clear(); + self.finished = None; + } + + /// Hands out the next run of positions holding a value, or `None` when none is left. + /// + /// Every run a series is cut into shares the one buffer per field, because cutting is a + /// slice; which run lands in which piece depends on when the caller asks, since rows pushed + /// later can only be positions past the ones already taken. What never happens is one piece + /// spanning a position with no value, or an empty position costing any storage. + pub fn take_run(&mut self, metric: MetricName) -> Result> { + let exhausted = self + .finished + .as_ref() + .is_none_or(|finished| finished.runs.is_empty()); + if exhausted && !self.indices.is_empty() { + self.finalize()?; + } + let Some(finished) = self.finished.as_mut() else { return Ok(None); }; + let Some(run) = finished.runs.pop_front() else { + return Ok(None); + }; + Self::cut(&self.schema, &self.grid, &metric, &finished.fields, &run).map(Some) + } + /// Returns every piece the pushed rows make up and resets the builder for the next series. + /// + /// One piece per maximal run of consecutive positions holding a value; an empty vector when + /// no pushed row held one. + pub fn finish(&mut self, metric: MetricName) -> Result> { + if !self.indices.is_empty() { + self.finalize()?; + } + self.next = 0; + let Some(finished) = self.finished.take() else { + return Ok(Vec::new()); + }; + let mut pieces = Vec::with_capacity(finished.runs.len()); + for run in finished.runs { + pieces.push(Self::cut( + &self.schema, + &self.grid, + &metric, + &finished.fields, + &run, + )?); + } + Ok(pieces) + } + + /// Finalizes the buffered rows into shared field buffers and cuts them into runs. + fn finalize(&mut self) -> Result<()> { + let fields = std::mem::take(&mut self.fields); let samples = fields .into_iter() .map(|mut field| { @@ -256,16 +279,63 @@ impl GridSeriesBuilder { Samples::try_from_mixed(floats, histograms).map_err(external) }) .collect::>>()?; - let time = - GridRange::try_new(self.grid.clone(), start, valid_end - start).map_err(external)?; let fields = SeriesFields::try_from_vec(samples).map_err(external)?; - Series::try_new(&self.schema, metric, TimeAxis::Grid(time), fields) - .map(Some) - .map_err(external) + let runs = runs_of(&self.indices); + self.indices.clear(); + self.finished = Some(Finished { fields, runs }); + Ok(()) + } + + /// Cuts `run` out of `fields` as one series on the grid. + fn cut( + schema: &Arc, + grid: &Arc, + metric: &MetricName, + fields: &SeriesFields, + run: &Run, + ) -> Result { + // Slicing offsets into the shared buffers, so a piece costs a descriptor, not a copy. + let fields = if fields.len() == 1 { + fields.as_slice()[0] + .slice(run.offset, run.len) + .map(SeriesFields::one) + .map_err(external)? + } else { + let sliced = fields + .iter() + .map(|field| field.slice(run.offset, run.len).map_err(external)) + .collect::>>()?; + SeriesFields::try_from_vec(sliced).map_err(external)? + }; + let time = GridRange::try_new(grid.clone(), run.start, run.len).map_err(external)?; + Series::try_new(schema, metric.clone(), TimeAxis::Grid(time), fields).map_err(external) } } +/// Cuts the retained indices into maximal runs of consecutive positions. +fn runs_of(indices: &[usize]) -> VecDeque { + let mut runs = VecDeque::new(); + let mut offset = 0; + while let Some(&start) = indices.get(offset) { + let mut len = 1; + while indices.get(offset + len) == Some(&(start + len)) { + len += 1; + } + runs.push_back(Run { start, offset, len }); + offset += len; + } + runs +} + impl FieldBuilder { + fn new() -> Self { + Self { + values: Vec::new(), + nulls: NullBufferBuilder::new(0), + histograms: None, + } + } + fn push_float(&mut self, value: Option) { self.values.push(value.unwrap_or_default()); self.nulls.append(value.is_some()); diff --git a/src/promql/src/grid_series/reference.rs b/src/promql/src/grid_series/reference.rs index 63ff3ea1682..1071b7ef410 100644 --- a/src/promql/src/grid_series/reference.rs +++ b/src/promql/src/grid_series/reference.rs @@ -29,7 +29,6 @@ use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName}; use rand::Rng; -use crate::grid_series::GridSeriesBuilder; use crate::histogram_eval::float_histogram::FloatHistogram; /// Values by absolute grid index, then by field; `None` is missing. @@ -120,6 +119,102 @@ fn assert_series_matches( assert_eq!(bits(&expand(actual)), bits(expected), "{context}"); } +/// Stitches the pieces of one series back into a dense matrix over the whole grid. +/// +/// A series is handed out as one piece per run of consecutive positions holding a value, so +/// comparing against a dense expectation means putting the pieces back together. Two pieces +/// covering one position would be a protocol violation, so it fails here rather than silently +/// overwriting. +pub(crate) fn stitch(pieces: &[Series]) -> Dense { + let mut dense: Option = None; + for piece in pieces { + let TimeAxis::Grid(range) = &piece.time else { + panic!("expected a grid series, got {:?}", piece.time); + }; + let dense = dense.get_or_insert_with(|| { + vec![vec![None; piece.fields.len()]; range.grid().timestamps().len()] + }); + for (field, samples) in piece.fields.iter().enumerate() { + for row in 0..range.len() { + let target = &mut dense[range.start() + row][field]; + assert!( + target.is_none() || matches!(samples.sample(row), SampleRef::Missing), + "two pieces hold a value at position {}", + range.start() + row + ); + *target = match samples.sample(row) { + SampleRef::Missing => None, + SampleRef::Float(value) => Some(value), + SampleRef::Histogram(_) => panic!("unexpected histogram sample"), + }; + } + } + } + dense.unwrap_or_default() +} + +/// The `(start, len)` of every piece of one series, in grid order. +pub(crate) fn piece_ranges(pieces: &[Series]) -> Vec<(usize, usize)> { + pieces + .iter() + .map(|piece| match &piece.time { + TimeAxis::Grid(range) => (range.start(), range.len()), + other => panic!("expected a grid series, got {other:?}"), + }) + .collect() +} + +/// Asserts `pieces` are the pieces of `expected`: they reproduce it, and together they cover +/// exactly the positions that hold a value, none of them twice. +pub(crate) fn assert_pieces_eq(pieces: &[Series], expected: &Dense, metric: &MetricName) { + for piece in pieces { + assert_eq!(&piece.metric, metric, "a piece changed the metric"); + } + let valued: Vec = expected + .iter() + .enumerate() + .filter(|(_, row)| row.iter().any(Option::is_some)) + .map(|(index, _)| index) + .collect(); + if valued.is_empty() { + // Nothing holds a value anywhere, so there is no piece at all -- not one piece of nulls. + assert!( + pieces.is_empty(), + "expected no pieces, got {}", + pieces.len() + ); + return; + } + // Bit comparison, since a NaN never equals itself. + let bits = |dense: &Dense| -> Vec>> { + dense + .iter() + .map(|row| row.iter().map(|value| value.map(f64::to_bits)).collect()) + .collect() + }; + assert_eq!(bits(&stitch(pieces)), bits(expected)); + let mut covered: Vec = piece_ranges(pieces) + .into_iter() + .flat_map(|(start, len)| start..start + len) + .collect(); + covered.sort_unstable(); + assert_eq!( + covered, valued, + "the pieces do not cover exactly the positions holding a value" + ); +} + +/// The points of each label set of `pieces`, folded back into one dense point map first. +/// +/// An operator hands out one piece per run of consecutive positions holding a value, while a +/// fixture pins dense points, so the pieces of a label set have to be joined before comparing. +pub(crate) fn points_by_labels(pieces: Vec) -> std::collections::BTreeMap { + crate::golden::fold_pieces(pieces) + .iter() + .map(|series| (labels_of(&series.metric), points_of(series))) + .collect() +} + /// Values covering the bit patterns kernels most often mishandle. pub(crate) fn special_value(rng: &mut impl Rng) -> f64 { const SPECIAL: [f64; 7] = [ @@ -277,16 +372,29 @@ pub(crate) fn labels_of(metric: &MetricName) -> Labels { } /// A single-field series of `schema` holding `points`; `None` without points. +/// +/// Built directly rather than through the builder: this is an *input* to an operator, so a hole +/// stays a null inside one series instead of cutting it into pieces. pub(crate) fn series_of( schema: &Arc, labels: &Labels, points: &Points, ) -> Option { - let mut builder = GridSeriesBuilder::try_new(schema.clone()).unwrap(); - for (&index, &bits) in points { - builder.push(index, &[Some(f64::from_bits(bits))]).unwrap(); - } - builder.finish(metric_of(labels)).unwrap() + let start = *points.keys().min()?; + let end = *points.keys().max()? + 1; + let values: Float64Array = (start..end) + .map(|index| points.get(&index).map(|bits| f64::from_bits(*bits))) + .collect(); + let time = GridRange::try_new(schema.eval_grid.clone().unwrap(), start, end - start).unwrap(); + Some( + Series::try_new( + schema, + metric_of(labels), + TimeAxis::Grid(time), + SeriesFields::one(Samples::from_float(values)), + ) + .unwrap(), + ) } /// The points of a single-field series, any NaN as one NaN: Prometheus' NaN payloads depend on diff --git a/src/promql/src/grid_series/tests.rs b/src/promql/src/grid_series/tests.rs index 4193beb09ab..8186603e0ec 100644 --- a/src/promql/src/grid_series/tests.rs +++ b/src/promql/src/grid_series/tests.rs @@ -12,15 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::mem::size_of; use std::sync::Arc; -use datatypes::series::samples::{FieldSpec, SeriesSchema}; -use datatypes::series::time::{EvalGrid, GridSpec}; +use datatypes::series::samples::{DenseSamplesRef, FieldSpec, Series, SeriesSchema}; +use datatypes::series::time::{EvalGrid, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName}; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; -use super::reference::{Labels, Points, assert_series_eq, points_of, random_dense, series_of}; +use super::reference::{ + Labels, Points, assert_pieces_eq, assert_series_eq, piece_ranges, points_of, random_dense, + series_of, stitch, +}; use super::{GridSeriesBuilder, merge_same_labelset}; fn grid_schema(fields: usize, grid_len: u64) -> Arc { @@ -48,8 +52,19 @@ fn metric(host: usize) -> MetricName { .unwrap() } +/// The pieces of one series, each expanded over the whole grid and stitched back together, have +/// to reproduce the dense matrix they were pushed from. +/// +/// This is the contract of the whole change: many pieces, one dense answer, and the pieces never +/// overlap and never cover a position holding no value. +/// The one piece of a series that can only have one; panics when it has several. +fn single(mut pieces: Vec) -> T { + assert_eq!(pieces.len(), 1, "expected exactly one piece"); + pieces.pop().unwrap() +} + #[test] -fn builder_matches_dense_reference() { +fn pieces_of_one_series_stitch_back_to_the_pushed_rows() { for seed in 0..200 { let mut rng = StdRng::seed_from_u64(seed); let fields = rng.random_range(1..=3); @@ -64,8 +79,8 @@ fn builder_matches_dense_reference() { builder.push(index, row).unwrap(); } } - let actual = builder.finish(metric(host)).unwrap(); - assert_series_eq(actual.as_ref(), &expected, &metric(host)); + let pieces = builder.finish(metric(host)).unwrap(); + assert_pieces_eq(&pieces, &expected, &metric(host)); } } } @@ -121,7 +136,7 @@ fn merge_combines_disjoint_fields_at_one_point() { let series = |row: [Option; 2]| { let mut builder = GridSeriesBuilder::try_new(schema.clone()).unwrap(); builder.push(0, &row).unwrap(); - builder.finish(metric(0)).unwrap().unwrap() + single(builder.finish(metric(0)).unwrap()) }; let merged = merge_same_labelset( &schema, @@ -142,3 +157,181 @@ fn merge_combines_disjoint_fields_at_one_point() { .is_err() ); } + +/// A piece ends where a position holds no value: two values far apart give two one-row pieces +/// instead of one long piece of nulls. +#[test] +fn pieces_never_bridge_positions_without_a_value() { + let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 1_000_000)).unwrap(); + builder.push(10, &[Some(1.0)]).unwrap(); + builder.push(900_000, &[Some(2.0)]).unwrap(); + assert!(builder.has_pending()); + + let pieces = builder.finish(metric(0)).unwrap(); + assert_eq!(piece_ranges(&pieces), vec![(10, 1), (900_000, 1)]); + assert_eq!( + pieces + .iter() + .map(|piece| match &piece.time { + TimeAxis::Grid(range) => range.len(), + _ => unreachable!(), + }) + .sum::(), + 2, + "two values, two rows" + ); + assert!(!builder.has_pending()); +} + +/// Taking the pieces one at a time gives the same shape as taking them all at once. +#[test] +fn pieces_can_be_taken_one_at_a_time() { + let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 10)).unwrap(); + builder.push(0, &[Some(1.0)]).unwrap(); + builder.push(5, &[Some(2.0)]).unwrap(); + builder.push(9, &[Some(3.0)]).unwrap(); + + let mut taken = Vec::new(); + while let Some(piece) = builder.take_run(metric(0)).unwrap() { + taken.push(piece); + } + assert_eq!(piece_ranges(&taken), vec![(0, 1), (5, 1), (9, 1)]); + assert!(!builder.has_pending()); + assert!(builder.take_run(metric(0)).unwrap().is_none()); + assert!(builder.finish(metric(0)).unwrap().is_empty()); +} + +/// A push whose values are all missing holds no row, so it neither opens nor widens a piece. +#[test] +fn an_all_missing_push_holds_no_row() { + let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 10)).unwrap(); + builder.push(2, &[Some(1.0)]).unwrap(); + builder.push(3, &[None]).unwrap(); + builder.push(4, &[Some(2.0)]).unwrap(); + builder.push(7, &[None]).unwrap(); + + let pieces = builder.finish(metric(0)).unwrap(); + assert_eq!(piece_ranges(&pieces), vec![(2, 1), (4, 1)]); + assert!(!builder.has_pending()); +} + +/// Values and nulls alternating over a long grid: every valued position is its own piece, so the +/// piece count grows with the values while the row count stays at one per value. +#[test] +fn alternating_values_and_nulls_yield_one_row_per_value() { + const GRID: usize = 200_000; + let mut builder = GridSeriesBuilder::try_new(grid_schema(1, GRID as u64)).unwrap(); + for index in 0..GRID { + let value = (index % 2 == 0).then_some(index as f64); + builder.push(index, &[value]).unwrap(); + } + let pieces = builder.finish(metric(0)).unwrap(); + assert_eq!( + pieces.len(), + GRID / 2, + "one piece per value, which is the accepted cost of this design" + ); + let expected: Vec<(usize, usize)> = (0..GRID / 2).map(|i| (i * 2, 1)).collect(); + assert_eq!(piece_ranges(&pieces), expected); +} + +/// Rows inside one piece stay aligned across fields: a field with no value where another has one +/// still gets a row there, holding a null. That is the one null a piece keeps. +#[test] +fn a_piece_keeps_its_fields_row_aligned() { + let mut builder = GridSeriesBuilder::try_new(grid_schema(2, 4)).unwrap(); + builder.push(1, &[Some(1.0), None]).unwrap(); + builder.push(2, &[None, Some(2.0)]).unwrap(); + let pieces = builder.finish(metric(0)).unwrap(); + assert_eq!( + piece_ranges(&pieces), + vec![(1, 2)], + "complementary fields at adjacent positions are ONE piece" + ); + assert_eq!( + stitch(&pieces), + vec![ + vec![None, None], + vec![Some(1.0), None], + vec![None, Some(2.0)], + vec![None, None], + ] + ); +} + +/// Every piece of one series is a slice of the same value buffer, so the pieces of a series with +/// many runs cost descriptors rather than copies of the data. +/// +/// The assertion is not vacuous: the pieces are separated by holes, so a builder copying each +/// piece would give every piece its own base address, while slices of one buffer are offset by +/// exactly the distance between their compact positions. +#[test] +fn pieces_share_one_values_buffer() { + let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 100)).unwrap(); + for (offset, index) in [0usize, 1, 2, 50, 51, 99].into_iter().enumerate() { + builder.push(index, &[Some(offset as f64)]).unwrap(); + } + let pieces = builder.finish(metric(0)).unwrap(); + assert_eq!(piece_ranges(&pieces), vec![(0, 3), (50, 2), (99, 1)]); + + let float = |piece: &Series| match piece.fields.as_slice()[0].dense() { + Some(DenseSamplesRef::Float(values)) => values.clone(), + _ => panic!("expected float samples"), + }; + // Compact offsets of the three runs: the holes between them are not in the buffer at all. + let offsets = [0usize, 3, 5]; + let base = float(&pieces[0]).values().as_ptr() as usize; + for (piece, offset) in pieces.iter().zip(offsets) { + let values = float(piece); + assert_eq!( + (values.values().as_ptr() as usize) - base, + offset * size_of::(), + "a piece is not a slice of the same buffer: it was copied" + ); + // The values are those pushed, so the offsets above are the ones that were sliced. + let expected: Vec = (offset..offset + values.len()).map(|v| v as f64).collect(); + assert_eq!(values.values().as_ref(), expected.as_slice()); + } + // One buffer, so the three pieces together hold exactly the six pushed rows. + let total: usize = pieces.iter().map(|piece| float(piece).len()).sum(); + assert_eq!(total, 6, "the pieces do not share one row-per-value buffer"); +} + +/// Dense pushes of the same positions give the same pieces whether the gaps were skipped or +/// pushed as all-missing rows. +#[test] +fn skipped_and_all_missing_positions_are_the_same_series() { + let mut skipped = GridSeriesBuilder::try_new(grid_schema(1, 10)).unwrap(); + let mut pushed = GridSeriesBuilder::try_new(grid_schema(1, 10)).unwrap(); + for index in 0..10 { + let value = [0, 1, 5].contains(&index).then_some(index as f64); + if value.is_none() { + skipped.push(index, &[None]).unwrap(); + } else { + skipped.push(index, &[value]).unwrap(); + } + pushed.push(index, &[value]).unwrap(); + } + let skipped = skipped.finish(metric(0)).unwrap(); + let pushed = pushed.finish(metric(0)).unwrap(); + assert_eq!(piece_ranges(&skipped), piece_ranges(&pushed)); + assert_eq!(stitch(&skipped), stitch(&pushed)); +} + +/// Series are handed out in the order their rows were pushed, so one builder serves many series. +#[test] +fn one_builder_serves_several_series() { + let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 10)).unwrap(); + builder.push(0, &[Some(1.0)]).unwrap(); + builder.push(2, &[Some(2.0)]).unwrap(); + let first = builder.finish(metric(0)).unwrap(); + assert_eq!(piece_ranges(&first), vec![(0, 1), (2, 1)]); + assert!(first.iter().all(|piece| piece.metric == metric(0))); + + builder.push(1, &[Some(3.0)]).unwrap(); + builder.push(3, &[Some(4.0)]).unwrap(); + let second = builder.finish(metric(1)).unwrap(); + assert_eq!(piece_ranges(&second), vec![(1, 1), (3, 1)]); + assert!(second.iter().all(|piece| piece.metric == metric(1))); + assert!(!builder.has_pending()); +} diff --git a/src/promql/src/histogram_eval.rs b/src/promql/src/histogram_eval.rs index d6ecf4fa261..ce1eeac3679 100644 --- a/src/promql/src/histogram_eval.rs +++ b/src/promql/src/histogram_eval.rs @@ -213,7 +213,10 @@ pub enum NativeHistogramFunction { } /// Applies `function` to the native histogram samples of `series`; float samples are dropped and -/// so is `__name__`. The result is `None` when the series has no histogram sample. +/// so is `__name__`. The result is empty when the series has no histogram sample. +/// +/// Histogram samples may leave holes, and a hole ends a piece, so one series can produce several: +/// each covers a run of consecutive positions that hold a result. /// /// Series that share a label set once their names are dropped must then go through /// [`merge_same_labelset`]. @@ -221,7 +224,7 @@ pub fn map_native_histogram( function: NativeHistogramFunction, schema: &Arc, series: &Series, -) -> Result> { +) -> Result> { let range = grid_range(series)?; let mut builder = GridSeriesBuilder::try_new(schema.clone())?; let mut buckets = Vec::new(); diff --git a/src/promql/src/histogram_eval/tests.rs b/src/promql/src/histogram_eval/tests.rs index 4b1b5da3a3c..48cb2d03622 100644 --- a/src/promql/src/histogram_eval/tests.rs +++ b/src/promql/src/histogram_eval/tests.rs @@ -27,7 +27,7 @@ use super::{ use crate::grid_series::merge_same_labelset; use crate::grid_series::reference::{ GoldenCase, Labels, OwnedHistogram, Points, canonical_bits, close, golden_cases, labels_of, - metric_of, mixed_series, points_of, + metric_of, mixed_series, points_by_labels, points_of, }; fn schema(case: &GoldenCase) -> Arc { @@ -52,10 +52,9 @@ fn assert_outcome( ) -> bool { match (actual, expected) { (Ok(actual), Ok(expected)) => { - let actual: BTreeMap<_, _> = actual - .iter() - .map(|series| (labels_of(&series.metric), points_of(series))) - .collect(); + // A result arrives as one piece per run of valued positions; a fixture pins + // dense points, so the pieces of each label set are folded back together. + let actual: BTreeMap<_, _> = points_by_labels(actual.clone()); let expected: BTreeMap<_, _> = expected .iter() .map(|(labels, points)| { @@ -143,10 +142,10 @@ fn native_histograms_match_prometheus() { }) .collect(); let map = |function| -> Result, DataFusionError> { - let mapped = input - .iter() - .filter_map(|series| map_native_histogram(function, &schema, series).transpose()) - .collect::, _>>()?; + let mut mapped = Vec::new(); + for series in &input { + mapped.extend(map_native_histogram(function, &schema, series)?); + } merge_same_labelset(&schema, mapped) }; let actual = match case.spec[0].as_str() { @@ -433,7 +432,8 @@ fn histogram_functions_drop_metadata_labels() { .unwrap(); let count = map_native_histogram(NativeHistogramFunction::Count, &schema, &native) .unwrap() - .unwrap(); + .pop() + .expect("a native histogram result"); let mut expected = labels(&[]); expected.remove("__name__"); assert_eq!(labels_of(&count.metric), expected); diff --git a/src/promql/src/map/broadcast.rs b/src/promql/src/map/broadcast.rs index 1c0bb4c46cb..c58d8ec692d 100644 --- a/src/promql/src/map/broadcast.rs +++ b/src/promql/src/map/broadcast.rs @@ -35,17 +35,18 @@ pub enum ScalarSeriesOperand<'a> { /// index, and drops the metric name. /// /// Prometheus scalars exist at every step; a missing scalar point here yields a missing output. -/// The output is trimmed to its first and last valid rows, and `None` means no valid row. The -/// scalar must be unlabelled and single-field on the same grid; histogram/mixed/raw inputs are -/// rejected even outside the overlap. Two unlabelled single-field inputs also evaluate -/// scalar–scalar operations. Same-labelset merging is left to the caller, as in +/// The output is trimmed to its first and last valid rows, and an empty result means no valid row. +/// A scalar point holding no value ends a piece, so one series can produce several. The scalar +/// must be unlabelled and single-field on the same grid; histogram/mixed/raw inputs are rejected +/// even outside the overlap. Two unlabelled single-field inputs also evaluate scalar–scalar +/// operations. Same-labelset merging is left to the caller, as in /// [`crate::map::map_math`]. pub fn map_arithmetic_series( schema: &Arc, vector: &Series, op: ArithmeticOp, scalar: ScalarSeriesOperand<'_>, -) -> Result> { +) -> Result> { let metric = drop_metric_name(&vector.metric)?; map_grid_scalar(schema, vector, scalar, metric, |left, right, _| { Some(op.calculate(left, right)) @@ -62,7 +63,7 @@ pub fn map_compare_series( vector: &Series, comparison: Comparison, scalar: ScalarSeriesOperand<'_>, -) -> Result> { +) -> Result> { let metric = if matches!(comparison, Comparison::Bool(_)) { drop_metric_name(&vector.metric)? } else { @@ -80,7 +81,7 @@ fn map_grid_scalar( scalar: ScalarSeriesOperand<'_>, metric: MetricName, calculate: impl Fn(f64, f64, f64) -> Option, -) -> Result> { +) -> Result> { let vector_range = validate_float_series(schema, vector)?; let (scalar_series, scalar_left) = match scalar { ScalarSeriesOperand::Left(s) => (s, true), diff --git a/src/promql/src/map/comparison.rs b/src/promql/src/map/comparison.rs index 41e4e73d04d..334c91a6b2a 100644 --- a/src/promql/src/map/comparison.rs +++ b/src/promql/src/map/comparison.rs @@ -45,14 +45,16 @@ pub enum Comparison { /// Compares a vector with a constant scalar, like Prometheus `VectorscalarBinop`. /// /// Each field is compared independently; a row is kept where any field passes a filter. The -/// output is trimmed to its first and last kept rows, and `None` means nothing passed. Raw axes -/// and histogram/mixed inputs share [`crate::map::map_math`]'s rejection contract. +/// output is trimmed to its first and last kept rows, and an empty result means nothing passed. +/// A filter keeps a subset of the input's rows, so a passed-over stretch ends a piece and one +/// series can produce several. Raw axes and histogram/mixed inputs share +/// [`crate::map::map_math`]'s rejection contract. pub fn map_compare( schema: &Arc, series: &Series, comparison: Comparison, scalar: ScalarOperand, -) -> Result> { +) -> Result> { let range = validate_float_series(schema, series)?; let mut builder = GridSeriesBuilder::try_new(schema.clone())?; let mut fields = series diff --git a/src/promql/src/map/tests.rs b/src/promql/src/map/tests.rs index a1e6769adb9..f2cf768306d 100644 --- a/src/promql/src/map/tests.rs +++ b/src/promql/src/map/tests.rs @@ -82,6 +82,46 @@ fn floats(samples: &[Option]) -> Samples { Samples::from_float(Float64Array::from(samples.to_vec())) } +/// The `(start, len)` of every piece of a mapped result, in grid order. +fn piece_ranges(pieces: &[Series]) -> Vec<(usize, usize)> { + pieces + .iter() + .map(|piece| { + let TimeAxis::Grid(range) = &piece.time else { + panic!("lost grid axis") + }; + (range.start(), range.len()) + }) + .collect() +} + +/// The `(start, len)` of one piece together with its values. +type PieceFloats = Vec<((usize, usize), Vec>)>; + +/// The field-`field` values of `pieces`, one entry per piece, with its absolute start. +fn piece_floats(pieces: &[Series], field: usize) -> PieceFloats { + pieces + .iter() + .map(|piece| { + let (start, _) = { + let TimeAxis::Grid(range) = &piece.time else { + panic!("lost grid axis") + }; + (range.start(), range.len()) + }; + let values = piece.fields.as_slice()[field] + .iter() + .map(|sample| match sample { + SampleRef::Float(value) => Some(value), + SampleRef::Missing => None, + _ => panic!("unexpected histogram"), + }) + .collect(); + ((start, piece.fields.as_slice()[field].len()), values) + }) + .collect() +} + fn assert_floats(actual: &Samples, expected: &[Option]) { assert_eq!(actual.len(), expected.len()); for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { diff --git a/src/promql/src/map/tests/broadcast.rs b/src/promql/src/map/tests/broadcast.rs index dd1c4ec415f..269d8fa10d0 100644 --- a/src/promql/src/map/tests/broadcast.rs +++ b/src/promql/src/map/tests/broadcast.rs @@ -33,13 +33,6 @@ fn scalar(schema: &SeriesSchema, start: usize, samples: Samples) -> Series { .unwrap() } -fn grid_range(series: &Series) -> (usize, usize) { - let TimeAxis::Grid(range) = &series.time else { - panic!("lost grid axis") - }; - (range.start(), range.len()) -} - #[test] fn time_varying_scalar_aligns_absolute_indices_across_independent_chunks() { // The vector covers 7..15 and the scalar 5..16, each chunked at different offsets. @@ -109,57 +102,50 @@ fn time_varying_scalar_aligns_absolute_indices_across_independent_chunks() { ArithmeticOp::Subtract, ScalarSeriesOperand::Left(&scalar), ) - .unwrap() .unwrap(); - assert_eq!(grid_range(&output), (7, 8)); - assert_floats( - output.fields.get(0).unwrap(), - &[ - Some(99.0), - Some(198.0), - None, - None, - Some(495.0), - Some(594.0), - Some(693.0), - Some(792.0), - ], + // The scalar holds no value at grid position 10, so neither field has a result there: that + // position is not a row, and the two sides of it form separate pieces. + assert_eq!(piece_ranges(&output), vec![(7, 3), (11, 4)]); + assert_eq!( + piece_floats(&output, 0), + vec![ + ((7, 3), vec![Some(99.0), Some(198.0), None]), + ( + (11, 4), + vec![Some(495.0), Some(594.0), Some(693.0), Some(792.0)] + ), + ] ); - assert_floats( - output.fields.get(1).unwrap(), - &[ - None, - Some(180.0), - Some(270.0), - None, - Some(450.0), - Some(540.0), - Some(630.0), - None, - ], + assert_eq!( + piece_floats(&output, 1), + vec![ + ((7, 3), vec![None, Some(180.0), Some(270.0)]), + ((11, 4), vec![Some(450.0), Some(540.0), Some(630.0), None]), + ] + ); + assert!(output.iter().all(|piece| piece.metric.name().is_none())); + assert!( + output + .iter() + .all(|piece| piece.metric.tags() == &input.metric.tags()[1..]) ); - assert_eq!(output.metric.name(), None); - assert_eq!(output.metric.tags(), &input.metric.tags()[1..]); let output = map_arithmetic_series( &schema, &input, ArithmeticOp::Subtract, ScalarSeriesOperand::Right(&scalar), ) - .unwrap() .unwrap(); - assert_floats( - output.fields.get(0).unwrap(), - &[ - Some(-99.0), - Some(-198.0), - None, - None, - Some(-495.0), - Some(-594.0), - Some(-693.0), - Some(-792.0), - ], + assert_eq!(piece_ranges(&output), vec![(7, 3), (11, 4)]); + assert_eq!( + piece_floats(&output, 0), + vec![ + ((7, 3), vec![Some(-99.0), Some(-198.0), None]), + ( + (11, 4), + vec![Some(-495.0), Some(-594.0), Some(-693.0), Some(-792.0)] + ), + ] ); } @@ -196,25 +182,29 @@ fn time_varying_comparison_keeps_vector_values_and_trims() { Comparison::Filter(ComparisonOp::Less), ScalarSeriesOperand::Left(&scalar), ) - .unwrap() .unwrap(); - assert_eq!(grid_range(&output), (10, 1)); - assert_floats(output.fields.get(0).unwrap(), &[Some(4.0)]); - assert_eq!(output.metric, input.metric); + // Only position 10 passes, and it is the whole result: one piece, one row. + assert_eq!(piece_ranges(&output), vec![(10, 1)]); + assert_eq!(piece_floats(&output, 0), vec![((10, 1), vec![Some(4.0)])]); + assert!(output.iter().all(|piece| piece.metric == input.metric)); let output = map_compare_series( &schema, &input, Comparison::Bool(ComparisonOp::Equal), ScalarSeriesOperand::Right(&scalar), ) - .unwrap() .unwrap(); - assert_eq!(grid_range(&output), (6, 6)); - assert_floats( - output.fields.get(0).unwrap(), - &[Some(1.0), None, None, Some(0.0), Some(0.0), Some(0.0)], + // Bool emits at every position where both operands exist. The scalar holds no value at grid + // position 7, so that position has no row and ends a piece; 8 to 10 follow it. + assert_eq!(piece_ranges(&output), vec![(6, 1), (9, 3)]); + assert_eq!( + piece_floats(&output, 0), + vec![ + ((6, 1), vec![Some(1.0)]), + ((9, 3), vec![Some(0.0), Some(0.0), Some(0.0)]), + ] ); - assert_eq!(output.metric.name(), None); + assert!(output.iter().all(|piece| piece.metric.name().is_none())); } #[test] @@ -254,13 +244,15 @@ fn disjoint_or_missing_overlap_produces_no_series() { ScalarSeriesOperand::Right(&scalar), ) .unwrap(); - match (output, expected) { - (None, None) => {} - (Some(output), Some((range, values))) => { - assert_eq!(grid_range(&output), range); - assert_floats(output.fields.get(0).unwrap(), &values); + // An overlap with no valid scalar point yields no piece at all, which is what `None` + // used to say. + match (output.is_empty(), expected) { + (true, None) => {} + (false, Some((range, values))) => { + assert_eq!(piece_ranges(&output), vec![range]); + assert_eq!(piece_floats(&output, 0), vec![(range, values)]); } - (output, expected) => panic!("{start}: {output:?} != {expected:?}"), + (_, expected) => panic!("{start}: {output:?} != {expected:?}"), } } } diff --git a/src/promql/src/map/tests/comparison.rs b/src/promql/src/map/tests/comparison.rs index ec7d0eaea2d..c6d9116c7b4 100644 --- a/src/promql/src/map/tests/comparison.rs +++ b/src/promql/src/map/tests/comparison.rs @@ -14,13 +14,6 @@ use super::*; -fn grid_range(series: &Series) -> (usize, usize) { - let TimeAxis::Grid(range) = &series.time else { - panic!("lost grid axis") - }; - (range.start(), range.len()) -} - #[test] fn filter_compares_fields_independently_and_trims_the_output() { let schema = Arc::new(schema(&["a", "b"])); @@ -42,24 +35,26 @@ fn filter_compares_fields_independently_and_trims_the_output() { Comparison::Filter(ComparisonOp::Greater), ScalarOperand::Right(4.0), ) - .unwrap() .unwrap(); - assert_eq!(grid_range(&output), (5, 4)); - assert_floats( - output.fields.get(0).unwrap(), - &[None, Some(5.0), None, Some(7.0)], + // Field 1 keeps position 5 and field 0 keeps position 6, so 5 and 6 stay one piece; position + // 7 fails in both fields, which costs no row and ends the piece; position 8 keeps field 0. + assert_eq!(piece_ranges(&output), vec![(5, 2), (8, 1)]); + assert_eq!( + piece_floats(&output, 0), + vec![((5, 2), vec![None, Some(5.0)]), ((8, 1), vec![Some(7.0)])] ); - assert_floats( - output.fields.get(1).unwrap(), - &[Some(9.0), None, None, None], + assert_eq!( + piece_floats(&output, 1), + vec![((5, 2), vec![Some(9.0), None]), ((8, 1), vec![None])] ); - assert_eq!(output.metric, input.metric); + assert!(output.iter().all(|piece| piece.metric == input.metric)); for scalar in [ScalarOperand::Right(100.0), ScalarOperand::Right(f64::NAN)] { let filter = Comparison::Filter(ComparisonOp::Greater); assert!( map_compare(&schema, &input, filter, scalar) .unwrap() - .is_none() + .is_empty(), + "nothing passes, so the filter yields no piece" ); } } @@ -78,10 +73,14 @@ fn filter_with_left_scalar_keeps_the_vector_value() { Comparison::Filter(ComparisonOp::Less), ScalarOperand::Left(2.0), ) - .unwrap() .unwrap(); - assert_eq!(grid_range(&output), (6, 3)); - assert_floats(output.fields.get(0).unwrap(), &[Some(3.0), None, Some(4.0)]); + // Position 6 holds 3.0 and position 8 holds 4.0; position 7 failed the filter, so it costs no + // row and the result is two pieces rather than one padded stretch. + assert_eq!(piece_ranges(&output), vec![(6, 1), (8, 1)]); + assert_eq!( + piece_floats(&output, 0), + vec![((6, 1), vec![Some(3.0)]), ((8, 1), vec![Some(4.0)])] + ); } #[test] @@ -102,13 +101,24 @@ fn bool_emits_every_present_field_and_drops_the_name() { Comparison::Bool(ComparisonOp::Equal), ScalarOperand::Right(0.0), ) - .unwrap() .unwrap(); - assert_eq!(grid_range(&output), (4, 3)); - assert_floats(output.fields.get(0).unwrap(), &[Some(1.0), None, Some(0.0)]); - assert_floats(output.fields.get(1).unwrap(), &[Some(1.0), Some(0.0), None]); - assert_eq!(output.metric.name(), None); - assert_eq!(output.metric.tags(), &input.metric.tags()[1..]); + // Every position keeps a value in at least one field, so the result is one piece; a field + // missing where the other has a value keeps a null row. + assert_eq!(piece_ranges(&output), vec![(4, 3)]); + assert_eq!( + piece_floats(&output, 0), + vec![((4, 3), vec![Some(1.0), None, Some(0.0)])] + ); + assert_eq!( + piece_floats(&output, 1), + vec![((4, 3), vec![Some(1.0), Some(0.0), None])] + ); + assert!(output.iter().all(|piece| piece.metric.name().is_none())); + assert!( + output + .iter() + .all(|piece| piece.metric.tags() == &input.metric.tags()[1..]) + ); } #[test] diff --git a/src/promql/src/map/tests/prometheus.rs b/src/promql/src/map/tests/prometheus.rs index fedeb845cbf..bd70a07858f 100644 --- a/src/promql/src/map/tests/prometheus.rs +++ b/src/promql/src/map/tests/prometheus.rs @@ -107,7 +107,8 @@ fn evaluate(case: &Case) -> Vec { let schema = &case.schema; let full_grid = || GridRange::try_new(schema.eval_grid.clone().unwrap(), 0, grid_len(case)).unwrap(); - let each = |f: &dyn Fn(&Series) -> Option| case.series.iter().filter_map(f).collect(); + let each = + |f: &dyn Fn(&Series) -> Vec| case.series.iter().flat_map(f).collect::>(); let scalar_series = || { let scalar = case.scalar.as_ref().expect("scalar operand"); match h[h.len() - 1].as_str() { @@ -116,11 +117,16 @@ fn evaluate(case: &Case) -> Vec { } }; match h[0].as_str() { - "math" => each(&|s| map_math(schema, s, math_op(h)).unwrap()), - "neg" => each(&|s| Some(map_negate(schema, s).unwrap())), + "math" => each(&|s| { + map_math(schema, s, math_op(h)) + .unwrap() + .into_iter() + .collect() + }), + "neg" => each(&|s| vec![map_negate(schema, s).unwrap()]), "arith" => { let operand = scalar_operand(&h[2], hex(&h[3])); - each(&|s| Some(map_arithmetic(schema, s, arithmetic_op(&h[1]), operand).unwrap())) + each(&|s| vec![map_arithmetic(schema, s, arithmetic_op(&h[1]), operand).unwrap()]) } "cmp" => { let operand = scalar_operand(&h[3], hex(&h[4])); diff --git a/src/promql/src/map_label/tests.rs b/src/promql/src/map_label/tests.rs index b90395f5f37..70a3199b16e 100644 --- a/src/promql/src/map_label/tests.rs +++ b/src/promql/src/map_label/tests.rs @@ -18,9 +18,7 @@ use std::sync::Arc; use datatypes::series::samples::{FieldSpec, SeriesSchema}; use super::{label_join, label_replace}; -use crate::grid_series::reference::{ - canonical_bits, golden_cases, labels_of, points_of, series_of, -}; +use crate::grid_series::reference::{canonical_bits, golden_cases, points_by_labels, series_of}; #[test] fn label_functions_match_prometheus() { @@ -52,10 +50,9 @@ fn label_functions_match_prometheus() { if expected.len() < inputs { merged += 1; } - let actual: BTreeMap<_, _> = actual - .iter() - .map(|series| (labels_of(&series.metric), points_of(series))) - .collect(); + // A result arrives as one piece per run of valued positions; a fixture pins + // dense points, so the pieces of each label set are folded back together. + let actual: BTreeMap<_, _> = points_by_labels(actual.clone()); let expected: BTreeMap<_, _> = expected .into_iter() .map(|(labels, points)| { diff --git a/src/promql/src/map_time.rs b/src/promql/src/map_time.rs index 7781be82ca3..8c285ac15b4 100644 --- a/src/promql/src/map_time.rs +++ b/src/promql/src/map_time.rs @@ -17,7 +17,7 @@ use std::sync::Arc; -use datafusion::arrow::array::Float64Array; +use datafusion::arrow::array::{Array, Float64Array}; use datafusion::error::{DataFusionError, Result}; use datatypes::series::MetricName; use datatypes::series::samples::{ @@ -57,7 +57,10 @@ pub fn date_of_eval_time(function: DateFunction, schema: &SeriesSchema) -> Resul /// A date function over `series`: each float value is read as Unix seconds and replaced by the /// date component, and the metric name is dropped. Missing values stay missing; histogram -/// samples are dropped, so the result is `None` when no float remains. +/// samples are dropped, so the result is empty when no float remains. +/// +/// A missing value is a hole like any other, so a series whose floats are interrupted produces +/// one piece per run of consecutive valued positions. /// /// Series that share a label set once their names are dropped must then go through /// [`merge_same_labelset`](crate::grid_series::merge_same_labelset). @@ -65,7 +68,7 @@ pub fn map_date( function: DateFunction, schema: &Arc, series: &Series, -) -> Result> { +) -> Result> { let TimeAxis::Grid(range) = &series.time else { return Err(DataFusionError::Execution( "date functions require an evaluated series".into(), @@ -75,11 +78,13 @@ pub fn map_date( metric.remove_all(&METADATA_LABELS); let map = |seconds: f64| function.apply(go_int64(seconds)); + // The fast path maps every float in place, so it needs each field to be entirely present: + // a null would survive as a hole, and the series would then span positions holding no value. + // A hole is enough to fall through to the builder, which cuts the result into pieces. let all_floats = series.fields.iter().all(|samples| { - samples - .segments() - .iter() - .all(|segment| matches!(segment.dense(), Some(DenseSamplesRef::Float(_)))) + samples.segments().iter().all(|segment| { + matches!(segment.dense(), Some(DenseSamplesRef::Float(floats)) if floats.null_count() == 0) + }) }); if all_floats { let fields = series @@ -100,12 +105,12 @@ pub fn map_date( }) .collect::>>()?; let fields = SeriesFields::try_from_vec(fields).map_err(external)?; - return Series::try_new(schema, metric, series.time.clone(), fields) - .map(Some) - .map_err(external); + let series = + Series::try_new(schema, metric, series.time.clone(), fields).map_err(external)?; + return Ok(vec![series]); } - // Histogram samples leave holes, which may move the ends of the series. + // Holes in any field may move the ends of the series, and a hole ends a piece. let mut builder = GridSeriesBuilder::try_new(schema.clone())?; let mut values = vec![None; series.fields.len()]; for row in 0..range.len() { diff --git a/src/promql/src/map_time/tests.rs b/src/promql/src/map_time/tests.rs index 7f96c6bb20f..927132a70b1 100644 --- a/src/promql/src/map_time/tests.rs +++ b/src/promql/src/map_time/tests.rs @@ -25,7 +25,8 @@ use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; use super::{DateFunction, date_of_eval_time, map_date, time}; use crate::grid_series::merge_same_labelset; use crate::grid_series::reference::{ - Labels, canonical_bits, golden_cases, labels_of, metric_of, points_of, series_of, + Labels, canonical_bits, golden_cases, labels_of, metric_of, points_by_labels, points_of, + series_of, }; fn schema(grid: Arc) -> Arc { @@ -61,12 +62,17 @@ fn time_functions_match_prometheus() { let actual: Vec = match (case.spec[0].as_str(), case.spec[1].as_str()) { ("eval_time", "time") => vec![time(&schema).unwrap()], ("eval_time", name) => vec![date_of_eval_time(function(name), &schema).unwrap()], - ("date", name) => case - .inputs - .iter() - .filter_map(|(labels, points)| series_of(&schema, labels, points)) - .filter_map(|series| map_date(function(name), &schema, &series).unwrap()) - .collect::>(), + ("date", name) => { + let mut actual = Vec::new(); + for series in case + .inputs + .iter() + .filter_map(|(labels, points)| series_of(&schema, labels, points)) + { + actual.extend(map_date(function(name), &schema, &series).unwrap()); + } + actual + } (kind, _) => panic!("unknown case {kind}"), }; // Dropping `__name__` can give two series one label set. @@ -79,10 +85,9 @@ fn time_functions_match_prometheus() { (actual, expected) => panic!("case {:?}: {actual:?} is not {expected:?}", case.spec), }; let (actual, expected) = actual; - let actual: BTreeMap<_, _> = actual - .iter() - .map(|series| (labels_of(&series.metric), points_of(series))) - .collect(); + // A date function keeps the values of its input but drops histograms and names, so its + // result is one piece per run of valued positions; the fixture pins dense points. + let actual: BTreeMap<_, _> = points_by_labels(actual); let expected: BTreeMap<_, _> = expected .into_iter() .map(|(labels, points)| { @@ -150,7 +155,8 @@ fn map_date_drops_histograms_and_maps_chunks() { let mixed = Samples::try_from_chunks(vec![histogram, floats(&[3600.0, 7200.0])]).unwrap(); let hours = map_date(DateFunction::Hour, &schema, &series(mixed)) .unwrap() - .unwrap(); + .pop() + .expect("a mixed series with one float"); assert_eq!( points_of(&hours), BTreeMap::from([(2, 1f64.to_bits()), (3, 2f64.to_bits())]) @@ -163,7 +169,8 @@ fn map_date_drops_histograms_and_maps_chunks() { let chunked = Samples::try_from_chunks(vec![floats(&[60.0]), floats(&[120.0, 180.0])]).unwrap(); let minutes = map_date(DateFunction::Minute, &schema, &series(chunked)) .unwrap() - .unwrap(); + .pop() + .expect("a chunked float series"); assert_eq!( points_of(&minutes), BTreeMap::from([ diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index 696156f4dfe..750c8b84e16 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -266,10 +266,10 @@ struct SeriesState { last_ts: i64, /// Next grid index to evaluate. cursor: usize, - /// Grid index after the last position the evaluator has decided, whether it holds a value or - /// not. This is what a consumer needs in order to advance, so it is reported as the chunk - /// span even where no value was produced. - completed: usize, + /// Whether the input, or the evaluated series, has ended. Until the queue of runs runs dry, + /// the state stays: the closing chunk still needs its metric, and every run already decided + /// still has to reach the consumer. + closing: bool, /// Grid index after the last position handed out to the consumer. emitted_end: usize, } @@ -539,15 +539,14 @@ impl RangeEvaluator { /// Consumes the next chunk of the current series, or starts a new series. /// - /// Returns the grid points this chunk decided, as one chunk whose range is absolute on the - /// evaluation grid; `None` when it decided no new point. A decided point whose window has no - /// result is a missing value inside the range, as it is in a whole series; the range is what - /// tells a consumer that the point is settled rather than still waiting for input. + /// Returns the first run of positions this chunk decided, addressed absolutely on the + /// evaluation grid; `None` when it decided no position holding a value. One push can decide + /// several runs, separated by stretches holding no value, so a caller takes the rest with + /// [`Self::pull`]: a decided position without a result is a row of no chunk, and dropping it + /// that way costs nothing. /// - /// The last chunk of a series is always returned, empty when it decided nothing new, because - /// that chunk is what closes the series for the consumer. - /// - /// The evaluator must not be reused after an error. + /// A series always closes: on its last run, or on an empty chunk after it when nothing is + /// left. The evaluator must not be reused after an error. pub fn push(&mut self, chunk: &RawSeriesChunk) -> Result> { if self.input_grid.is_some() { return Err(DataFusionError::Execution( @@ -562,17 +561,24 @@ impl RangeEvaluator { self.evaluate(Some( i128::from(last_ts) + i128::from(self.window.offset_ms), ))?; - return self.emit(false); + return self.emit(); } self.close_series() } - /// Evaluates one complete evaluated series, such as the inner result of a subquery: the + /// Evaluates one run of an evaluated series, such as the inner result of a subquery: the /// value at each grid point is a sample at that time. Stale markers are kept as values, /// since the input is computed. /// - /// The input arrives complete, so its result is one closing chunk. - pub fn push_series(&mut self, series: &Series) -> Result> { + /// `last` says whether this is the final run of its series. A sparse inner result arrives as + /// several runs, and the windows of a later run read the samples of the earlier ones, so the + /// state a series retains lives on across them: only the closing call ends it. Handing over + /// the runs separately without saying which is last would close the series early and lose + /// exactly the samples a window across the gap needs. + /// + /// The result of a call can be several chunks when the run holds gaps; the caller takes the + /// rest with [`Self::pull`]. + pub fn push_series(&mut self, series: &Series, last: bool) -> Result> { let TimeAxis::Grid(range) = &series.time else { return Err(DataFusionError::Execution( "evaluated range input must be a grid series".into(), @@ -586,74 +592,127 @@ impl RangeEvaluator { "evaluated series does not match the input schema".into(), )); } - if self.series.is_some() { - return Err(DataFusionError::Execution( - "evaluated series pushed inside a raw series".into(), - )); + let last_ts = range.timestamps()[range.len() - 1]; + match &mut self.series { + None => { + self.output.begin_series(); + self.series = Some(SeriesState { + primary_key: None, + metric: series.metric.clone(), + last_ts, + cursor: 0, + closing: false, + emitted_end: 0, + }); + } + Some(state) => { + // A run continues its series; the earlier runs' samples stay retained for it. + if state.primary_key.is_some() { + return Err(DataFusionError::Execution( + "evaluated series pushed inside a raw series".into(), + )); + } + if state.closing { + return Err(DataFusionError::Execution( + "evaluated series pushed after it closed".into(), + )); + } + if state.metric != series.metric { + return Err(DataFusionError::Execution( + "evaluated series changed identity before its last run".into(), + )); + } + if range.timestamps()[0] <= state.last_ts { + return Err(DataFusionError::Execution(format!( + "evaluated series runs are not increasing: {} after {}", + range.timestamps()[0], + state.last_ts + ))); + } + state.last_ts = last_ts; + } } - self.series = Some(SeriesState { - primary_key: None, - metric: series.metric.clone(), - last_ts: 0, - cursor: 0, - completed: 0, - emitted_end: 0, - }); self.ingest(&range.timestamps(), &series.fields, false)?; - self.close_series() + if last { + return self.close_series(); + } + // Later runs only hold samples after `last_ts`, so every point up to it is decided. The + // samples are shifted onto the evaluation timeline by the selector offset, so the ready + // point is on that timeline too. + self.evaluate(Some( + i128::from(last_ts) + i128::from(self.window.offset_ms), + ))?; + self.emit() } /// Evaluates the rest of the series of the last input chunk and closes it. + /// + /// The first piece left over is handed out here and the rest by [`Self::pull`]; only the run + /// that sees nothing behind it carries `is_last`. fn close_series(&mut self) -> Result> { self.evaluate(None)?; - let chunk = self.emit(true)?; - self.series = None; - Ok(chunk) + self.series + .as_mut() + .expect("every path that closes a series started one") + .closing = true; + self.emit() } - /// Hands out the positions decided since the last chunk, if any. + /// Hands out the next piece the last push decided, or the closing chunk once there is none. /// - /// The span covers everything decided, so a position decided to hold no value travels with - /// the chunk that decided it: a consumer needs that progress to advance, and to tell a - /// finished position from one still waiting for input. `is_last` closes the series, and then a - /// chunk is always handed out, empty when there is nothing left to report. - fn emit(&mut self, is_last: bool) -> Result> { + /// A push can decide several runs of positions, separated by stretches holding no value; one + /// chunk carries one run, so a consumer takes them one at a time. `None` means the series is + /// still open and nothing is pending. + pub fn pull(&mut self) -> Result> { + if self.series.is_none() { + return Ok(None); + } + self.emit() + } + + /// Hands out one run of the current series, and closes the series when nothing is left. + /// + /// A run holds a value at every position it covers, so a position decided to hold none costs + /// no row: it lies between two chunks rather than inside one. A run that sits over the + /// remaining decisions is addressed after the positions before it, which is all a chunk of one + /// series ever needs to say. `is_last` closes the series, and a series always closes exactly + /// once: on its last run, or on an empty chunk after it when no run is left. + fn emit(&mut self) -> Result> { let Some(state) = self.series.as_ref() else { return Ok(None); }; - let (start, end) = (state.emitted_end, state.completed); - // `evaluate` opens the builder's span at the first not-yet-handed-out position even when - // this push completed nothing, so finishing here would produce a zero-length chunk that - // claims progress the push did not make. Only the last chunk is handed out regardless. - if end == start && !is_last { - return Ok(None); - } + let closing = state.closing; + let emitted_end = state.emitted_end; let mut metric = state.metric.clone(); if self.drops_metric_name { metric.remove_all(&METADATA_LABELS); } - if end > start { - // Every decided position joins the span, including the ones without a value. - self.output.cover_from(start)?; - self.output.cover_through(end)?; - } - let Some(series) = self.output.finish(metric)? else { - debug_assert_eq!(end, start, "a decided position widens the span"); - return if is_last { - self.empty_chunk(start) + let Some(series) = self.output.take_run(metric)? else { + return if closing { + self.empty_chunk(emitted_end) } else { Ok(None) }; }; - self.series - .as_mut() - .expect("checked at the entry of emit") - .emitted_end = end; + let TimeAxis::Grid(range) = &series.time else { + unreachable!("the builder addresses every run on the grid") + }; + let (start, end) = (range.start(), range.start() + range.len()); + let is_last = closing && !self.output.has_pending(); + if is_last { + self.series = None; + } else { + self.series + .as_mut() + .expect("checked at the entry of emit") + .emitted_end = end; + debug_assert!(start >= emitted_end, "a run never goes back"); + } EvaluatedChunk::try_new(series, is_last).map(Some) } /// A closing chunk without values, addressed after the last position handed out. - fn empty_chunk(&self, at: usize) -> Result> { + fn empty_chunk(&mut self, at: usize) -> Result> { let state = self.series.as_ref().expect("checked by the caller"); let mut metric = state.metric.clone(); if self.drops_metric_name { @@ -665,16 +724,22 @@ impl RangeEvaluator { let time = GridRange::try_new(self.grid.clone(), at, 0).map_err(external)?; let series = Series::try_new(&self.output_schema, metric, TimeAxis::Grid(time), fields) .map_err(external)?; + self.series = None; EvaluatedChunk::try_new(series, true).map(Some) } - /// Checks that the input did not end inside a series. + /// Checks that the input did not end inside a series, with pieces nobody took. pub fn finish(self) -> Result<()> { if self.series.is_some() { return Err(DataFusionError::Execution( "raw series input ended before the last chunk of a series".into(), )); } + if self.output.has_pending() { + return Err(DataFusionError::Execution( + "range evaluation ended with pieces still to pull".into(), + )); + } Ok(()) } @@ -699,12 +764,13 @@ impl RangeEvaluator { "range evaluation requires materialized series labels".into(), ) })?; + self.output.begin_series(); self.series = Some(SeriesState { primary_key: Some(chunk.primary_key.clone()), metric, last_ts: time[time.len() - 1], cursor: 0, - completed: 0, + closing: false, emitted_end: 0, }); } @@ -844,14 +910,6 @@ impl RangeEvaluator { /// Evaluates grid points up to `ready` on the evaluation timeline, or all remaining points /// when `ready` is `None`. fn evaluate(&mut self, ready: Option) -> Result<()> { - // Positions handed out so far stay behind the builder's span, so a chunk never repeats or - // reorders them. - let emitted = self - .series - .as_ref() - .expect("checked by check_chunk") - .emitted_end; - self.output.cover_from(emitted)?; let points_read = self.points_read(); let state = self.series.as_mut().expect("checked by check_chunk"); let spec = self.grid.spec(); @@ -985,44 +1043,22 @@ impl RangeEvaluator { &mut self.batch_calls, )?; } - // How far the series is decided. A point is decided once it has been evaluated, once its - // window can no longer gain a sample, or -- at the end of the series or of what the input - // has reached -- once no retained sample reaches it. The last case matters: the loop stops - // at the first such point instead of walking the rest of the grid, so the points behind it - // still have to be reported as decided, or a consumer waits for input that decided them. - let completed = if empty_tail { - match self.replay { - Replay::PerPoint => { - let mut decided = state.cursor; - if let Some(ready) = ready { - while decided < points_read && i128::from(grid[decided]) <= ready { - decided += 1; - } - } else { - decided = points_read; - } - // Later rounds start evaluating from here, and none of these points can gain - // a value, so the cursor may skip them. - state.cursor = decided; - decided + // A point is decided once it has been evaluated, once its window can no longer gain a + // sample, or -- at the end of the series or of what the input has reached -- once no + // retained sample reaches it. The last case is what keeps a long empty stretch cheap: the + // loop stops at the first such point instead of walking the rest of the grid, and none of + // the points behind it can gain a value, so the cursor skips them. + if empty_tail && matches!(self.replay, Replay::PerPoint) { + let mut decided = state.cursor; + if let Some(ready) = ready { + while decided < points_read && i128::from(grid[decided]) <= ready { + decided += 1; } - // An anchored selector broadcasts its one window over the whole grid, so deciding - // that window decides every point. Its window ends at the grid's start rather than - // at each point, so it is decided once the input has ended or has passed that end. - Replay::Once | Replay::EveryPoint => match ready { - None => grid.len(), - Some(ready) if ready >= i128::from(spec.start_ms) => grid.len(), - Some(_) => state.completed, - }, + } else { + decided = points_read; } - } else if matches!(self.replay, Replay::PerPoint) { - state.cursor - } else if state.cursor > 0 { - grid.len() - } else { - 0 - }; - state.completed = state.completed.max(completed); + state.cursor = decided; + } for field in &mut self.fields { // After the last window, samples are still ingested so that the overflow and // histogram checks do not depend on how the series is chunked, but none are kept. diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index b485319c134..2420143d34f 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -17,6 +17,7 @@ use std::ops::Range; use std::sync::{Arc, Mutex}; use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS; +use datafusion::arrow::array::builder::NullBufferBuilder; use datafusion::arrow::array::{ArrayRef, Float64Array, TimestampMillisecondArray, UInt32Array}; use datafusion::arrow::buffer::{Buffer, ScalarBuffer}; use datafusion::arrow::datatypes::{DataType, Field}; @@ -31,7 +32,7 @@ use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{ FieldSpec, HistogramSamples, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; -use datatypes::series::time::{EvalGrid, GridSpec, TimeAxis}; +use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName}; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; @@ -45,9 +46,9 @@ use crate::functions::{ Changes, CountOverTime, IDelta, LastOverTime, MaxOverTime, MinOverTime, PresentOverTime, Resets, }; use crate::grid_series::reference::{ - Dense, GoldenCase, OwnedHistogram, assert_histogram_close, assert_series_eq, - assert_series_eq_any_nan, close, expand, golden_cases, labels_of, metric_of, mixed_series, - random_dense, special_value, + Dense, GoldenCase, OwnedHistogram, Points, assert_histogram_close, assert_pieces_eq, + assert_series_eq, assert_series_eq_any_nan, close, expand, golden_cases, labels_of, metric_of, + mixed_series, random_dense, special_value, }; use crate::grid_series::{GridSample, GridSeriesBuilder}; use crate::histogram_eval::float_histogram::FloatHistogram; @@ -198,6 +199,29 @@ fn random_chunks(rng: &mut StdRng, rows: &[Row], fields: usize, host: u64) -> Ve chunks } +/// The absolute grid position `series` starts at. +fn grid_start(series: &Series) -> usize { + match &series.time { + TimeAxis::Grid(range) => range.start(), + other => panic!("expected a grid series, got {other:?}"), + } +} + +/// How many rows of `series` hold a value in any field. +fn rows_with_a_value(series: &Series) -> usize { + let TimeAxis::Grid(range) = &series.time else { + panic!("expected a grid series, got {:?}", series.time); + }; + (0..range.len()) + .filter(|&row| { + series + .fields + .iter() + .any(|field| !matches!(field.sample(row), SampleRef::Missing)) + }) + .count() +} + /// Whether every sample of every field is missing. fn all_missing(series: &Series) -> bool { series.fields.iter().all(|field| { @@ -206,20 +230,47 @@ fn all_missing(series: &Series) -> bool { } /// Pushes every chunk of one series, keeping what the evaluator hands out on the way. +/// +/// A push can decide several runs of positions, and one chunk carries one run, so every push is +/// followed by taking the rest. fn collect_chunks( evaluator: &mut RangeEvaluator, pieces: &[RawSeriesChunk], ) -> Vec { - pieces - .iter() - .flat_map(|piece| evaluator.push(piece).unwrap()) - .collect() + let mut chunks = Vec::new(); + for piece in pieces { + chunks.extend(evaluator.push(piece).unwrap()); + drain_chunks(evaluator, &mut chunks); + } + chunks } -/// Folds the chunks of one series back into one series, the way a consumer that keeps every value +/// Takes every piece the evaluator already holds, without pushing anything more. +fn drain_chunks(evaluator: &mut RangeEvaluator, chunks: &mut Vec) { + while let Some(chunk) = evaluator.pull().unwrap() { + chunks.push(chunk); + } +} + +/// Ingests one complete evaluated series and returns every chunk it produced. +fn evaluate_series(evaluator: &mut RangeEvaluator, series: &Series) -> Vec { + let mut chunks: Vec<_> = evaluator + .push_series(series, true) + .unwrap() + .into_iter() + .collect(); + drain_chunks(evaluator, &mut chunks); + chunks +} + +/// Folds the chunks of one series into one dense series, the way a consumer that keeps every value /// would, and checks the chunk protocol: absolute ranges, never going backwards, all of the same /// series, and one closing chunk last. /// +/// The result is deliberately dense -- the gaps between chunks become null rows -- because a value +/// comparison wants one series over the whole span. Row counts must never be read off this: doing +/// so would hide exactly the allocation this change removes. +/// /// The range check is explicit rather than left to the builder, whose own ordering check only sees /// the rows holding a value: a closing chunk with no rows must still start at or after the end of /// the previous chunk, and an empty chunk at a wrong position is exactly what would pass otherwise. @@ -230,7 +281,9 @@ fn fold_chunks(chunks: &[EvaluatedChunk], schema: &Arc) -> Option< .series .metric .clone(); - let mut builder = GridSeriesBuilder::try_new(schema.clone()).unwrap(); + let width = chunks[0].series.fields.len(); + let grid_len = schema.eval_grid.as_ref().unwrap().timestamps().len(); + let mut rows: Vec>>> = (0..grid_len).map(|_| None).collect(); let mut closing = false; let mut previous_end = 0; for chunk in chunks { @@ -251,7 +304,7 @@ fn fold_chunks(chunks: &[EvaluatedChunk], schema: &Arc) -> Option< .map(|field| field.iter()) .collect(); for row in 0..range.len() { - let values: Vec<_> = fields + let values: Vec> = fields .iter_mut() .map( |field| match field.next().expect("the range length is checked") { @@ -263,12 +316,90 @@ fn fold_chunks(chunks: &[EvaluatedChunk], schema: &Arc) -> Option< }, ) .collect(); + let position = range.start() + row; // Positions only increase across chunks, so an overlap is an error here. - builder.push_samples(range.start() + row, &values).unwrap(); + if values.iter().any(|value| value.is_some()) { + assert!( + rows[position].is_none(), + "two chunks hold a value at position {position}" + ); + rows[position] = Some(values); + } } } assert!(closing, "the series never closed"); - builder.finish(metric).unwrap() + assert_eq!( + width, + schema.fields.len(), + "the fold changed the field count" + ); + dense_series(&rows, schema.clone(), metric) +} + +/// Builds one series covering every row of `rows`, with a null where no chunk held a value. +/// +/// This is deliberately not the builder: the builder hands out one piece per run of valued +/// positions, and a value comparison wants a single dense series. Row counts must never be read +/// off this -- doing so would hide exactly the allocation this change removes. +fn dense_series( + rows: &[Option>>], + schema: Arc, + metric: MetricName, +) -> Option { + let start = rows.iter().position(Option::is_some)?; + let end = rows.iter().rposition(Option::is_some)? + 1; + let rows = &rows[start..end]; + let fields = (0..schema.fields.len()) + .map(|field| { + let mut values = Vec::with_capacity(rows.len()); + let mut nulls = NullBufferBuilder::new(rows.len()); + let mut histograms: Option<(HistogramBatchBuilder, Vec>)> = None; + for row in rows { + match row.as_ref().and_then(|row| row[field].as_ref()) { + Some(GridSample::Float(value)) => { + values.push(*value); + nulls.append(true); + if let Some((_, indices)) = &mut histograms { + indices.push(None); + } + } + Some(GridSample::Histogram(h)) => { + values.push(0.0); + nulls.append(false); + let (batch, indices) = histograms + .get_or_insert_with(|| (HistogramBatchBuilder::new(), Vec::new())); + while indices.len() < values.len() - 1 { + indices.push(None); + } + indices.push(Some(h.push_to(batch).unwrap())); + } + None => { + values.push(0.0); + nulls.append(false); + if let Some((_, indices)) = &mut histograms { + indices.push(None); + } + } + } + } + let floats = Float64Array::new(values.into(), nulls.finish()); + match histograms { + None => Samples::from_float(floats), + Some((batch, indices)) => { + let histograms = HistogramSamples::try_new( + UInt32Array::from(indices), + batch.finish().unwrap(), + ) + .unwrap(); + Samples::try_from_mixed(floats, histograms).unwrap() + } + } + }) + .collect::>(); + let grid = schema.eval_grid.clone().expect("the fold is on a grid"); + let time = GridRange::try_new(grid, start, rows.len()).unwrap(); + let fields = SeriesFields::try_from_vec(fields).unwrap(); + Some(Series::try_new(&schema, metric, TimeAxis::Grid(time), fields).unwrap()) } fn random_rows(rng: &mut StdRng, fields: usize) -> Vec { @@ -834,7 +965,8 @@ fn empty_input_and_series_without_results() { probe_evaluator(1, grid(0, 10, 4), window).finish().unwrap(); // A series whose samples all miss the grid still closes, and its closing chunk says the whole - // grid was decided: every point is a settled missing value, not a point still waiting. + // grid was decided: every point is a settled missing value, not a point still waiting. A + // settled point that holds no value is reported by the close itself, not by a row. let mut evaluator = probe_evaluator(1, grid(0, 10, 4), window); let after_grid = chunk(&[(31, vec![Some(1.0)])], 1, 0, true); let closed = evaluator @@ -843,7 +975,11 @@ fn empty_input_and_series_without_results() { .expect("a series closes"); assert!(closed.is_last); assert_eq!(closed.range().start(), 0); - assert_eq!(closed.range().len(), 4); + assert_eq!( + closed.range().len(), + 0, + "no point of the grid holds a value" + ); assert!(all_missing(&closed.series)); // A series whose only sample is stale does the same: the row is dropped, the points behind it // are decided. @@ -853,16 +989,16 @@ fn empty_input_and_series_without_results() { .unwrap() .expect("a series closes"); assert!(closed.is_last); - assert_eq!((closed.range().start(), closed.range().len()), (0, 4)); + assert_eq!((closed.range().start(), closed.range().len()), (0, 0)); assert!(all_missing(&closed.series)); evaluator.finish().unwrap(); } /// A push that completes nothing must not hand out a chunk. /// -/// `evaluate` opens the builder's span at the first position it has not handed out yet, even when -/// this push settled no position, so finishing unconditionally yields a zero-length series rather -/// than none. Handing that out would report progress the push did not make. +/// A position that settles to no value is not a row, so a push that settled only such positions +/// has no run to hand out. Emitting an empty chunk instead would report progress the push did not +/// make, and a consumer that keys on chunks would see a decision that never happened. #[test] fn a_push_that_completes_nothing_hands_out_no_chunk() { let window = RangeWindow { @@ -879,13 +1015,28 @@ fn a_push_that_completes_nothing_hands_out_no_chunk() { "a push that completed no position must not hand out a chunk" ); - // The closing push still hands one out, and it reports every position of the grid. - let closed = evaluator - .push(&chunk(&[(100, vec![Some(2.0)])], 1, 0, true)) - .unwrap() - .expect("a series closes"); - assert!(closed.is_last); - assert_eq!((closed.range().start(), closed.range().len()), (0, 3)); + // The closing push hands out the one position of the grid that holds a value, and that same + // chunk is the close: nothing follows it. The two positions without a value cost no row. + let mut chunks = Vec::new(); + chunks.extend( + evaluator + .push(&chunk(&[(100, vec![Some(2.0)])], 1, 0, true)) + .unwrap(), + ); + drain_chunks(&mut evaluator, &mut chunks); + assert_eq!( + chunks.len(), + 1, + "one valued position, and it closes the series" + ); + assert_eq!((chunks[0].range().start(), chunks[0].range().len()), (0, 1)); + assert!(chunks[0].is_last); + let folded = fold_chunks(&chunks, evaluator.output_schema()).expect("the series completed"); + assert_eq!( + rows_with_a_value(&folded), + 1, + "only the first grid point holds a value" + ); evaluator.finish().unwrap(); } @@ -909,21 +1060,23 @@ fn a_series_that_ends_early_still_closes() { assert_eq!((handed.range().start(), handed.range().len()), (0, 2)); // The last sample lies past every remaining window, so points 2 to 4 are decided to hold no - // value. The closing chunk reports them rather than trimming them away. + // value. They cost no row: the close is what reports that they are settled, and it starts + // where the last handed-out run ended. let last = chunk(&[(45, vec![Some(3.0)])], 1, 0, true); let closed = evaluator.push(&last).unwrap().expect("a series closes"); assert!(closed.is_last); - assert_eq!((closed.range().start(), closed.range().len()), (2, 3)); + assert_eq!((closed.range().start(), closed.range().len()), (2, 0)); assert!(all_missing(&closed.series)); + assert_eq!(rows_with_a_value(&closed.series), 0); } -/// A chunk that decides only missing positions still has to be handed out before the series ends. +/// A stretch of decided positions holding no value costs no row, and does not delay the close. /// -/// Without it a consumer cannot tell that those positions are settled: it would keep their -/// windows open and wait for input that has already been shown to contribute nothing. The values -/// are all missing, so only the span itself carries the progress. +/// The positions are settled as soon as the sampler pushes past them, but settling them allocates +/// nothing: a consumer learns they hold no value from the run that follows them, or from the +/// close when nothing follows. #[test] -fn a_chunk_of_decided_missing_positions_is_handed_out_before_the_series_ends() { +fn decided_missing_positions_cost_no_rows_and_do_not_delay_the_close() { // `rate` over a one-second window on grid 0,1,2,3,4s. let window = RangeWindow { range_ms: 1_000, @@ -949,28 +1102,35 @@ fn a_chunk_of_decided_missing_positions_is_handed_out_before_the_series_ends() { assert!(!first.is_last); assert_eq!((first.range().start(), first.range().len()), (0, 1)); - // B: the sample at 2s decides that 1s has no window content and 2s has a single sample, so - // neither yields a rate. Neither point can change once a sample at 4s arrives: that sample - // lies past both windows. + // B settles 1s and 2s: neither yields a rate, and neither point can change once a sample at + // 4s arrives, since that sample lies past both windows. Nothing is handed out, because a + // position holding no value is not a row -- and the series has not ended, so there is no + // close to report yet. let b = chunk(&[(2_000, vec![Some(3.0)])], 1, 0, false); - let second = evaluator - .push(&b) - .unwrap() - .expect("points 1 and 2 are decided, missing or not"); - assert!(!second.is_last, "the series has not ended"); - assert_eq!((second.range().start(), second.range().len()), (1, 2)); - assert!(all_missing(&second.series)); + assert!( + evaluator.push(&b).unwrap().is_none(), + "settled positions holding no value are not rows" + ); + assert!( + evaluator.pull().unwrap().is_none(), + "the series is still open" + ); - // C closes the series and reports the rest. + // C closes the series. 3s and 4s hold no rate either, so the close carries the progress: it + // starts where the last row ended and holds none. let c = chunk(&[(4_000, vec![Some(4.0)])], 1, 0, true); - let last = evaluator.push(&c).unwrap().expect("a series closes"); + let mut chunks = vec![first]; + chunks.extend(evaluator.push(&c).unwrap()); + drain_chunks(&mut evaluator, &mut chunks); + let last = chunks.last().expect("a series always closes"); assert!(last.is_last); - assert_eq!((last.range().start(), last.range().len()), (3, 2)); + assert_eq!((last.range().start(), last.range().len()), (1, 0)); - // Folding the three chunks reproduces the whole grid, so the missing spans cost nothing. - let chunks = [first, second, last]; + // Folding the chunks reproduces the one point that holds a value; the empty stretch cost no + // row at any point along the way. let folded = fold_chunks(&chunks, evaluator.output_schema()).expect("the series completed"); assert_eq!(folded.metric, output_metric(RangeFunction::Rate, 0)); + assert_eq!((grid_start(&folded), rows_with_a_value(&folded)), (0, 1)); } /// The closing chunk of a series is labelled like the chunks before it, including the metadata @@ -994,17 +1154,488 @@ fn the_closing_chunk_is_labelled_like_the_chunks_before_it() { assert!(!handed.is_last); assert_eq!(handed.series.metric.name(), None); - // The last sample is past every remaining window, so the closing chunk carries decided - // missing positions and must still be labelled the same. + // The last sample is past every remaining window, so the close reports the settled positions + // that hold no value, and it must be labelled the same as the chunk before it. let last = chunk(&[(45, vec![Some(5.0)])], 1, 0, true); - let closed = evaluator.push(&last).unwrap().expect("a series closes"); + let mut chunks = vec![handed]; + chunks.extend(evaluator.push(&last).unwrap()); + drain_chunks(&mut evaluator, &mut chunks); + let closed = chunks.last().expect("a series always closes"); assert!(closed.is_last); - assert!(!closed.range().is_empty()); + assert_eq!( + closed.range().len(), + 0, + "the settled positions hold no value" + ); assert!(all_missing(&closed.series)); - assert_eq!(closed.series.metric, handed.series.metric); + assert_eq!(closed.series.metric, chunks[0].series.metric); assert_eq!(closed.series.metric.name(), None); } +/// The `(start, len)` of every chunk handed out, in order. +fn chunk_ranges(chunks: &[EvaluatedChunk]) -> Vec<(usize, usize)> { + chunks + .iter() + .map(|chunk| (chunk.range().start(), chunk.range().len())) + .collect() +} + +/// The rows handed out over every chunk of one series. +fn total_rows(chunks: &[EvaluatedChunk]) -> usize { + chunks.iter().map(|chunk| chunk.range().len()).sum() +} + +/// A one-millisecond window, so the value at a grid point is the sample sitting exactly on it. +fn pinpoint(window: RangeWindow) -> RangeEvaluator { + probe_evaluator(1, grid(0, 1, 1_000_000), window) +} + +fn one_ms() -> RangeWindow { + RangeWindow { + range_ms: 1, + offset_ms: 0, + anchor_ms: None, + } +} + +/// Two samples a million positions apart cost two rows: a position holding no value is not a +/// row, so the empty stretch between them is never materialised. +#[test] +fn a_huge_gap_costs_one_row_per_value() { + let mut evaluator = pinpoint(one_ms()); + let rows = [(10, vec![Some(1.0)]), (900_000, vec![Some(2.0)])]; + let chunks = collect_chunks(&mut evaluator, &[chunk(&rows, 1, 0, true)]); + + assert_eq!( + chunk_ranges(&chunks), + vec![(10, 1), (900_000, 1)], + "one chunk per value, each over its own position" + ); + assert_eq!(total_rows(&chunks), 2, "two values, two rows"); + for chunk in &chunks { + let (start, len) = (chunk.range().start(), chunk.range().len()); + let end = start + len; + assert!( + end <= 11 || start >= 900_000, + "chunk {start}..{end} reaches into the empty stretch" + ); + assert_ne!( + (start, end), + (0, 1_000_000), + "no chunk spans the whole grid" + ); + } + assert!(chunks.last().unwrap().is_last); + evaluator.finish().unwrap(); +} + +/// A series whose first value comes late is addressed at that position: nothing is allocated for +/// the positions before it. +#[test] +fn a_very_late_first_value_allocates_nothing_before_it() { + let mut evaluator = pinpoint(one_ms()); + let chunks = collect_chunks( + &mut evaluator, + &[chunk(&[(999_000, vec![Some(1.0)])], 1, 0, true)], + ); + + assert_eq!(chunk_ranges(&chunks), vec![(999_000, 1)]); + assert_eq!(total_rows(&chunks), 1); + assert!(chunks[0].is_last); + evaluator.finish().unwrap(); +} + +/// A series whose last value comes early closes on the value it has: the positions after it are +/// settled and hold nothing, which the close reports without a row for any of them. +#[test] +fn a_very_early_last_value_closes_without_rows_for_the_rest() { + let mut evaluator = pinpoint(one_ms()); + let first = chunk(&[(0, vec![Some(1.0)])], 1, 0, false); + let mut chunks = vec![evaluator.push(&first).unwrap().expect("point 0 is decided")]; + assert!(!chunks[0].is_last); + chunks.extend( + evaluator + .push(&chunk(&[(5, vec![Some(2.0)])], 1, 0, true)) + .unwrap(), + ); + drain_chunks(&mut evaluator, &mut chunks); + + assert_eq!(chunk_ranges(&chunks), vec![(0, 1), (5, 1)]); + assert_eq!( + total_rows(&chunks), + 2, + "the two positions holding a value, and no others" + ); + assert!(chunks.last().unwrap().is_last); + evaluator.finish().unwrap(); +} + +/// A push that advances over a long blank stretch hands out nothing for it, and a later push still +/// yields its own value: skipping the stretch loses no sample. +#[test] +fn a_blank_stretch_hands_out_nothing_and_loses_the_next_value() { + let mut evaluator = pinpoint(one_ms()); + let mut chunks = Vec::new(); + chunks.extend( + evaluator + .push(&chunk(&[(10, vec![Some(1.0)])], 1, 0, false)) + .unwrap(), + ); + assert_eq!( + chunk_ranges(&chunks), + vec![(10, 1)], + "only the position holding a value is handed out" + ); + assert!(!chunks[0].is_last); + assert!(evaluator.pull().unwrap().is_none()); + + chunks.extend( + evaluator + .push(&chunk(&[(900_000, vec![Some(2.0)])], 1, 0, true)) + .unwrap(), + ); + drain_chunks(&mut evaluator, &mut chunks); + assert_eq!(chunk_ranges(&chunks), vec![(10, 1), (900_000, 1)]); + assert_eq!(total_rows(&chunks), 2); + assert!(chunks.last().unwrap().is_last); + + let folded = fold_chunks(&chunks, evaluator.output_schema()).expect("the series completed"); + assert_eq!( + rows_with_a_value(&folded), + 2, + "the later value reached the consumer" + ); + evaluator.finish().unwrap(); +} + +/// A series with no value anywhere still closes, exactly once, on a chunk holding no rows. +#[test] +fn a_series_without_any_result_closes_once() { + // The only sample lies before the grid, so no window contains it. + let mut evaluator = probe_evaluator(1, grid(5, 1, 1_000_000), one_ms()); + let mut chunks = Vec::new(); + chunks.extend( + evaluator + .push(&chunk(&[(0, vec![Some(1.0)])], 1, 0, true)) + .unwrap(), + ); + drain_chunks(&mut evaluator, &mut chunks); + + assert_eq!(chunks.len(), 1, "a series closes exactly once"); + assert!(chunks[0].is_last); + assert_eq!(chunk_ranges(&chunks), vec![(0, 0)]); + assert_eq!(total_rows(&chunks), 0); + assert!(evaluator.pull().unwrap().is_none()); + evaluator.finish().unwrap(); +} + +/// A valued prefix followed by an all-empty remainder still closes, and the remainder costs no +/// row. +#[test] +fn a_valued_prefix_and_an_empty_remainder_still_close() { + let mut evaluator = pinpoint(one_ms()); + let mut chunks = vec![ + evaluator + .push(&chunk(&[(3, vec![Some(1.0)])], 1, 0, false)) + .unwrap() + .expect("point 3 is decided"), + ]; + assert_eq!(chunk_ranges(&chunks), vec![(3, 1)]); + assert!(!chunks[0].is_last); + + // The last row is stale, so it is dropped and the remainder holds no value at all. + let last = chunk(&[(900_000, vec![Some(stale())])], 1, 0, true); + chunks.extend(evaluator.push(&last).unwrap()); + drain_chunks(&mut evaluator, &mut chunks); + + assert_eq!(chunk_ranges(&chunks), vec![(3, 1), (4, 0)]); + assert_eq!(total_rows(&chunks), 1, "the remainder holds no rows"); + assert!(chunks.last().unwrap().is_last); + evaluator.finish().unwrap(); +} + +/// Folding the chunks of a sparse series gives the same series as folding the same samples with a +/// row for every position holding no value: a missing position and an uncovered one mean the same +/// thing to a consumer. +#[test] +fn a_sparse_series_folds_like_the_same_data_with_explicit_nulls() { + let grid = grid(0, 1_000, 40); + let window = RangeWindow { + range_ms: 3_000, + offset_ms: 0, + anchor_ms: None, + }; + let rows = [ + (0, vec![Some(1.0)]), + (1_000, vec![Some(2.0)]), + (2_000, vec![Some(3.0)]), + (20_000, vec![Some(4.0)]), + (21_000, vec![Some(5.0)]), + (39_000, vec![Some(6.0)]), + ]; + let mut evaluator = probe_evaluator(1, grid.clone(), window); + let chunks = collect_chunks(&mut evaluator, &[chunk(&rows, 1, 0, true)]); + let folded = fold_chunks(&chunks, evaluator.output_schema()).expect("the series completed"); + + let expected = reference(&rows, &grid, window, 1, true, true); + let spread = expected.iter().filter(|row| row[0].is_some()).count(); + assert_eq!( + total_rows(&chunks), + spread, + "a row per position holding a value, and none for the rest" + ); + assert_eq!( + expand(&folded), + expected, + "the sparse result equals the one written as null rows" + ); + evaluator.finish().unwrap(); +} + +/// The runs of one evaluated series share the evaluator's retained samples: a window reaching +/// back across the gap to an earlier run reads both. +/// +/// This is what makes a sparse inner result usable. Closing the series after its first run, or +/// promoting each run to a series of its own, would leave the window at 10ms reading 3 alone +/// instead of 2 + 3. +#[test] +fn a_window_reads_across_the_gap_between_runs_of_one_series() { + let inner = grid(0, 1, 11); + let schema = Arc::new(SeriesSchema { + fields: raw_schema(1).fields, + eval_grid: Some(inner), + }); + // One point at 10ms; the window reaches back 11ms, which takes in the point at 0ms. + let window = RangeWindow { + range_ms: 11, + offset_ms: 0, + anchor_ms: None, + }; + let mut evaluator = + RangeEvaluator::try_new(&schema, grid(10, 1, 1), window, RangeFunction::SumOverTime) + .unwrap(); + let labels = BTreeMap::from([("job".to_string(), "x".to_string())]); + let run = |point: usize, value: f64| { + mixed_series( + &schema, + &labels, + &Points::from([(point, value.to_bits())]), + &BTreeMap::new(), + ) + .unwrap() + }; + + let mut chunks = Vec::new(); + chunks.extend(evaluator.push_series(&run(0, 2.0), false).unwrap()); + drain_chunks(&mut evaluator, &mut chunks); + assert!( + chunks.is_empty(), + "the run at 0ms decides no point of the outer grid" + ); + chunks.extend(evaluator.push_series(&run(10, 3.0), true).unwrap()); + drain_chunks(&mut evaluator, &mut chunks); + + let closed = chunks.last().expect("the series closes"); + assert!(closed.is_last); + assert!(matches!( + closed.series.fields.as_slice()[0].sample(0), + SampleRef::Float(sum) if sum == 5.0 + )); + evaluator.finish().unwrap(); +} + +/// The samples decide the rows, not the input chunking: the same logical data split at different +/// boundaries folds to the same series over the same number of rows. +#[test] +fn raw_chunk_boundaries_do_not_change_the_rows() { + let grid = grid(0, 1_000, 40); + let window = RangeWindow { + range_ms: 2_000, + offset_ms: 0, + anchor_ms: None, + }; + let rows = [ + (0, vec![Some(1.0)]), + (1_000, vec![Some(2.0)]), + (10_000, vec![Some(3.0)]), + (11_000, vec![Some(4.0)]), + (30_000, vec![Some(5.0)]), + ]; + let expected = reference(&rows, &grid, window, 1, true, true); + let expected_rows = expected.iter().filter(|row| row[0].is_some()).count(); + let splits: [&[usize]; 4] = [&[], &[2], &[2, 4], &[1, 2, 3, 4]]; + + let mut outcomes = Vec::new(); + for split in splits { + let mut chunks = Vec::new(); + let mut start = 0; + let mut evaluator = probe_evaluator(1, grid.clone(), window); + for end in split.iter().copied().chain(std::iter::once(rows.len())) { + let piece = chunk(&rows[start..end], 1, 0, end == rows.len()); + chunks.extend(evaluator.push(&piece).unwrap()); + drain_chunks(&mut evaluator, &mut chunks); + start = end; + } + let folded = fold_chunks(&chunks, evaluator.output_schema()).expect("the series completed"); + assert_eq!(expand(&folded), expected, "split {split:?} differs"); + // No chunk ever spans a position holding no value, whatever the chunking: the rows are + // consecutive grid positions, and the positions between two chunks are the empty ones. + for chunk in &chunks { + let range = chunk.range(); + assert!( + range.len() <= 3, + "split {split:?} handed out {} rows at once over a series with no three-value run", + range.len() + ); + } + outcomes.push(total_rows(&chunks)); + evaluator.finish().unwrap(); + } + // Which chunk a run lands in follows the input boundaries, since a push has to hand its + // decided positions out before the next one changes them. What must not depend on chunking is + // the number of rows: an empty position never costs one. + assert!( + outcomes.windows(2).all(|pair| pair[0] == pair[1]), + "chunking changed the rows handed out: {outcomes:?}" + ); + assert_eq!(outcomes, vec![expected_rows; outcomes.len()]); +} + +/// Values and nulls alternating: one row per value and one chunk per value, which is what this +/// design costs for data that never holds two consecutive positions. +#[test] +fn alternating_values_and_nulls_hand_out_one_row_per_value() { + let mut evaluator = probe_evaluator(1, grid(0, 1, 10), one_ms()); + let rows: Vec = (0..10) + .map(|index| { + let value = (index % 2 == 0).then_some(index as f64 + 1.0); + (index, vec![value]) + }) + .collect(); + let chunks = collect_chunks(&mut evaluator, &[chunk(&rows, 1, 0, true)]); + + assert_eq!( + chunk_ranges(&chunks), + vec![(0, 1), (2, 1), (4, 1), (6, 1), (8, 1)], + "one chunk per value: five values, five chunks" + ); + assert_eq!(total_rows(&chunks), 5); + assert!(chunks.last().unwrap().is_last); + assert_eq!(chunks.iter().filter(|chunk| chunk.is_last).count(), 1); + evaluator.finish().unwrap(); +} + +/// Values and nulls alternating over 200,000 positions: 100,000 valued positions cost 100,000 +/// rows, not one per position, and each value is its own piece. +/// +/// The piece count is the accepted cost of this design; the row count is what must not regress. +#[test] +fn interleaved_values_over_a_long_grid_cost_one_row_per_value() { + const GRID: u64 = 200_000; + let mut evaluator = probe_evaluator(1, grid(0, 1, GRID), one_ms()); + let rows: Vec = (0..GRID) + .map(|index| { + let value = (index % 2 == 0).then_some(index as f64); + (index as i64, vec![value]) + }) + .collect(); + let chunks = collect_chunks(&mut evaluator, &[chunk(&rows, 1, 0, true)]); + + assert_eq!( + total_rows(&chunks), + (GRID / 2) as usize, + "one row per valued position, never one per position" + ); + assert_eq!( + chunks.len(), + (GRID / 2) as usize, + "one piece per value; the last one carries the close" + ); + assert!(chunks.last().unwrap().is_last); + assert_eq!(chunks.iter().filter(|chunk| chunk.is_last).count(), 1); + for chunk in &chunks { + assert_eq!( + chunk.range().len(), + 1, + "every valued position is its own piece" + ); + assert_eq!( + chunk.range().start() % 2, + 0, + "only even positions hold a value" + ); + } + evaluator.finish().unwrap(); +} + +/// An anchored selector broadcasts one value over every grid point, so every position holds one: +/// the result is a single contiguous piece, not one piece per position. +#[test] +fn an_anchored_replay_stays_one_contiguous_piece() { + let window = RangeWindow { + range_ms: 10, + offset_ms: 0, + anchor_ms: Some(5), + }; + for step_invariant in [true, false] { + let mut evaluator = if step_invariant { + // `Replay::Once`: the first point's result holds at every point. + probe_evaluator(1, grid(0, 10, 100), window) + } else { + // `Replay::EveryPoint`: the first point's window is evaluated at every point. + per_point_probe_evaluator(1, grid(0, 10, 100), window) + }; + let chunks = collect_chunks( + &mut evaluator, + &[chunk(&[(0, vec![Some(1.0)])], 1, 0, true)], + ); + assert_eq!( + chunk_ranges(&chunks), + vec![(0, 100)], + "every position holds a value, so the whole grid is one piece (step_invariant={step_invariant})" + ); + assert_eq!(total_rows(&chunks), 100); + assert!(chunks[0].is_last); + evaluator.finish().unwrap(); + } +} + +/// Fields of one run stay row-aligned: a field with no value at a position another field fills +/// keeps a null row there. That null is the layout, not a bridged gap. +#[test] +fn a_run_keeps_its_fields_aligned_and_nulls_only_the_missing_one() { + let mut evaluator = probe_evaluator(2, grid(0, 1, 6), one_ms()); + let rows = [ + (0, vec![Some(1.0), None]), + (1, vec![None, Some(2.0)]), + (2, vec![Some(3.0), Some(4.0)]), + ]; + let chunks = collect_chunks(&mut evaluator, &[chunk(&rows, 2, 0, true)]); + + assert_eq!( + chunk_ranges(&chunks), + vec![(0, 3)], + "three positions, one run" + ); + let series = &chunks[0].series; + let observed: Vec> = (0..3) + .map(|row| { + series + .fields + .iter() + .map(|field| !matches!(field.sample(row), SampleRef::Missing)) + .collect() + }) + .collect(); + assert_eq!( + observed, + vec![vec![true, false], vec![false, true], vec![true, true]], + "both fields carry a row at every position of the run" + ); + assert!(chunks[0].is_last); + evaluator.finish().unwrap(); +} + #[test] fn rejects_invalid_parameters() { let zero_range = RangeWindow { @@ -1413,13 +2044,14 @@ fn nulls_change_the_reset_positions_of_each_field_independently() { } /// A random evaluated series on `grid`; values may carry the stale bit pattern, which computed -/// input keeps as an ordinary NaN. +/// input keeps as an ordinary NaN. The rows hold holes, so the series arrives as one piece per run +/// of positions holding a value. fn random_evaluated( rng: &mut StdRng, grid: &Arc, fields: usize, host: u64, -) -> (Option, Vec) { +) -> (Vec, Vec) { let mut dense = random_dense(rng, grid.timestamps().len(), fields); for value in dense.iter_mut().flatten().flatten() { if rng.random_bool(0.05) { @@ -1444,6 +2076,20 @@ fn random_evaluated( (builder.finish(metric(host)).unwrap(), rows) } +/// Pushes the pieces of one evaluated input series, the last of them closing it, and drains the +/// chunks. +fn evaluate_pieces(evaluator: &mut RangeEvaluator, pieces: &[Series]) -> Vec { + let mut chunks = Vec::new(); + for (index, piece) in pieces.iter().enumerate() { + let last = index + 1 == pieces.len(); + if let Some(chunk) = evaluator.push_series(piece, last).unwrap() { + chunks.push(chunk); + } + drain_chunks(evaluator, &mut chunks); + } + chunks +} + #[test] fn subquery_series_match_references() { for seed in 0..300 { @@ -1459,9 +2105,10 @@ fn subquery_series_match_references() { fields: raw_schema(fields).fields, eval_grid: Some(inner.clone()), }; - let (Some(series), rows) = random_evaluated(&mut rng, &inner, fields, seed) else { + let (series, rows) = random_evaluated(&mut rng, &inner, fields, seed); + if series.is_empty() { continue; - }; + } let mut probe = RangeEvaluator::with_kernel( &schema, outer.clone(), @@ -1472,22 +2119,16 @@ fn subquery_series_match_references() { ) .unwrap(); let expected = reference(&rows, &outer, window, fields, false, true); - let evaluated = probe - .push_series(&series) - .unwrap() - .expect("the input closes"); - assert!(evaluated.is_last); - let result = fold_chunks(std::slice::from_ref(&evaluated), probe.output_schema()); + let evaluated = evaluate_pieces(&mut probe, &series); + assert!(evaluated.last().expect("the input closes").is_last); + let result = fold_chunks(&evaluated, probe.output_schema()); assert_series_eq(result.as_ref(), &expected, &metric(seed)); for function in udf_functions() { let mut evaluator = RangeEvaluator::try_new(&schema, outer.clone(), window, function).unwrap(); let expected = udf_reference(function, &rows, &outer, window, fields, false); - let evaluated = evaluator - .push_series(&series) - .unwrap() - .expect("the input closes"); - let result = fold_chunks(std::slice::from_ref(&evaluated), evaluator.output_schema()); + let evaluated = evaluate_pieces(&mut evaluator, &series); + let result = fold_chunks(&evaluated, evaluator.output_schema()); assert_series_eq(result.as_ref(), &expected, &output_metric(function, seed)); } } @@ -1535,8 +2176,12 @@ fn rejects_input_of_the_other_kind() { let mut builder = GridSeriesBuilder::try_new(Arc::new(evaluated)).unwrap(); builder.push(0, &[Some(1.0)]).unwrap(); - let series = builder.finish(metric(0)).unwrap().unwrap(); - execution_error(probe_evaluator(1, grid(0, 10, 4), window).push_series(&series)); + let series = builder + .finish(metric(0)) + .unwrap() + .pop() + .expect("one contiguous run"); + execution_error(probe_evaluator(1, grid(0, 10, 4), window).push_series(&series, true)); } /// The range function a golden fixture names, with its constant arguments. @@ -2085,12 +2730,11 @@ fn absent_over_time_is_absent_over_present_over_time() { RangeFunction::PresentOverTime, ) .unwrap(); - let closed = evaluator - .push(&chunk(&rows, 1, host as u64, true)) - .unwrap() - .expect("the series closes"); - assert!(closed.is_last); - present.push(closed.series); + let input = chunk(&rows, 1, host as u64, true); + let chunks = collect_chunks(&mut evaluator, std::slice::from_ref(&input)); + let folded = + fold_chunks(&chunks, evaluator.output_schema()).expect("every input series closes"); + present.push(folded); } let schema = SeriesSchema { fields: raw_schema(1).fields, @@ -2101,7 +2745,9 @@ fn absent_over_time_is_absent_over_present_over_time() { let none = MetricName::try_new(None, Vec::new()).unwrap(); (vec![vec![None]; grid_spec[2] as usize], none) }); - assert_series_eq(actual.as_ref(), &expected, &labels); + // `absent` over single-field inputs writes a value at every point where it is absent, so + // the pieces stitched back give the dense expectation. + assert_pieces_eq(&actual, &expected, &labels); checked += 1; } assert_eq!(checked, 120); @@ -2276,7 +2922,9 @@ fn evaluated_histograms_drop_counter_reset_hints() { }; let mut evaluator = RangeEvaluator::try_new(&schema, grid(10, 10, 1), window, RangeFunction::Resets).unwrap(); - let result = evaluator.push_series(&series).unwrap().unwrap().series; + let mut chunks = evaluate_series(&mut evaluator, &series); + assert_eq!(chunks.len(), 1); + let result = chunks.pop().unwrap().series; assert!(matches!( result.fields.as_slice()[0].sample(0), SampleRef::Float(resets) if resets == 0.0 diff --git a/src/promql/src/select.rs b/src/promql/src/select.rs index daa711c7fd8..f1e367d6a81 100644 --- a/src/promql/src/select.rs +++ b/src/promql/src/select.rs @@ -127,9 +127,7 @@ pub fn topk( for point in sorted { builder.push(point, &[value_at(&series[index], point)?])?; } - if let Some(built) = builder.finish(series[index].metric.clone())? { - result.push(built); - } + result.extend(builder.finish(series[index].metric.clone())?); } Ok(result) } @@ -157,9 +155,17 @@ pub fn scalar(schema: &SeriesSchema, series: &[Series]) -> Result { builder.push(point, &[value])?; } let empty = MetricName::try_new(None, Vec::new()).map_err(external)?; - Ok(builder - .finish(empty)? - .expect("every point of a scalar has a value")) + // Every grid point is written above, with a value or a NaN, so the result is one contiguous + // piece. A different shape would mean this invariant broke, and dropping the extra pieces + // silently would hide it. + let mut pieces = builder.finish(empty)?; + if pieces.len() != 1 { + return Err(DataFusionError::Execution(format!( + "scalar produced {} pieces, expected exactly one over the grid", + pieces.len() + ))); + } + Ok(pieces.pop().expect("checked to hold one piece")) } /// `absent(v)`: 1 with `labels` at every point where no series is present. @@ -167,11 +173,11 @@ pub fn scalar(schema: &SeriesSchema, series: &[Series]) -> Result { /// `absent_over_time(v[r])` is this over the result of `present_over_time(v[r])`. When `v[r]` is /// a range selector, `labels` come from its matchers as for `absent(v)`; for a subquery /// Prometheus derives no labels. -pub fn absent( - schema: &SeriesSchema, - series: &[Series], - labels: MetricName, -) -> Result> { +/// +/// A point where something is absent but another field is not contributes no row, so the result +/// is several pieces when the output fields take turns being absent. It is empty only when the +/// grid has no points. +pub fn absent(schema: &SeriesSchema, series: &[Series], labels: MetricName) -> Result> { let points = grid_points(schema, series)?; let fields = schema.fields.len(); // Each field is absent on its own. diff --git a/src/promql/src/select/tests.rs b/src/promql/src/select/tests.rs index 848db75315d..eefe638081c 100644 --- a/src/promql/src/select/tests.rs +++ b/src/promql/src/select/tests.rs @@ -15,17 +15,18 @@ use std::collections::BTreeMap; use std::sync::Arc; +use datafusion::arrow::array::Float64Array; use datafusion::error::DataFusionError; -use datatypes::series::samples::{FieldSpec, Series, SeriesSchema}; -use datatypes::series::time::{EvalGrid, GridSpec}; +use datatypes::series::samples::{FieldSpec, Samples, Series, SeriesFields, SeriesSchema}; +use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName}; use super::{ Grouping, LabelMatcher, MatchOp, SortOrder, absent, absent_labels, natural_less, scalar, sort_instant, topk, }; -use crate::grid_series::GridSeriesBuilder; -use crate::grid_series::reference::{Dense, assert_series_eq}; +use crate::golden::fold_pieces; +use crate::grid_series::reference::{Dense, assert_pieces_eq, assert_series_eq, piece_ranges}; fn schema(points: u64, fields: usize) -> SeriesSchema { SeriesSchema { @@ -69,12 +70,35 @@ fn dense(points: usize, values: &str) -> Dense { dense } +/// The `dense` matrix as one trimmed series, `None` when every row is missing. +/// +/// An *input*, so the holes stay nulls inside one series: the builder would cut them into pieces, +/// and the operators under test take one series per input. fn build(schema: &SeriesSchema, metric: MetricName, dense: &Dense) -> Option { - let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone())).unwrap(); - for (index, row) in dense.iter().enumerate() { - builder.push(index, row).unwrap(); - } - builder.finish(metric).unwrap() + let start = dense + .iter() + .position(|row| row.iter().any(Option::is_some))?; + let end = dense + .iter() + .rposition(|row| row.iter().any(Option::is_some))? + + 1; + let rows = &dense[start..end]; + let fields = (0..schema.fields.len()) + .map(|field| { + let values: Float64Array = rows.iter().map(|row| row[field]).collect(); + Samples::from_float(values) + }) + .collect::>(); + let time = GridRange::try_new(schema.eval_grid.clone().unwrap(), start, rows.len()).unwrap(); + Some( + Series::try_new( + schema, + metric, + TimeAxis::Grid(time), + SeriesFields::try_from_vec(fields).unwrap(), + ) + .unwrap(), + ) } fn names(list: &str) -> Vec> { @@ -168,7 +192,9 @@ fn select_operators_match_prometheus() { other => panic!("unknown case {other}"), }; - let actual: BTreeMap = actual + // A result arrives as one piece per run of valued positions; the fixtures pin the dense + // values, so the pieces of each label set are folded back together first. + let actual: BTreeMap = fold_pieces(actual) .into_iter() .map(|series| (render(&series.metric), series)) .collect(); @@ -340,6 +366,9 @@ fn absent_evaluates_fields_independently() { let input = vec![vec![Some(3.0), None], vec![None, Some(4.0)]]; let series = vec![build(&schema, metric("__name__=a"), &input).unwrap()]; let result = absent(&schema, &series, metric("-")).unwrap(); + // The two fields take turns holding a value, but a row is kept when either field has one, so + // both positions stay in one piece; the missing field carries a null there. + assert_eq!(piece_ranges(&result), vec![(0, 2)]); let expected = vec![vec![None, Some(1.0)], vec![Some(1.0), None]]; - assert_series_eq(result.as_ref(), &expected, &metric("-")); + assert_pieces_eq(&result, &expected, &metric("-")); } diff --git a/src/promql/src/vector_match.rs b/src/promql/src/vector_match.rs index 43a136198ba..8f6b582a800 100644 --- a/src/promql/src/vector_match.rs +++ b/src/promql/src/vector_match.rs @@ -423,9 +423,7 @@ fn merge_fields(fields: Vec, schema: Arc) -> Result, fields: usize) -> Side { for (index, row) in values.iter().enumerate() { builder.push(index, row).unwrap(); } - if let Some(built) = builder.finish(metric(&labels)).unwrap() { - series.push(built); - dense.push((labels, values)); - } + // Random rows can hold holes, so one label set arrives as one piece per run of valued + // positions. Every piece is kept: together they cover exactly the valued positions, which + // is what the dense matrix behind the reference holds. + series.extend(builder.finish(metric(&labels)).unwrap()); + dense.push((labels, values)); } Side { schema, @@ -422,7 +423,9 @@ fn reference_set( fn assert_output(actual: Result, DataFusionError>, expected: Expected, seed: u64) { match (actual, expected) { (Ok(actual), Ok(expected)) => { - let actual: BTreeMap = actual + // A result arrives as one piece per run of valued positions; the reference is dense, + // so the pieces of each label set are folded back together first. + let actual: BTreeMap = crate::golden::fold_pieces(actual) .into_iter() .map(|series| (labels_of(&series.metric), series)) .collect(); @@ -580,7 +583,11 @@ fn reports_the_earliest_failing_point() { .iter() .map(|(name, value)| (name.to_string(), value.to_string())) .collect(); - builder.finish(metric(&labels)).unwrap().unwrap() + builder + .finish(metric(&labels)) + .unwrap() + .pop() + .expect("each call pushes one run") }; let mut lhs = vec![ series(&[("__name__", "a"), ("job", "z")], &[0]), @@ -696,14 +703,14 @@ fn vector_operations_match_prometheus() { let value = values.get(&point).map(|bits| f64::from_bits(*bits)); builder.push(point, &[value]).unwrap(); } - let Some(series) = builder.finish(metric(&labels)).unwrap() else { - continue; - }; - if labels.get("__name__").map(String::as_str) == Some("a") { - lhs.push(series); + // A series line can hold holes, so it arrives as one piece per run of valued + // positions; each piece carries its own grid range. + let side = if labels.get("__name__").map(String::as_str) == Some("a") { + &mut lhs } else { - rhs.push(series); - } + &mut rhs + }; + side.extend(builder.finish(metric(&labels)).unwrap()); } "result" => { let values = values @@ -761,11 +768,19 @@ fn vector_operations_match_prometheus() { }; match (actual, error) { (Ok(actual), None) => { - let actual: BTreeMap> = actual - .iter() - .map(|series| (labels_of(&series.metric), points_of(series))) - .collect(); - assert_close(&actual, &expected, case); + // A label set arrives as one piece per run of valued positions; the values of all + // its pieces together are the series Prometheus evaluated at those points. + let mut folded: BTreeMap> = BTreeMap::new(); + for series in &actual { + let points = folded.entry(labels_of(&series.metric)).or_default(); + for (point, bits) in points_of(series) { + assert!( + points.insert(point, bits).is_none(), + "{case}: {point} handed out twice" + ); + } + } + assert_close(&folded, &expected, case); matched += 1; } (Err(actual), Some(expected)) => { @@ -804,7 +819,11 @@ fn colliding_results_fail_by_where_they_collide() { .iter() .map(|(name, value)| (name.to_string(), value.to_string())) .collect(); - builder.finish(metric(&labels)).unwrap().unwrap() + builder + .finish(metric(&labels)) + .unwrap() + .pop() + .expect("each call pushes one point") }; let lhs = vec![ series(&[("__name__", "a"), ("__type__", "counter"), ("job", "x")]), @@ -1001,48 +1020,56 @@ fn histogram_operators_match_prometheus() { (expected, actual) => panic!("{context}: got {actual:?}, expected {expected:?}"), }; let (expected, actual) = expected; - let actual: BTreeMap = actual - .into_iter() - .map(|series| (labels_of(&series.metric), series)) - .collect(); + // A label set arrives as one piece per run of valued positions, so its pieces are gathered + // before comparing: together they must cover exactly the points Prometheus reported. + let mut folded: BTreeMap> = BTreeMap::new(); + for series in actual { + folded + .entry(labels_of(&series.metric)) + .or_default() + .push(series); + } assert_eq!( - actual.keys().collect::>(), + folded.keys().collect::>(), expected.keys().collect::>(), "{context}" ); let no_histograms = BTreeMap::new(); - for (labels, series) in &actual { - let TimeAxis::Grid(range) = &series.time else { - panic!("expected a grid series"); - }; + for (labels, pieces) in &folded { let floats = &expected[labels]; let texts = case.result_histograms.get(labels).unwrap_or(&no_histograms); - let mut points = 0; - for (row, sample) in series.fields.as_slice()[0].iter().enumerate() { - let point = range.start() + row; - match sample { - SampleRef::Missing => continue, - SampleRef::Float(value) => { - let want = f64::from_bits(floats[&point]); - assert!( - crate::grid_series::reference::close(value, want, 1e-10), - "{context} at {point}: {value} vs {want}" - ); - } - SampleRef::Histogram(view) => { - let want = OwnedHistogram::parse(&texts[&point]); - assert_histogram_close( - &FloatHistogram::try_from_view(&view).unwrap(), - &FloatHistogram::try_from_view(&want.view()).unwrap(), - 1e-10, - &format!("{context} at {point}"), - ); - histograms += 1; + let mut seen = BTreeSet::new(); + for series in pieces { + let TimeAxis::Grid(range) = &series.time else { + panic!("expected a grid series"); + }; + for (row, sample) in series.fields.as_slice()[0].iter().enumerate() { + let point = range.start() + row; + match sample { + SampleRef::Missing => continue, + SampleRef::Float(value) => { + let want = f64::from_bits(floats[&point]); + assert!( + crate::grid_series::reference::close(value, want, 1e-10), + "{context} at {point}: {value} vs {want}" + ); + } + SampleRef::Histogram(view) => { + let want = OwnedHistogram::parse(&texts[&point]); + assert_histogram_close( + &FloatHistogram::try_from_view(&view).unwrap(), + &FloatHistogram::try_from_view(&want.view()).unwrap(), + 1e-10, + &format!("{context} at {point}"), + ); + histograms += 1; + } } + assert!(seen.insert(point), "{context}: {point} handed out twice"); } - points += 1; } - assert_eq!(points, floats.len() + texts.len(), "{context}"); + let wanted: BTreeSet = floats.keys().chain(texts.keys()).copied().collect(); + assert_eq!(seen, wanted, "{context}"); } matched += 1; }