diff --git a/src/promql/src/grid_series.rs b/src/promql/src/grid_series.rs index b5634b259e9..19d2ae2d1dd 100644 --- a/src/promql/src/grid_series.rs +++ b/src/promql/src/grid_series.rs @@ -24,7 +24,7 @@ use datafusion::error::{DataFusionError, Result}; use datatypes::series::MetricName; use datatypes::series::histogram::HistogramBatchBuilder; use datatypes::series::samples::{ - HistogramSamples, RowCursor, SampleRef, Samples, Series, SeriesFields, SeriesSchema, + HistogramSamples, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; use datatypes::series::time::{EvalGrid, GridSpan, TimeAxis}; @@ -310,6 +310,13 @@ pub(crate) fn label_set(metric: &MetricName) -> LabelSet { /// Merges series that share a label set into one, as Prometheus does after a function that /// rewrites labels or drops `__name__`; two of them holding one field at one point fail. +/// +/// The merge rearranges the payloads instead of rewriting them: a merged row takes the value its +/// member carries at that position -- a float, a NaN, or a native histogram -- and a field another +/// field's row does not fill keeps a null there. The values keep their storage: a run of rows one +/// member holds in one dense segment is handed out as a [`Samples::slice`] of that segment, so a +/// histogram table is shared rather than copied. The result costs one row per position holding a +/// value, plus the rows the other fields fill, and nothing for a position of the grid holding none. pub fn merge_same_labelset(schema: &Arc, series: Vec) -> Result> { let mut groups: HashMap> = HashMap::with_capacity(series.len()); let mut collided = false; @@ -328,111 +335,272 @@ pub fn merge_same_labelset(schema: &Arc, series: Vec) -> R return Ok(series); } + // The merged axis and the fields placed on it are the schema's grid: a member of another grid + // would land its rows at positions naming other timestamps. + let grid = schema.eval_grid.clone().ok_or_else(|| { + DataFusionError::Execution("grid series schema requires an evaluation grid".into()) + })?; let mut series: Vec> = series.into_iter().map(Some).collect(); let mut output = Vec::with_capacity(groups.len()); - let mut builder = GridSeriesBuilder::try_new(schema.clone())?; - // `(absolute position, member slot, compact row)`, sorted by position before merging. The - // slot indexes `members`, so the merge below picks the member's cursor directly instead of - // searching for the member per row. + // `(absolute position, member slot, compact row)`, sorted by position before merging. The slot + // indexes the group's fragments, so a row names its member without a search. let mut rows: Vec<(usize, usize, usize)> = Vec::new(); - let mut values = vec![None; schema.fields.len()]; - let mut merged = vec![None; schema.fields.len()]; + // The position of each merged row, ascending, with the positions several fragments share held + // once. + let mut positions: Vec = Vec::new(); for (labels, members) in groups { if let [member] = members[..] { output.extend(series[member].take()); continue; } - builder.begin_series(); - rows.clear(); - for (member_slot, &member) in members.iter().enumerate() { - let member_series = series[member] - .as_ref() - .expect("each series is in one group"); - if member_series.time.grid().is_none() { + // Validate every fragment before indexing it: the merge reads its fields and places its + // rows on the schema's grid. + let mut fragments: Vec<&Series> = Vec::with_capacity(members.len()); + for &member in &members { + let fragment = series[member].as_ref().ok_or_else(|| { + DataFusionError::Execution("each series is in exactly one label set".into()) + })?; + let Some(fragment_grid) = fragment.time.grid() else { return Err(DataFusionError::Execution( "merging requires evaluated series".into(), )); + }; + if fragment_grid.spec() != grid.spec() { + return Err(DataFusionError::Execution( + "merging requires one evaluation grid".into(), + )); } - // The axis names the positions this member holds, and one cursor per field reads its - // values in the same order, so a member of several runs costs its rows. - let mut cursors: Vec> = member_series + if fragment.fields.len() != schema.fields.len() { + return Err(DataFusionError::Execution(format!( + "merging requires {} fields, a fragment holds {}", + schema.fields.len(), + fragment.fields.len() + ))); + } + // The alignment is checked before a row is read: a field of another length would either + // run off the axis or leave values the axis never reaches. + let time_len = fragment.time.len(); + if let Some((field, samples)) = fragment .fields .iter() - .map(|field| field.cursor()) - .collect(); - for (point, row) in member_series.time.positions() { - if read_row(&mut cursors, row, &mut values)? { - rows.push((point, member_slot, row)); + .enumerate() + .find(|(_, samples)| samples.len() != time_len) + { + return Err(DataFusionError::Execution(format!( + "merging requires every field to hold the {time_len} rows of its axis, field \ + {field} holds {}", + samples.len() + ))); + } + fragments.push(fragment); + } + rows.clear(); + for (member_slot, fragment) in fragments.iter().enumerate() { + // One forward reader per field: the axis names the rows that exist, and a row holding + // no value in any field is not a merged row. + let mut readers: Vec> = + fragment.fields.iter().map(FieldReader::new).collect(); + for (position, row) in fragment.time.positions() { + let mut present = false; + for reader in &mut readers { + let (segment, offset) = reader.locate(row)?; + present |= !matches!(segment.sample(offset), SampleRef::Missing); + } + if present { + rows.push((position, member_slot, row)); } } } - // By position, then by member slot: the slots follow the order `members` was built in, so - // the merge below still walks each member's rows forward and its cursors never go back. + // By position, then by member slot: the slots follow the order the fragments were collected + // in, so a member's rows only go forward and its readers never go back. rows.sort_unstable(); - // One forward cursor per member and field, so re-reading a row costs neither a chunk scan - // nor an allocation. - let mut cursors: Vec>> = members - .iter() - .map(|&member| { - let member_series = series[member] - .as_ref() - .expect("each series is in one group"); - member_series - .fields - .iter() - .map(|field| field.cursor()) - .collect() - }) - .collect(); - let mut start = 0; - while start < rows.len() { - let point = rows[start].0; - let end = start + rows[start..].partition_point(|&(p, _, _)| p == point); - // Rows of one point merge field by field; only a field present twice collides. - merged.iter_mut().for_each(|value| *value = None); - for &(_, member_slot, row) in &rows[start..end] { - read_row(&mut cursors[member_slot], row, &mut values)?; - for (slot, value) in merged.iter_mut().zip(&values) { - if value.is_some() { - if slot.is_some() { - let labels: Vec<_> = labels - .iter() - .map(|(name, value)| format!("{name}=\"{value}\"")) - .collect(); - return Err(DataFusionError::Execution(format!( - "vector cannot contain metrics with the same labelset {{{}}}", - labels.join(", ") - ))); - } - *slot = *value; - } - } - } - builder.push(point, &merged)?; - start = end; + positions.clear(); + positions.extend(rows.iter().map(|&(position, _, _)| position)); + positions.dedup(); + let mut fields = Vec::with_capacity(schema.fields.len()); + for field in 0..schema.fields.len() { + let mut readers: Vec> = fragments + .iter() + .map(|fragment| FieldReader::new(&fragment.fields.as_slice()[field])) + .collect(); + fields.push(merge_field(&mut readers, &rows, &labels)?); } - let metric = series[members[0]].as_ref().unwrap().metric.clone(); - output.extend(builder.finish(metric)?); + // The runs are all the axis remembers about the holes, so a sparse merge stores one span + // per run and no row for the positions between them. + let time = + TimeAxis::from_grid_spans(grid.clone(), spans_of(&positions)).map_err(external)?; + let fields = SeriesFields::try_from_vec(fields).map_err(external)?; + // The first fragment names the output, as it always has: a label set ignores empty values, + // so the metric of the first member is the one the merged series keeps. + let metric = fragments[0].metric.clone(); + output.push(Series::try_new(schema, metric, time, fields).map_err(external)?); } Ok(output) } -/// Reads the float fields of `row` through the member's cursors; returns whether any is present. -fn read_row(cursors: &mut [RowCursor<'_>], row: usize, values: &mut [Option]) -> Result { - let mut present = false; - for (value, cursor) in values.iter_mut().zip(cursors) { - *value = match cursor.at(row).expect("the axis and the fields are aligned") { - SampleRef::Missing => None, - SampleRef::Float(value) => Some(value), - SampleRef::Histogram(_) => { - return Err(DataFusionError::NotImplemented( - "merging histogram series with the same label set".into(), - )); +/// Builds one field of the merged series, one sample per merged row. +/// +/// The rows are walked in output order. A row holding a value of this field in one member continues +/// the run of rows that member holds in one dense segment, and a run is handed out as one +/// [`Samples::slice`]; the rows another field fills become one null run, so the field stays aligned +/// with the merged axis while sharing the values it carries. +fn merge_field( + readers: &mut [FieldReader<'_>], + rows: &[(usize, usize, usize)], + labels: &LabelSet, +) -> Result { + let mut chunks: Vec = Vec::new(); + // The run of values the last merged row continued, if any. + let mut run: Option> = None; + // Merged rows this field leaves empty, waiting for the null run that carries them. + let mut missing = 0; + let mut start = 0; + while start < rows.len() { + let position = rows[start].0; + let mut end = start; + // At most one member may hold this field here; the second value is the collision Prometheus + // rejects, since the two label sets became one. + let mut value: Option<(usize, &Samples, usize)> = None; + while end < rows.len() && rows[end].0 == position { + let (_, member, row) = rows[end]; + let (segment, offset) = readers[member].locate(row)?; + if !matches!(segment.sample(offset), SampleRef::Missing) { + if value.is_some() { + let labels: Vec<_> = labels + .iter() + .map(|(name, value)| format!("{name}=\"{value}\"")) + .collect(); + return Err(DataFusionError::Execution(format!( + "vector cannot contain metrics with the same labelset {{{}}}", + labels.join(", ") + ))); + } + value = Some((member, segment, offset)); } - }; - present |= value.is_some(); + end += 1; + } + match value { + Some((member, segment, offset)) => { + if let Some(run) = &mut run + && run.continues(member, segment, offset) + { + run.len += 1; + } else { + if let Some(run) = run.take() { + run.push(&mut chunks)?; + } + push_missing(&mut chunks, &mut missing); + run = Some(FieldRun { + member, + segment, + offset, + len: 1, + }); + } + } + None => { + if let Some(run) = run.take() { + run.push(&mut chunks)?; + } + missing += 1; + } + } + start = end; + } + if let Some(run) = run { + run.push(&mut chunks)?; + } + push_missing(&mut chunks, &mut missing); + Samples::try_from_chunks(chunks).map_err(external) +} + +/// A run of merged rows one member field fills out of one dense segment, without copying values. +/// +/// The run grows only while the next merged row is the same member's next row in the same segment, +/// so handing it out is one [`Samples::slice`] of that segment: the payload stays where it is, and +/// the rows a hole skipped are not part of the run. +struct FieldRun<'a> { + /// The member slot the run reads, which indexes the [`FieldReader`]s of the field. + member: usize, + /// The dense segment holding the run's values. + segment: &'a Samples, + /// Offset of the run's first row inside `segment`. + offset: usize, + /// How many rows of `segment` the run covers. + len: usize, +} + +impl FieldRun<'_> { + /// Returns whether the value at `offset` of `segment` continues the run: the same member's next + /// row in the same dense segment. + fn continues(&self, member: usize, segment: &Samples, offset: usize) -> bool { + self.member == member + && std::ptr::eq(self.segment, segment) + && self.offset + self.len == offset + } + + /// Pushes the run as one slice of its dense segment. + fn push(self, chunks: &mut Vec) -> Result<()> { + chunks.push( + self.segment + .slice(self.offset, self.len) + .map_err(external)?, + ); + Ok(()) + } +} + +/// Reads one field's rows by locating the dense segment each row sits in. +/// +/// [`Samples::sample`] rescans a chunked field from its first segment on every row, so reading a +/// field row by row would cost a scan over the segments before it. The rows a merge reads only go +/// forward, so this walks the segments once and returns the segment with the offset of the row +/// inside it, which is what a [`FieldRun`] slices. +struct FieldReader<'a> { + segments: &'a [Samples], + /// Index of the segment `start` belongs to. + segment: usize, + /// Logical row the current segment starts at. + start: usize, +} + +impl<'a> FieldReader<'a> { + /// Creates a reader at the first row of `samples`. + fn new(samples: &'a Samples) -> Self { + Self { + segments: samples.segments(), + segment: 0, + start: 0, + } + } + + /// Returns the dense segment holding `row` and the offset of `row` inside it. + /// + /// Rows must not go backwards. A row past the field is an error rather than a panic: a member is + /// only read after its fields are validated to align with its axis. + fn locate(&mut self, row: usize) -> Result<(&'a Samples, usize)> { + while let Some(segment) = self.segments.get(self.segment) { + if let Some(offset) = row + .checked_sub(self.start) + .filter(|offset| *offset < segment.len()) + { + return Ok((segment, offset)); + } + self.segment += 1; + self.start += segment.len(); + } + Err(DataFusionError::Execution( + "merging requires each field to be row-aligned with its time axis".into(), + )) + } +} + +/// Pushes the merged rows a field leaves empty as one null run. +fn push_missing(chunks: &mut Vec, missing: &mut usize) { + if *missing != 0 { + chunks.push(Samples::from_float(Float64Array::new_null(*missing))); + *missing = 0; } - Ok(present) } pub(crate) fn external(error: datatypes::error::Error) -> DataFusionError { diff --git a/src/promql/src/grid_series/tests.rs b/src/promql/src/grid_series/tests.rs index 59e833e3fd3..a64ce8a94e6 100644 --- a/src/promql/src/grid_series/tests.rs +++ b/src/promql/src/grid_series/tests.rs @@ -15,15 +15,20 @@ use std::mem::size_of; use std::sync::Arc; -use datatypes::series::samples::{DenseSamplesRef, FieldSpec, SampleRef, SeriesSchema}; -use datatypes::series::time::{EvalGrid, GridSpec}; +use datafusion::arrow::array::{Float64Array, UInt32Array}; +use datatypes::series::histogram::{HistogramBatch, HistogramBatchBuilder}; +use datatypes::series::samples::{ + DenseSamplesRef, FieldSpec, HistogramSamples, SampleRef, Samples, Series, SeriesFields, + SeriesSchema, +}; +use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName}; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; use super::reference::{ - Labels, Points, assert_pieces_eq, assert_result_eq, points_of, random_dense, run_ranges, - series_of, stitch, + Labels, OwnedHistogram, Points, assert_pieces_eq, assert_result_eq, metric_of, points_of, + random_dense, run_ranges, series_of, stitch, }; use super::{GridSeriesBuilder, merge_same_labelset}; @@ -479,6 +484,325 @@ fn finish_hands_out_only_the_rows_pushed_after_a_prefix_flush() { assert!(!builder.has_pending()); } +// --------------------------------------------------------------------------------------------- +// Merging: one label set handed over in several fragments. +// +// A runtime hands one label set over as fragments, and the merge is the only place that puts them +// back into one series. What these tests pin is that the values move without being rebuilt: the +// merged series shares the fragments' payloads, keeps native histograms and NaNs, and still costs +// one row per position holding a value. +// --------------------------------------------------------------------------------------------- + +/// The start of the float buffer a dense float segment reads, to show a merge shared the buffer +/// instead of copying it. +fn float_ptr(segment: &Samples) -> *const f64 { + match segment.dense() { + Some(DenseSamplesRef::Float(values)) => values.values().as_ptr(), + _ => panic!("expected a dense float segment"), + } +} + +type FragmentRow<'a> = (usize, Option, Option<&'a str>, Option); + +/// A two-field fragment: field 0 holds a float or a native histogram, field 1 a float. +/// +/// `rows` holds `(position, field 0 float, field 0 histogram, field 1 float)` in ascending position +/// order; a row holds a value when some field has one at that position. +fn fragment_with_histograms( + schema: &Arc, + labels: &Labels, + rows: &[FragmentRow<'_>], +) -> (Series, Arc) { + let mut batch = HistogramBatchBuilder::new(); + let mut spans: Vec = Vec::new(); + let mut floats = Vec::with_capacity(rows.len()); + let mut indices = Vec::with_capacity(rows.len()); + let mut seconds = Vec::with_capacity(rows.len()); + for &(position, float, histogram, second) in rows { + match spans.last_mut() { + Some(span) if span.start() + span.len() == position => { + *span = GridSpan::new(span.start(), span.len() + 1); + } + _ => spans.push(GridSpan::new(position, 1)), + } + floats.push(float); + indices.push(histogram.map(|text| { + batch + .push(OwnedHistogram::parse(text).view()) + .expect("the fixture histogram is valid") + })); + seconds.push(second); + } + let batch = batch.finish().expect("an empty histogram table is valid"); + let histograms = HistogramSamples::try_new(UInt32Array::from(indices), batch.clone()).unwrap(); + let mixed = Samples::try_from_mixed(Float64Array::from(floats), histograms).unwrap(); + let fields = SeriesFields::try_from_vec(vec![ + mixed, + Samples::from_float(Float64Array::from(seconds)), + ]) + .unwrap(); + let time = TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), spans).unwrap(); + ( + Series::try_new(schema, metric_of(labels), time, fields).unwrap(), + batch, + ) +} + +/// Two fragments a boundary kept apart -- the first holding position 0, the second positions 1 and +/// 2 -- become one series of one run, each fragment's rows at its own positions. +#[test] +fn merge_of_adjacent_fragments_is_one_run() { + let schema = grid_schema(1, 4); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + let first = series_of(&schema, &labels, &Points::from([(0, 1f64.to_bits())])).unwrap(); + let second = series_of( + &schema, + &labels, + &Points::from([(1, 2f64.to_bits()), (2, 3f64.to_bits())]), + ) + .unwrap(); + let first_ptr = float_ptr(&first.fields.as_slice()[0].segments()[0]); + let second_ptr = float_ptr(&second.fields.as_slice()[0].segments()[0]); + + let merged = merge_same_labelset(&schema, vec![first, second]).unwrap(); + assert_eq!(merged.len(), 1, "one label set, one merged series"); + assert_eq!(merged[0].time.len(), 3, "one row per value"); + assert_eq!( + run_ranges(&merged[0]), + vec![(0, 3)], + "fragments holding adjacent positions share one run" + ); + assert_eq!( + points_of(&merged[0]), + Points::from([ + (0, 1f64.to_bits()), + (1, 2f64.to_bits()), + (2, 3f64.to_bits()), + ]) + ); + // One slice per fragment: the second fragment's two rows are one slice of its own buffer, and + // neither slice copies a value. + let chunks = merged[0].fields.as_slice()[0].segments(); + assert_eq!(chunks.len(), 2, "one slice per fragment"); + assert_eq!(float_ptr(&chunks[0]), first_ptr); + assert_eq!(float_ptr(&chunks[1]), second_ptr); + assert_eq!(chunks[1].len(), 2, "the fragment's two rows are one slice"); +} + +/// Native histograms, floats, NaNs and complementary fields merge into one aligned series, and +/// every value keeps the storage it already had: the histogram table and the float buffers are +/// shared, not rebuilt. +#[test] +fn merge_keeps_native_histograms_and_complementary_fields_without_copying_them() { + let schema = grid_schema(2, 4); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + let histogram = "0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///"; + // The first fragment holds a native histogram in field 0 and a float in field 1 at position 0. + let (first, first_batch) = + fragment_with_histograms(&schema, &labels, &[(0, None, Some(histogram), Some(1.0))]); + // The second holds field 0's float at position 1 and field 1's NaN at position 2, leaving the + // other field missing at each. + let (second, _) = fragment_with_histograms( + &schema, + &labels, + &[(1, Some(2.0), None, None), (2, None, None, Some(f64::NAN))], + ); + let second_field1 = float_ptr(&second.fields.as_slice()[1].segments()[0]); + + let merged = merge_same_labelset(&schema, vec![first, second]).unwrap(); + assert_eq!(merged.len(), 1); + assert_eq!( + run_ranges(&merged[0]), + vec![(0, 3)], + "positions 0, 1 and 2 are one run" + ); + assert_eq!(merged[0].time.len(), 3); + assert_eq!(merged[0].fields.len(), 2); + + // Field 0: the histogram, the float, and a null at the position only field 1 fills. + let field0 = merged[0].fields.as_slice()[0].segments(); + assert_eq!(field0.len(), 3, "a histogram, a float, and one null run"); + let DenseSamplesRef::Mixed(mixed) = field0[0].dense().unwrap() else { + panic!("the histogram lost its mixed column") + }; + assert!( + Arc::ptr_eq(mixed.histograms().batch(), &first_batch), + "the histogram table was rebuilt" + ); + assert!( + matches!(field0[0].sample(0), SampleRef::Histogram(view) if view.count == 1.0), + "the histogram did not survive as a histogram" + ); + assert!( + matches!(field0[1].sample(0), SampleRef::Float(value) if value.to_bits() == 2f64.to_bits()), + "field 0 lost the other fragment's float" + ); + assert!( + matches!(field0[2].sample(0), SampleRef::Missing), + "field 0 filled a position only field 1 holds" + ); + + // Field 1: its value, the null field 0 fills, and the NaN, which is a value like any other. + let field1 = merged[0].fields.as_slice()[1].segments(); + assert_eq!(field1.len(), 3, "a float, one null run, and a NaN"); + assert!( + matches!(field1[0].sample(0), SampleRef::Float(value) if value.to_bits() == 1f64.to_bits()) + ); + assert!(matches!(field1[1].sample(0), SampleRef::Missing)); + assert!( + matches!(field1[2].sample(0), SampleRef::Float(value) if value.is_nan()), + "the NaN was dropped" + ); + // The NaN came out as a slice of the second fragment's buffer, one row in. + assert_eq!( + float_ptr(&field1[2]), + second_field1.wrapping_add(1), + "the NaN was copied instead of sliced" + ); + + // Two fragments holding one field at one position still collide, histograms included. + let at_zero = + || fragment_with_histograms(&schema, &labels, &[(0, None, Some(histogram), None)]).0; + assert!( + merge_same_labelset(&schema, vec![at_zero(), at_zero()]).is_err(), + "two histograms of one field at one position merged" + ); +} + +/// A merge over many fragments of many segments keeps one row per value: a million-position grid +/// costs a span per run and a sample per value, and locating a row never rescans the segments +/// before it. +#[test] +fn merge_of_many_segments_keeps_one_row_per_value() { + const GRID: usize = 1_000_000; + const SEGMENTS: usize = 1_000; + let schema = grid_schema(1, GRID as u64); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + // A fragment of one value per segment, one chunk per value, the segments a thousand positions + // apart. + let fragment = |offset: usize| { + let mut chunks = Vec::with_capacity(SEGMENTS); + let mut spans = Vec::with_capacity(SEGMENTS); + for segment in 0..SEGMENTS { + let position = offset + segment * (GRID / SEGMENTS); + chunks.push(Samples::from_float(Float64Array::from(vec![ + position as f64, + ]))); + spans.push(GridSpan::new(position, 1)); + } + let time = TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), spans).unwrap(); + let fields = SeriesFields::one(Samples::try_from_chunks(chunks).unwrap()); + Series::try_new(&schema, metric_of(&labels), time, fields).unwrap() + }; + + let merged = merge_same_labelset(&schema, vec![fragment(0), fragment(1)]).unwrap(); + assert_eq!(merged.len(), 1); + let series = &merged[0]; + assert_eq!( + series.time.grid().unwrap().timestamps().len(), + GRID, + "the grid really holds a million positions" + ); + assert_eq!(series.time.len(), 2 * SEGMENTS, "one row per value"); + assert_eq!( + series.time.runs().count(), + SEGMENTS, + "two adjacent values per segment are one run, and the holes between are spans" + ); + assert_eq!(run_ranges(series)[0], (0, 2)); + let field = &series.fields.as_slice()[0]; + assert_eq!( + field.len(), + 2 * SEGMENTS, + "the field holds one sample per merged row" + ); + assert_eq!( + field.segments().len(), + 2 * SEGMENTS, + "one chunk per value: no hole was densified into the payload" + ); + assert!(field.segments().iter().all(|chunk| chunk.len() == 1)); + assert_eq!( + points_of(series).len(), + 2 * SEGMENTS, + "every value survived and no hole became one" + ); +} + +/// A label set whose fragments all closed without a value still yields one series: a runtime that +/// closes a label set needs one answer per set, and an empty grid series is the legal one. +#[test] +fn merge_of_empty_fragments_yields_one_empty_series() { + let schema = grid_schema(2, 4); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + let empty = || { + let time = + TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), Vec::new()).unwrap(); + let fields = SeriesFields::try_from_vec(vec![ + Samples::from_float(Float64Array::new_null(0)), + Samples::from_float(Float64Array::new_null(0)), + ]) + .unwrap(); + Series::try_new(&schema, metric_of(&labels), time, fields).unwrap() + }; + + let merged = merge_same_labelset(&schema, vec![empty(), empty()]).unwrap(); + assert_eq!(merged.len(), 1, "the label set vanished"); + assert_eq!(merged[0].metric, metric_of(&labels)); + assert_eq!(merged[0].time.len(), 0); + assert!( + merged[0].time.grid().is_some(), + "an empty series keeps its grid" + ); + assert!( + run_ranges(&merged[0]).is_empty(), + "an empty series has no run" + ); + assert_eq!(merged[0].fields.len(), 2); + for field in merged[0].fields.iter() { + assert!(field.is_empty(), "an empty fragment contributed a row"); + } +} + +/// A `Series` built as a struct literal can carry fields that do not line up with its axis; the +/// merge checks the alignment before it reads a row, so it reports such a fragment instead of +/// reading past a field or dropping the values the axis never reaches. +#[test] +fn merge_rejects_fragments_whose_fields_do_not_fill_their_axis() { + let schema = grid_schema(1, 8); + let grid = schema.eval_grid.clone().unwrap(); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + // A well-formed fragment gives the malformed one a label set to merge into. + let partner = || series_of(&schema, &labels, &Points::from([(1, 7f64.to_bits())])).unwrap(); + // `(axis rows, field rows)`: a field shorter than its axis, one longer than it, and a value on + // an axis of no rows at all. The last two leave every axis row self-consistent, so only the + // merge's alignment check catches them. + for (axis_rows, field_rows) in [(2, 1), (1, 2), (0, 1)] { + let spans = if axis_rows == 0 { + Vec::new() + } else { + vec![GridSpan::new(1, axis_rows)] + }; + let time = TimeAxis::from_grid_spans(grid.clone(), spans).unwrap(); + let values = Float64Array::from( + (0..field_rows) + .map(|row| row as f64 + 1.0) + .collect::>(), + ); + let malformed = Series { + metric: metric_of(&labels), + time, + fields: SeriesFields::one(Samples::from_float(values)), + }; + let error = merge_same_labelset(&schema, vec![partner(), malformed]) + .expect_err("a fragment whose fields do not fill its axis merged"); + assert!( + error.to_string().contains("rows of its axis"), + "{axis_rows} axis rows with a {field_rows}-row field: {error}" + ); + } +} + // --------------------------------------------------------------------------------------------- // Acceptance: the builder's observable shape. // diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index ada6cbe323c..3aeb9b16470 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -35,12 +35,30 @@ //! half a query or panicking halfway through one. //! //! A node that rewrites labels — a window drops the metric name and the empty-valued labels, a map -//! drops the name — can turn two distinct series into one label set, and each of them still closes -//! on its own chunk. The node that did the rewriting is where the second one is refused, before the -//! node above evaluates it: a label set that has closed cannot be produced again, and a chunk that -//! holds a value where the same field already holds one cannot be merged without holding whole -//! series. A chunk that continues a label set where it ended, or that fills positions the set has -//! not occupied, is handed on. +//! drops the name — can turn two distinct input series into one output label set. That pair is +//! legal when the two hold values at disjoint positions, which is exactly what +//! [`crate::grid_series::merge_same_labelset`] merges: `is_last` closes the source series whose +//! data the chunk carries, not the label set it shares with another series, so a second series may +//! fill the positions the first one left empty. The node that rewrote the labels keeps which +//! positions each output label set already occupies; a second series that puts a value where the +//! same field already holds one is refused there — before a node above reads it — while a chunk +//! that continues a set where it ended, or fills positions the set has not occupied, is handed on. +//! +//! A label set reachable by more than one series needs one more guarantee: a window reads one +//! series to its `is_last` before the next one, so the per-series state of its evaluator ends +//! before a second series onto the same set arrives. The window immediately above such a rewriting +//! node therefore collects its whole input, merges each canonical label set once with +//! [`crate::grid_series::merge_same_labelset`], and only then evaluates it: every logical series +//! reaches its evaluator once and whole, and the pieces that would have been separate streams +//! become one. Such a window reports at the end of its input instead of as its input arrives. A +//! window directly over a source, and a map at the root, are not affected and keep streaming their +//! chunks on as they produce them. +//! +//! What leaves the tree is therefore a piece stream, not a series collection: a chunk's `is_last` +//! says the source series it carries ended. [`NativeExecutor::finish`] performs the merge for every +//! affected window inside the tree. A caller that needs one series per canonical label set from the +//! root itself — a downstream window outside this runtime, or a protocol that reports one series — +//! collects the root's chunks and merges them with the same helper. use std::collections::hash_map::Entry; use std::collections::{HashMap, VecDeque}; @@ -59,7 +77,7 @@ use datatypes::series::samples::{ use datatypes::series::time::{GridRange, TimeAxis}; use datatypes::series::{MetricName, SeriesOrdering}; -use crate::grid_series::{LabelSet, label_set}; +use crate::grid_series::{LabelSet, label_set, merge_same_labelset}; use crate::map::{MathOp, drop_metric_name, map_math}; use crate::native::batch::EvaluatedChunk; use crate::native::metrics::{NodeMetrics, NodePath}; @@ -91,7 +109,10 @@ impl NativeChunk { } } - /// Whether this chunk closes its series. + /// Whether this chunk closes the source series whose data it carries. + /// + /// A chunk never closes the label set it holds: two source series can share one output label + /// set when the positions they fill are disjoint, and each of them ends on its own chunk. fn is_last(&self) -> bool { match self { Self::Raw(chunk) => chunk.is_last, @@ -99,17 +120,6 @@ impl NativeChunk { } } - /// The identity of the series this chunk belongs to, when the chunk names it. - /// - /// A raw chunk in bound-label mode carries its identity in its key and no metric name, so there - /// is nothing to compare; an evaluated chunk always names the series it holds. - fn metric(&self) -> Option<&MetricName> { - match self { - Self::Raw(chunk) => chunk.metric.as_ref(), - Self::Evaluated(chunk) => Some(&chunk.series.metric), - } - } - /// An estimate of the bytes this chunk holds. /// /// It is what the chunk alone stands for, so a buffer or a histogram table two chunks share is @@ -144,6 +154,70 @@ fn evaluated_bytes(chunk: &EvaluatedChunk) -> usize { std::mem::size_of::().saturating_add(fields_bytes(&chunk.series.fields)) } +/// The bytes one evaluated series holds: its header, the axis that addresses it, the identity it +/// carries and the sample buffers behind its fields. +/// +/// It is the figure a fragment of an affected window is charged with as it arrives. The axis's runs +/// and the segments of its fields are counted in one pass over the series, so the estimate costs +/// the fragment rather than a walk over everything the node holds. A payload a fragment shares with +/// another — a histogram table behind two slices of it, the grid behind every axis — is counted +/// once per fragment: that over-count is accepted here rather than a deduplication that would have +/// to keep state across fragments. +fn series_bytes(series: &Series) -> usize { + let runs = series.time.runs().count(); + let segments: usize = series + .fields + .iter() + .map(|field| field.segments().len()) + .sum(); + std::mem::size_of::() + .saturating_add(std::mem::size_of::()) + .saturating_add(runs.saturating_mul(std::mem::size_of::<(usize, usize)>())) + .saturating_add( + segments.saturating_mul(std::mem::size_of::() + std::mem::size_of::()), + ) + .saturating_add(fields_bytes(&series.fields)) + .saturating_add(metric_bytes(&series.metric)) +} + +/// An estimate of the workspace [`crate::grid_series::merge_same_labelset`] needs for fragments +/// that hold `rows` rows between them. +/// +/// The helper sorts one `(position, member, row)` triple per fragment row and keeps the distinct +/// positions beside it, so the figure charges those vectors at their widest. Every field of every +/// fragment gets a reader, and every merged field is built as a vector of run descriptors -- one +/// slice of a fragment's segment or one run of missing rows -- before it becomes one field again, +/// so a row is charged the descriptors it can become in the worst case, several `Samples` headers +/// and their `Arc` conversions, rather than one. The output side keeps one series and one field +/// header per merged series, which is as many as there are fragments. +/// +/// The sample payload is not charged: a merged run is a slice of the fragment's own segment, so the +/// merge copies no values and the fragments are what hold them. A histogram table behind several +/// fragments is likewise left to the fragments' own estimates, which count it once per fragment. +fn merge_workspace_bytes(rows: usize, fragments: usize, fields: usize) -> usize { + let sorted_rows = rows.saturating_mul( + std::mem::size_of::<(usize, usize, usize)>() + std::mem::size_of::(), + ); + let readers = fragments.saturating_mul( + fields.saturating_mul(std::mem::size_of::() + 4 * std::mem::size_of::()), + ); + // What one merged field can hold while it is built: one descriptor per row at the very worst + // (alternating missing rows and values from different fragments), kept once as the run vector + // and once as the flattened field that is made from it. + let merged_field_per_row = + 2 * std::mem::size_of::() + 3 * std::mem::size_of::(); + let merged_fields = rows + .saturating_mul(fields) + .saturating_mul(merged_field_per_row); + let output = fragments.saturating_mul( + std::mem::size_of::() + fields.saturating_mul(std::mem::size_of::()), + ); + sorted_rows + .saturating_add(readers) + .saturating_add(merged_fields) + .saturating_add(output) +} + /// The bytes the fields of a chunk hold: the sample buffers of every segment, and the histogram /// tables those segments reference. fn fields_bytes(fields: &SeriesFields) -> usize { @@ -219,6 +293,51 @@ struct NodeSpec { input: Option, } +/// The input a window with a [`NodeRuntime::merge`] collects until its input ends. +/// +/// Such a window cannot evaluate the series under one canonical label set one after another: its +/// evaluator closes a series on the chunk carrying `is_last`, and the points a window across the +/// boundary needs are exactly the ones that closed series held. The fragments are therefore kept +/// whole, merged into one series per label set with +/// [`crate::grid_series::merge_same_labelset`], and only then evaluated. +struct MergeInput { + /// The schema the fragments are addressed on: their grid and their field count. + schema: Arc, + /// The series received so far, in the order they arrived. + fragments: Vec, + /// An estimate of the bytes the fragments and the merge that follows them stand for. + /// + /// A fragment is measured once as it arrives; the merge's workspace is added once, before the + /// helper runs, from the rows, segments and fields of the fragments as they were collected. + /// Neither figure walks the buffer again, and the space the fragments' payload shares is + /// counted once per fragment rather than deduplicated. + bytes: usize, +} + +impl MergeInput { + /// A buffer for the fragments of one window's input, which are addressed on `schema`. + fn new(schema: Arc) -> Self { + Self { + schema, + fragments: Vec::new(), + bytes: 0, + } + } + + /// The bytes of the fragments and of the workspace merging them needs. + /// + /// The workspace is what the helper allocates for the rows the fragments hold; the sample + /// payload is shared with them, so it is not counted twice here. + fn workspace_bytes(&self) -> usize { + let rows: usize = self + .fragments + .iter() + .map(|fragment| fragment.time.len()) + .sum(); + merge_workspace_bytes(rows, self.fragments.len(), self.schema.fields.len()) + } +} + /// What every node holds: its metric handles and the bytes it reserves. /// /// The reservation is the pool's, so a node that buffers input competes with every other operator @@ -301,7 +420,13 @@ impl Run { /// /// Occupancy is per field and per position, not per chunk range: a chunk reports the positions it /// decided, which include the ones holding no value, and series that share a decided range while -/// sharing no sample merge cleanly, as they do in [`crate::grid_series::merge_same_labelset`]. +/// sharing no sample merge cleanly, as they do in [`crate::grid_series::merge_same_labelset`]. A +/// chunk holding no value occupies nothing and changes nothing. +/// +/// A set is never retired: `is_last` closes the source series whose data the chunk carries, and a +/// later series may still fill the positions the closed one left empty. Every run handed out stays +/// charged until the node is released, which is what lets a later chunk be refused against the +/// positions an earlier series already occupied. /// /// The table is one node's own: a node knows what it has handed out itself and sees nothing of what /// the node below kept, so a label set costs its bytes again in every node that keeps a table, and @@ -316,8 +441,7 @@ struct Emitted { /// figure is read after every output; walking the table there would cost a pass over every entry /// recorded so far for each output. Folding one entry's change in as it happens keeps the read /// constant, and the update is the shape of the change itself: a vector's length before and - /// after [`absorb`], one vector per field a history gains, and one terminal pass over a closing - /// history's vector lengths. + /// after [`absorb`], and one vector per field a history gains. counts: Counts, } @@ -328,8 +452,7 @@ struct Counts { vectors: usize, /// The occupied runs in every vector. runs: usize, - /// The payload of every label set and of every owner: the bytes of their names and values with - /// one row per label. + /// The payload of every label set: the bytes of its names and values with one row per label. payload: usize, } @@ -338,31 +461,6 @@ struct Counts { struct History { /// The occupied runs of each field, in position order and disjoint. fields: Vec>, - /// The source series that filled this label set, when the chunk that did named it. - /// - /// A chunk holding no value is handed over to close a series, never to fill a label set, so it - /// closes this one only when it belongs to the series that filled it: a second series that - /// produced nothing here is a series this label set never saw, and closing on its `is_last` - /// would leave the series that did produce the values unable to finish. `None` is a set filled - /// by chunks that named no series, where there is nothing to compare a closing chunk against. - owner: Option, - /// Whether the series on this label set closed. A second series cannot close it again. - closed: bool, -} - -impl History { - /// Whether a chunk of `source` holding no value is the one that closes this label set. - /// - /// Only the series that filled it can: a series that produced nothing here is one this label - /// set never saw, so closing on its `is_last` would take the close away from the series that - /// did fill it. A chunk naming no series is compared with nothing and closes the set, which is - /// what every chunk did before the owner was kept. - fn closed_by(&self, source: Option<&MetricName>) -> bool { - match (self.owner.as_ref(), source) { - (Some(owner), Some(source)) => owner == source, - _ => true, - } - } } /// The bytes a label set holds: each label's name and value with the pair that refers to them. @@ -377,8 +475,7 @@ fn label_bytes(labels: &LabelSet) -> usize { /// to them. /// /// This is the convention [`label_bytes`] keeps: the payload of the shared strings and one row per -/// label. The `Option` a [`History`] keeps its owner in is not counted here, being part -/// of the header that entry's slot is charged for. +/// label. fn metric_bytes(metric: &MetricName) -> usize { metric.name().map_or(0, |name| name.len()) + std::mem::size_of_val(metric.tags()) @@ -392,23 +489,13 @@ fn metric_bytes(metric: &MetricName) -> usize { impl Emitted { /// Records what `chunk` occupies, rejecting it against what this node already handed out. /// - /// `source` is the identity of the input series `chunk` came from, when the chunk names one: a - /// label set is filled by the series that contributes its values, and it is that series whose - /// closing chunk closes it (see [`History::owner`]). - /// - /// A label set that has closed cannot be reached by a second series: the node would hand on two - /// chunks that its consumer cannot tell apart, and the merge the caller wants spans the first - /// series, whose state the evaluator above has already closed. Such a pair does merge in - /// Prometheus, so this is a limitation of the streaming evaluator rather than a collision; it is - /// refused instead of being answered wrongly (see [`closed_label_set`]). A chunk of a set still - /// open is refused only where it holds a value at a position that same field already holds one - /// at, which is the case no merge can resolve. - fn occupy( - &mut self, - path: &NodePath, - source: Option<&MetricName>, - chunk: &EvaluatedChunk, - ) -> Result<()> { + /// A second series onto a label set is legal when it holds its values where the first one held + /// none: the two merge into one series, which is what + /// [`crate::grid_series::merge_same_labelset`] does. What no merge resolves is two values of one + /// field at one position, so that is the only thing refused here. `is_last` is not consulted: it + /// closes the source series the chunk carries, not the label set, and a later series may still + /// fill the positions that one left empty. + fn occupy(&mut self, path: &NodePath, chunk: &EvaluatedChunk) -> Result<()> { let labels = label_set(&chunk.series.metric); let occupied: Vec> = chunk .series @@ -418,18 +505,7 @@ impl Emitted { .map(|(index, field)| occupied_runs(path, index, field, &chunk.series.time)) .collect::>()?; let empty = occupied.iter().all(Vec::is_empty); - let recorded = self.sets.get(&labels); - if let Some(history) = recorded { - if history.closed { - // A series that produced nothing under a closed label set contributes no sample, so - // there is nothing to report, nothing to merge and nothing to refuse. One that did - // produce values is the second series this set cannot take. - return if empty { - Ok(()) - } else { - Err(closed_label_set(path, &labels)) - }; - } + if let Some(history) = self.sets.get(&labels) { for (index, runs) in occupied.iter().enumerate() { let stored = history.fields.get(index).map_or(&[][..], Vec::as_slice); for run in runs { @@ -444,16 +520,10 @@ impl Emitted { } } } - // A chunk holding no value records nothing. Past a closed set the same series is the - // one that answered empty, and on an open set it is the close of the series that filled - // it -- but only of that series: a different one closes a label set it never wrote to, - // which would leave the series that did write to it unable to finish. - if empty && !(chunk.is_last && history.closed_by(source)) { - return Ok(()); - } - } else if empty { - // The first chunk onto a label set holds no value: a series that answered empty, with - // nothing to record, nothing to close and nothing to merge. + } + if empty { + // A chunk holding no value records nothing and closes nothing: a series that answered + // empty leaves every earlier series on this label set exactly where it was. return Ok(()); } let fields = chunk.series.fields.len(); @@ -464,19 +534,6 @@ impl Emitted { entry.insert(History::default()) } }; - // The series that contributes the values is the one that owns the label set, so a chunk of - // another one cannot close it later on. - if !empty - && let Some(source) = source - && history.owner.as_ref() != Some(source) - { - self.counts.payload = self - .counts - .payload - .saturating_sub(history.owner.as_ref().map_or(0, metric_bytes)) - .saturating_add(metric_bytes(source)); - history.owner = Some(source.clone()); - } if history.fields.len() < fields { self.counts.vectors += fields - history.fields.len(); history.fields.resize_with(fields, Vec::new); @@ -487,24 +544,16 @@ impl Emitted { absorb(stored, &runs); self.counts.runs = self.counts.runs - before + stored.len(); } - if chunk.is_last { - history.closed = true; - // No later chunk reads these runs: a closed label set refuses every series that would - // use them. Keeping them charges the pool for a series that has already been answered. - self.counts.runs -= history.fields.iter().map(Vec::len).sum::(); - self.counts.vectors -= history.fields.len(); - history.fields = Vec::new(); - } Ok(()) } /// An estimate of the bytes this table holds, which the node reserves for. /// /// It counts one label-set slot and one history header per entry, one vector per field of a - /// history, the runs in those vectors, and the payload of every label set and owner. Each of - /// those is a running total, so the figure is read in constant time however many series the node - /// has handed out; it leaves out the map's buckets, the slack of a vector's capacity and the - /// `Arc` headers of the strings it shares, so it is an approximation rather than a measurement. + /// history, the runs in those vectors, and the payload of every label set. Each of those is a + /// running total, so the figure is read in constant time however many series the node has + /// handed out; it leaves out the map's buckets, the slack of a vector's capacity and the `Arc` + /// headers of the strings it shares, so it is an approximation rather than a measurement. fn bytes(&self) -> usize { let slots = self.sets.len() * (std::mem::size_of::() + std::mem::size_of::()); @@ -708,8 +757,12 @@ struct MapRuntime { /// The per-node run-time state of a node. struct NodeRuntime { buffer: NodeBuffer, - /// Source chunks queued by the caller, for an input node, each with the estimate it was queued - /// with: what a chunk is worth is read once, as it enters, and given back as it leaves. + /// The chunks this node holds for its consumer, each with the estimate it was queued with. + /// + /// An input node's queue is filled by the caller, and a window's by the chunks it computed while + /// flushing its collected input; no node uses it for both. A chunk is measured once, as it + /// enters, and the figure it was queued with is given back as it leaves, so neither the queue + /// nor the handover walks it. queued: VecDeque<(NativeChunk, usize)>, /// A window node's evaluator, with its own input and output grid; `None` before it is built and /// once it is closed. @@ -719,6 +772,10 @@ struct NodeRuntime { /// What this node has already handed out under each output label set, for a node that rewrites /// labels: a window drops the metric name and the empty-valued labels, a map drops the name. emitted: Option, + /// The input a window collects until its input ends, for a window whose input can hold two + /// series under one label set; `None` for a window that evaluates its chunks as they arrive, + /// and once the flush that merges the collected input has taken it. + merge: Option, /// Whether the series the last chunk handed over belongs to is still open. /// /// Only an input node ever sets this, because its queue is the one the caller fills; the flag is @@ -814,10 +871,10 @@ impl NodeRuntime { if let Some(output) = &output { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); - // What it handed out is what the label sets of this node now hold. The identity is the - // input's: `map_chunk` has already rewritten the output's label set, and a series is - // the one that arrived. - self.track(path, Some(&chunk.series.metric), output)?; + // What it handed out is what the label sets of this node now hold: `map_chunk` has + // already rewritten the output's label set, so the label set of the output is the one + // two input series can share. + self.track(path, output)?; } // The chunk is gone and the label sets this node has handed out are what is left. let emitted = self.emitted_bytes(); @@ -826,14 +883,23 @@ impl NodeRuntime { } /// Feeds one chunk to this node's window. + /// + /// A window that collects its input keeps the whole series of every chunk it is handed and + /// evaluates nothing yet: the label sets of those fragments are only canonical once the input + /// has ended, and reading them as separate series would close the state of the one before in + /// the evaluator. Every other window evaluates what it is handed as it arrives, which is what + /// lets it answer before its input series ends. fn window(&mut self, path: &NodePath, chunk: NativeChunk) -> Result> { + if self.merge.is_some() { + let NativeChunk::Evaluated(chunk) = chunk else { + return Err(DataFusionError::Execution(format!( + "the window at {path} collects evaluated fragments, but it was handed raw \ + samples" + ))); + }; + return self.collect(path, chunk); + } let (positions, closing) = (chunk.positions(), chunk.is_last()); - // Which series this chunk came from, for the label-set table below. A window consumes one - // series to its `is_last` before the next, so the chunk that closes an output label set is - // the one of the series that produced its values, which is what lets the table accept a - // closing chunk of a series that wrote to it. A raw chunk in bound-label mode names no - // series, so there is nothing to pass on. - let source = chunk.metric(); // The chunk is held for as long as the evaluator consumes it. self.buffer.grow(chunk.bytes())?; let metrics = Arc::clone(&self.buffer.metrics); @@ -864,9 +930,7 @@ impl NodeRuntime { if let Some(output) = &output { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); - // What it handed out is what the label sets of this node now hold, and the series that - // filled one is the series its chunks came from. - self.track(path, source, output)?; + self.track(path, output)?; } // The chunk has been consumed: what this node still holds is what the evaluator kept of it // and the label sets it has already handed out. Both are charged whether or not this chunk @@ -883,22 +947,84 @@ impl NodeRuntime { Ok(output) } - /// Records what this node hands out under its output label set. + /// Keeps one fragment of this node's collected input, charged for as it arrives. /// - /// `source` is the identity of the input series the chunk came from, when there is one: a node - /// that rewrites labels is where two input series become indistinguishable, so this is where - /// the second one is refused, and it is also the only place that knows which series filled the - /// label set a chunk closes. A node above reads what this one hands over, and a window above - /// would evaluate the two as two series and report both. Checking at the root would be too late - /// for that — the answer would already have been computed. - fn track( + /// The fragment is measured once, here, and its estimate stands until the flush that merges it + /// is over: a later chunk adds its own estimate rather than walking the buffer again. What is + /// estimated is what the fragment keeps alive, so a sample payload two fragments share is + /// counted once per fragment; the merge itself copies no values, and its workspace is charged + /// separately before it runs. + fn collect( &mut self, path: &NodePath, - source: Option<&MetricName>, - output: &EvaluatedChunk, - ) -> Result<()> { + chunk: EvaluatedChunk, + ) -> Result> { + let Some(merge) = self.merge.as_mut() else { + return Err(DataFusionError::Execution(format!( + "the window at {path} holds no collected input" + ))); + }; + let EvaluatedChunk { series, is_last } = chunk; + let positions = series.time.len(); + let bytes = series_bytes(&series); + // The fragment is held from here on, so the pool admits it before this node keeps it: a + // rejected fragment leaves nothing behind. + self.buffer.grow(bytes)?; + merge.bytes = merge.bytes.saturating_add(bytes); + merge.fragments.push(series); + let metrics = Arc::clone(&self.buffer.metrics); + metrics.record_input(1, positions); + if is_last { + // The source series whose data this fragment carries ended, which is what `is_last` + // says; the label set it shares with another series is not closed by it. + metrics.record_completed_series(1); + } + // What this node holds is the fragments and the label sets it has already handed out; its + // evaluator has read none of them yet. + let retained = self + .window + .as_ref() + .map_or(0, RangeEvaluator::retained_bytes); + let emitted = self.emitted_bytes(); + let pending = self.merge.as_ref().map_or(0, |merge| merge.bytes); + self.buffer + .resize(retained.saturating_add(emitted).saturating_add(pending))?; + Ok(None) + } + + /// Queues one output this node computed while flushing its collected input. + /// + /// The chunk waits for the pull that hands it up the tree, and its estimate is added as it is + /// queued and given back as it leaves, so the queue costs the sum of what it holds. + fn enqueue_output(&mut self, chunk: EvaluatedChunk) -> Result<()> { + let bytes = evaluated_bytes(&chunk); + self.buffer.grow(bytes)?; + self.queued + .push_back((NativeChunk::Evaluated(chunk), bytes)); + Ok(()) + } + + /// Hands over the next output this node computed while flushing, if there is one. + /// + /// This is not a source handover: [`Self::open_source_series`] and the input metrics follow the + /// chunks the caller queued, and a chunk this node produced itself is neither. + fn take_output(&mut self) -> Result> { + let Some((chunk, bytes)) = self.queued.pop_front() else { + return Ok(None); + }; + self.buffer.shrink(bytes)?; + Ok(Some(chunk)) + } + + /// Records what this node hands out under its output label set. + /// + /// A node that rewrites labels is where two input series become indistinguishable, so this is + /// where a second one is refused: a node above reads what this one hands over, and a window + /// above would evaluate the two as two series and report both. Checking at the root would be + /// too late for that — the answer would already have been computed. + fn track(&mut self, path: &NodePath, output: &EvaluatedChunk) -> Result<()> { match self.emitted.as_mut() { - Some(emitted) => emitted.occupy(path, source, output), + Some(emitted) => emitted.occupy(path, output), // A node that keeps its input's labels cannot make two series one. None => Ok(()), } @@ -916,9 +1042,11 @@ impl NodeRuntime { // The window goes first: dropping the evaluator is what gives back the memory its // reservation was taken for. Returning the reservation while the evaluator still held the // samples would let the pool admit memory the process has not released, for as long as the - // caller keeps the stopped executor alive. The label sets this node handed out go with it. + // caller keeps the stopped executor alive. The label sets this node handed out and the + // fragments it collected go with it. self.window = None; self.emitted = None; + self.merge = None; // A node that holds no chunk holds no series either, so nothing it handed over is still // open for it: the flag is what closing the execution reads, and it must not survive the // state that could have kept a series alive. @@ -968,6 +1096,9 @@ impl NativeExecutionState { let mut nodes: Vec = Vec::new(); let mut paths: Vec = Vec::new(); let mut runtimes: Vec = Vec::new(); + // The bound expression of each node, in the same order: the pass below reads the node it + // configures from here, so nothing about an operation is copied onto the node's spec. + let mut exprs: Vec<&NativeExpr> = Vec::new(); let mut source: Option<(usize, Arc)> = None; let mut node = tree.root(); let mut path = NodePath::root(); @@ -1015,6 +1146,7 @@ impl NativeExecutionState { window: None, map: None, emitted: None, + merge: None, open_source_series: false, }; match &node.expr { @@ -1066,6 +1198,7 @@ impl NativeExecutionState { tag, input: child.map(|_| index + 1), }); + exprs.push(&node.expr); paths.push(path.clone()); runtimes.push(runtime); let Some(child) = child else { @@ -1075,6 +1208,66 @@ impl NativeExecutionState { path = path.input(); } + // One reverse pass sets where a merge has to happen, from the input upwards: the pass above + // walked the root first, so a node's input is the node after it and has been decided by the + // time the node itself is. + // + // A source is a stream of series, each with its own label set, so its output needs no merge: + // that is what keeps `Input -> Window` streaming and reporting as its input arrives. A map + // drops the metric name, so its output can hold two input series under one label set, and + // every node above it needs the merge. A window collects its input and merges it when its + // input can hold two series under one label set: reading them as series one after another + // would end the first in the evaluator before the second arrives, and a window across the + // boundary needs both. + // + // A window's own output needs the same when it rewrites labels -- `rate` drops the name, so + // two input series can become one label set -- or when it did not merge its input: + // `last_over_time` keeps the name, but a tag holding an empty value and an absent tag are + // two input series and one canonical label set, so the pair only becomes one series if it + // was merged before the window read it. + // + // The flags this needs are the pass's own: one per node, filled from the input upwards, and + // they and the expressions go when the pass ends. A node's spec therefore stays what the + // tree said, and nothing about an operation is kept once the state is built. + { + let mut holds_shared: Vec = vec![false; nodes.len()]; + for (index, expr) in exprs.into_iter().enumerate().rev() { + let input_holds_shared = + nodes[index].input.is_some_and(|child| holds_shared[child]); + match nodes[index].tag { + NodeTag::Input => {} + NodeTag::Map => holds_shared[index] = true, + NodeTag::Window => { + let (drops_metric_name, input_schema) = match expr { + NativeExpr::Window { input, op } => ( + op.function.drops_metric_name(), + input.output.samples().cloned(), + ), + _ => { + return Err(DataFusionError::Execution(format!( + "the node at {} is a window without a bound window operation", + paths[index] + ))); + } + }; + if input_holds_shared { + let schema = input_schema.ok_or_else(|| { + DataFusionError::Execution(format!( + "the window at {} merges its input, but its input produces no \ + samples", + paths[index] + )) + })?; + runtimes[index].merge = Some(MergeInput::new(schema)); + } + // A window's own output can hold two series under one label set when it drops + // the name, or when it did not merge its input and so never joined the two. + holds_shared[index] = drops_metric_name || !input_holds_shared; + } + } + } + } + // The runtime's output is an evaluated chunk. Raw samples have no grid, and a scalar or // aggregate state is not a query value, so neither can be the tree's answer. match tree.root().output.samples() { @@ -1146,6 +1339,19 @@ impl NativeExecutionState { .count() } + /// The input that ended before its last chunk, if there is one. + /// + /// It is read before anything is merged: a window that collects its input closes every series + /// it merges with a synthetic `is_last`, so a series the caller never ended would be + /// indistinguishable from one that ended afterwards. + fn truncated(&self) -> Option { + self.paths + .iter() + .zip(self.runtimes.iter()) + .find(|(_, runtime)| runtime.open_source_series) + .map(|(path, _)| truncated_input(path)) + } + /// Closes every node, reporting an input that ended mid-series. /// /// A drain finds nothing left to emit: a window reports its results on the chunk that closes @@ -1177,6 +1383,11 @@ impl NativeExecutionState { /// /// The driver owns the state and nothing else: every decision a node makes was bound before the /// tree existed, so a pull only reads the position and runs the bound operation. +/// +/// A window directly over a source evaluates its chunks as they arrive, and a map at the root hands +/// its chunks on as it produces them: both stream. A window whose input can hold two series under +/// one canonical label set collects that input instead, merges each set once and evaluates it, so +/// it reports at [`Self::finish`] rather than as its input arrives. pub struct NativeExecutor { state: NativeExecutionState, phase: Phase, @@ -1220,7 +1431,15 @@ impl NativeExecutor { /// The next chunk the root produces, or `None` when nothing has settled yet. /// /// Every node takes whole chunks from its input, so a caller that keeps pushing and pulling - /// materialises nothing beyond the chunk in hand. + /// materialises nothing beyond the chunk in hand -- except below a window that collects its + /// input, which holds that input until [`Self::finish`]. + /// + /// A chunk's `is_last` says the series whose data it carries ended. It does not say its label + /// set is finished: two source series whose labels were rewritten into one set are two pieces + /// of one logical series, and the merge that makes them one is + /// [`crate::grid_series::merge_same_labelset`]'s. Every window that collects its input performs + /// that merge itself, so a root below such a window hands over one series per label set; a map + /// at the root hands over pieces, and a caller that needs one series per label set merges them. pub fn next_chunk(&mut self) -> Result> { self.check_running()?; // The root is the node the state was built from, which the pass puts first. @@ -1240,12 +1459,21 @@ impl NativeExecutor { result } - /// Ends the input: drains what has settled, closes every node and releases every reservation. + /// Ends the input: drains what has settled, merges what the windows that collect their input + /// hold, closes every node and releases every reservation. /// /// Every series must have closed by now, in every tree: a window's evaluator reports the series /// it is still holding, and a tree with no window has its input node report one it handed over /// without the chunk that ends it. An input that ends mid-series is an error here rather than a - /// series the caller never sees close. + /// series the caller never sees close, and it is refused before any collected input is merged: + /// merging closes what it merges. + /// + /// The merge comes next, deepest window first, and what it hands up is drained as it is + /// produced. What the root hands over is therefore a piece stream: a chunk's `is_last` says the + /// source series it carries ended, and two of them can share one label set. A caller that needs + /// one series per label set from the root merges them with + /// [`crate::grid_series::merge_same_labelset`] as well, exactly as this runtime merges the input + /// of the windows it collects for. pub fn finish(&mut self) -> Result> { let mut drained = Vec::new(); loop { @@ -1255,6 +1483,16 @@ impl NativeExecutor { Err(error) => return Err(error), } } + // A source series that never ended is refused before anything is merged: the close a merge + // synthesises would make it look like one that did. + if let Some(error) = self.state.truncated() { + self.stop(&error); + return Err(error); + } + if let Err(error) = self.flush_merges(&mut drained) { + self.stop(&error); + return Err(error); + } match self.state.close() { Ok(()) => { self.phase = Phase::Finished; @@ -1267,6 +1505,117 @@ impl NativeExecutor { } } + /// Merges the collected input of every window that collects it, and drains the root after each + /// merged series. + /// + /// Deeper windows go first: a window above one of them collects the chunks the one below hands + /// up, so flushing the shallow one first would merge an input it has not received yet. The + /// queue of a flushed node is emptied by the root drain that follows each of its merged series, + /// so a chunk it produced never stands beside the fragments it was computed from. + fn flush_merges(&mut self, drained: &mut Vec) -> Result<()> { + for index in (0..self.state.runtimes.len()).rev() { + // A window that collects its input is the one node holding a [`MergeInput`], and the + // flush takes it: the same node is not visited twice. + if self.state.runtimes[index].merge.is_none() { + continue; + } + self.flush_merge(index, drained)?; + } + Ok(()) + } + + /// Merges the collected input of the node at `index` and evaluates it, one merged series at a + /// time. + /// + /// Each merged series is a whole series: it is handed to the evaluator as one closing series, so + /// the window reports on it once, and its chunk is queued and drained up the tree before the + /// next one is evaluated. That is what keeps the reservation honest: the fragments and the + /// merge's workspace stay charged while the flush runs, and the queue of a node never holds an + /// earlier series beside the fragments of a later one. + fn flush_merge(&mut self, index: usize, drained: &mut Vec) -> Result<()> { + let path = self.state.paths[index].clone(); + let Some(merge) = self.state.runtimes[index].merge.take() else { + return Ok(()); + }; + if merge.fragments.is_empty() { + // Nothing arrived, so there is nothing to merge and nothing to answer: the window's + // evaluator never read a series and the charge goes back. + return self.settle_merge(index); + } + // The workspace the merge allocates is charged before it runs, from the rows, segments and + // fields of the fragments as they were collected. + let workspace = merge.workspace_bytes(); + let held = merge.bytes.saturating_add(workspace); + let schema = Arc::clone(&merge.schema); + self.state.runtimes[index].buffer.grow(workspace)?; + // The fragments' charge stands for the merged series too -- a merged run is a slice of a + // fragment's own segment, so no value is copied -- and the workspace stays charged until + // the flush is over. + let merged = merge_same_labelset(&schema, merge.fragments)?; + for series in merged { + let output = { + let runtime = &mut self.state.runtimes[index]; + let Some(evaluator) = runtime.window.as_mut() else { + return Err(closed(&path)); + }; + let metrics = Arc::clone(&runtime.buffer.metrics); + let _timer = metrics.timer(); + evaluator.push_series(&series, true)? + }; + if let Some(output) = output { + let runtime = &mut self.state.runtimes[index]; + runtime + .buffer + .metrics + .record_grid_points(output.series.time.len()); + runtime + .buffer + .metrics + .record_output(1, valid_values(&output)); + runtime.track(&path, &output)?; + let retained = runtime + .window + .as_ref() + .map_or(0, RangeEvaluator::retained_bytes); + let emitted = runtime.emitted_bytes(); + runtime + .buffer + .resize(retained.saturating_add(emitted).saturating_add(held))?; + runtime.enqueue_output(output)?; + } + self.drain_root(drained)?; + } + self.settle_merge(index) + } + + /// Sets the reservation of the node at `index` to what it holds once its flush is over. + fn settle_merge(&mut self, index: usize) -> Result<()> { + let runtime = &mut self.state.runtimes[index]; + let retained = runtime + .window + .as_ref() + .map_or(0, RangeEvaluator::retained_bytes); + let emitted = runtime.emitted_bytes(); + runtime.buffer.resize(retained.saturating_add(emitted)) + } + + /// Hands the root's outputs to `drained` until the tree has nothing settled. + fn drain_root(&mut self, drained: &mut Vec) -> Result<()> { + loop { + match self.pull(0)? { + Some(NativeChunk::Evaluated(chunk)) => drained.push(chunk), + Some(NativeChunk::Raw(_)) => { + return Err(DataFusionError::Execution( + "the native runtime produces evaluated chunks, but its root produced raw \ + samples" + .to_string(), + )); + } + None => return Ok(()), + } + } + } + /// The next chunk of the node at `index`. fn pull(&mut self, index: usize) -> Result> { let tag = self.state.nodes[index].tag; @@ -1287,6 +1636,12 @@ impl NativeExecutor { } } NodeTag::Window => { + // A chunk this window computed while flushing its collected input leaves first: it + // was produced before the window was drained, and the pull that hands it up is the + // one that empties the queue. + if let Some(chunk) = self.state.runtimes[index].take_output()? { + return Ok(Some(chunk)); + } let child = input.ok_or_else(|| missing_input(tag))?; // A window reports on the chunk that closes a series, so a chunk that decides // nothing yields nothing and the window asks its input again. @@ -1463,26 +1818,6 @@ fn unsupported_ordering(ordering: SeriesOrdering, input: &NodePath) -> DataFusio )) } -/// The rejection of a second series onto a label set the node already closed. -/// -/// This is a limitation of this streaming evaluator, not a PromQL collision. Two series whose -/// distinct label sets were rewritten into one do merge when they hold values in different places: -/// [`crate::grid_series::merge_same_labelset`] accepts exactly that, rejecting only two values of -/// one field at one position. What this runtime cannot do is merge across a series that has already -/// closed, because the evaluator closes its per-series state on the chunk carrying `is_last`: -/// nothing is left to merge the second series into, and the node hands chunks on as it produces -/// them, so it cannot hold the first series back until it knows whether a second one follows. -/// -/// The case is therefore refused rather than answered wrongly: reporting the two as one series, or -/// the first series twice, would both be a claim this layer cannot stand behind. -fn closed_label_set(path: &NodePath, labels: &LabelSet) -> DataFusionError { - DataFusionError::Execution(format!( - "the node at {path} already closed the label set {labels:?}, and a second input series \ - produces it: answering would report one series twice, and merging the two would need \ - whole series" - )) -} - /// The rejection of a chunk holding a value where the same field already holds one. /// /// No merge resolves this one: at `position`, field `field` of the label set `labels` would carry @@ -1497,7 +1832,7 @@ fn occupied_position( DataFusionError::Execution(format!( "the node at {path} produces two series under the label set {labels:?} that both hold a \ value of field {field} at position {position}: one occupies {previous:?} and another \ - {run:?}. Merging them would need whole series, which this layer does not hold", + {run:?}, and no merge resolves two values of one field at one position", position = run.start.max(previous.start), )) } diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index c424ebda404..925b9cffcec 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -35,9 +35,10 @@ use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::{ Emitted, NativeChunk, NativeExecutionState, NativeExecutor, NodeBuffer, NodeRuntime, - absorb_rebuilds, map_chunk, raw_bytes, + absorb_rebuilds, evaluated_bytes, map_chunk, raw_bytes, }; use crate::evaluated::EvaluatedChunk; +use crate::grid_series::merge_same_labelset; use crate::map::MathOp; use crate::native::metrics::{NodeMetric, NodeMetrics, NodePath}; use crate::native::plan::{ @@ -356,6 +357,7 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { window: None, map: None, emitted: None, + merge: None, open_source_series: false, } } @@ -905,9 +907,10 @@ fn an_unimplemented_node_is_reported_not_panicked() { /// Each node reports its own chunks, grid points and closed series, at its own position. /// /// The two windows decide different traffic — the inner one four grid points of its own grid, the -/// outer one two of its own — so a single total for the tree cannot produce both numbers. They take -/// and hand over the same number of chunks, which is what streaming means here: a node passes on one -/// chunk per chunk it took in, instead of holding its input until a whole series is available. +/// outer one two of its own — so a single total for the tree cannot produce both numbers. The inner +/// window reads the source as it arrives and hands over one chunk per chunk it took in; the outer +/// one collects those chunks, because the inner one keeps the metric name and its output can hold +/// two source series under one label set, and reports the one merged series its input ended with. #[test] fn each_node_records_its_own_metrics() { let inner_grid = grid(0, 60_000, 4); @@ -939,26 +942,23 @@ fn each_node_records_its_own_metrics() { .push_raw(raw_chunk(&schema, &[180_000], &[4.0], true)) .unwrap(); let out = run(&mut execution); - // The outer window reports each point as the inner one settles it: one chunk per inner chunk, - // and an empty chunk that closes the series. - assert_eq!( - addressed(&out), - vec![(0, vec![Some(1.0)]), (1, vec![Some(3.0)]), (2, Vec::new()),] - ); + // The outer window reports the two points of its grid once its input ended, in the one chunk of + // the series it merged from the inner window's pieces. + assert_eq!(addressed(&out), vec![(0, vec![Some(1.0), Some(3.0)])]); assert!(out.last().unwrap().is_last); let outer = NodePath::root(); let inner = outer.input(); let source = inner.input(); - // Three source chunks reach the inner window, and the chunks it hands over reach the outer one - // one for one, because neither window buffers. + // Three source chunks reach the inner window, which hands one chunk on per chunk it took in. + // The outer window takes those three pieces in and reports the one series they merge into. assert_eq!(count(&set, &source, NodeMetric::INPUT_BATCHES), 3); assert_eq!(count(&set, &source, NodeMetric::OUTPUT_BATCHES), 3); assert_eq!(count(&set, &inner, NodeMetric::INPUT_BATCHES), 3); assert_eq!(count(&set, &outer, NodeMetric::INPUT_BATCHES), 3); assert_eq!(count(&set, &inner, NodeMetric::OUTPUT_BATCHES), 3); - assert_eq!(count(&set, &outer, NodeMetric::OUTPUT_BATCHES), 3); + assert_eq!(count(&set, &outer, NodeMetric::OUTPUT_BATCHES), 1); // The grid points each window decided, which is its own output range: four on the inner grid // and two on the outer one, which is the figure that tells the two nodes apart. assert_eq!(count(&set, &inner, NodeMetric::EVALUATED_GRID_POINTS), 4); @@ -1098,13 +1098,110 @@ fn a_pool_that_cannot_admit_a_chunk_releases_what_it_held() { ); } -/// A map that drops the metric name cannot hand two series on under one label set. +/// Two series that a map turns into one label set are merged before the window above reads them. /// -/// `a{job="x"}` and `b{job="x"}` arrive whole, so each says it is the last chunk of its own series, -/// and `abs` drops the name, so both become `{job="x"}`. A window above the map reads chunks as -/// they arrive, so it would take them for two series and answer once per series; the only answer -/// the data has is the merged series, which this layer does not hold. The map refuses the second -/// one before the window above evaluates it. +/// `a{job="x"}` and `b{job="x"}` arrive whole, so each says it is the last chunk of its own source +/// series, and `abs` drops the name, so both become `{job="x"}`. The two hold their values at +/// different positions, so they are one series with a hole each and the answer is the window over +/// the merged series: `sum_over_time` sees 1 and 3 and answers 4, `count_over_time` answers 2. A +/// window that read the two as two series would answer twice, once per source series, and close +/// twice. +/// +/// The window above the map is the node that merges: its input can hold two series under one label +/// set, so it collects the whole input, merges each label set once with +/// [`crate::grid_series::merge_same_labelset`], and only then evaluates. Nothing comes out of it +/// while the pieces arrive, which is the price of merging; what comes out is one series. +#[test] +fn two_series_onto_one_label_set_after_a_map_are_merged_into_one_series() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + // One map and two maps: the label set is rewritten at the first one either way, and the second + // only rewrites it again, so both shapes are one affected window over one rewritten set. + let shapes = |function: RangeFunction| { + [ + ( + "a map", + NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + function, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(), + ), + ( + "two maps", + NativeTree::try_new(window_with( + map( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + vec![MathOp::Abs], + ), + function, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(), + ), + ] + }; + + for (function, expected) in [ + // The two values at inner positions 0 and 1 both fall in the one window of the outer grid. + (RangeFunction::SumOverTime, 4.0), + (RangeFunction::CountOverTime, 2.0), + ] { + for (shape, tree) in shapes(function) { + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + // Each source series is closed properly, and each holds its value where the other holds + // none, so the pair is one logical series and one answer. + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + vec![Some(1.0), None], + true, + )) + .unwrap(); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("b", "x"), + 0, + vec![None, Some(3.0)], + true, + )) + .unwrap(); + // Nothing settles while the pieces arrive: the merged series is what the window evaluates, + // and it does not exist before the input ends. + assert!( + execution.next_chunk().unwrap().is_none(), + "{shape} with {function:?} reported a piece it had not merged yet" + ); + let out = execution.finish().expect("the merged series evaluates"); + assert_eq!( + decided(&out), + vec![(0, Some(expected))], + "{shape} with {function:?} did not answer over the merged series" + ); + assert_eq!( + out.iter().filter(|chunk| chunk.is_last).count(), + 1, + "{shape} with {function:?} closed the one merged series more than once" + ); + } + } +} + +/// Two closed series that hold a value at the same position are still refused under one label set. +/// +/// The pair below maps into one label set and both hold a value at position 0 of the field, which +/// no merge resolves and Prometheus rejects for two series whose label sets became equal. The +/// refusal is the map's own, before the window above evaluates anything, and it names the position +/// rather than a closed label set: a closed source series is not a closed label set. #[test] fn two_series_onto_one_label_set_after_a_map_are_rejected() { let inner_grid = grid(0, 60_000, 2); @@ -1121,7 +1218,6 @@ fn two_series_onto_one_label_set_after_a_map_are_rejected() { }; let schema = evaluated_schema(Arc::clone(&inner_grid)); - // The first series closes, so its window answer comes out on its own. let mut execution = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); execution .push_evaluated(evaluated_chunk_of( @@ -1132,28 +1228,24 @@ fn two_series_onto_one_label_set_after_a_map_are_rejected() { true, )) .unwrap(); - let first = execution - .next_chunk() - .unwrap() - .expect("the first series settles the outer point"); - assert_eq!(sample_values(&first), vec![Some(1.0)]); - assert!(first.is_last); - - // The second one maps onto the label set the first one closed. Answering would produce a second - // chunk with the same labels at the same point. + // The first series closed, and the window above collects it rather than reporting it. + assert!( + execution.next_chunk().unwrap().is_none(), + "the window above the map reported a piece before its input ended" + ); execution .push_evaluated(evaluated_chunk_of( &schema, named_metric("b", "x"), 0, - vec![None, Some(3.0)], + vec![Some(3.0), Some(4.0)], true, )) .unwrap(); let error = match execution.next_chunk() { - Ok(None) => panic!("the second series settled nothing at all"), + Ok(None) => panic!("the second series was accepted at a position the first one holds"), Ok(Some(chunk)) => panic!( - "the map handed a second series on at the label set the first one closed: {:?}", + "two values at one position were handed on: {:?}", decided(&[chunk]) ), Err(error) => error, @@ -1164,27 +1256,301 @@ fn two_series_onto_one_label_set_after_a_map_are_rejected() { "the rejection does not name the label set: {message}" ); assert!( - message.contains("closed"), - "the rejection does not say the label set was already closed: {message}" + message.contains("position 0"), + "the rejection does not name the shared position: {message}" + ); +} + +/// An empty tag and an absent one are two source series and one canonical label set. +/// +/// `requests{host="web-1", zone=""}` and `requests{host="web-1"}` are distinct series to a scan: an +/// empty tag value is a present label, an absent one is not. `last_over_time` keeps the metric name +/// and every tag, so the inner window hands both on as two pieces, each closing its own source +/// series, and the two pieces carry different metrics. The outer window is the node that merges +/// them: a consumer compares label sets without the empty value, so the two are one series there. +/// Merging first is what makes the outer `sum_over_time` answer 4 at the second point -- the two +/// pieces hold 1 at the first point and 3 at the second -- where evaluating each piece on its own +/// would answer 3. +#[test] +fn an_empty_tag_and_an_absent_one_are_one_label_set_to_the_window_above() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(0, 60_000, 2); + let inner = || { + // A one-millisecond window on a 60 s grid, so every point reads only the sample at its own + // timestamp and each source series decides one point. + window_with( + input(), + RangeFunction::LastOverTime, + 1, + None, + Arc::clone(&inner_grid), + ) + }; + let chain = || { + window_with( + inner(), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + ) + }; + let schema = raw_schema(); + let push_both = |execution: &mut NativeExecutor| { + execution + .push_raw(raw_chunk_of( + &schema, + b"series-a", + host_metric(Some("")), + &[0], + &[1.0], + true, + )) + .unwrap(); + execution + .push_raw(raw_chunk_of( + &schema, + b"series-b", + host_metric(None), + &[60_000], + &[3.0], + true, + )) + .unwrap(); + }; + + // The inner window alone hands both series on, and they are two series: the empty tag survives + // `last_over_time`, which keeps the name and every tag. + let inner_tree = NativeTree::try_new(inner()).unwrap(); + let mut inner_execution = executor(&inner_tree, pool(), &ExecutionPlanMetricsSet::new()); + push_both(&mut inner_execution); + let pieces = run(&mut inner_execution); + assert_eq!( + pieces.len(), + 2, + "the inner window did not hand both series on" + ); + assert_ne!( + pieces[0].series.metric, pieces[1].series.metric, + "the two source series were not two series to `last_over_time`" ); - // What the rejection protects: one series carrying both samples averages to 2 at that point, - // which is the answer neither of the two separate series can produce. - let mut merged = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); - merged - .push_evaluated(evaluated_chunk_of( - &schema, - named_metric("c", "x"), - 0, - vec![Some(1.0), Some(3.0)], - true, - )) - .unwrap(); - let answer = merged + // The chain merges them before the outer window reads them. + let tree = NativeTree::try_new(chain()).unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + push_both(&mut execution); + let out = run(&mut execution); + assert_eq!( + decided(&out), + vec![(0, Some(1.0)), (1, Some(4.0))], + "the outer window did not answer over the merged label set" + ); + assert_eq!( + out.iter().filter(|chunk| chunk.is_last).count(), + 1, + "the merged label set closed more than once" + ); +} + +/// A window that collects its whole input gives every byte back when the execution closes. +/// +/// The fragments it holds, the workspace it merges them with and the chunks it queued while +/// flushing are all charged while they live, so the pool never admits memory the node still owns. +/// The close releases all of them, and the figures read zero while the executor is still alive. +#[test] +fn a_window_that_merges_its_input_releases_what_it_collected() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let tree = NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + let set = ExecutionPlanMetricsSet::new(); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &set); + for (name, values) in [("a", vec![Some(1.0), None]), ("b", vec![None, Some(3.0)])] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, "x"), + 0, + values, + true, + )) + .unwrap(); + } + // Pulling takes both fragments out of the queue and into the window, which charges them. + assert!( + execution.next_chunk().unwrap().is_none(), + "the collecting window reported a piece" + ); + let held = execution.state().reserved_bytes(); + let window_held = execution.state().runtimes[0].buffer.reservation.size(); + assert!(held > 0, "the collected input is not charged for"); + assert_eq!( + held, + pool.reserved(), + "the state and the pool disagree on what the collected input holds" + ); + + let out = execution.finish().expect("the merged series evaluates"); + assert_eq!(decided(&out), vec![(0, Some(4.0))]); + // The fragments, the workspace, the queue and the evaluator are all gone. + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().nodes_holding_windows(), 0); + let current = NodePath::root().metric_name(NodeMetric::CURRENT_RESERVED_BYTES); + assert_eq!(gauge(&set, ¤t), 0); + let peak = NodePath::root().partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, 0); + assert!( + gauge(&set, &peak) >= window_held, + "the peak does not cover the input the window collected" + ); +} + +/// A pool that cannot admit what a collecting chain holds fails the execution and gives everything +/// back. +/// +/// The window collects its whole input, so the fragment it keeps costs more than the chunk it was +/// made from: the pool below holds room for the chunk and no more, so one of the charges the chain +/// makes fails. Whichever it is, the failure hands every reservation back while the executor is +/// still alive, and the evaluators and the collected fragments go with it. +#[test] +fn a_pool_that_cannot_admit_a_collected_fragment_releases_what_it_held() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let tree = NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + let chunk = evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + vec![Some(1.0), None], + true, + ); + // Room for the chunk the source queue holds, which is what the pool admits first, and nothing + // for the label sets the map records or the fragment the window collects. + let pool = bounded_pool(evaluated_bytes(&chunk) + 1); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated(chunk) + .expect("the source queue holds the chunk"); + + let error = execution .next_chunk() + .expect_err("the chain was admitted by a pool that cannot hold what it makes of the chunk"); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "{error}" + ); + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + assert_eq!( + execution.state().nodes_holding_windows(), + 0, + "the stopped execution still holds a window's samples" + ); +} + +/// A merge whose workspace the pool cannot admit stops the execution and gives everything back. +/// +/// The fragments are admitted one by one as they arrive, so their charge is not what fails here: +/// what fails is the workspace the merge needs, taken in `finish` before the helper runs. The first +/// run measures what the collected input holds where the pool admits it; the second is given that +/// much and a little over -- enough for every fragment, not for the workspace, which charges at +/// least one `(position, member, row)` triple and one position per row. The failure releases the +/// fragments, the evaluators and the queues while the executor is still alive. +#[test] +fn a_pool_that_cannot_admit_the_merge_workspace_releases_what_it_held() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let tree = || { + NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) .unwrap() - .expect("the merged series settles the outer point"); - assert_eq!(sample_values(&answer), vec![Some(2.0)]); + }; + let schema = evaluated_schema(Arc::clone(&inner_grid)); + // Two closed source series, each holding its value where the other holds none, so the fragments + // do merge and the merge is what needs the workspace. + let push_both = |execution: &mut NativeExecutor| { + for (name, values) in [("a", vec![Some(-1.0), None]), ("b", vec![None, Some(-3.0)])] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, "x"), + 0, + values, + true, + )) + .unwrap(); + } + }; + + // What the chain holds once its input is collected, measured where the pool admits it. + let mut reference = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); + push_both(&mut reference); + assert!( + reference.next_chunk().unwrap().is_none(), + "the collecting window reported a piece" + ); + let measured = reference.state().reserved_bytes(); + assert!(measured > 0, "the collected input is not charged for"); + drop(reference); + + // Room for exactly what the collected input holds, and not for the merge's workspace. + let pool = bounded_pool(measured + 64); + let mut execution = executor(&tree(), Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + push_both(&mut execution); + assert!( + execution.next_chunk().unwrap().is_none(), + "the collecting window reported a piece" + ); + let collected = execution.state().reserved_bytes(); + assert_eq!( + collected, measured, + "the collected input was charged differently the second time, so the pool is not sized for it" + ); + assert_eq!(collected, pool.reserved()); + + let error = execution + .finish() + .expect_err("the merge ran without its workspace admitted"); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "{error}" + ); + // Everything the chain held went back while the executor is alive: the fragments, the + // evaluator and both queues. + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + assert_eq!( + execution.state().nodes_holding_windows(), + 0, + "the stopped execution still holds a window's samples" + ); + // A stopped execution is not resumed. + let again = execution.next_chunk().unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); } /// A window that drops empty-valued labels cannot hand two series on under one label set either. @@ -1195,6 +1561,12 @@ fn two_series_onto_one_label_set_after_a_map_are_rejected() { /// grid out twice under the same labels and the same timestamps. No map is involved, so the /// rejection has to be the node's own — a check at the root would be too late, because the window /// above would already have evaluated the two as two series. +/// +/// The two cover the same positions of the same field, which is the collision no merge resolves: +/// the refusal names the position, not a closed label set, because closing a source series says +/// nothing about the label set it shared with another one. `rate` needs two samples, so neither +/// series decides position 0 -- it holds the single sample at its own timestamp -- and both decide +/// positions 1 to 4. The first position both occupy is therefore 1. #[test] fn two_series_onto_one_label_set_after_a_window_are_rejected() { let out_grid = grid(0, 60_000, 5); @@ -1224,7 +1596,17 @@ fn two_series_onto_one_label_set_after_a_window_are_rejected() { .next_chunk() .unwrap() .expect("the first series settles the grid"); - assert!(!first.series.time.is_empty()); + // The decided positions of the first series, which are the ones the second one has to share. + assert_eq!( + first.series.time.runs().count(), + 1, + "the first series decided more than one run" + ); + assert_eq!( + first.series.time.first_position(), + Some(1), + "`rate` decided a position the single sample at 0 cannot settle" + ); assert!(first.is_last); // The second series is a different one to the scan and the same one to `rate`. @@ -1249,7 +1631,10 @@ fn two_series_onto_one_label_set_after_a_window_are_rejected() { let message = error.to_string(); assert!(message.contains("host"), "{message}"); assert!(message.contains("web-1"), "{message}"); - assert!(message.contains("closed"), "{message}"); + assert!( + message.contains("position 1"), + "the rejection does not name the first position both series hold: {message}" + ); // Two series carrying different hosts stay distinct, which is what a rate over a label that // survives the rewrite looks like. @@ -1287,9 +1672,9 @@ fn two_series_onto_one_label_set_after_a_window_are_rejected() { /// A chunk that holds a value where the same field already holds one is rejected. /// -/// Neither piece closes its series, so this is not a closed label set: the refusal is about the -/// positions themselves. `v0` would carry two values at position 0 under one label set, which no -/// merge can resolve, so the node refuses rather than picking one. +/// Neither piece closes its series, and neither needs to: the refusal is about the positions +/// themselves. `v0` would carry two values at position 0 under one label set, which no merge can +/// resolve, so the node refuses rather than picking one. #[test] fn two_series_holding_a_value_at_one_position_are_rejected() { let map_grid = grid(0, 60_000, 2); @@ -1336,18 +1721,16 @@ fn two_series_holding_a_value_at_one_position_are_rejected() { assert!(message.contains("position 0"), "{message}"); } -/// Two closed series that hold no position of the same field in common still cannot be handed on: -/// merging across a closed series is not implemented by this streaming evaluator, so the pair is -/// refused rather than answered wrongly. +/// Two closed series under one label set are two pieces of one logical series. /// -/// Neither piece holds a value where the other does — each has a missing value where the other holds -/// one — so the two do merge in Prometheus, and [`crate::grid_series::merge_same_labelset`] accepts -/// exactly this. What refuses it is the label set having closed on the piece carrying `is_last`: the -/// evaluator above has already closed its per-series state for it, so the node cannot hold the first -/// series back until it knows whether a second one follows. The refusal has to say so; a test that -/// passed both pieces as open chunks would be proving a merge the runtime never performs. +/// `a{job="x"}` and `b{job="x"}` are two series to the input and one label set to `abs`, which drops +/// the name. Each holds a value where the other holds none, and each says it is the last chunk of +/// its own source series — which is what `is_last` means here: the source series ended, not the +/// label set. The map hands both pieces on, and merging the two pieces with +/// [`crate::grid_series::merge_same_labelset`] gives the one series the data has, which is what a +/// caller holding the root's pieces does. #[test] -fn a_merge_across_a_closed_series_is_not_implemented() { +fn a_merge_across_two_closed_series_is_the_root_piece_stream() { let map_grid = grid(0, 60_000, 2); let tree = NativeTree::try_new(map( evaluated_input(Arc::clone(&map_grid)), @@ -1370,25 +1753,60 @@ fn a_merge_across_a_closed_series_is_not_implemented() { )) .unwrap(); } - let first = execution - .next_chunk() - .unwrap() - .expect("the first closed series is handed on before the second one arrives"); - assert_eq!(sample_values(&first), vec![Some(1.0), None]); - // The second one would merge with it, which this runtime does not do across a closed series. - let error = match execution.next_chunk() { - Ok(None) => panic!("the map produced no chunk for the closed label set"), - Ok(Some(chunk)) => panic!( - "a merge across a closed series was handed on instead of refused: {:?}", - decided(&[chunk]) - ), - Err(error) => error, - }; - let message = error.to_string(); - assert!(message.contains("job"), "{message}"); + // Both pieces come out of the root, one per source series, and neither is refused. + let mut pieces = Vec::new(); + loop { + match execution.next_chunk() { + Ok(Some(chunk)) => pieces.push(chunk), + Ok(None) => break, + Err(error) => panic!("a closed source series was refused: {error}"), + } + } + pieces.extend( + execution + .finish() + .expect("the map holds no collected input"), + ); + assert_eq!(pieces.len(), 2, "the root did not hand over both pieces"); assert!( - message.contains("already closed the label set"), - "{message}" + pieces.iter().all(|piece| piece.is_last), + "a piece of a closed source series did not close it" + ); + + // The one series the two pieces are, merged the way a consumer of the root's pieces merges + // them: positions 0 and 1 of field 0, holding 1 and 3. + let merged = merge_same_labelset( + &evaluated_schema(Arc::clone(&map_grid)), + pieces.into_iter().map(|piece| piece.series).collect(), + ) + .expect("the two pieces hold disjoint positions"); + assert_eq!( + merged.len(), + 1, + "the two pieces did not merge into one logical series" + ); + assert_eq!( + merged[0].metric, + { + let mut mapped = named_metric("a", "x"); + mapped.remove("__name__"); + mapped + }, + "the merged series does not carry the label set both pieces produced" + ); + assert_eq!( + merged[0] + .fields + .get(0) + .expect("one field") + .iter() + .map(|sample| match sample { + SampleRef::Float(value) => Some(value), + _ => None, + }) + .collect::>(), + vec![Some(1.0), Some(3.0)], + "the merged series does not hold both pieces' values at their positions" ); } @@ -1484,8 +1902,8 @@ fn a_nan_occupies_its_position_where_a_missing_sample_does_not() { (vec![Some(1.0)], vec![None], true), (vec![None], vec![Some(f64::NAN)], true), ]; - // Both chunks are open, so the label set is still open when the second series arrives: a closed - // set refuses every second series, and this test is about what occupies a position. + // Both chunks are open and neither needs to close: what the check reads is which positions a + // chunk occupies, and that does not depend on `is_last`. let drain = |execution: &mut NativeExecutor| -> Result<(), DataFusionError> { while execution.next_chunk()?.is_some() {} Ok(()) @@ -1522,11 +1940,13 @@ fn a_nan_occupies_its_position_where_a_missing_sample_does_not() { } } -/// One series arriving in pieces is not two series: a chunk that continues where its label set -/// ended is handed on. +/// One series arriving in pieces is not two series: the pieces are merged into the one series they +/// are, and the window above reports it once. /// -/// The map is passed twice for one label set, and the window above it reports the whole series once -/// the piece carrying `is_last` arrives. +/// The map is passed twice for one label set, so the window above collects both pieces and merges +/// them with [`crate::grid_series::merge_same_labelset`] before it evaluates: the two pieces hold +/// one position each, the window across them needs both, and answering per piece would close the +/// first series in the evaluator before the second arrived. #[test] fn a_series_that_continues_where_it_ended_is_not_a_second_series() { let inner_grid = grid(0, 60_000, 4); @@ -1551,6 +1971,8 @@ fn a_series_that_continues_where_it_ended_is_not_a_second_series() { false, )) .unwrap(); + // Nothing comes out of the collecting window before its input ended, and the piece here does + // not end it. while let Some(chunk) = execution.next_chunk().unwrap() { assert!( !chunk.is_last, @@ -1819,14 +2241,13 @@ fn an_interleaved_input_is_refused_without_a_window() { /// same label set, is not a collision: the second contributes no sample, so the answer is just the /// first one's values. /// -/// This is the other order of [`two_series_with_no_result_do_not_collide`], and the one that used to -/// fail: by the time the empty series arrives the label set is already closed, and refusing it -/// failed an execution whose answer was never in doubt. +/// This is the other order of [`two_series_with_no_result_do_not_collide`]: a series that produced +/// values under a label set, followed by one that produced none. The empty one occupies no +/// position, so it records nothing and changes nothing, and the answer is the first one's values. /// -/// The set is closed here, which is what makes the empty series a later one that also answers -/// empty. Its mirror image -- an empty closing chunk that arrives while the set is still open -- is -/// [`an_empty_closing_chunk_of_another_series_does_not_close_a_label_set`], where the same series -/// is not a harmless extra but would take the close away from the series that filled the set. +/// The first series closed, which closes the source series and not the label set: the empty series +/// is a later one that also answers empty, and +/// [`an_empty_closing_chunk_of_another_series_does_not_close_a_label_set`] is its mirror image. #[test] fn a_series_with_no_result_after_a_closed_one_is_passed_over() { let map_grid = grid(0, 60_000, 1); @@ -2370,7 +2791,7 @@ fn a_series_whose_axis_and_fields_disagree_is_rejected() { let mut emitted = Emitted::default(); let error = emitted - .occupy(&NodePath::root(), Some(&chunk.series.metric), &chunk) + .occupy(&NodePath::root(), &chunk) .expect_err("a field with fewer samples than the axis places rows was accepted"); let message = error.to_string(); assert!( @@ -2414,7 +2835,7 @@ fn a_sparse_series_that_moves_forward_is_appended_to_its_history() { false, ); emitted - .occupy(&path, Some(&chunk.series.metric), &chunk) + .occupy(&path, &chunk) .unwrap_or_else(|error| panic!("position {position} was refused: {error}")); }; // The runs stored under the one label set, which is what `absorb` keeps in position order.