1use std::collections::{HashSet, VecDeque};
22use std::sync::Arc;
23
24use common_query::promql_annotations::PromqlAnnotationCollector;
25use datafusion::error::{DataFusionError, Result};
26use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation};
27use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
28use datatypes::arrow::array::{Array, ArrowPrimitiveType, Float64Array, PrimitiveArray};
29use datatypes::arrow::buffer::{Buffer, ScalarBuffer};
30use datatypes::series::histogram::HistogramView;
31use datatypes::series::raw::{RawSeriesChunk, RawTimestamps};
32use datatypes::series::samples::{
33 DenseSamplesRef, FieldSpec, RowCursor, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
34};
35use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis};
36use datatypes::series::{SeriesLabels, SeriesOrdering};
37
38use crate::aggregate;
39use crate::grid_series::{
40 GridSample, GridSeriesBuilder, fields_bytes, merge_same_labelset, owned, series_bytes,
41 table_bytes,
42};
43use crate::histogram_eval::float_histogram::FloatHistogram;
44use crate::histogram_eval::{
45 HistogramFunction, HistogramParameters, evaluate_histograms_with_annotations,
46 map_native_histogram,
47};
48use crate::info::{InfoSelector, info_with_reservation};
49use crate::instant_eval::{
50 info_sample_times, instant_candidate_span, select_instant_at, select_instants,
51 timestamp_of_evaluated, timestamp_of_selection,
52};
53use crate::map::{
54 ArithmeticOp, Comparison, ComparisonOp, ParameterizedMath, ScalarOperand, ScalarSeriesOperand,
55 drop_metric_name, is_float_series, map_arithmetic_literal, map_arithmetic_series,
56 map_compare_literal, map_compare_series, map_math, map_math_with_parameters,
57};
58use crate::map_time::{self, DateFunction};
59use crate::native::aggregate::{AggregateOutput, AggregateRuntime};
60use crate::native::batch::EvaluatedChunk;
61use crate::native::metrics::NodeMetrics;
62use crate::native::plan::{
63 BoundInstant, BoundScalar, BoundSetOp, BoundVectorOp, Grouping, InstantValue, MapOp,
64 NativeExpr, NativeNode, NativeTree, NativeType, ParameterizedOp, unifies_its_own_contributions,
65};
66use crate::native::state::{StateChunk, state_bytes};
67use crate::range_eval::RangeEvaluator;
68use crate::select::{self, SortOrder};
69use crate::vector_match::{
70 BinaryKind, BinaryMatching, Cardinality, DuplicateEvidence, FillValues, MatchingLabels,
71 binary_vectors_with_reservation, set_vectors_with_reservation, validate_binary_operand,
72};
73
74#[cfg(test)]
75mod tests;
76
77enum NativeChunk {
82 Raw(RawSeriesChunk),
84 Evaluated(EvaluatedChunk),
86 AggregateState(StateChunk),
88}
89
90impl NativeChunk {
91 fn positions(&self) -> usize {
93 match self {
94 Self::Raw(chunk) => chunk.time.len(),
95 Self::Evaluated(chunk) => chunk.series.time.len(),
96 Self::AggregateState(StateChunk::Series { series, .. }) => {
97 series.iter().map(|s| s.time.len()).sum()
98 }
99 Self::AggregateState(StateChunk::Row(row)) => row.time.len(),
100 }
101 }
102
103 fn describe(&self) -> &'static str {
105 match self {
106 Self::Raw(_) => "raw samples",
107 Self::Evaluated(_) => "an evaluated chunk",
108 Self::AggregateState(_) => "aggregate state",
109 }
110 }
111
112 fn is_last(&self) -> bool {
117 match self {
118 Self::Raw(chunk) => chunk.is_last,
119 Self::Evaluated(chunk) => chunk.is_last,
120 Self::AggregateState(_) => true,
124 }
125 }
126
127 fn bytes(&self) -> usize {
131 match self {
132 Self::Raw(chunk) => raw_bytes(chunk),
133 Self::Evaluated(chunk) => evaluated_bytes(chunk),
134 Self::AggregateState(chunk) => state_bytes(chunk),
135 }
136 }
137}
138
139pub(crate) fn raw_bytes(chunk: &RawSeriesChunk) -> usize {
144 std::mem::size_of::<RawSeriesChunk>()
145 .saturating_add(buffer_bytes(&chunk.primary_key))
146 .saturating_add(chunk.metric.as_ref().map_or(0, metric_bytes))
147 .saturating_add(buffer_bytes(chunk.time.as_buffer().inner()))
148 .saturating_add(fields_bytes(&chunk.fields))
149}
150
151pub(super) fn evaluated_bytes(chunk: &EvaluatedChunk) -> usize {
155 std::mem::size_of::<EvaluatedChunk>().saturating_add(fields_bytes(&chunk.series.fields))
156}
157
158pub(crate) fn chunk_bytes_beside_samples(series: &Series) -> usize {
170 series_bytes(series)
171 .saturating_sub(fields_bytes(&series.fields))
172 .saturating_sub(std::mem::size_of::<Series>())
173}
174
175pub(crate) fn operand_chunk_bytes(series: &Series) -> usize {
193 chunk_bytes_beside_samples(series)
194 .saturating_add(std::mem::size_of::<Series>())
195 .saturating_add(sample_slice_bytes(&series.fields))
196}
197
198pub(crate) fn field_segments(fields: &SeriesFields) -> impl Iterator<Item = &Samples> + '_ {
205 fields.iter().flat_map(|field| field.segments())
206}
207
208fn sample_slice_bytes(fields: &SeriesFields) -> usize {
217 field_segments(fields)
218 .map(|segment| match segment.dense() {
219 Some(DenseSamplesRef::Float(values)) => {
220 values.len().saturating_mul(std::mem::size_of::<f64>())
221 }
222 Some(DenseSamplesRef::Histogram(histograms)) => histograms
223 .indices()
224 .len()
225 .saturating_mul(std::mem::size_of::<u32>()),
226 Some(DenseSamplesRef::Mixed(mixed)) => mixed
227 .floats()
228 .len()
229 .saturating_mul(std::mem::size_of::<f64>())
230 .saturating_add(
231 mixed
232 .histograms()
233 .indices()
234 .len()
235 .saturating_mul(std::mem::size_of::<u32>()),
236 ),
237 None => 0,
239 })
240 .fold(0usize, usize::saturating_add)
241}
242
243pub(crate) fn unbilled_sample_buffers(
272 series: &Series,
273 billed: &HashSet<usize>,
274) -> (Vec<usize>, usize) {
275 let mut fresh: Vec<usize> = Vec::new();
276 let mut bytes = 0usize;
277 for field in series.fields.iter() {
278 for segment in field.segments() {
279 match segment.dense() {
280 Some(DenseSamplesRef::Float(values)) => {
281 unbilled_array_buffers(values, &mut fresh, billed, &mut bytes)
282 }
283 Some(DenseSamplesRef::Histogram(histograms)) => {
284 unbilled_array_buffers(histograms.indices(), &mut fresh, billed, &mut bytes)
285 }
286 Some(DenseSamplesRef::Mixed(mixed)) => {
287 unbilled_array_buffers(mixed.floats(), &mut fresh, billed, &mut bytes);
288 unbilled_array_buffers(
289 mixed.histograms().indices(),
290 &mut fresh,
291 billed,
292 &mut bytes,
293 );
294 }
295 None => {}
297 }
298 }
299 }
300 (fresh, bytes)
301}
302
303fn unbilled_array_buffers<T: ArrowPrimitiveType>(
306 values: &PrimitiveArray<T>,
307 fresh: &mut Vec<usize>,
308 billed: &HashSet<usize>,
309 bytes: &mut usize,
310) {
311 unbilled_buffer(values.values().inner(), fresh, billed, bytes);
312 if let Some(nulls) = values.nulls() {
313 unbilled_buffer(nulls.buffer(), fresh, billed, bytes);
314 }
315}
316
317fn unbilled_buffer(
319 buffer: &Buffer,
320 fresh: &mut Vec<usize>,
321 billed: &HashSet<usize>,
322 bytes: &mut usize,
323) {
324 let held = buffer_bytes(buffer);
325 if held == 0 {
326 return;
328 }
329 let identity = buffer.data_ptr().as_ptr() as usize;
330 if billed.contains(&identity) || fresh.contains(&identity) {
331 return;
332 }
333 fresh.push(identity);
334 *bytes = bytes
335 .saturating_add(held)
336 .saturating_add(std::mem::size_of::<usize>());
337}
338
339pub(crate) fn unbilled_tables(series: &Series, billed: &HashSet<usize>) -> (Vec<usize>, usize) {
359 let mut fresh: Vec<usize> = Vec::new();
360 let mut bytes = 0usize;
361 for field in series.fields.iter() {
362 for segment in field.segments() {
363 let table = match segment.dense() {
364 Some(DenseSamplesRef::Histogram(histograms)) => histograms.batch(),
365 Some(DenseSamplesRef::Mixed(mixed)) => mixed.histograms().batch(),
366 _ => continue,
367 };
368 let identity = Arc::as_ptr(table) as usize;
369 if billed.contains(&identity) || fresh.contains(&identity) {
370 continue;
371 }
372 fresh.push(identity);
373 bytes = bytes
374 .saturating_add(table_bytes(table))
375 .saturating_add(std::mem::size_of::<usize>());
376 }
377 }
378 (fresh, bytes)
379}
380
381pub(crate) fn merge_workspace_bytes(rows: usize, fragments: usize, fields: usize) -> usize {
386 let sorted_rows = rows.saturating_mul(
387 std::mem::size_of::<(usize, usize, usize)>() + std::mem::size_of::<usize>(),
388 );
389 let readers = fragments.saturating_mul(
390 fields.saturating_mul(std::mem::size_of::<Samples>() + 4 * std::mem::size_of::<usize>()),
391 );
392 let merged_field_per_row =
395 2 * std::mem::size_of::<Samples>() + 3 * std::mem::size_of::<usize>();
396 let merged_fields = rows
397 .saturating_mul(fields)
398 .saturating_mul(merged_field_per_row);
399 let output = fragments.saturating_mul(
400 std::mem::size_of::<Series>() + fields.saturating_mul(std::mem::size_of::<Samples>()),
401 );
402 sorted_rows
403 .saturating_add(readers)
404 .saturating_add(merged_fields)
405 .saturating_add(output)
406}
407
408fn buffer_bytes(buffer: &Buffer) -> usize {
411 buffer.capacity().max(buffer.len())
412}
413
414#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
419pub struct InputId(usize);
420
421impl InputId {
422 pub fn new(index: usize) -> Self {
424 Self(index)
425 }
426
427 pub fn index(self) -> usize {
429 self.0
430 }
431}
432
433struct OpenSeries {
438 metric: SeriesLabels,
440 last_position: Option<usize>,
442}
443
444struct MergeInput {
454 schema: Arc<SeriesSchema>,
456 fragments: Vec<Series>,
458 bytes: usize,
460 open: Option<OpenSeries>,
463}
464
465impl MergeInput {
466 fn new(schema: Arc<SeriesSchema>) -> Self {
468 Self {
469 schema,
470 fragments: Vec::new(),
471 bytes: 0,
472 open: None,
473 }
474 }
475
476 fn check(&mut self, series: &Series, is_last: bool) -> Result<()> {
482 let on_grid = match (&self.schema.eval_grid, series.time.grid()) {
483 (Some(input), Some(grid)) => input.spec() == grid.spec(),
484 _ => false,
485 };
486 if !on_grid
487 || series.fields.len() != self.schema.fields.len()
488 || series
489 .fields
490 .iter()
491 .any(|field| field.len() != series.time.len())
492 {
493 return Err(DataFusionError::Execution(
494 "merge input does not match its input schema".to_string(),
495 ));
496 }
497 let (first, last) = (series.time.first_position(), series.time.last_position());
498 if !is_last && first.is_none() {
499 return Err(DataFusionError::Execution(
500 "merge input has no position before the last run of its series".to_string(),
501 ));
502 }
503 if let Some(open) = &self.open
504 && open.metric != series.metric
505 {
506 return Err(DataFusionError::Execution(
507 "merge input changed identity before its last run".to_string(),
508 ));
509 }
510 if let Some(previous) = self.open.as_ref().and_then(|open| open.last_position)
511 && let Some(first) = first
512 && first <= previous
513 {
514 return Err(DataFusionError::Execution(format!(
515 "merge input runs are not increasing: {first} after {previous}"
516 )));
517 }
518 self.open = if is_last {
519 None
520 } else {
521 Some(OpenSeries {
522 metric: series.metric.clone(),
523 last_position: last,
524 })
525 };
526 Ok(())
527 }
528
529 fn workspace_bytes(&self) -> usize {
533 let rows: usize = self
534 .fragments
535 .iter()
536 .map(|fragment| fragment.time.len())
537 .sum();
538 merge_workspace_bytes(rows, self.fragments.len(), self.schema.fields.len())
539 }
540}
541
542pub(super) struct NodeBuffer {
549 metrics: Arc<NodeMetrics>,
550 reservation: MemoryReservation,
551 grid: Option<usize>,
560}
561
562impl NodeBuffer {
563 pub(super) fn new(
568 name: impl Into<String>,
569 metrics: Arc<NodeMetrics>,
570 pool: &Arc<dyn MemoryPool>,
571 ) -> Self {
572 let consumer = MemoryConsumer::new(name.into());
573 Self {
574 metrics,
575 reservation: consumer.register(pool),
576 grid: None,
577 }
578 }
579
580 pub(super) fn reserve_grid(&mut self, grid: &EvalGrid) -> Result<()> {
602 if self.grid.is_some() || grid.is_materialized() {
603 return Ok(());
604 }
605 let len = usize::try_from(grid.spec().len).map_err(|_| {
606 DataFusionError::Execution("grid length does not fit memory size".to_string())
607 })?;
608 let bytes = len.checked_mul(std::mem::size_of::<i64>()).ok_or_else(|| {
609 DataFusionError::Execution("grid timestamp size overflow".to_string())
610 })?;
611 self.grow(bytes)?;
612 self.grid = Some(bytes);
613 Ok(())
614 }
615
616 pub(super) fn grow(&mut self, bytes: usize) -> Result<()> {
618 self.reservation.try_grow(bytes)?;
619 self.record();
620 Ok(())
621 }
622
623 pub(super) fn resize(&mut self, bytes: usize) -> Result<()> {
628 self.reservation
629 .try_resize(bytes.saturating_add(self.grid.unwrap_or(0)))?;
630 self.record();
631 Ok(())
632 }
633
634 fn shrink(&mut self, bytes: usize) -> Result<()> {
636 self.reservation.try_shrink(bytes)?;
637 self.record();
638 Ok(())
639 }
640
641 fn transfer(&mut self, bytes: usize) -> Result<MemoryReservation> {
645 if bytes > self.reservation.size() {
649 return Err(DataFusionError::Internal(format!(
650 "a queued chunk holds {bytes} bytes, more than the {} its node reserves",
651 self.reservation.size()
652 )));
653 }
654 let reservation = self.reservation.split(bytes);
655 self.record();
656 Ok(reservation)
657 }
658
659 fn record(&self) {
661 self.metrics.record_reserved_bytes(self.reservation.size());
662 }
663}
664
665impl Drop for NodeBuffer {
666 fn drop(&mut self) {
667 self.reservation.free();
668 self.record();
669 }
670}
671
672fn metric_bytes(metric: &SeriesLabels) -> usize {
674 metric.name().map_or(0, |name| name.len())
675 + std::mem::size_of_val(metric.tags())
676 + metric
677 .tags()
678 .iter()
679 .map(|tag| tag.name.len() + tag.value.len())
680 .sum::<usize>()
681}
682
683struct MapRuntime {
685 ops: Arc<[MapOp]>,
686 schema: Arc<SeriesSchema>,
688}
689
690struct InstantRuntime {
695 selection: BoundInstant,
698 schema: Arc<SeriesSchema>,
700 output: GridSeriesBuilder,
702 chunks: Vec<RawSeriesChunk>,
704 held: usize,
706}
707
708impl InstantRuntime {
709 fn try_new(input: &SeriesSchema, op: &BoundInstant) -> Result<Self> {
711 let schema = Arc::new(SeriesSchema {
714 fields: Arc::clone(&input.fields),
715 eval_grid: Some(Arc::clone(&op.output_grid)),
716 });
717 Ok(Self {
718 selection: op.clone(),
719 output: GridSeriesBuilder::try_new(Arc::clone(&schema))?,
720 schema,
721 chunks: Vec::new(),
722 held: 0,
723 })
724 }
725
726 fn buffered_bytes(&self) -> usize {
728 self.held
729 }
730
731 fn gather_bytes(&self, closing: &RawSeriesChunk) -> usize {
751 let points = self.selected_points(closing);
755 let chunks = self.chunks.len().saturating_add(1);
756 let rows = self
757 .chunks
758 .iter()
759 .chain(std::iter::once(closing))
760 .map(|chunk| chunk.time.len())
761 .fold(0usize, usize::saturating_add);
762 let fields = self.schema.fields.len();
763 let descriptor = std::mem::size_of::<Samples>();
764 let segments = self
765 .chunks
766 .iter()
767 .chain(std::iter::once(closing))
768 .flat_map(|chunk| chunk.fields.as_slice())
769 .map(|field| field.segments().len())
770 .fold(0usize, usize::saturating_add);
771 let axis = rows.saturating_mul(std::mem::size_of::<i64>());
772 let layout = chunks
773 .saturating_mul(fields)
774 .saturating_mul(descriptor)
775 .saturating_add(segments.saturating_mul(3).saturating_mul(descriptor))
776 .saturating_add(fields.saturating_mul(std::mem::size_of::<Vec<Samples>>()));
777 let selection =
778 points.saturating_mul(std::mem::size_of::<u64>() + std::mem::size_of::<i64>());
779 let mut rows_of_points = points.saturating_mul(
780 std::mem::size_of::<usize>() + fields.saturating_mul(std::mem::size_of::<f64>() + 1),
781 );
782 for largest in self.largest_histograms(closing).iter().flatten() {
783 rows_of_points = rows_of_points.saturating_add(
784 points.saturating_mul(std::mem::size_of::<Option<u32>>().saturating_add(*largest)),
785 );
786 }
787 let row = fields.saturating_mul(
788 std::mem::size_of::<Option<GridSample>>() + std::mem::size_of::<RowCursor<'_>>(),
789 );
790 axis.saturating_add(layout)
791 .saturating_add(selection)
792 .saturating_add(row)
793 .saturating_add(rows_of_points.saturating_mul(2))
794 }
795
796 fn selected_points(&self, closing: &RawSeriesChunk) -> usize {
801 let spec = self.selection.output_grid.spec();
802 if self.selection.at_ms.is_some() {
803 return usize::try_from(spec.len).unwrap_or(usize::MAX);
804 }
805 if spec.step_ms <= 0 || self.selection.lookback_ms < 0 {
807 return 0;
808 }
809 let query_end = grid_end_ms(spec);
810 if query_end < spec.start_ms {
811 return 0;
812 }
813 let series = || self.chunks.iter().chain(std::iter::once(closing));
814 let endpoints = series()
815 .find_map(|chunk| chunk.time.as_buffer().first().copied())
816 .zip(
817 series()
818 .rev()
819 .find_map(|chunk| chunk.time.as_buffer().last().copied()),
820 );
821 let span = instant_candidate_span(
822 endpoints,
823 spec.start_ms..=query_end,
824 spec.step_ms,
825 self.selection.lookback_ms,
826 self.selection.offset_ms,
827 );
828 usize::try_from(span.count).unwrap_or(usize::MAX)
829 }
830
831 fn largest_histograms(&self, closing: &RawSeriesChunk) -> Vec<Option<usize>> {
836 let mut largest = vec![None; self.schema.fields.len()];
837 for chunk in self.chunks.iter().chain(std::iter::once(closing)) {
838 for (slot, field) in largest.iter_mut().zip(chunk.fields.as_slice()) {
839 if let Some(bytes) = histogram_row_bytes(field) {
840 *slot = Some(slot.unwrap_or(0).max(bytes));
841 }
842 }
843 }
844 largest
845 }
846
847 fn push(&mut self, chunk: RawSeriesChunk) -> Result<Option<EvaluatedChunk>> {
852 if let Some(open) = self.chunks.first()
853 && (open.primary_key.as_slice() != chunk.primary_key.as_slice()
854 || open.metric != chunk.metric)
855 {
856 return Err(series_changed());
859 }
860 let closing = chunk.is_last;
861 self.held = self.held.saturating_add(raw_bytes(&chunk));
862 self.chunks.push(chunk);
863 if !closing {
864 return Ok(None);
865 }
866 self.gather().map(Some)
867 }
868
869 fn gather(&mut self) -> Result<EvaluatedChunk> {
871 let chunk = self.select()?;
872 self.chunks.clear();
875 self.chunks.shrink_to_fit();
876 self.held = 0;
877 Ok(chunk)
878 }
879
880 fn select(&mut self) -> Result<EvaluatedChunk> {
882 let Some(first) = self.chunks.first() else {
883 return Err(DataFusionError::Execution(
884 "the instant selection holds no series to select".to_string(),
885 ));
886 };
887 let metric = first.metric.clone().ok_or_else(no_labels)?;
888 let time = buffered_time(&self.chunks)?;
890 let fields = buffered_fields(&self.chunks, self.schema.fields.len())?;
891 let grid = Arc::clone(&self.selection.output_grid);
892 let spec = grid.spec();
893 if let Some(at_ms) = self.selection.at_ms {
896 let timestamp_window = if self.selection.value == InstantValue::Timestamp
897 && self.selection.lookback_ms >= 0
898 {
899 let anchor = at_ms as i128;
900 let shifted = anchor - self.selection.offset_ms as i128;
901 let lower = anchor.max(shifted) - self.selection.lookback_ms as i128;
902 let upper = anchor.min(shifted);
903 if lower > upper || (lower == upper && self.selection.lookback_ms != 0) {
904 None
905 } else {
906 let effective_lookback = i64::try_from(upper - lower).ok();
907 effective_lookback.and_then(|lookback| {
908 i64::try_from(upper).ok().map(|upper| (upper, lookback))
909 })
910 }
911 } else {
912 Some((at_ms, self.selection.lookback_ms))
913 };
914 let Some((selection_at, selection_lookback)) = timestamp_window else {
915 let metric = drop_metric_name(&metric)?;
916 return no_row_chunk(&self.schema, metric);
917 };
918 let Some(index) = select_instant_at(
919 &time,
920 &fields,
921 selection_at,
922 selection_lookback,
923 if self.selection.value == InstantValue::Timestamp {
924 0
925 } else {
926 self.selection.offset_ms
927 },
928 )?
929 else {
930 return no_row_chunk(&self.schema, self.output_metric(&metric)?);
931 };
932 let grid_len = usize::try_from(spec.len).unwrap_or(usize::MAX);
933 if self.selection.value != InstantValue::Sample {
934 let indices = vec![index; grid_len];
935 let timestamps = grid
936 .timestamps()
937 .map_err(crate::grid_series::external)?
938 .to_vec();
939 return self.project(&metric, &time, &fields, &indices, ×tamps);
940 }
941 self.output.begin_series();
942 let mut cursors: Vec<RowCursor<'_>> = fields.iter().map(Samples::cursor).collect();
943 let mut row = Vec::with_capacity(fields.len());
944 for cursor in &mut cursors {
945 row.push(owned(
946 cursor
947 .at(index as usize)
948 .ok_or_else(|| missing_row(index as usize))?,
949 )?);
950 }
951 for position in 0..grid_len {
952 self.output.push_samples(position, &row)?;
953 }
954 return match self.output.finish(metric.clone())? {
955 Some(series) => EvaluatedChunk::try_new(series, true),
956 None => no_row_chunk(&self.schema, metric),
957 };
958 }
959 let (indices, timestamps) = select_instants(
960 &time,
961 &fields,
962 spec.start_ms..=grid_end_ms(spec),
963 spec.step_ms,
964 self.selection.lookback_ms,
965 self.selection.offset_ms,
966 )?;
967 if self.selection.value != InstantValue::Sample {
968 return self.project(&metric, &time, &fields, &indices, ×tamps);
969 }
970 self.output.begin_series();
971 let mut cursors: Vec<RowCursor<'_>> = fields.iter().map(Samples::cursor).collect();
974 let mut row: Vec<Option<GridSample>> = (0..fields.len()).map(|_| None).collect();
976 let mut read: Option<usize> = None;
977 for (index, timestamp) in indices.iter().zip(×tamps) {
978 let index = *index as usize;
979 let position = grid_position(&grid, *timestamp)?;
982 if read != Some(index) {
984 for (slot, cursor) in row.iter_mut().zip(&mut cursors) {
985 let sample = cursor.at(index).ok_or_else(|| missing_row(index))?;
986 *slot = owned(sample)?;
987 }
988 read = Some(index);
989 }
990 self.output.push_samples(position, &row)?;
993 }
994 match self.output.finish(metric.clone())? {
997 Some(series) => EvaluatedChunk::try_new(series, true),
998 None => no_row_chunk(&self.schema, metric),
999 }
1000 }
1001
1002 fn output_metric(&self, metric: &SeriesLabels) -> Result<SeriesLabels> {
1004 match self.selection.value {
1005 InstantValue::Timestamp => drop_metric_name(metric),
1006 InstantValue::Sample | InstantValue::InfoTimestamp => Ok(metric.clone()),
1007 }
1008 }
1009
1010 fn project(
1012 &self,
1013 metric: &SeriesLabels,
1014 time: &RawTimestamps,
1015 fields: &SeriesFields,
1016 indices: &[u64],
1017 timestamps: &[i64],
1018 ) -> Result<EvaluatedChunk> {
1019 let projected = match self.selection.value {
1020 InstantValue::Timestamp => {
1021 timestamp_of_selection(&self.schema, metric, time, fields, indices, timestamps)?
1022 }
1023 InstantValue::InfoTimestamp => {
1024 info_sample_times(&self.schema, metric, time, fields, indices, timestamps)?
1025 }
1026 InstantValue::Sample => {
1027 return Err(DataFusionError::Internal(
1028 "an instant selection of samples has no sample times to project".to_string(),
1029 ));
1030 }
1031 };
1032 match projected {
1033 Some(series) => EvaluatedChunk::try_new(series, true),
1034 None => no_row_chunk(&self.schema, self.output_metric(metric)?),
1035 }
1036 }
1037}
1038
1039#[derive(Default)]
1045struct RetainedInput {
1046 open: Option<(SeriesLabels, usize)>,
1052 series: Vec<Series>,
1054 ends: Vec<usize>,
1059 tables: HashSet<usize>,
1066 held: usize,
1071}
1072
1073impl RetainedInput {
1074 fn pending(&self, chunk: &EvaluatedChunk) -> usize {
1079 let end = if chunk.is_last {
1080 std::mem::size_of::<usize>()
1081 } else {
1082 0
1083 };
1084 let (_, tables) = unbilled_tables(&chunk.series, &self.tables);
1085 tables
1086 .saturating_add(operand_chunk_bytes(&chunk.series))
1087 .saturating_add(end)
1088 }
1089
1090 fn retain(&mut self, chunk: EvaluatedChunk, reader: Reader) -> Result<()> {
1095 let (first, last) = (
1098 chunk.series.time.first_position(),
1099 chunk.series.time.last_position(),
1100 );
1101 let metric = chunk.series.metric.clone();
1102 let end = self.open.as_ref().map_or(0, |(_, end)| *end);
1105 if let Some((open, _)) = &self.open
1106 && *open != metric
1107 {
1108 let (owner, input) = (reader.owner(), reader.input());
1109 return Err(DataFusionError::Execution(format!(
1110 "{owner} reads whole series, and {input} handed over {metric:?} before {open:?} \
1111 ended"
1112 )));
1113 }
1114 if let Some(first) = first
1115 && first < end
1116 {
1117 let (owner, input) = (reader.owner(), reader.input());
1118 return Err(DataFusionError::Execution(format!(
1119 "{owner} was handed chunks of {metric:?} by {input} that do not continue each \
1120 other: one starts at position {first}, after the series already reached {end}"
1121 )));
1122 }
1123 self.open = (!chunk.is_last).then(|| (metric, last.map_or(end, |last| last + 1)));
1124 self.enqueue(chunk);
1125 Ok(())
1126 }
1127
1128 fn ensure_closed(&self, reader: Reader) -> Result<()> {
1131 match &self.open {
1132 Some((metric, _)) => Err(DataFusionError::Execution(format!(
1133 "the input of {} ended before the last chunk of a series: {} handed over \
1134 {metric:?} without the chunk that closes it",
1135 reader.owner(),
1136 reader.input()
1137 ))),
1138 None => Ok(()),
1139 }
1140 }
1141
1142 fn enqueue(&mut self, chunk: EvaluatedChunk) {
1144 let closing = chunk.is_last;
1145 let (tables, bytes) = unbilled_tables(&chunk.series, &self.tables);
1149 self.held = self
1152 .held
1153 .saturating_add(if closing {
1154 std::mem::size_of::<usize>()
1155 } else {
1156 0
1157 })
1158 .saturating_add(operand_chunk_bytes(&chunk.series))
1159 .saturating_add(bytes);
1160 self.tables.extend(tables);
1163 self.series.push(chunk.series);
1164 if closing {
1165 self.ends.push(self.series.len());
1166 }
1167 }
1168
1169 fn boundaries(&self) -> impl Iterator<Item = std::ops::Range<usize>> + '_ {
1171 self.ends.iter().scan(0, |start, &end| {
1172 let range = *start..end;
1173 *start = end;
1174 Some(range)
1175 })
1176 }
1177
1178 fn assembly_bytes(&self, schema: &SeriesSchema) -> Option<usize> {
1192 let samples = std::mem::size_of::<Samples>();
1193 let grids = std::mem::size_of::<GridSpan>();
1194 let width = schema.fields.len();
1195 let mut bytes = 0usize;
1196 for boundary in self.boundaries() {
1197 let chunks = &self.series[boundary];
1198 let mut runs = 0usize;
1201 let mut segments = 0usize;
1202 for chunk in chunks {
1203 runs = runs.checked_add(chunk.time.runs().count())?;
1204 for field in chunk.fields.iter() {
1205 segments = segments.checked_add(field.segments().len())?;
1206 }
1207 }
1208 let descriptors = chunks
1212 .len()
1213 .checked_mul(width)?
1214 .checked_add(segments.checked_mul(3)?.checked_add(width)?)?;
1215 let axis = runs.checked_mul(
1218 grids
1219 .checked_mul(2)?
1220 .checked_add(std::mem::size_of::<usize>())?,
1221 )?;
1222 bytes = bytes
1223 .checked_add(std::mem::size_of::<Series>())?
1224 .checked_add(width.checked_mul(samples)?)?
1225 .checked_add(descriptors.checked_mul(samples)?)?
1226 .checked_add(axis)?;
1227 }
1228 Some(bytes)
1229 }
1230
1231 fn assemble(&self, schema: &SeriesSchema, reader: Reader) -> Result<Vec<Series>> {
1238 let grid = schema.eval_grid.clone().ok_or_else(|| {
1239 let (owner, input) = (reader.owner(), reader.input());
1240 DataFusionError::Execution(format!(
1241 "{owner} assembles {input} on an evaluation grid, and its schema names none"
1242 ))
1243 })?;
1244 let mut assembled = Vec::with_capacity(self.ends.len());
1245 for boundary in self.boundaries() {
1246 let chunks = &self.series[boundary];
1247 let metric = chunks
1248 .first()
1249 .map(|chunk| chunk.metric.clone())
1250 .ok_or_else(|| {
1251 let (owner, input) = (reader.owner(), reader.input());
1252 DataFusionError::Execution(format!(
1253 "{owner} closed a logical series of {input} without a chunk to assemble"
1254 ))
1255 })?;
1256 let runs = chunks
1257 .iter()
1258 .map(|chunk| chunk.time.runs().count())
1259 .fold(0usize, usize::saturating_add);
1260 let mut spans = Vec::with_capacity(runs);
1261 for chunk in chunks {
1262 for run in chunk.time.runs() {
1263 spans.push(GridSpan::new(run.position, run.len));
1264 }
1265 }
1266 let mut fields = Vec::with_capacity(schema.fields.len());
1267 for index in 0..schema.fields.len() {
1268 let mut segments = Vec::with_capacity(chunks.len());
1269 for chunk in chunks {
1270 let field = chunk.fields.get(index).ok_or_else(|| {
1271 let (owner, input) = (reader.owner(), reader.input());
1272 DataFusionError::Execution(format!(
1273 "{owner} cannot assemble {input}: a chunk of it carries {} fields, not \
1274 {}",
1275 chunk.fields.len(),
1276 schema.fields.len()
1277 ))
1278 })?;
1279 segments.push(field.clone());
1280 }
1281 fields.push(Samples::try_from_chunks(segments).map_err(series_error)?);
1282 }
1283 let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?;
1284 let time = TimeAxis::from_grid_spans(grid.clone(), spans).map_err(series_error)?;
1285 assembled.push(Series::try_new(schema, metric, time, fields).map_err(series_error)?);
1286 }
1287 Ok(assembled)
1288 }
1289
1290 fn release(&mut self) {
1292 self.open = None;
1293 self.series.clear();
1294 self.series.shrink_to_fit();
1295 self.ends.clear();
1296 self.ends.shrink_to_fit();
1297 self.tables.clear();
1300 self.tables.shrink_to_fit();
1301 self.held = 0;
1302 }
1303}
1304
1305struct BinaryRuntime {
1311 node_index: usize,
1312 evidence: Option<Arc<DuplicateEvidence>>,
1314 annotations: Option<PromqlAnnotationCollector>,
1316 kernel: PairKernel,
1318 schemas: [Arc<SeriesSchema>; 2],
1321 operands: [RetainedInput; 2],
1323 computed: bool,
1325}
1326
1327enum PairKernel {
1329 Binary(Arc<BinaryMatching>),
1331 Set(BoundSetOp),
1333 Info(InfoSelector),
1335}
1336
1337impl PairKernel {
1338 fn node(&self) -> &'static str {
1340 match self {
1341 Self::Binary(_) => "the binary node",
1342 Self::Set(_) => "the set node",
1343 Self::Info(_) => "the info node",
1344 }
1345 }
1346}
1347
1348fn side_name(index: usize) -> &'static str {
1350 match index {
1351 0 => "left",
1352 _ => "right",
1353 }
1354}
1355
1356#[derive(Clone, Copy)]
1358enum Reader {
1359 Operand { side: usize, node: &'static str },
1361 Vector,
1363}
1364
1365impl Reader {
1366 fn owner(self) -> String {
1367 match self {
1368 Self::Operand { node, .. } => node.to_string(),
1369 Self::Vector => "the vector operation".to_string(),
1370 }
1371 }
1372
1373 fn input(self) -> String {
1374 match self {
1375 Self::Operand { side, .. } => format!("its {} operand", side_name(side)),
1376 Self::Vector => "its input".to_string(),
1377 }
1378 }
1379}
1380
1381impl BinaryRuntime {
1382 fn slot(&self, field: usize) -> (usize, usize) {
1384 (self.node_index, field)
1385 }
1386
1387 fn new(
1389 kernel: PairKernel,
1390 schemas: [Arc<SeriesSchema>; 2],
1391 node_index: usize,
1392 evidence: Option<Arc<DuplicateEvidence>>,
1393 ) -> Self {
1394 Self {
1395 node_index,
1396 evidence,
1397 annotations: None,
1398 kernel,
1399 schemas,
1400 operands: [RetainedInput::default(), RetainedInput::default()],
1401 computed: false,
1402 }
1403 }
1404
1405 fn reader(&self, side: usize) -> Reader {
1407 Reader::Operand {
1408 side,
1409 node: self.kernel.node(),
1410 }
1411 }
1412
1413 fn retained_bytes(&self) -> usize {
1415 self.operands
1416 .iter()
1417 .map(|operand| operand.held)
1418 .fold(0usize, usize::saturating_add)
1419 }
1420
1421 fn assembly_bytes(&self) -> Option<usize> {
1423 let [left, right] = &self.operands;
1424 let [left_schema, right_schema] = &self.schemas;
1425 left.assembly_bytes(left_schema)?
1426 .checked_add(right.assembly_bytes(right_schema)?)
1427 }
1428
1429 fn assemble(&self) -> Result<[Vec<Series>; 2]> {
1431 let [left, right] = &self.operands;
1432 let [left_schema, right_schema] = &self.schemas;
1433 Ok([
1434 left.assemble(left_schema, self.reader(0))?,
1435 right.assemble(right_schema, self.reader(1))?,
1436 ])
1437 }
1438
1439 fn pending(&self, side: usize, chunk: &EvaluatedChunk) -> Result<usize> {
1443 self.operands
1444 .get(side)
1445 .map(|operand| operand.pending(chunk))
1446 .ok_or_else(invalid_binary_operand)
1447 }
1448
1449 fn closed(&self) -> Result<()> {
1454 for (side, operand) in self.operands.iter().enumerate() {
1455 operand.ensure_closed(self.reader(side))?;
1456 }
1457 Ok(())
1458 }
1459
1460 fn retain(&mut self, side: usize, chunk: EvaluatedChunk) -> Result<()> {
1462 let Some(schema) = self.schemas.get(side) else {
1467 return Err(invalid_binary_operand());
1468 };
1469 validate_binary_operand(schema.as_ref(), std::slice::from_ref(&chunk.series)).map_err(
1470 |error| {
1471 DataFusionError::Execution(format!(
1472 "{} rejected its {} operand: {error}",
1473 self.kernel.node(),
1474 side_name(side)
1475 ))
1476 },
1477 )?;
1478 let reader = self.reader(side);
1479 let Some(operand) = self.operands.get_mut(side) else {
1480 return Err(invalid_binary_operand());
1481 };
1482 operand.retain(chunk, reader)
1483 }
1484
1485 fn compute(&mut self, buffer: &mut NodeBuffer) -> Result<Option<Vec<Series>>> {
1494 if self.computed {
1498 return Ok(None);
1499 }
1500 self.closed()?;
1501 let [left_schema, right_schema] = &self.schemas;
1502 let retained = self.retained_bytes();
1503 let node = self.kernel.node();
1507 let assembly = self
1508 .assembly_bytes()
1509 .ok_or_else(|| reservation_overflow(node))?;
1510 buffer.grow(assembly)?;
1511 let assembled = match self.assemble() {
1512 Ok(assembled) => assembled,
1513 Err(error) => {
1514 buffer.resize(retained)?;
1518 return Err(error);
1519 }
1520 };
1521 let [left, right] = &assembled;
1522 let metrics = Arc::clone(&buffer.metrics);
1526 let output = {
1527 let _timer = metrics.timer();
1530 let mut reserve = |workspace: usize| {
1531 let bytes = retained
1532 .checked_add(assembly)
1533 .and_then(|held| held.checked_add(workspace))
1534 .ok_or_else(|| reservation_overflow(node))?;
1535 buffer.resize(bytes)
1536 };
1537 match &self.kernel {
1538 PairKernel::Binary(matching) => {
1539 let evidence = self.evidence.as_deref();
1540 binary_vectors_with_reservation(
1541 matching,
1542 left_schema,
1543 left,
1544 right_schema,
1545 right,
1546 evidence.map(|evidence| crate::vector_match::NodeEvidence {
1547 node: self.slot(0).0,
1548 evidence,
1549 }),
1550 self.annotations.as_ref(),
1551 &mut reserve,
1552 )
1553 }
1554 PairKernel::Set(set) => set_vectors_with_reservation(
1555 set.op,
1556 &set.labels,
1557 left_schema,
1558 left,
1559 right_schema,
1560 right,
1561 &mut reserve,
1562 ),
1563 PairKernel::Info(selector) => {
1566 info_with_reservation(left_schema, left, right, selector, &mut reserve)
1567 }
1568 }
1569 };
1570 let output = output?;
1574 drop(assembled);
1578 for operand in &mut self.operands {
1579 operand.release();
1580 }
1581 self.computed = true;
1582 Ok(Some(output))
1583 }
1584}
1585
1586struct VectorRuntime {
1591 op: BoundVectorOp,
1592 schema: Arc<SeriesSchema>,
1594 input: RetainedInput,
1595 merge_input: bool,
1598 computed: bool,
1600 annotations: Option<PromqlAnnotationCollector>,
1601 parameter: Option<Vec<Option<f64>>>,
1603 parameter_bytes: usize,
1605}
1606
1607impl VectorRuntime {
1608 fn try_new(op: BoundVectorOp, schema: Arc<SeriesSchema>) -> Result<Self> {
1610 let bound_grouping = match &op {
1614 BoundVectorOp::TopK { group, .. }
1615 | BoundVectorOp::LimitK { group, .. }
1616 | BoundVectorOp::CountValues { group, .. } => Some(group),
1617 _ => None,
1618 };
1619 if let Some(group) = bound_grouping {
1620 let names: Vec<&str> = match group {
1621 Grouping::By(names) | Grouping::Without(names) => {
1622 names.iter().map(AsRef::as_ref).collect()
1623 }
1624 };
1625 let grouping = match group {
1626 Grouping::By(_) => aggregate::Grouping::By(&names),
1627 Grouping::Without(_) => aggregate::Grouping::Without(&names),
1628 };
1629 match &op {
1630 BoundVectorOp::CountValues { label, .. } => {
1631 aggregate::validate_count_values(&schema, label, grouping)?
1632 }
1633 _ => aggregate::validate_vector_grouping(&schema, grouping)?,
1634 }
1635 }
1636 Ok(Self {
1637 op,
1638 schema,
1639 input: RetainedInput::default(),
1640 merge_input: false,
1641 computed: false,
1642 annotations: None,
1643 parameter: None,
1644 parameter_bytes: 0,
1645 })
1646 }
1647
1648 fn compute(&mut self, buffer: &mut NodeBuffer) -> Result<Option<Vec<Series>>> {
1655 self.compute_with_histogram_parameters(buffer, &[])
1656 }
1657
1658 fn compute_with_histogram_parameters(
1659 &mut self,
1660 buffer: &mut NodeBuffer,
1661 parameters: &[&[Option<f64>]],
1662 ) -> Result<Option<Vec<Series>>> {
1663 if self.computed {
1664 return Ok(None);
1665 }
1666 self.input.ensure_closed(Reader::Vector)?;
1667 let retained = self.input.held.saturating_add(self.parameter_bytes);
1670 let assembly = self
1671 .input
1672 .assembly_bytes(&self.schema)
1673 .ok_or_else(vector_overflow)?;
1674 buffer.grow(assembly)?;
1675 let assembled = match self.input.assemble(&self.schema, Reader::Vector) {
1676 Ok(assembled) => assembled,
1677 Err(error) => {
1678 buffer.resize(retained)?;
1679 return Err(error);
1680 }
1681 };
1682 let assembled = if self.merge_input {
1686 let rows = assembled.iter().map(|series| series.time.len()).sum();
1687 buffer.grow(merge_workspace_bytes(
1688 rows,
1689 assembled.len(),
1690 self.schema.fields.len(),
1691 ))?;
1692 merge_same_labelset(&self.schema, assembled)?
1693 } else {
1694 assembled
1695 };
1696 if !parameters.is_empty() && !matches!(self.op, BoundVectorOp::Histogram(_)) {
1697 return Err(DataFusionError::Internal(
1698 "histogram parameters supplied to non-histogram op".into(),
1699 ));
1700 }
1701 let assembled = if !parameters.is_empty() {
1702 let rows = assembled.iter().map(|series| series.time.len()).sum();
1703 buffer.grow(merge_workspace_bytes(
1704 rows,
1705 assembled.len(),
1706 self.schema.fields.len(),
1707 ))?;
1708 merge_same_labelset(&self.schema, assembled)?
1709 } else {
1710 assembled
1711 };
1712 if !parameters.is_empty() {
1713 let grid = self
1714 .schema
1715 .eval_grid
1716 .as_ref()
1717 .ok_or_else(|| DataFusionError::Internal("histogram grid missing".into()))?;
1718 if parameters
1719 .iter()
1720 .any(|values| values.len() != grid.spec().len as usize)
1721 {
1722 return Err(DataFusionError::Internal(
1723 "histogram parameter length differs from its grid".into(),
1724 ));
1725 }
1726 }
1727 if self.parameter.is_some() && !matches!(self.op, BoundVectorOp::TopK { .. }) {
1728 return Err(DataFusionError::Internal(
1729 "only topk accepts a per-point k".into(),
1730 ));
1731 }
1732 if let Some(values) = self.parameter.as_ref() {
1733 let grid = self
1734 .schema
1735 .eval_grid
1736 .as_ref()
1737 .ok_or_else(|| DataFusionError::Internal("topk grid missing".into()))?;
1738 if values.len() != grid.spec().len as usize {
1739 return Err(DataFusionError::Internal(
1740 "topk parameter length differs from its grid".into(),
1741 ));
1742 }
1743 }
1744 buffer.grow(vector_workspace_bytes(&self.op, &self.schema, &assembled))?;
1745 let metrics = Arc::clone(&buffer.metrics);
1746 let output = {
1747 let _timer = metrics.timer();
1748 if parameters.is_empty() {
1749 vector_series_with_k(
1750 &self.op,
1751 &self.schema,
1752 &assembled,
1753 self.parameter.as_deref(),
1754 self.annotations.as_ref(),
1755 )?
1756 } else {
1757 let function = match self.op {
1758 BoundVectorOp::Histogram(function) => function,
1759 _ => {
1760 return Err(DataFusionError::Internal(
1761 "parameterized histogram op mismatch".into(),
1762 ));
1763 }
1764 };
1765 let histogram_parameters = match function {
1766 HistogramFunction::Quantile(_) => HistogramParameters {
1767 quantile: Some(parameters[0]),
1768 lower: None,
1769 upper: None,
1770 },
1771 HistogramFunction::Fraction { .. } => HistogramParameters {
1772 quantile: None,
1773 lower: Some(parameters[0]),
1774 upper: Some(parameters[1]),
1775 },
1776 };
1777 evaluate_histograms_with_annotations(
1778 function,
1779 &self.schema,
1780 &assembled,
1781 Some(histogram_parameters),
1782 self.annotations.as_ref(),
1783 )?
1784 }
1785 };
1786 self.input.release();
1787 self.computed = true;
1788 Ok(Some(output))
1789 }
1790}
1791
1792fn vector_overflow() -> DataFusionError {
1794 DataFusionError::Execution(
1795 "the input of the vector operation does not fit one address space: the bytes it would \
1796 reserve overflow"
1797 .to_string(),
1798 )
1799}
1800
1801fn vector_series_with_k(
1802 op: &BoundVectorOp,
1803 schema: &Arc<SeriesSchema>,
1804 series: &[Series],
1805 values: Option<&[Option<f64>]>,
1806 collector: Option<&PromqlAnnotationCollector>,
1807) -> Result<Vec<Series>> {
1808 let grouping = |group: &Grouping| match group {
1809 Grouping::By(labels) => select::Grouping::By(labels.to_vec()),
1810 Grouping::Without(labels) => select::Grouping::Without(labels.to_vec()),
1811 };
1812 match op {
1813 BoundVectorOp::TopK { k, top, group } => {
1814 if let Some(values) = values {
1815 let grid = schema.eval_grid.as_ref().ok_or_else(|| {
1816 DataFusionError::Internal("topk output has no evaluation grid".into())
1817 })?;
1818 if values.len() != grid.spec().len as usize {
1819 return Err(DataFusionError::Internal(
1820 "topk parameter length differs from its grid".into(),
1821 ));
1822 }
1823 select::topk_at(
1824 |point| match values[point] {
1828 Some(k) => select::k_param(k, series.len()),
1829 None => Ok(None),
1830 },
1831 *top,
1832 &grouping(group),
1833 schema,
1834 series,
1835 )
1836 } else {
1837 select::topk(*k, *top, &grouping(group), schema, series)
1838 }
1839 }
1840 BoundVectorOp::LimitK { k, group } => select::limitk(*k, &grouping(group), schema, series),
1841 BoundVectorOp::LimitRatio { ratio } => select::limit_ratio(*ratio, schema, series),
1842 BoundVectorOp::Sort(order) => select::sort_instant(order, schema, series.to_vec()),
1845 BoundVectorOp::Histogram(function) => evaluate_histograms_with_annotations(
1849 *function,
1850 schema,
1851 &merge_same_labelset(schema, series.to_vec())?,
1852 None,
1853 collector,
1854 ),
1855 BoundVectorOp::CountValues { label, group } => {
1856 let (by, labels) = match group {
1857 Grouping::By(labels) => (true, labels),
1858 Grouping::Without(labels) => (false, labels),
1859 };
1860 let labels: Vec<&str> = labels.iter().map(|label| &**label).collect();
1861 let grouping = if by {
1862 aggregate::Grouping::By(&labels)
1863 } else {
1864 aggregate::Grouping::Without(&labels)
1865 };
1866 aggregate::count_values(schema, series, label, grouping)
1867 }
1868 BoundVectorOp::Absent { labels } => Ok(select::absent(schema, series, labels.clone())?
1869 .into_iter()
1870 .collect()),
1871 }
1872}
1873
1874fn vector_workspace_bytes(op: &BoundVectorOp, schema: &SeriesSchema, series: &[Series]) -> usize {
1888 let fields = schema.fields.len();
1889 match op {
1890 BoundVectorOp::Sort(order) => {
1891 let rebuilds = matches!(order, SortOrder::Asc | SortOrder::Desc);
1892 return series.iter().fold(0usize, |total, item| {
1893 let floats = if rebuilds
1894 && item
1895 .fields
1896 .iter()
1897 .any(|field| histogram_row_bytes(field).is_some())
1898 {
1899 item.time.len().saturating_mul(std::mem::size_of::<f64>())
1900 } else {
1901 0
1902 };
1903 total
1904 .saturating_add(std::mem::size_of::<(f64, Series)>())
1905 .saturating_add(floats)
1906 });
1907 }
1908 BoundVectorOp::Absent { .. } => {
1909 let points = schema.eval_grid.as_ref().map_or(0, |grid| {
1910 usize::try_from(grid.spec().len).unwrap_or(usize::MAX)
1911 });
1912 return points.saturating_mul(fields.saturating_mul(1 + std::mem::size_of::<f64>()));
1913 }
1914 BoundVectorOp::Histogram(_) => {
1915 let rows: usize = series.iter().map(|item| item.time.len()).sum();
1916 let label = std::mem::size_of::<(Arc<str>, Arc<str>)>();
1917 let row = std::mem::size_of::<(f64, f64)>() + fields * std::mem::size_of::<f64>();
1918 let per_series = std::mem::size_of::<(f64, &Series)>()
1919 + fields * std::mem::size_of::<RowCursor<'_>>();
1920 return series.iter().fold(
1921 merge_workspace_bytes(rows, series.len(), fields),
1922 |total, item| {
1923 total
1924 .saturating_add(per_series)
1925 .saturating_add((item.metric.tags().len() + 1).saturating_mul(label))
1926 .saturating_add(item.time.len().saturating_mul(row))
1927 },
1928 );
1929 }
1930 BoundVectorOp::CountValues { .. } => {
1931 let label = std::mem::size_of::<(Arc<str>, Arc<str>)>();
1932 let value = 24;
1935 let group = std::mem::size_of::<Vec<f64>>()
1936 + fields * std::mem::size_of::<f64>()
1937 + std::mem::size_of::<Series>()
1938 + fields * std::mem::size_of::<Samples>();
1939 return series.iter().fold(0usize, |total, item| {
1940 let labels = 2 * (item.metric.tags().len() + 2) * label + value;
1941 let samples = item.time.len().saturating_mul(fields);
1942 total.saturating_add(samples.saturating_mul(group + labels))
1943 });
1944 }
1945 BoundVectorOp::TopK { .. }
1946 | BoundVectorOp::LimitK { .. }
1947 | BoundVectorOp::LimitRatio { .. } => {}
1948 }
1949 let row = std::mem::size_of::<(usize, usize)>()
1950 + std::mem::size_of::<(usize, usize, f64)>()
1951 + fields * std::mem::size_of::<f64>();
1952 let per_series = 2 * std::mem::size_of::<usize>()
1953 + std::mem::size_of::<Vec<(usize, usize)>>()
1954 + std::mem::size_of::<RowCursor<'_>>()
1955 + std::mem::size_of::<Series>()
1956 + fields * std::mem::size_of::<Samples>();
1957 let label = std::mem::size_of::<(Arc<str>, Arc<str>)>();
1958 series.iter().fold(0usize, |total, item| {
1959 let rows = item.time.len();
1960 let labels = item.metric.tags().len() + 1;
1961 let histograms = item
1962 .fields
1963 .iter()
1964 .filter_map(histogram_row_bytes)
1965 .fold(0usize, |bytes, widest| {
1966 bytes.saturating_add(widest.saturating_mul(rows))
1967 });
1968 total
1969 .saturating_add(rows.saturating_mul(row))
1970 .saturating_add(per_series)
1971 .saturating_add(labels.saturating_mul(label))
1972 .saturating_add(histograms)
1973 })
1974}
1975
1976#[derive(Clone, Copy, Debug)]
1978enum BroadcastOp {
1979 Arithmetic(ArithmeticOp),
1981 Compare(Comparison),
1983}
1984
1985enum BroadcastScalar {
1987 Literal(ScalarOperand),
1989 Dynamic {
1993 left: bool,
1995 value: Option<Series>,
1996 },
1997}
1998
1999struct BroadcastRuntime {
2005 scalar: BroadcastScalar,
2007 vector_left: bool,
2009 op: BroadcastOp,
2011 sample_schema: Arc<SeriesSchema>,
2014 scalar_bytes: usize,
2016 annotations: Option<PromqlAnnotationCollector>,
2017}
2018
2019struct ParameterizedMapRuntime {
2022 op: ParameterizedOp,
2023 schema: Arc<SeriesSchema>,
2024 input_literal: Option<f64>,
2028 input_produced: bool,
2029 literals: Vec<Option<f64>>,
2031 values: Vec<Option<Series>>,
2033 parameter_bytes: usize,
2035}
2036
2037impl ParameterizedMapRuntime {
2038 fn ready(&self) -> bool {
2039 self.values.iter().all(Option::is_some)
2040 }
2041
2042 fn apply(&self, chunk: &EvaluatedChunk) -> Result<Option<Series>> {
2044 let value = |index: usize| {
2045 self.values
2046 .get(index)
2047 .and_then(Option::as_ref)
2048 .ok_or_else(|| {
2049 DataFusionError::Execution(
2050 "the map was applied before its parameters arrived".to_string(),
2051 )
2052 })
2053 };
2054 let function = match self.op {
2055 ParameterizedOp::Round => ParameterizedMath::Round {
2056 to_nearest: value(0)?,
2057 },
2058 ParameterizedOp::Clamp => ParameterizedMath::Clamp {
2059 min: value(0)?,
2060 max: value(1)?,
2061 },
2062 ParameterizedOp::ClampMin => ParameterizedMath::ClampMin { min: value(0)? },
2063 ParameterizedOp::ClampMax => ParameterizedMath::ClampMax { max: value(0)? },
2064 ParameterizedOp::MaxOf => ParameterizedMath::MaxOf { other: value(0)? },
2065 ParameterizedOp::MinOf => ParameterizedMath::MinOf { other: value(0)? },
2066 };
2067 map_math_with_parameters(&self.schema, &chunk.series, function)
2068 }
2069}
2070
2071impl BroadcastRuntime {
2072 fn awaits_scalar(&self) -> bool {
2074 matches!(self.scalar, BroadcastScalar::Dynamic { value: None, .. })
2075 }
2076
2077 fn drops_labels(&self) -> bool {
2085 match self.op {
2086 BroadcastOp::Arithmetic(_) | BroadcastOp::Compare(Comparison::Bool(_)) => true,
2087 BroadcastOp::Compare(Comparison::Filter(_)) => false,
2088 }
2089 }
2090
2091 fn record_dropped_histograms(&self, dropped_histogram: bool, op: impl std::fmt::Display) {
2096 if dropped_histogram && let Some(collector) = &self.annotations {
2097 collector.record_info(format!(
2098 "{op}: dropped native histogram samples because this binary operation is not supported for native histograms"
2099 ));
2100 }
2101 }
2102
2103 fn output_metric(&self, metric: &SeriesLabels) -> Result<SeriesLabels> {
2107 if self.drops_labels() {
2108 drop_metric_name(metric)
2109 } else {
2110 Ok(metric.clone())
2111 }
2112 }
2113
2114 fn apply(&self, chunk: &EvaluatedChunk) -> Result<Option<Series>> {
2120 let output = match &self.scalar {
2121 BroadcastScalar::Literal(operand) => match self.op {
2122 BroadcastOp::Arithmetic(op) => {
2123 let (output, dropped_histogram) =
2124 map_arithmetic_literal(&self.sample_schema, &chunk.series, op, *operand)?;
2125 self.record_dropped_histograms(dropped_histogram, op);
2126 Some(output)
2127 }
2128 BroadcastOp::Compare(comparison) => {
2129 let (output, dropped_histogram) = map_compare_literal(
2130 &self.sample_schema,
2131 &chunk.series,
2132 comparison,
2133 *operand,
2134 )?;
2135 self.record_dropped_histograms(dropped_histogram, comparison);
2136 output
2137 }
2138 },
2139 BroadcastScalar::Dynamic { left, value } => {
2140 let value = value.as_ref().ok_or_else(|| {
2141 DataFusionError::Execution(
2142 "the binary node broadcast a scalar that has not arrived".to_string(),
2143 )
2144 })?;
2145 let operand = if *left {
2146 ScalarSeriesOperand::Left(value)
2147 } else {
2148 ScalarSeriesOperand::Right(value)
2149 };
2150 match self.op {
2151 BroadcastOp::Arithmetic(op) => {
2152 if !is_float_series(&chunk.series) {
2153 return Err(DataFusionError::NotImplemented(
2154 "dynamic scalar arithmetic does not support histogram or mixed samples"
2155 .into(),
2156 ));
2157 }
2158 map_arithmetic_series(&self.sample_schema, &chunk.series, op, operand)?
2159 }
2160 BroadcastOp::Compare(comparison) => {
2161 let (output, dropped_histogram) = map_compare_series(
2162 &self.sample_schema,
2163 &chunk.series,
2164 comparison,
2165 operand,
2166 )?;
2167 self.record_dropped_histograms(dropped_histogram, comparison);
2168 output
2169 }
2170 }
2171 }
2172 };
2173 match output {
2174 Some(output) => Ok(Some(output)),
2175 None if chunk.is_last => {
2176 let metric = self.output_metric(&chunk.series.metric)?;
2177 no_row_series(&self.sample_schema, &chunk.series, metric).map(Some)
2178 }
2179 None => Ok(None),
2180 }
2181 }
2182}
2183
2184fn buffered_time(chunks: &[RawSeriesChunk]) -> Result<RawTimestamps> {
2186 let len = chunks.iter().map(|chunk| chunk.time.len()).sum();
2187 let mut timestamps: Vec<i64> = Vec::with_capacity(len);
2188 for chunk in chunks {
2189 timestamps.extend_from_slice(chunk.time.as_buffer());
2190 }
2191 RawTimestamps::try_new(ScalarBuffer::from(timestamps)).map_err(series_error)
2192}
2193
2194fn buffered_fields(chunks: &[RawSeriesChunk], fields: usize) -> Result<SeriesFields> {
2198 let mut per_field: Vec<Vec<Samples>> = vec![Vec::with_capacity(chunks.len()); fields];
2199 for chunk in chunks {
2200 for (field, slot) in chunk.fields.iter().zip(&mut per_field) {
2201 slot.push(field.clone());
2202 }
2203 }
2204 let fields = per_field
2205 .into_iter()
2206 .map(|chunks| Samples::try_from_chunks(chunks).map_err(series_error))
2207 .collect::<Result<Vec<_>>>()?;
2208 SeriesFields::try_from_vec(fields).map_err(series_error)
2209}
2210
2211fn histogram_row_bytes(field: &Samples) -> Option<usize> {
2214 let holds_histograms = field.segments().iter().any(|segment| {
2215 matches!(
2216 segment.dense(),
2217 Some(DenseSamplesRef::Histogram(_) | DenseSamplesRef::Mixed(_))
2218 )
2219 });
2220 if !holds_histograms {
2221 return None;
2222 }
2223 Some(
2224 field
2225 .iter()
2226 .filter_map(|sample| match sample {
2227 SampleRef::Histogram(view) => Some(histogram_bytes(&view)),
2228 _ => None,
2229 })
2230 .fold(0, usize::max),
2231 )
2232}
2233
2234fn histogram_bytes(view: &HistogramView<'_>) -> usize {
2237 let custom = view
2238 .custom_values
2239 .len()
2240 .saturating_mul(std::mem::size_of::<f64>());
2241 let sides = [view.positive, view.negative]
2242 .iter()
2243 .map(|side| {
2244 side.span_offsets
2245 .len()
2246 .saturating_mul(2)
2247 .saturating_mul(std::mem::size_of::<i32>())
2248 .saturating_add(
2249 side.buckets
2250 .len()
2251 .saturating_mul(std::mem::size_of::<f64>()),
2252 )
2253 })
2254 .fold(0usize, usize::saturating_add);
2255 HISTOGRAM_ROW_HEADER_BYTES
2256 .saturating_add(custom)
2257 .saturating_add(sides)
2258}
2259
2260const HISTOGRAM_ROW_HEADER_BYTES: usize =
2265 7 * std::mem::size_of::<i64>() + 7 * std::mem::size_of::<u32>();
2266
2267fn grid_end_ms(spec: GridSpec) -> i64 {
2271 (i128::from(spec.start_ms) + i128::from(spec.step_ms) * (i128::from(spec.len) - 1)) as i64
2272}
2273
2274fn grid_position(grid: &EvalGrid, timestamp: i64) -> Result<usize> {
2279 let spec = grid.spec();
2280 if spec.step_ms > 0
2283 && let Some(offset) = timestamp.checked_sub(spec.start_ms)
2284 && offset >= 0
2285 {
2286 let (position, remainder) = (offset / spec.step_ms, offset % spec.step_ms);
2287 if remainder == 0 && (position as u64) < spec.len {
2288 return Ok(position as usize);
2289 }
2290 }
2291 let offset = i128::from(timestamp) - i128::from(spec.start_ms);
2292 let step = i128::from(spec.step_ms);
2293 let position = offset.div_euclid(step);
2294 if offset.rem_euclid(step) != 0 || position < 0 || position >= i128::from(spec.len) {
2295 return Err(DataFusionError::Execution(format!(
2296 "the instant selection reported the timestamp {timestamp}ms, which is not a point of \
2297 its grid {spec:?}"
2298 )));
2299 }
2300 Ok(position as usize)
2301}
2302
2303fn ensure_grid(grid: Option<&EvalGrid>, time: &TimeAxis) -> Result<()> {
2305 if grid.is_none_or(|grid| {
2306 time.grid()
2307 .is_none_or(|actual| actual.spec() != grid.spec())
2308 }) {
2309 return Err(DataFusionError::Execution(
2310 "vector() input does not match its evaluation grid".to_string(),
2311 ));
2312 }
2313 Ok(())
2314}
2315
2316fn scalar_schema(grid: Arc<EvalGrid>) -> SeriesSchema {
2318 SeriesSchema {
2319 fields: Arc::from([FieldSpec {
2320 name: "value".into(),
2321 }]),
2322 eval_grid: Some(grid),
2323 }
2324}
2325
2326fn grid_chunk_bytes(grid: &EvalGrid) -> Result<usize> {
2328 let len = usize::try_from(grid.spec().len).map_err(|_| {
2329 DataFusionError::Execution("scalar grid length does not fit memory size".into())
2330 })?;
2331 std::mem::size_of::<EvaluatedChunk>()
2332 .checked_add(std::mem::size_of::<Float64Array>())
2333 .and_then(|bytes| {
2334 len.checked_mul(std::mem::size_of::<f64>())
2335 .and_then(|values| bytes.checked_add(values))
2336 })
2337 .ok_or_else(|| DataFusionError::Execution("scalar allocation size overflow".into()))
2338}
2339
2340fn map_workspace_bytes(ops: &[MapOp], series: &Series) -> Result<usize> {
2346 let (mut previous, mut bound) = (0usize, 0usize);
2347 let mut first = true;
2348 for op in ops {
2349 let workspace = match op {
2350 MapOp::Label(_) => continue,
2351 MapOp::Math(_) if !first || is_float_series(series) => mapped_workspace_bytes(series)?,
2352 _ if first => built_series_workspace_bytes(series)?,
2353 _ => built_workspace_bytes(series.time.len(), series.time.len(), series.fields.len())?,
2354 };
2355 let live = previous
2356 .checked_add(workspace)
2357 .ok_or_else(|| workspace_overflow(series.time.len(), series.fields.len()))?;
2358 bound = bound.max(live);
2359 previous = workspace;
2360 first = false;
2361 }
2362 Ok(bound)
2363}
2364
2365fn mapped_workspace_bytes(series: &Series) -> Result<usize> {
2373 let segments = series
2374 .fields
2375 .iter()
2376 .map(|field| field.segments().len())
2377 .fold(0usize, usize::saturating_add);
2378 let bound = || {
2379 let mut bytes = assembly_bytes(series.fields.len(), segments, &series.metric)?;
2380 for field in series.fields.iter() {
2381 let row = histogram_row_bytes(field).map_or(std::mem::size_of::<f64>(), |histogram| {
2382 histogram.max(std::mem::size_of::<f64>())
2383 });
2384 for segment in field.segments() {
2385 bytes = segment
2386 .len()
2387 .checked_mul(row)?
2388 .checked_add(64 + BUFFER_HEADER_BYTES)?
2389 .checked_add(bytes)?;
2390 }
2391 }
2392 Some(bytes)
2393 };
2394 bound().ok_or_else(|| workspace_overflow(series.time.len(), series.fields.len()))
2395}
2396
2397fn built_series_workspace_bytes(series: &Series) -> Result<usize> {
2401 let fields = series.fields.len();
2402 let rows = built_workspace_bytes(series.time.len(), series.time.runs().count(), fields)?;
2403 assembly_bytes(fields, fields, &series.metric)
2404 .and_then(|assembly| assembly.checked_add(rows))
2405 .ok_or_else(|| workspace_overflow(series.time.len(), fields))
2406}
2407
2408fn assembly_bytes(fields: usize, segments: usize, metric: &SeriesLabels) -> Option<usize> {
2414 let descriptors = segments
2415 .checked_mul(6)?
2416 .checked_add(fields.checked_mul(16)?)?
2417 .checked_add(8)?
2418 .checked_mul(std::mem::size_of::<Samples>())?;
2419 descriptors
2420 .checked_add(std::mem::size_of_val(metric.tags()))?
2421 .checked_add(BUFFER_HEADER_BYTES + std::mem::size_of::<Series>())
2422}
2423
2424const BUFFER_HEADER_BYTES: usize = 64;
2426
2427fn built_workspace_bytes(rows: usize, runs: usize, fields: usize) -> Result<usize> {
2436 let cost = |kept: usize, split: usize| {
2437 let capacity = kept.checked_mul(2)?.checked_add(4)?;
2438 let indices = capacity.checked_mul(std::mem::size_of::<usize>())?;
2439 let validity = kept.div_ceil(8).checked_mul(2)?.checked_add(64)?;
2440 let field = capacity
2441 .checked_mul(std::mem::size_of::<f64>())?
2442 .checked_add(validity)?;
2443 let spans = split
2444 .checked_mul(2 * std::mem::size_of::<GridSpan>() + 2 * std::mem::size_of::<usize>())?;
2445 fields
2446 .checked_mul(field)?
2447 .checked_add(indices)?
2448 .checked_add(spans)
2449 };
2450 let runs = runs.min(rows);
2451 let fragmented = rows.checked_add(runs).map(|total| total.div_ceil(2));
2452 fragmented
2453 .and_then(|fragmented| Some(cost(rows, runs)?.max(cost(fragmented, fragmented)?)))
2454 .ok_or_else(|| workspace_overflow(rows, fields))
2455}
2456
2457fn workspace_overflow(rows: usize, fields: usize) -> DataFusionError {
2458 DataFusionError::Execution(format!(
2459 "the workspace for {rows} rows of {fields} fields does not fit one address space"
2460 ))
2461}
2462
2463fn window_workspace_bytes(
2473 window: &RangeEvaluator,
2474 last_ts: Option<i64>,
2475 last: bool,
2476 fields: &SeriesFields,
2477 metric: &SeriesLabels,
2478) -> Result<usize> {
2479 let rows = window.output_rows_bound(last_ts, last);
2480 let width = window.output_schema().fields.len();
2481 let floats = assembly_bytes(width, width, metric)
2482 .ok_or_else(|| workspace_overflow(rows, width))?
2483 .checked_add(built_workspace_bytes(rows, rows, width)?)
2484 .ok_or_else(|| workspace_overflow(rows, width))?;
2485 if !window.yields_histograms() {
2486 return Ok(floats);
2487 }
2488 let retained = window
2489 .widest_retained_histogram()
2490 .map(|heap| heap.saturating_add(HISTOGRAM_ROW_HEADER_BYTES));
2491 let incoming = fields.iter().filter_map(histogram_row_bytes).max();
2492 let Some(widest) = retained.max(incoming) else {
2493 return Ok(floats);
2494 };
2495 let histograms = || {
2496 let row = widest
2497 .checked_mul(2)?
2498 .checked_add(2 * std::mem::size_of::<Option<u32>>() + std::mem::size_of::<u32>() + 1)?;
2499 let in_flight = widest.checked_add(std::mem::size_of::<FloatHistogram>())?;
2500 rows.checked_mul(row)?
2501 .checked_add(in_flight)?
2502 .checked_mul(width)?
2503 .checked_add(floats)
2504 };
2505 histograms().ok_or_else(|| {
2506 DataFusionError::Execution(format!(
2507 "the histogram workspace for {rows} rows of {width} fields does not fit one address \
2508 space"
2509 ))
2510 })
2511}
2512
2513fn last_sample_ms(chunk: &NativeChunk) -> Result<Option<i64>> {
2515 match chunk {
2516 NativeChunk::Raw(chunk) => Ok(chunk.time.as_buffer().last().copied()),
2517 NativeChunk::Evaluated(chunk) => Ok(last_series_ms(&chunk.series)),
2518 NativeChunk::AggregateState(_) => Err(DataFusionError::Execution(
2519 "an aggregate state chunk reached a node that reads values or samples".to_string(),
2520 )),
2521 }
2522}
2523
2524fn last_series_ms(series: &Series) -> Option<i64> {
2526 let row = series.time.len().checked_sub(1)?;
2527 series.time.timestamp(row)
2528}
2529
2530fn scalar_chunk(grid: Arc<EvalGrid>, value: f64) -> Result<EvaluatedChunk> {
2532 scalar_chunk_on(&scalar_schema(Arc::clone(&grid)), grid, value)
2533}
2534
2535fn scalar_chunk_on(
2537 schema: &SeriesSchema,
2538 grid: Arc<EvalGrid>,
2539 value: f64,
2540) -> Result<EvaluatedChunk> {
2541 let len = grid.spec().len as usize;
2542 let time = GridRange::try_new(grid, 0, len).map_err(series_error)?;
2543 let values = Float64Array::from(vec![value; len]);
2544 let fields = SeriesFields::one(Samples::from_float(values));
2545 let metric = SeriesLabels::try_new(None, Vec::new()).map_err(series_error)?;
2546 let series =
2547 Series::try_new(schema, metric, TimeAxis::Grid(time), fields).map_err(series_error)?;
2548 EvaluatedChunk::try_new(series, true)
2549}
2550
2551fn no_row_chunk(schema: &SeriesSchema, metric: SeriesLabels) -> Result<EvaluatedChunk> {
2556 let grid = schema.eval_grid.clone().ok_or_else(|| {
2557 DataFusionError::Execution(
2558 "an instant selection produces an evaluated chunk, which is addressed on a grid"
2559 .to_string(),
2560 )
2561 })?;
2562 let empty = Samples::from_float(Float64Array::from(Vec::<f64>::new()));
2563 let fields =
2564 SeriesFields::try_from_vec(vec![empty; schema.fields.len()]).map_err(series_error)?;
2565 let time = GridRange::try_new(grid, 0, 0).map_err(series_error)?;
2566 let series =
2567 Series::try_new(schema, metric, TimeAxis::Grid(time), fields).map_err(series_error)?;
2568 EvaluatedChunk::try_new(series, true)
2569}
2570
2571struct RuntimeNode {
2573 metrics: Arc<NodeMetrics>,
2574 op: RuntimeOp,
2575}
2576
2577enum RuntimeOp {
2579 Input(InputId),
2580 Scalar,
2581 ScalarOf {
2582 input: Box<RuntimeNode>,
2583 input_schema: Arc<SeriesSchema>,
2584 grid: Arc<EvalGrid>,
2585 retained: RetainedInput,
2586 produced: bool,
2587 state: NodeState,
2588 },
2589 EvalTime {
2591 grid: Arc<EvalGrid>,
2592 date: Option<DateFunction>,
2593 produced: bool,
2594 state: NodeState,
2595 },
2596 VectorOf {
2599 input: Box<RuntimeNode>,
2600 literal: Option<f64>,
2601 produced: bool,
2602 schema: Arc<SeriesSchema>,
2603 state: NodeState,
2604 },
2605 Instant {
2606 input: Box<RuntimeNode>,
2607 instant: InstantRuntime,
2608 state: NodeState,
2609 },
2610 Merge {
2611 input: Box<RuntimeNode>,
2612 merge: Option<MergeInput>,
2613 state: NodeState,
2614 },
2615 Window {
2616 input: Box<RuntimeNode>,
2617 window: Option<RangeEvaluator>,
2619 merge: Option<MergeInput>,
2620 state: NodeState,
2621 },
2622 Map {
2623 input: Box<RuntimeNode>,
2624 map: MapRuntime,
2625 state: NodeState,
2626 },
2627 ParameterizedMap {
2628 input: Box<RuntimeNode>,
2629 parameters: Vec<RuntimeNode>,
2630 map: ParameterizedMapRuntime,
2631 state: NodeState,
2632 },
2633 Timestamp {
2634 input: Box<RuntimeNode>,
2635 schema: Arc<SeriesSchema>,
2636 state: NodeState,
2637 },
2638 Binary {
2639 left: Box<RuntimeNode>,
2640 right: Box<RuntimeNode>,
2641 binary: BinaryRuntime,
2642 state: NodeState,
2643 },
2644 Broadcast {
2645 left: Box<RuntimeNode>,
2646 right: Box<RuntimeNode>,
2647 broadcast: BroadcastRuntime,
2648 state: NodeState,
2649 },
2650 Aggregate {
2651 input: Box<RuntimeNode>,
2652 aggregate: AggregateRuntime,
2653 state: NodeState,
2654 },
2655 Vector {
2656 input: Box<RuntimeNode>,
2657 vector: VectorRuntime,
2658 state: NodeState,
2659 },
2660 ParameterizedTopK {
2661 input: Box<RuntimeNode>,
2662 parameter: Option<Box<RuntimeNode>>,
2664 vector: VectorRuntime,
2665 state: NodeState,
2666 },
2667 ParameterizedAggregate {
2668 input: Box<RuntimeNode>,
2669 parameter: Option<Box<RuntimeNode>>,
2671 aggregate: AggregateRuntime,
2672 state: NodeState,
2673 },
2674 ParameterizedHistogram {
2675 input: Box<RuntimeNode>,
2676 parameters: Vec<Option<RuntimeNode>>,
2678 literals: Vec<Option<f64>>,
2679 vector: VectorRuntime,
2680 values: Vec<Option<Vec<Option<f64>>>>,
2681 parameter_bytes: Vec<usize>,
2682 state: NodeState,
2683 },
2684}
2685
2686struct NodeState {
2690 queued: VecDeque<(NativeChunk, usize)>,
2691 queued_tables: usize,
2692 buffer: NodeBuffer,
2693}
2694
2695#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2701enum LeafKind {
2702 Raw,
2703 Evaluated,
2704 AggregateState,
2705}
2706
2707impl LeafKind {
2708 fn of(output: &NativeType) -> Result<Self> {
2710 match output {
2711 NativeType::Samples(schema) if schema.eval_grid.is_some() => Ok(Self::Evaluated),
2712 NativeType::Samples(_) => Ok(Self::Raw),
2713 NativeType::AggregateState(_) => Ok(Self::AggregateState),
2714 NativeType::Scalar(_) => Err(DataFusionError::Execution(
2715 "an input leaf cannot be bound to a scalar".to_string(),
2716 )),
2717 }
2718 }
2719
2720 fn describe(self) -> &'static str {
2722 match self {
2723 Self::Raw => "raw samples",
2724 Self::Evaluated => "an evaluated series",
2725 Self::AggregateState => "aggregate state",
2726 }
2727 }
2728
2729 fn accepts(self, chunk: &NativeChunk) -> bool {
2731 matches!(
2732 (self, chunk),
2733 (Self::Raw, NativeChunk::Raw(_))
2734 | (Self::Evaluated, NativeChunk::Evaluated(_))
2735 | (Self::AggregateState, NativeChunk::AggregateState(_))
2736 )
2737 }
2738}
2739
2740struct InputSlot {
2742 source_index: usize,
2743 kind: LeafKind,
2744 open_source_series: bool,
2746 open_queued_series: bool,
2754 state: NodeState,
2755}
2756
2757impl InputSlot {
2758 fn ends_open(&self) -> bool {
2760 self.open_source_series || self.open_queued_series
2761 }
2762}
2763
2764pub struct NativeExecutionState {
2767 live: Option<LiveExecution>,
2768}
2769
2770struct LiveExecution {
2771 root: RuntimeNode,
2772 inputs: Vec<InputSlot>,
2773 scalar_root: Option<(Arc<EvalGrid>, f64, NodeState)>,
2775}
2776
2777impl NodeState {
2778 fn context(&self, error: DataFusionError) -> DataFusionError {
2783 let name = self.buffer.reservation.consumer().name();
2784 match error {
2785 DataFusionError::Execution(message) => {
2786 DataFusionError::Execution(format!("{name}: {message}"))
2787 }
2788 other => DataFusionError::Context(name.to_string(), Box::new(other)),
2789 }
2790 }
2791
2792 pub(super) fn new(
2793 name: impl Into<String>,
2794 metrics: Arc<NodeMetrics>,
2795 pool: &Arc<dyn MemoryPool>,
2796 ) -> Self {
2797 let name = name.into();
2798 Self {
2799 queued: VecDeque::new(),
2800 queued_tables: 0,
2801 buffer: NodeBuffer::new(name, metrics, pool),
2802 }
2803 }
2804}
2805
2806const NATIVE_STACK_RED_ZONE: usize = 512 * 1024;
2813
2814const NATIVE_STACK_GROWTH: usize = 4 * 1024 * 1024;
2816
2817impl RuntimeNode {
2818 fn build(
2821 node: &NativeNode,
2822 pool: &Arc<dyn MemoryPool>,
2823 inputs: &mut Vec<InputSlot>,
2824 binary_before: &mut usize,
2825 location: String,
2826 duplicate_evidence: Option<Arc<DuplicateEvidence>>,
2827 sources: &SourceFacts,
2828 ) -> Result<Self> {
2829 stacker::maybe_grow(NATIVE_STACK_RED_ZONE, NATIVE_STACK_GROWTH, || {
2830 Self::build_within_stack(
2831 node,
2832 pool,
2833 inputs,
2834 binary_before,
2835 location,
2836 duplicate_evidence,
2837 sources,
2838 )
2839 })
2840 }
2841
2842 fn build_within_stack(
2843 node: &NativeNode,
2844 pool: &Arc<dyn MemoryPool>,
2845 inputs: &mut Vec<InputSlot>,
2846 binary_before: &mut usize,
2847 location: String,
2848 duplicate_evidence: Option<Arc<DuplicateEvidence>>,
2849 sources: &SourceFacts,
2850 ) -> Result<Self> {
2851 let metrics = Arc::new(NodeMetrics::default());
2852 let op = match &node.expr {
2853 NativeExpr::Input(bound) => {
2854 if bound.ordering == SeriesOrdering::Interleaved {
2855 return Err(DataFusionError::NotImplemented(format!(
2856 "the native runtime does not accept {:?} input ordering",
2857 bound.ordering
2858 )));
2859 }
2860 let id = InputId(inputs.len());
2861 inputs.push(InputSlot {
2862 source_index: bound.source_index,
2863 kind: LeafKind::of(&node.output)?,
2864 open_source_series: false,
2865 open_queued_series: false,
2866 state: NodeState::new(
2867 format!(
2868 "native.input at {location} (source_index={})",
2869 bound.source_index
2870 ),
2871 Arc::clone(&metrics),
2872 pool,
2873 ),
2874 });
2875 RuntimeOp::Input(id)
2876 }
2877 NativeExpr::Scalar(_) => RuntimeOp::Scalar,
2878 NativeExpr::ScalarOf { input } => {
2879 let input_schema = input.output.samples().cloned().ok_or_else(|| {
2880 DataFusionError::Execution("scalar() consumes non-sample input".to_string())
2881 })?;
2882 if input_schema.fields.len() != 1 {
2883 return Err(DataFusionError::NotImplemented(
2884 "the native runtime does not execute multi-field scalar()".into(),
2885 ));
2886 }
2887 let grid = input_schema.eval_grid.clone().ok_or_else(|| {
2888 DataFusionError::Execution("scalar() consumes raw samples".to_string())
2889 })?;
2890 let child = Self::build(
2891 input,
2892 pool,
2893 inputs,
2894 binary_before,
2895 format!("{location}.input"),
2896 duplicate_evidence.clone(),
2897 sources,
2898 )?;
2899 RuntimeOp::ScalarOf {
2900 input: Box::new(child),
2901 input_schema,
2902 grid,
2903 retained: RetainedInput::default(),
2904 produced: false,
2905 state: NodeState::new(
2906 format!("native.scalar_of at {location}"),
2907 Arc::clone(&metrics),
2908 pool,
2909 ),
2910 }
2911 }
2912 NativeExpr::EvalTime { date } => {
2913 let NativeType::Scalar(grid) = &node.output else {
2914 return Err(DataFusionError::Execution(
2915 "the evaluation time does not produce a scalar".to_string(),
2916 ));
2917 };
2918 RuntimeOp::EvalTime {
2919 grid: Arc::clone(grid),
2920 date: *date,
2921 produced: false,
2922 state: NodeState::new(
2923 format!("native.time at {location}"),
2924 Arc::clone(&metrics),
2925 pool,
2926 ),
2927 }
2928 }
2929 NativeExpr::VectorOf { input } => {
2930 let schema = node.output.samples().cloned().ok_or_else(|| {
2931 DataFusionError::Execution("vector() does not produce samples".to_string())
2932 })?;
2933 let literal = match &input.expr {
2934 NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
2935 _ => None,
2936 };
2937 let child = Self::build(
2938 input,
2939 pool,
2940 inputs,
2941 binary_before,
2942 format!("{location}.input"),
2943 duplicate_evidence.clone(),
2944 sources,
2945 )?;
2946 RuntimeOp::VectorOf {
2947 input: Box::new(child),
2948 literal,
2949 produced: false,
2950 schema,
2951 state: NodeState::new(
2952 format!("native.vector_of at {location}"),
2953 Arc::clone(&metrics),
2954 pool,
2955 ),
2956 }
2957 }
2958 NativeExpr::Instant { input, op } => {
2959 let child = Self::build(
2960 input,
2961 pool,
2962 inputs,
2963 binary_before,
2964 format!("{location}.input"),
2965 duplicate_evidence.clone(),
2966 sources,
2967 )?;
2968 let input_schema = input.output.samples().cloned().ok_or_else(|| {
2969 DataFusionError::Execution(
2970 "instant selection consumes non-sample input".to_string(),
2971 )
2972 })?;
2973 RuntimeOp::Instant {
2974 input: Box::new(child),
2975 instant: InstantRuntime::try_new(&input_schema, op)?,
2976 state: {
2977 NodeState::new(
2978 format!("native.instant at {location}"),
2979 Arc::clone(&metrics),
2980 pool,
2981 )
2982 },
2983 }
2984 }
2985 NativeExpr::Merge { input } => {
2986 let child = Self::build(
2987 input,
2988 pool,
2989 inputs,
2990 binary_before,
2991 format!("{location}.input"),
2992 duplicate_evidence.clone(),
2993 sources,
2994 )?;
2995 let schema = node.output.samples().cloned().ok_or_else(|| {
2996 DataFusionError::Execution("merge does not produce samples".to_string())
2997 })?;
2998 let state = NodeState::new(
2999 format!("native.merge at {location}"),
3000 Arc::clone(&metrics),
3001 pool,
3002 );
3003 RuntimeOp::Merge {
3004 input: Box::new(child),
3005 merge: Some(MergeInput::new(schema)),
3006 state,
3007 }
3008 }
3009 NativeExpr::Window { input, op } => {
3010 let child = Self::build(
3011 input,
3012 pool,
3013 inputs,
3014 binary_before,
3015 format!("{location}.input"),
3016 duplicate_evidence.clone(),
3017 sources,
3018 )?;
3019 let input_schema = input.output.samples().cloned().ok_or_else(|| {
3020 DataFusionError::Execution("window consumes non-sample input".to_string())
3021 })?;
3022 let unification =
3026 unifies_its_own_contributions(input, &sources.tags, &sources.metrics);
3027 let merge = matches!(unification, Some(false))
3028 .then(|| MergeInput::new(Arc::clone(&input_schema)));
3029 let state = NodeState::new(
3030 format!("native.window at {location}"),
3031 Arc::clone(&metrics),
3032 pool,
3033 );
3034 RuntimeOp::Window {
3035 input: Box::new(child),
3036 window: Some(RangeEvaluator::try_new(
3039 &input_schema,
3040 Arc::clone(&op.output_grid),
3041 op.window,
3042 op.function,
3043 )?),
3044 merge,
3045 state,
3046 }
3047 }
3048 NativeExpr::Map { input, op } => {
3049 let child = Self::build(
3050 input,
3051 pool,
3052 inputs,
3053 binary_before,
3054 format!("{location}.input"),
3055 duplicate_evidence.clone(),
3056 sources,
3057 )?;
3058 let schema = node.output.samples().cloned().ok_or_else(|| {
3059 DataFusionError::Execution("map does not produce samples".to_string())
3060 })?;
3061 let state = NodeState::new(
3062 format!("native.map at {location}"),
3063 Arc::clone(&metrics),
3064 pool,
3065 );
3066 RuntimeOp::Map {
3067 input: Box::new(child),
3068 map: MapRuntime {
3069 ops: Arc::clone(&op.ops),
3070 schema,
3071 },
3072 state,
3073 }
3074 }
3075 NativeExpr::ParameterizedMap {
3076 input,
3077 op,
3078 parameters,
3079 } => {
3080 let child = Self::build(
3081 input,
3082 pool,
3083 inputs,
3084 binary_before,
3085 format!("{location}.input"),
3086 duplicate_evidence.clone(),
3087 sources,
3088 )?;
3089 let schema = match &node.output {
3093 NativeType::Samples(schema) => Arc::clone(schema),
3094 NativeType::Scalar(grid) => Arc::new(scalar_schema(Arc::clone(grid))),
3095 NativeType::AggregateState(_) => {
3096 return Err(DataFusionError::Execution(
3097 "map does not produce samples or a scalar, but aggregate state"
3098 .to_string(),
3099 ));
3100 }
3101 };
3102 let literals = parameters
3103 .iter()
3104 .map(|parameter| match ¶meter.expr {
3105 NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
3106 _ => None,
3107 })
3108 .collect();
3109 let input_literal = match &input.expr {
3112 NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
3113 _ => None,
3114 };
3115 let nodes = parameters
3116 .iter()
3117 .enumerate()
3118 .map(|(index, parameter)| {
3119 Self::build(
3120 parameter,
3121 pool,
3122 inputs,
3123 binary_before,
3124 format!("{location}.parameter{index}"),
3125 duplicate_evidence.clone(),
3126 sources,
3127 )
3128 })
3129 .collect::<Result<Vec<_>>>()?;
3130 let state = NodeState::new(
3131 format!("native.map at {location}"),
3132 Arc::clone(&metrics),
3133 pool,
3134 );
3135 RuntimeOp::ParameterizedMap {
3136 input: Box::new(child),
3137 parameters: nodes,
3138 map: ParameterizedMapRuntime {
3139 op: *op,
3140 schema,
3141 input_literal,
3142 input_produced: false,
3143 literals,
3144 values: vec![None; parameters.len()],
3145 parameter_bytes: 0,
3146 },
3147 state,
3148 }
3149 }
3150 NativeExpr::Timestamp { input } => {
3151 let child = Self::build(
3152 input,
3153 pool,
3154 inputs,
3155 binary_before,
3156 format!("{location}.input"),
3157 duplicate_evidence.clone(),
3158 sources,
3159 )?;
3160 let schema = node.output.samples().cloned().ok_or_else(|| {
3161 DataFusionError::Execution("timestamp does not produce samples".to_string())
3162 })?;
3163 let state = NodeState::new(
3164 format!("native.timestamp at {location}"),
3165 Arc::clone(&metrics),
3166 pool,
3167 );
3168 RuntimeOp::Timestamp {
3169 input: Box::new(child),
3170 schema,
3171 state,
3172 }
3173 }
3174 NativeExpr::Binary {
3175 left,
3176 right,
3177 matching,
3178 } => {
3179 let left_schema = left.output.samples();
3180 let right_schema = right.output.samples();
3181 let (binary, broadcast) = match (left_schema, right_schema) {
3182 (Some(left_schema), Some(right_schema))
3183 if left_schema.eval_grid.is_some() && right_schema.eval_grid.is_some() =>
3184 {
3185 let node_index = *binary_before;
3186 *binary_before += 1;
3187 (
3188 Some(BinaryRuntime::new(
3189 PairKernel::Binary(Arc::new(matching.clone())),
3190 [Arc::clone(left_schema), Arc::clone(right_schema)],
3191 node_index,
3192 duplicate_evidence.clone(),
3193 )),
3194 None,
3195 )
3196 }
3197 _ => (None, Some(broadcast_runtime(left, right, matching)?)),
3198 };
3199 let left_node = Self::build(
3200 left,
3201 pool,
3202 inputs,
3203 binary_before,
3204 format!("{location}.left"),
3205 duplicate_evidence.clone(),
3206 sources,
3207 )?;
3208 let right_node = Self::build(
3209 right,
3210 pool,
3211 inputs,
3212 binary_before,
3213 format!("{location}.right"),
3214 duplicate_evidence.clone(),
3215 sources,
3216 )?;
3217 match (binary, broadcast) {
3218 (Some(binary), None) => RuntimeOp::Binary {
3219 left: Box::new(left_node),
3220 right: Box::new(right_node),
3221 binary,
3222 state: NodeState::new(
3223 format!("native.binary at {location}"),
3224 Arc::clone(&metrics),
3225 pool,
3226 ),
3227 },
3228 (None, Some(broadcast)) => {
3229 let state = NodeState::new(
3230 format!("native.binary at {location}"),
3231 Arc::clone(&metrics),
3232 pool,
3233 );
3234 RuntimeOp::Broadcast {
3235 left: Box::new(left_node),
3236 right: Box::new(right_node),
3237 broadcast,
3238 state,
3239 }
3240 }
3241 _ => {
3242 return Err(DataFusionError::Internal(
3243 "binary runtime build selected conflicting operation modes".to_string(),
3244 ));
3245 }
3246 }
3247 }
3248 NativeExpr::Set { left, right, op } => {
3249 let (Some(left_schema), Some(right_schema)) =
3250 (left.output.samples(), right.output.samples())
3251 else {
3252 return Err(DataFusionError::Execution(
3253 "a set operation consumes two vectors".to_string(),
3254 ));
3255 };
3256 let node_index = *binary_before;
3257 *binary_before += 1;
3258 let set = BinaryRuntime::new(
3259 PairKernel::Set(op.clone()),
3260 [Arc::clone(left_schema), Arc::clone(right_schema)],
3261 node_index,
3262 duplicate_evidence.clone(),
3263 );
3264 let left_node = Self::build(
3265 left,
3266 pool,
3267 inputs,
3268 binary_before,
3269 format!("{location}.left"),
3270 duplicate_evidence.clone(),
3271 sources,
3272 )?;
3273 let right_node = Self::build(
3274 right,
3275 pool,
3276 inputs,
3277 binary_before,
3278 format!("{location}.right"),
3279 duplicate_evidence.clone(),
3280 sources,
3281 )?;
3282 RuntimeOp::Binary {
3283 left: Box::new(left_node),
3284 right: Box::new(right_node),
3285 binary: set,
3286 state: NodeState::new(
3287 format!("native.set at {location}"),
3288 Arc::clone(&metrics),
3289 pool,
3290 ),
3291 }
3292 }
3293 NativeExpr::Info {
3294 base,
3295 info,
3296 selector,
3297 } => {
3298 let (Some(base_schema), Some(info_schema)) =
3299 (base.output.samples(), info.output.samples())
3300 else {
3301 return Err(DataFusionError::Execution(
3302 "info consumes two vectors".to_string(),
3303 ));
3304 };
3305 let node_index = *binary_before;
3306 *binary_before += 1;
3307 let runtime = BinaryRuntime::new(
3308 PairKernel::Info(selector.clone()),
3309 [Arc::clone(base_schema), Arc::clone(info_schema)],
3310 node_index,
3311 duplicate_evidence.clone(),
3312 );
3313 let base_node = Self::build(
3314 base,
3315 pool,
3316 inputs,
3317 binary_before,
3318 format!("{location}.base"),
3319 duplicate_evidence.clone(),
3320 sources,
3321 )?;
3322 let info_node = Self::build(
3323 info,
3324 pool,
3325 inputs,
3326 binary_before,
3327 format!("{location}.info"),
3328 duplicate_evidence.clone(),
3329 sources,
3330 )?;
3331 RuntimeOp::Binary {
3332 left: Box::new(base_node),
3333 right: Box::new(info_node),
3334 binary: runtime,
3335 state: NodeState::new(
3336 format!("native.info at {location}"),
3337 Arc::clone(&metrics),
3338 pool,
3339 ),
3340 }
3341 }
3342 NativeExpr::Aggregate { input, op } => {
3343 let schema = node
3344 .output
3345 .samples()
3346 .or_else(|| input.output.samples())
3347 .cloned()
3348 .ok_or_else(|| {
3349 DataFusionError::Execution("aggregate does not produce samples".to_string())
3350 })?;
3351 let mut state = NodeState::new(
3352 format!("native.aggregate at {location}"),
3353 Arc::clone(&metrics),
3354 pool,
3355 );
3356 let aggregate = AggregateRuntime::new(op.clone(), schema, &mut state.buffer)?;
3357 let child = Self::build(
3358 input,
3359 pool,
3360 inputs,
3361 binary_before,
3362 format!("{location}.input"),
3363 duplicate_evidence.clone(),
3364 sources,
3365 )?;
3366 RuntimeOp::Aggregate {
3367 input: Box::new(child),
3368 aggregate,
3369 state,
3370 }
3371 }
3372 NativeExpr::ParameterizedAggregate {
3373 input,
3374 op,
3375 parameter,
3376 } => {
3377 let schema = node
3378 .output
3379 .samples()
3380 .or_else(|| input.output.samples())
3381 .cloned()
3382 .ok_or_else(|| {
3383 DataFusionError::Execution(
3384 "a parameterized aggregate does not produce samples".into(),
3385 )
3386 })?;
3387 let mut state = NodeState::new(
3388 format!("native.aggregate at {location}"),
3389 Arc::clone(&metrics),
3390 pool,
3391 );
3392 let aggregate =
3393 AggregateRuntime::new_parameterized(op.clone(), schema, &mut state.buffer)?;
3394 let child = Self::build(
3395 input,
3396 pool,
3397 inputs,
3398 binary_before,
3399 format!("{location}.input"),
3400 duplicate_evidence.clone(),
3401 sources,
3402 )?;
3403 let parameter = Self::build(
3406 parameter,
3407 pool,
3408 inputs,
3409 binary_before,
3410 format!("{location}.parameter"),
3411 duplicate_evidence.clone(),
3412 sources,
3413 )?;
3414 RuntimeOp::ParameterizedAggregate {
3415 input: Box::new(child),
3416 parameter: Some(Box::new(parameter)),
3417 aggregate,
3418 state,
3419 }
3420 }
3421 NativeExpr::ParameterizedTopK {
3422 input,
3423 op,
3424 parameter,
3425 } => {
3426 let schema = node.output.samples().cloned().ok_or_else(|| {
3427 DataFusionError::Execution("parameterized topk does not produce samples".into())
3428 })?;
3429 let one_field = schema.fields.len() == 1;
3430 if !one_field {
3431 return Err(DataFusionError::NotImplemented(
3432 "the native runtime does not execute multi-field vector operations".into(),
3433 ));
3434 }
3435 let vector = VectorRuntime::try_new(op.clone(), schema)?;
3436 let child = Self::build(
3437 input,
3438 pool,
3439 inputs,
3440 binary_before,
3441 format!("{location}.input"),
3442 duplicate_evidence.clone(),
3443 sources,
3444 )?;
3445 let parameter = Self::build(
3446 parameter,
3447 pool,
3448 inputs,
3449 binary_before,
3450 format!("{location}.parameter"),
3451 duplicate_evidence.clone(),
3452 sources,
3453 )?;
3454 let state = NodeState::new(
3455 format!("native.vector at {location}"),
3456 Arc::clone(&metrics),
3457 pool,
3458 );
3459 RuntimeOp::ParameterizedTopK {
3460 input: Box::new(child),
3461 parameter: Some(Box::new(parameter)),
3462 vector,
3463 state,
3464 }
3465 }
3466 NativeExpr::ParameterizedHistogram {
3467 input,
3468 op,
3469 parameters,
3470 } => {
3471 if !matches!(op, BoundVectorOp::Histogram(_)) {
3472 return Err(DataFusionError::Internal(
3473 "parameterized histogram has non-histogram op".into(),
3474 ));
3475 }
3476 if parameters.len()
3477 != match op {
3478 BoundVectorOp::Histogram(HistogramFunction::Quantile(_)) => 1,
3479 BoundVectorOp::Histogram(HistogramFunction::Fraction { .. }) => 2,
3480 _ => 0,
3481 }
3482 {
3483 return Err(DataFusionError::Internal(
3484 "parameterized histogram has the wrong arity".into(),
3485 ));
3486 }
3487 let literals = parameters
3488 .iter()
3489 .map(|parameter| match ¶meter.expr {
3490 NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
3491 _ => None,
3492 })
3493 .collect();
3494 let schema = node.output.samples().cloned().ok_or_else(|| {
3495 DataFusionError::Execution(
3496 "parameterized histogram does not produce samples".into(),
3497 )
3498 })?;
3499 let vector = VectorRuntime::try_new(op.clone(), schema)?;
3500 let child = Self::build(
3501 input,
3502 pool,
3503 inputs,
3504 binary_before,
3505 format!("{location}.input"),
3506 duplicate_evidence.clone(),
3507 sources,
3508 )?;
3509 let mut built = Vec::with_capacity(parameters.len());
3510 for (index, parameter) in parameters.iter().enumerate() {
3511 let runtime = Self::build(
3512 parameter,
3513 pool,
3514 inputs,
3515 binary_before,
3516 format!("{location}.parameter{index}"),
3517 duplicate_evidence.clone(),
3518 sources,
3519 )?;
3520 built.push(Some(runtime));
3521 }
3522 RuntimeOp::ParameterizedHistogram {
3523 input: Box::new(child),
3524 parameter_bytes: vec![0; built.len()],
3525 values: vec![None; built.len()],
3526 parameters: built,
3527 literals,
3528 vector,
3529 state: NodeState::new(
3530 format!("native.vector at {location}"),
3531 Arc::clone(&metrics),
3532 pool,
3533 ),
3534 }
3535 }
3536 NativeExpr::Vector { input, op } => {
3537 let schema = node.output.samples().cloned().ok_or_else(|| {
3538 DataFusionError::Execution(
3539 "vector operation does not produce samples".to_string(),
3540 )
3541 })?;
3542 let one_field = matches!(
3543 op,
3544 BoundVectorOp::TopK { .. }
3545 | BoundVectorOp::LimitK { .. }
3546 | BoundVectorOp::Sort(SortOrder::Asc | SortOrder::Desc)
3547 );
3548 if one_field && schema.fields.len() != 1 {
3549 return Err(DataFusionError::NotImplemented(
3550 "the native runtime does not execute multi-field vector operations"
3551 .to_string(),
3552 ));
3553 }
3554 let mut vector = VectorRuntime::try_new(op.clone(), schema)?;
3555 let child = Self::build(
3556 input,
3557 pool,
3558 inputs,
3559 binary_before,
3560 format!("{location}.input"),
3561 duplicate_evidence.clone(),
3562 sources,
3563 )?;
3564 let limitk = matches!(op, BoundVectorOp::LimitK { .. });
3565 if limitk
3566 && matches!(
3567 unifies_its_own_contributions(input, &sources.tags, &sources.metrics),
3568 Some(false)
3569 )
3570 {
3571 vector.merge_input = true;
3572 }
3573 RuntimeOp::Vector {
3574 input: Box::new(child),
3575 vector,
3576 state: NodeState::new(
3577 format!("native.vector at {location}"),
3578 Arc::clone(&metrics),
3579 pool,
3580 ),
3581 }
3582 }
3583 };
3584 Ok(Self { metrics, op })
3585 }
3586
3587 fn register_metrics(&self, name: &str, set: &ExecutionPlanMetricsSet, partition: usize) {
3588 self.metrics.register(name, set, partition);
3589 match &self.op {
3590 RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => {}
3591 RuntimeOp::ScalarOf { input, .. } => {
3592 input.register_metrics(&format!("{name}.input"), set, partition)
3593 }
3594 RuntimeOp::Instant { input, .. }
3595 | RuntimeOp::Window { input, .. }
3596 | RuntimeOp::Merge { input, .. }
3597 | RuntimeOp::Map { input, .. }
3598 | RuntimeOp::Timestamp { input, .. }
3599 | RuntimeOp::Aggregate { input, .. }
3600 | RuntimeOp::Vector { input, .. }
3601 | RuntimeOp::VectorOf { input, .. } => {
3602 input.register_metrics(&format!("{name}.input"), set, partition)
3603 }
3604 RuntimeOp::Binary { left, right, .. } | RuntimeOp::Broadcast { left, right, .. } => {
3605 left.register_metrics(&format!("{name}.left"), set, partition);
3606 right.register_metrics(&format!("{name}.right"), set, partition);
3607 }
3608 RuntimeOp::ParameterizedTopK {
3609 input, parameter, ..
3610 }
3611 | RuntimeOp::ParameterizedAggregate {
3612 input, parameter, ..
3613 } => {
3614 input.register_metrics(&format!("{name}.input"), set, partition);
3615 if let Some(parameter) = parameter {
3616 parameter.register_metrics(&format!("{name}.parameter"), set, partition);
3617 }
3618 }
3619 RuntimeOp::ParameterizedHistogram {
3620 input, parameters, ..
3621 } => {
3622 input.register_metrics(&format!("{name}.input"), set, partition);
3623 for (i, parameter) in parameters.iter().enumerate() {
3624 if let Some(parameter) = parameter {
3625 parameter.register_metrics(&format!("{name}.parameter{i}"), set, partition);
3626 }
3627 }
3628 }
3629 RuntimeOp::ParameterizedMap {
3630 input, parameters, ..
3631 } => {
3632 input.register_metrics(&format!("{name}.input"), set, partition);
3633 for (index, parameter) in parameters.iter().enumerate() {
3634 parameter.register_metrics(&format!("{name}.parameter{index}"), set, partition);
3635 }
3636 }
3637 }
3638 }
3639
3640 fn reserved_bytes(&self) -> usize {
3641 match &self.op {
3642 RuntimeOp::Input(_) | RuntimeOp::Scalar => 0,
3643 RuntimeOp::EvalTime { state, .. } => state.buffer.reservation.size(),
3644 RuntimeOp::ScalarOf { input, state, .. } => state
3647 .buffer
3648 .reservation
3649 .size()
3650 .saturating_add(input.reserved_bytes()),
3651 RuntimeOp::Instant { input, state, .. }
3652 | RuntimeOp::Window { input, state, .. }
3653 | RuntimeOp::Merge { input, state, .. }
3654 | RuntimeOp::Map { input, state, .. }
3655 | RuntimeOp::Timestamp { input, state, .. }
3656 | RuntimeOp::Aggregate { input, state, .. }
3657 | RuntimeOp::Vector { input, state, .. }
3658 | RuntimeOp::VectorOf { input, state, .. } => state
3659 .buffer
3660 .reservation
3661 .size()
3662 .saturating_add(input.reserved_bytes()),
3663 RuntimeOp::Binary {
3664 left, right, state, ..
3665 }
3666 | RuntimeOp::Broadcast {
3667 left, right, state, ..
3668 } => state
3669 .buffer
3670 .reservation
3671 .size()
3672 .saturating_add(left.reserved_bytes())
3673 .saturating_add(right.reserved_bytes()),
3674 RuntimeOp::ParameterizedHistogram {
3675 input,
3676 parameters,
3677 state,
3678 ..
3679 } => parameters.iter().fold(
3680 state
3681 .buffer
3682 .reservation
3683 .size()
3684 .saturating_add(input.reserved_bytes()),
3685 |n, p| n.saturating_add(p.as_ref().map_or(0, RuntimeNode::reserved_bytes)),
3686 ),
3687 RuntimeOp::ParameterizedTopK {
3688 input,
3689 parameter,
3690 state,
3691 ..
3692 }
3693 | RuntimeOp::ParameterizedAggregate {
3694 input,
3695 parameter,
3696 state,
3697 ..
3698 } => state
3699 .buffer
3700 .reservation
3701 .size()
3702 .saturating_add(input.reserved_bytes())
3703 .saturating_add(parameter.as_ref().map_or(0, |p| p.reserved_bytes())),
3704 RuntimeOp::ParameterizedMap {
3705 input,
3706 parameters,
3707 state,
3708 ..
3709 } => parameters.iter().fold(
3710 state
3711 .buffer
3712 .reservation
3713 .size()
3714 .saturating_add(input.reserved_bytes()),
3715 |total, parameter| total.saturating_add(parameter.reserved_bytes()),
3716 ),
3717 }
3718 }
3719}
3720
3721impl RuntimeNode {
3726 fn set_annotations(&mut self, collector: PromqlAnnotationCollector) {
3727 match &mut self.op {
3728 RuntimeOp::Window { input, window, .. } => {
3729 if let Some(window) = window {
3730 window.set_annotations(Some(collector.clone()));
3731 }
3732 input.set_annotations(collector);
3733 }
3734 RuntimeOp::Map { input, .. } => input.set_annotations(collector),
3738 RuntimeOp::ParameterizedMap {
3739 input, parameters, ..
3740 } => {
3741 input.set_annotations(collector.clone());
3742 for parameter in parameters {
3743 parameter.set_annotations(collector.clone());
3744 }
3745 }
3746 RuntimeOp::VectorOf { input, .. }
3747 | RuntimeOp::Instant { input, .. }
3748 | RuntimeOp::Merge { input, .. } => input.set_annotations(collector),
3749 RuntimeOp::Binary {
3750 left,
3751 right,
3752 binary,
3753 ..
3754 } => {
3755 binary.annotations = Some(collector.clone());
3756 left.set_annotations(collector.clone());
3757 right.set_annotations(collector);
3758 }
3759 RuntimeOp::Broadcast {
3760 left,
3761 right,
3762 broadcast,
3763 ..
3764 } => {
3765 broadcast.annotations = Some(collector.clone());
3766 left.set_annotations(collector.clone());
3767 right.set_annotations(collector);
3768 }
3769 RuntimeOp::Aggregate {
3770 input, aggregate, ..
3771 } => {
3772 aggregate.set_annotations(collector.clone());
3775 input.set_annotations(collector);
3776 }
3777 RuntimeOp::ParameterizedAggregate {
3778 input,
3779 parameter,
3780 aggregate,
3781 ..
3782 } => {
3783 aggregate.set_annotations(collector.clone());
3786 input.set_annotations(collector.clone());
3787 if let Some(parameter) = parameter {
3788 parameter.set_annotations(collector);
3789 }
3790 }
3791 RuntimeOp::Timestamp { input, .. } => input.set_annotations(collector),
3792 RuntimeOp::Vector { input, vector, .. } => {
3793 vector.annotations = Some(collector.clone());
3794 input.set_annotations(collector);
3795 }
3796 RuntimeOp::ScalarOf { input, .. } => input.set_annotations(collector),
3799 RuntimeOp::ParameterizedTopK {
3801 input,
3802 parameter,
3803 vector,
3804 ..
3805 } => {
3806 vector.annotations = Some(collector.clone());
3807 input.set_annotations(collector.clone());
3808 if let Some(parameter) = parameter {
3809 parameter.set_annotations(collector);
3810 }
3811 }
3812 RuntimeOp::ParameterizedHistogram {
3815 input,
3816 parameters,
3817 vector,
3818 ..
3819 } => {
3820 vector.annotations = Some(collector.clone());
3821 input.set_annotations(collector.clone());
3822 for parameter in parameters.iter_mut().flatten() {
3823 parameter.set_annotations(collector.clone());
3824 }
3825 }
3826 RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => {}
3827 }
3828 }
3829
3830 fn pull(
3839 &mut self,
3840 inputs: &mut [InputSlot],
3841 inputs_finished: bool,
3842 ) -> Result<Option<NativeChunk>> {
3843 stacker::maybe_grow(NATIVE_STACK_RED_ZONE, NATIVE_STACK_GROWTH, || {
3844 self.pull_within_stack(inputs, inputs_finished)
3845 })
3846 }
3847
3848 fn pull_within_stack(
3849 &mut self,
3850 inputs: &mut [InputSlot],
3851 inputs_finished: bool,
3852 ) -> Result<Option<NativeChunk>> {
3853 match &mut self.op {
3854 RuntimeOp::Input(id) => {
3858 let input = *id;
3859 let count = inputs.len();
3860 let slot = inputs
3861 .get_mut(input.index())
3862 .ok_or_else(|| no_input(count, input))?;
3863 slot.pop_source()
3864 }
3865 RuntimeOp::Scalar => Ok(None),
3869 RuntimeOp::ScalarOf {
3870 input,
3871 input_schema,
3872 grid,
3873 retained,
3874 produced,
3875 state,
3876 } => {
3877 while let Some(chunk) = input.pull(inputs, inputs_finished)? {
3878 let NativeChunk::Evaluated(chunk) = chunk else {
3879 return Err(DataFusionError::Execution(
3880 "scalar() consumes evaluated chunks, not raw samples".into(),
3881 ));
3882 };
3883 validate_binary_operand(input_schema, std::slice::from_ref(&chunk.series))
3884 .map_err(|error| {
3885 DataFusionError::Execution(format!(
3886 "scalar() rejected its input: {error}"
3887 ))
3888 })?;
3889 let pending = retained.pending(&chunk);
3890 state.buffer.grow(pending).map_err(|e| state.context(e))?;
3891 retained
3892 .retain(chunk, Reader::Vector)
3893 .map_err(|e| state.context(e))?;
3894 state
3895 .buffer
3896 .resize(retained.held)
3897 .map_err(|e| state.context(e))?;
3898 }
3899 if !inputs_finished || !input.settled(inputs) {
3900 return Ok(None);
3901 }
3902 if !*produced {
3903 let len = grid.spec().len as usize;
3904 let bytes = grid_chunk_bytes(grid).map_err(|e| state.context(e))?;
3905 let counts_bytes = len.saturating_mul(std::mem::size_of::<u8>());
3908 let assembly = retained
3909 .assembly_bytes(input_schema)
3910 .ok_or_else(vector_overflow)?;
3911 state
3912 .buffer
3913 .grow(assembly.saturating_add(bytes).saturating_add(counts_bytes))
3914 .map_err(|e| state.context(e))?;
3915 let assembled = retained
3916 .assemble(input_schema, Reader::Vector)
3917 .map_err(|e| state.context(e))?;
3918 retained.release();
3919 let answer =
3924 select::scalar(input_schema, &assembled).map_err(|e| state.context(e))?;
3925 drop(assembled);
3928 state.buffer.resize(bytes).map_err(|e| state.context(e))?;
3929 let schema = scalar_schema(Arc::clone(grid));
3932 let series =
3933 Series::try_new(&schema, answer.metric, answer.time, answer.fields)
3934 .map_err(series_error)?;
3935 state.queued.push_back((
3936 NativeChunk::Evaluated(EvaluatedChunk::try_new(series, true)?),
3937 bytes,
3938 ));
3939 *produced = true;
3940 }
3941 state.pop_queued(evaluated_values)
3942 }
3943 RuntimeOp::EvalTime {
3944 grid,
3945 date,
3946 produced,
3947 state,
3948 } => {
3949 if !std::mem::replace(produced, true) {
3950 state
3953 .buffer
3954 .reserve_grid(grid)
3955 .map_err(|error| state.context(error))?;
3956 let schema = scalar_schema(Arc::clone(grid));
3957 state
3958 .produce(grid, || match date {
3959 None => map_time::time(&schema),
3960 Some(date) => map_time::date_of_eval_time(*date, &schema),
3961 })
3962 .map_err(|error| state.context(error))?;
3963 }
3964 state.pop_queued(evaluated_values)
3965 }
3966 RuntimeOp::VectorOf {
3967 input,
3968 literal,
3969 produced,
3970 schema,
3971 state,
3972 } => {
3973 if let Some(value) = literal {
3974 if !std::mem::replace(produced, true) {
3975 let grid = schema.eval_grid.clone().ok_or_else(|| {
3976 DataFusionError::Execution(
3977 "vector() produces values without a grid".to_string(),
3978 )
3979 })?;
3980 state
3981 .produce(&grid, || {
3982 Ok(scalar_chunk_on(schema, Arc::clone(&grid), *value)?.series)
3983 })
3984 .map_err(|error| state.context(error))?;
3985 }
3986 return state.pop_queued(evaluated_values);
3987 }
3988 let Some(chunk) = input.pull(inputs, inputs_finished)? else {
3990 return Ok(None);
3991 };
3992 let NativeChunk::Evaluated(EvaluatedChunk { series, is_last }) = chunk else {
3993 return Err(DataFusionError::Execution(
3994 "vector() consumes an evaluated scalar, not raw samples".to_string(),
3995 ));
3996 };
3997 ensure_grid(schema.eval_grid.as_deref(), &series.time)?;
3998 let series = Series::try_new(schema, series.metric, series.time, series.fields)
3999 .map_err(series_error)?;
4000 Ok(Some(NativeChunk::Evaluated(EvaluatedChunk::try_new(
4001 series, is_last,
4002 )?)))
4003 }
4004 RuntimeOp::Instant {
4005 input,
4006 instant,
4007 state,
4008 } => {
4009 let selection = instant;
4010 loop {
4013 let Some(chunk) = input.pull(inputs, inputs_finished)? else {
4014 return Ok(None);
4015 };
4016 if let Some(output) = state
4017 .instant(selection, chunk)
4018 .map_err(|error| state.context(error))?
4019 {
4020 return Ok(Some(NativeChunk::Evaluated(output)));
4021 }
4022 }
4023 }
4024 RuntimeOp::Merge {
4025 input,
4026 merge,
4027 state,
4028 } => {
4029 if let Some(chunk) = state.take_output()? {
4030 return Ok(Some(chunk));
4031 }
4032 while let Some(chunk) = input.pull(inputs, inputs_finished)? {
4033 let NativeChunk::Evaluated(chunk) = chunk else {
4034 return Err(DataFusionError::Execution(
4035 "merge consumes evaluated samples, not raw samples".into(),
4036 ));
4037 };
4038 state.collect_merge(
4039 merge.as_mut().ok_or_else(|| {
4040 DataFusionError::Execution("merge buffer was released".into())
4041 })?,
4042 chunk,
4043 )?;
4044 }
4045 Ok(None)
4046 }
4047 RuntimeOp::Window {
4048 input,
4049 window,
4050 merge,
4051 state,
4052 } => {
4053 if let Some(chunk) = state.take_output().map_err(|error| state.context(error))? {
4057 return Ok(Some(chunk));
4058 }
4059 let Some(evaluator) = window.as_mut() else {
4060 return Err(no_window());
4061 };
4062 loop {
4065 let Some(chunk) = input.pull(inputs, inputs_finished)? else {
4066 return Ok(None);
4067 };
4068 if let Some(output) = state
4069 .window(evaluator, merge, chunk)
4070 .map_err(|error| state.context(error))?
4071 {
4072 return Ok(Some(NativeChunk::Evaluated(output)));
4073 }
4074 }
4075 }
4076 RuntimeOp::Map { input, map, state } => {
4077 let operation = map;
4078 loop {
4081 let Some(chunk) = input.pull(inputs, inputs_finished)? else {
4082 return Ok(None);
4083 };
4084 let NativeChunk::Evaluated(chunk) = chunk else {
4085 return Err(DataFusionError::Execution(
4086 "the map node consumes an evaluated chunk, not raw samples".to_string(),
4087 ));
4088 };
4089 if let Some(output) = state
4090 .map(operation, chunk)
4091 .map_err(|error| state.context(error))?
4092 {
4093 return Ok(Some(NativeChunk::Evaluated(output)));
4094 }
4095 }
4096 }
4097 RuntimeOp::ParameterizedMap {
4098 input,
4099 parameters,
4100 map,
4101 state,
4102 } => {
4103 let operation = map;
4104 for (index, parameter) in parameters.iter_mut().enumerate() {
4107 let slot = &mut operation.values[index];
4108 if slot.is_some() {
4109 continue;
4110 }
4111 if let Some(value) = operation.literals[index] {
4112 let grid = operation.schema.eval_grid.clone().ok_or_else(|| {
4113 DataFusionError::Execution(
4114 "a map produces values without a grid".to_string(),
4115 )
4116 })?;
4117 state
4118 .hold_constant(&mut operation.parameter_bytes, slot, grid, value)
4119 .map_err(|error| state.context(error))?;
4120 continue;
4121 }
4122 while let Some(chunk) = parameter.pull(inputs, inputs_finished)? {
4123 state
4124 .hold_scalar(&mut operation.parameter_bytes, slot, chunk)
4125 .map_err(|error| state.context(error))?;
4126 }
4127 }
4128 if !operation.ready() {
4131 if !inputs_finished
4134 || !parameters.iter().all(|parameter| parameter.settled(inputs))
4135 {
4136 return Ok(None);
4137 }
4138 return Err(DataFusionError::Execution(
4139 "a map parameter did not hand over its value".to_string(),
4140 ));
4141 }
4142 if let Some(value) = operation.input_literal
4145 && !std::mem::replace(&mut operation.input_produced, true)
4146 {
4147 let grid = operation.schema.eval_grid.clone().ok_or_else(|| {
4148 DataFusionError::Execution(
4149 "a map produces values without a grid".to_string(),
4150 )
4151 })?;
4152 let mut slot = None;
4153 state
4154 .hold_constant(&mut operation.parameter_bytes, &mut slot, grid, value)
4155 .map_err(|error| state.context(error))?;
4156 let series = slot.expect("the constant input was just built");
4157 let chunk = EvaluatedChunk::try_new(series, true)
4158 .map_err(|error| state.context(error))?;
4159 return state
4160 .parameterized_map(operation, chunk)
4161 .map_err(|error| state.context(error))
4162 .map(|output| output.map(NativeChunk::Evaluated));
4163 }
4164 loop {
4165 let chunk = match input.pull(inputs, inputs_finished)? {
4166 Some(NativeChunk::Evaluated(chunk)) => chunk,
4167 Some(NativeChunk::Raw(_)) => {
4168 return Err(DataFusionError::Execution(
4169 "the map node consumes an evaluated chunk, not raw samples"
4170 .to_string(),
4171 ));
4172 }
4173 Some(NativeChunk::AggregateState(_)) => {
4174 return Err(DataFusionError::Execution(
4175 "an aggregate state chunk reached a node that reads values or samples"
4176 .to_string(),
4177 ));
4178 }
4179 None => return Ok(None),
4180 };
4181 if let Some(output) = state
4182 .parameterized_map(operation, chunk)
4183 .map_err(|error| state.context(error))?
4184 {
4185 return Ok(Some(NativeChunk::Evaluated(output)));
4186 }
4187 }
4188 }
4189 RuntimeOp::Timestamp {
4190 input,
4191 schema,
4192 state,
4193 } => loop {
4194 let Some(chunk) = input.pull(inputs, inputs_finished)? else {
4195 return Ok(None);
4196 };
4197 let NativeChunk::Evaluated(chunk) = chunk else {
4198 return Err(DataFusionError::Execution(
4199 "timestamp consumes evaluated samples, not raw samples".into(),
4200 ));
4201 };
4202 if let Some(output) = state
4203 .timestamp(schema, chunk)
4204 .map_err(|error| state.context(error))?
4205 {
4206 return Ok(Some(NativeChunk::Evaluated(output)));
4207 }
4208 },
4209 RuntimeOp::Binary {
4210 left,
4211 right,
4212 binary,
4213 state,
4214 } => {
4215 let operation = binary;
4216 while let Some(chunk) = left.pull(inputs, inputs_finished)? {
4220 state
4221 .retain_binary(operation, 0, chunk)
4222 .map_err(|error| state.context(error))?;
4223 }
4224 while let Some(chunk) = right.pull(inputs, inputs_finished)? {
4225 state
4226 .retain_binary(operation, 1, chunk)
4227 .map_err(|error| state.context(error))?;
4228 }
4229 if !inputs_finished || !left.settled(inputs) || !right.settled(inputs) {
4233 return Ok(None);
4234 }
4235 state
4236 .compute_binary(operation)
4237 .map_err(|error| state.context(error))?;
4238 state.pop_queued(evaluated_values)
4241 }
4242 RuntimeOp::Broadcast {
4243 left,
4244 right,
4245 broadcast,
4246 state,
4247 } => {
4248 let operation = broadcast;
4249 let (vector, scalar) = if operation.vector_left {
4252 (&mut **left, &mut **right)
4253 } else {
4254 (&mut **right, &mut **left)
4255 };
4256 if let BroadcastScalar::Dynamic { value, .. } = &mut operation.scalar
4257 && value.is_none()
4258 {
4259 while let Some(chunk) = scalar.pull(inputs, inputs_finished)? {
4260 state
4261 .hold_scalar(&mut operation.scalar_bytes, value, chunk)
4262 .map_err(|error| state.context(error))?;
4263 }
4264 }
4265 if operation.awaits_scalar() {
4266 if !inputs_finished || !scalar.settled(inputs) {
4269 return Ok(None);
4270 }
4271 return Err(DataFusionError::Execution(
4272 "a broadcast scalar did not hand over its value".to_string(),
4273 ));
4274 }
4275 loop {
4278 let Some(chunk) = vector.pull(inputs, inputs_finished)? else {
4279 return Ok(None);
4280 };
4281 if let Some(output) = state
4282 .broadcast(operation, chunk)
4283 .map_err(|error| state.context(error))?
4284 {
4285 return Ok(Some(NativeChunk::Evaluated(output)));
4286 }
4287 }
4288 }
4289 RuntimeOp::Aggregate {
4290 input,
4291 aggregate,
4292 state,
4293 } => {
4294 let fold = aggregate;
4295 while let Some(chunk) = input.pull(inputs, inputs_finished)? {
4298 state
4299 .retain_aggregate(fold, chunk)
4300 .map_err(|error| state.context(error))?;
4301 }
4302 if !inputs_finished || !input.settled(inputs) {
4303 return Ok(None);
4304 }
4305 state
4306 .compute_aggregate(fold)
4307 .map_err(|error| state.context(error))?;
4308 state.pop_queued(evaluated_values)
4311 }
4312 RuntimeOp::ParameterizedAggregate {
4313 input,
4314 parameter,
4315 aggregate,
4316 state,
4317 } => {
4318 let fold = aggregate;
4319 if let Some(parameter_node) = parameter.as_mut() {
4326 let mut slot = None;
4327 let mut held = 0usize;
4328 while let Some(chunk) = parameter_node.pull(inputs, inputs_finished)? {
4329 state
4330 .hold_scalar(&mut held, &mut slot, chunk)
4331 .map_err(|error| state.context(error))?;
4332 }
4333 let series = {
4334 if !parameter_node.settled(inputs) {
4345 while let Some(chunk) = input.pull(inputs, inputs_finished)? {
4346 state
4347 .retain_aggregate(fold, chunk)
4348 .map_err(|error| state.context(error))?;
4349 }
4350 return Ok(None);
4351 }
4352 slot.ok_or_else(|| {
4353 DataFusionError::Execution(
4354 "the quantile parameter produced no scalar".into(),
4355 )
4356 })?
4357 };
4358 fold.hold_parameter(series, &mut state.buffer)
4359 .map_err(|error| state.context(error))?;
4360 parameter_node.finish_windows()?;
4363 *parameter = None;
4364 }
4365 while let Some(chunk) = input.pull(inputs, inputs_finished)? {
4366 state
4367 .retain_aggregate(fold, chunk)
4368 .map_err(|error| state.context(error))?;
4369 }
4370 if !inputs_finished || !input.settled(inputs) {
4371 return Ok(None);
4372 }
4373 state
4374 .compute_aggregate(fold)
4375 .map_err(|error| state.context(error))?;
4376 state.pop_queued(evaluated_values)
4377 }
4378 RuntimeOp::ParameterizedTopK {
4379 input,
4380 parameter,
4381 vector,
4382 state,
4383 } => {
4384 let operation = vector;
4385 if operation.parameter.is_none() {
4386 let mut slot = None;
4387 let parameter_node = parameter.as_mut().ok_or_else(|| {
4388 DataFusionError::Internal("topk parameter already consumed".into())
4389 })?;
4390 while let Some(chunk) = parameter_node.pull(inputs, inputs_finished)? {
4391 state
4392 .hold_scalar(&mut operation.parameter_bytes, &mut slot, chunk)
4393 .map_err(|error| state.context(error))?;
4394 }
4395 let series = {
4396 if !parameter_node.settled(inputs) {
4400 return Ok(None);
4401 }
4402 slot.ok_or_else(|| {
4403 DataFusionError::Execution("topk parameter produced no scalar".into())
4404 })?
4405 };
4406 let grid = operation
4407 .schema
4408 .eval_grid
4409 .as_ref()
4410 .ok_or_else(|| DataFusionError::Internal("topk grid missing".into()))?;
4411 let len = grid.spec().len as usize;
4412 if series.time.len() != len {
4413 return Err(DataFusionError::Execution(
4414 "topk parameter does not cover its grid".into(),
4415 ));
4416 }
4417 let bytes = len.saturating_mul(std::mem::size_of::<Option<f64>>());
4420 state
4421 .buffer
4422 .grow(bytes)
4423 .map_err(|error| state.context(error))?;
4424 let mut values = Vec::with_capacity(len);
4425 {
4426 let mut cursor = series.fields.as_slice()[0].cursor();
4427 for row in 0..len {
4428 values.push(match cursor.at(row) {
4429 Some(SampleRef::Float(value)) => Some(value),
4430 _ => None,
4431 });
4432 }
4433 }
4434 select::validate_topk_parameters(&values)
4435 .map_err(|error| state.context(error))?;
4436 operation.parameter = Some(values);
4437 drop(series);
4440 operation.parameter_bytes = bytes;
4441 state
4442 .settle_vector(operation)
4443 .map_err(|error| state.context(error))?;
4444 parameter_node.finish_windows()?;
4447 *parameter = None;
4448 }
4449 while let Some(chunk) = input.pull(inputs, inputs_finished)? {
4450 state
4451 .retain_vector(operation, chunk)
4452 .map_err(|error| state.context(error))?;
4453 }
4454 if !inputs_finished || !input.settled(inputs) {
4455 return Ok(None);
4456 }
4457 state
4458 .compute_vector(operation)
4459 .map_err(|error| state.context(error))?;
4460 state.pop_queued(evaluated_values)
4461 }
4462 RuntimeOp::ParameterizedHistogram {
4463 input,
4464 parameters,
4465 literals,
4466 vector,
4467 values,
4468 parameter_bytes,
4469 state,
4470 } => {
4471 let operation = vector;
4472 for index in 0..parameters.len() {
4473 if values[index].is_none() {
4474 let mut slot = None;
4475 if let Some(value) = literals[index] {
4476 let grid = operation.schema.eval_grid.clone().ok_or_else(|| {
4477 DataFusionError::Internal("histogram grid missing".into())
4478 })?;
4479 state.hold_constant(
4480 &mut parameter_bytes[index],
4481 &mut slot,
4482 grid,
4483 value,
4484 )?;
4485 } else {
4486 let parameter = parameters[index].as_mut().ok_or_else(|| {
4487 DataFusionError::Internal(
4488 "histogram parameter already consumed".into(),
4489 )
4490 })?;
4491 while let Some(chunk) = parameter.pull(inputs, inputs_finished)? {
4492 state.hold_scalar(&mut parameter_bytes[index], &mut slot, chunk)?;
4493 }
4494 if !parameter.settled(inputs) {
4495 return Ok(None);
4496 }
4497 }
4498 let series = slot.ok_or_else(|| {
4499 DataFusionError::Execution(
4500 "histogram parameter produced no scalar".into(),
4501 )
4502 })?;
4503 let len = operation
4504 .schema
4505 .eval_grid
4506 .as_ref()
4507 .ok_or_else(|| {
4508 DataFusionError::Internal("histogram grid missing".into())
4509 })?
4510 .spec()
4511 .len as usize;
4512 if series.time.len() != len {
4513 return Err(DataFusionError::Execution(
4514 "histogram parameter does not cover its grid".into(),
4515 ));
4516 }
4517 let bytes = len.saturating_mul(std::mem::size_of::<Option<f64>>());
4520 state.buffer.grow(bytes)?;
4521 let collected = {
4522 let mut cursor = series.fields.as_slice()[0].cursor();
4523 (0..len)
4524 .map(|row| match cursor.at(row) {
4525 Some(SampleRef::Float(v)) => Some(v),
4526 _ => None,
4527 })
4528 .collect::<Vec<Option<f64>>>()
4529 };
4530 values[index] = Some(collected);
4531 parameter_bytes[index] = bytes;
4534 drop(series);
4535 operation.parameter_bytes = parameter_bytes
4536 .iter()
4537 .copied()
4538 .fold(0usize, usize::saturating_add);
4539 state.settle_vector(operation)?;
4540 if let Some(parameter) = &mut parameters[index] {
4541 parameter.finish_windows()?;
4542 }
4543 parameters[index] = None;
4544 }
4545 }
4546 while let Some(chunk) = input.pull(inputs, inputs_finished)? {
4550 state.retain_vector(operation, chunk)?;
4551 }
4552 if !inputs_finished || !input.settled(inputs) {
4553 return Ok(None);
4554 }
4555 let collected = values
4556 .iter()
4557 .map(|v| {
4558 v.as_deref().ok_or_else(|| {
4559 DataFusionError::Internal("histogram parameters not collected".into())
4560 })
4561 })
4562 .collect::<Result<Vec<_>>>()?;
4563 state.compute_histogram(operation, &collected)?;
4564 state.pop_queued(evaluated_values)
4565 }
4566 RuntimeOp::Vector {
4567 input,
4568 vector,
4569 state,
4570 } => {
4571 let operation = vector;
4572 while let Some(chunk) = input.pull(inputs, inputs_finished)? {
4575 state
4576 .retain_vector(operation, chunk)
4577 .map_err(|error| state.context(error))?;
4578 }
4579 if !inputs_finished || !input.settled(inputs) {
4580 return Ok(None);
4581 }
4582 state
4583 .compute_vector(operation)
4584 .map_err(|error| state.context(error))?;
4585 state.pop_queued(evaluated_values)
4586 }
4587 }
4588 }
4589
4590 fn settled(&self, inputs: &[InputSlot]) -> bool {
4596 match &self.op {
4597 RuntimeOp::Input(id) => inputs
4600 .get(id.index())
4601 .is_some_and(|slot| slot.state.queued.is_empty()),
4602 RuntimeOp::Scalar => true,
4605 RuntimeOp::EvalTime {
4606 produced, state, ..
4607 } => *produced && state.queued.is_empty(),
4608 RuntimeOp::ScalarOf {
4609 input,
4610 produced,
4611 retained,
4612 state,
4613 ..
4614 } => {
4615 *produced && state.queued.is_empty() && retained.held == 0 && input.settled(inputs)
4616 }
4617 RuntimeOp::ParameterizedMap {
4618 input,
4619 parameters,
4620 state,
4621 ..
4622 } => {
4623 state.queued.is_empty()
4624 && input.settled(inputs)
4625 && parameters.iter().all(|parameter| parameter.settled(inputs))
4626 }
4627 RuntimeOp::ParameterizedHistogram {
4628 input,
4629 vector,
4630 state,
4631 ..
4632 } => {
4633 state.queued.is_empty() && vector.computed && input.settled(inputs)
4636 }
4637 RuntimeOp::ParameterizedTopK {
4638 input,
4639 vector,
4640 state,
4641 ..
4642 } => {
4643 state.queued.is_empty() && vector.computed && input.settled(inputs)
4646 }
4647 RuntimeOp::VectorOf {
4648 input,
4649 literal,
4650 produced,
4651 state,
4652 ..
4653 } => {
4654 state.queued.is_empty() && (*produced || literal.is_none()) && input.settled(inputs)
4655 }
4656 RuntimeOp::Instant { input, state, .. }
4659 | RuntimeOp::Map { input, state, .. }
4660 | RuntimeOp::Timestamp { input, state, .. } => {
4661 state.queued.is_empty() && input.settled(inputs)
4662 }
4663 RuntimeOp::Window {
4666 input,
4667 merge,
4668 state,
4669 ..
4670 } => state.queued.is_empty() && merge.is_none() && input.settled(inputs),
4671 RuntimeOp::Merge {
4672 input,
4673 merge,
4674 state,
4675 } => state.queued.is_empty() && merge.is_none() && input.settled(inputs),
4676 RuntimeOp::Aggregate {
4680 input,
4681 aggregate,
4682 state,
4683 } => state.queued.is_empty() && aggregate.computed && input.settled(inputs),
4684 RuntimeOp::ParameterizedAggregate {
4687 input,
4688 aggregate,
4689 state,
4690 ..
4691 } => state.queued.is_empty() && aggregate.computed && input.settled(inputs),
4692 RuntimeOp::Vector {
4693 input,
4694 vector,
4695 state,
4696 } => state.queued.is_empty() && vector.computed && input.settled(inputs),
4697 RuntimeOp::Binary {
4700 left,
4701 right,
4702 binary,
4703 state,
4704 } => {
4705 state.queued.is_empty()
4706 && binary.computed
4707 && left.settled(inputs)
4708 && right.settled(inputs)
4709 }
4710 RuntimeOp::Broadcast {
4713 left, right, state, ..
4714 } => state.queued.is_empty() && left.settled(inputs) && right.settled(inputs),
4715 }
4716 }
4717
4718 fn flush_ready_merges(&mut self, inputs: &[InputSlot]) -> Result<bool> {
4724 match &mut self.op {
4725 RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => Ok(false),
4726 RuntimeOp::ScalarOf { input, .. } => input.flush_ready_merges(inputs),
4727 RuntimeOp::ParameterizedMap {
4728 input, parameters, ..
4729 } => {
4730 let mut flushed = input.flush_ready_merges(inputs)?;
4731 for parameter in parameters {
4732 flushed |= parameter.flush_ready_merges(inputs)?;
4733 }
4734 Ok(flushed)
4735 }
4736 RuntimeOp::Instant { input, .. }
4737 | RuntimeOp::Map { input, .. }
4738 | RuntimeOp::Timestamp { input, .. }
4739 | RuntimeOp::Aggregate { input, .. }
4740 | RuntimeOp::Vector { input, .. }
4741 | RuntimeOp::VectorOf { input, .. } => input.flush_ready_merges(inputs),
4742 RuntimeOp::ParameterizedHistogram {
4743 input, parameters, ..
4744 } => {
4745 let mut flushed = input.flush_ready_merges(inputs)?;
4746 for p in parameters.iter_mut().flatten() {
4747 flushed |= p.flush_ready_merges(inputs)?;
4748 }
4749 Ok(flushed)
4750 }
4751 RuntimeOp::ParameterizedTopK {
4752 input, parameter, ..
4753 }
4754 | RuntimeOp::ParameterizedAggregate {
4755 input, parameter, ..
4756 } => {
4757 let mut flushed = input.flush_ready_merges(inputs)?;
4758 if let Some(parameter) = parameter {
4759 flushed |= parameter.flush_ready_merges(inputs)?;
4760 }
4761 Ok(flushed)
4762 }
4763 RuntimeOp::Binary { left, right, .. } | RuntimeOp::Broadcast { left, right, .. } => {
4764 let left_flushed = left.flush_ready_merges(inputs)?;
4765 let right_flushed = right.flush_ready_merges(inputs)?;
4766 Ok(left_flushed || right_flushed)
4767 }
4768 RuntimeOp::Merge {
4769 input,
4770 merge,
4771 state,
4772 } => {
4773 let mut flushed = input.flush_ready_merges(inputs)?;
4774 if merge.is_some() && input.settled(inputs) {
4775 state.flush_canonical_merge(merge)?;
4776 flushed = true;
4777 }
4778 Ok(flushed)
4779 }
4780 RuntimeOp::Window {
4781 input,
4782 window,
4783 merge,
4784 state,
4785 } => {
4786 let mut flushed = input.flush_ready_merges(inputs)?;
4787 if merge.is_some() && input.settled(inputs) {
4790 let Some(evaluator) = window.as_mut() else {
4791 return Err(no_window());
4792 };
4793 state
4794 .flush_merge(evaluator, merge)
4795 .map_err(|error| state.context(error))?;
4796 flushed = true;
4797 }
4798 Ok(flushed)
4799 }
4800 }
4801 }
4802
4803 fn any_merge_pending(&self) -> bool {
4805 match &self.op {
4806 RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => false,
4807 RuntimeOp::ScalarOf { input, .. } => input.any_merge_pending(),
4808 RuntimeOp::ParameterizedMap {
4809 input, parameters, ..
4810 } => input.any_merge_pending() || parameters.iter().any(RuntimeNode::any_merge_pending),
4811 RuntimeOp::Instant { input, .. }
4812 | RuntimeOp::Map { input, .. }
4813 | RuntimeOp::Timestamp { input, .. }
4814 | RuntimeOp::Aggregate { input, .. }
4815 | RuntimeOp::Vector { input, .. }
4816 | RuntimeOp::VectorOf { input, .. } => input.any_merge_pending(),
4817 RuntimeOp::ParameterizedHistogram {
4818 input, parameters, ..
4819 } => {
4820 input.any_merge_pending()
4821 || parameters
4822 .iter()
4823 .flatten()
4824 .any(RuntimeNode::any_merge_pending)
4825 }
4826 RuntimeOp::ParameterizedTopK {
4827 input, parameter, ..
4828 }
4829 | RuntimeOp::ParameterizedAggregate {
4830 input, parameter, ..
4831 } => {
4832 input.any_merge_pending()
4833 || parameter.as_ref().is_some_and(|p| p.any_merge_pending())
4834 }
4835 RuntimeOp::Binary { left, right, .. } | RuntimeOp::Broadcast { left, right, .. } => {
4836 left.any_merge_pending() || right.any_merge_pending()
4837 }
4838 RuntimeOp::Window { input, merge, .. } => merge.is_some() || input.any_merge_pending(),
4840 RuntimeOp::Merge { input, merge, .. } => merge.is_some() || input.any_merge_pending(),
4841 }
4842 }
4843
4844 fn unclosed(&self) -> Result<()> {
4849 match &self.op {
4850 RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => Ok(()),
4851 RuntimeOp::ScalarOf {
4852 input,
4853 retained,
4854 state,
4855 ..
4856 } => {
4857 retained
4858 .ensure_closed(Reader::Vector)
4859 .map_err(|error| state.context(error))?;
4860 input.unclosed()
4861 }
4862 RuntimeOp::ParameterizedMap {
4863 input, parameters, ..
4864 } => {
4865 input.unclosed()?;
4866 parameters.iter().try_for_each(RuntimeNode::unclosed)
4867 }
4868 RuntimeOp::Instant { input, .. }
4869 | RuntimeOp::Map { input, .. }
4870 | RuntimeOp::Timestamp { input, .. }
4871 | RuntimeOp::Window { input, .. }
4872 | RuntimeOp::Aggregate { input, .. }
4873 | RuntimeOp::VectorOf { input, .. }
4874 | RuntimeOp::Merge { input, .. } => input.unclosed(),
4875 RuntimeOp::ParameterizedTopK {
4876 input,
4877 parameter,
4878 vector,
4879 state,
4880 } => {
4881 vector
4882 .input
4883 .ensure_closed(Reader::Vector)
4884 .map_err(|e| state.context(e))?;
4885 input.unclosed()?;
4886 if let Some(parameter) = parameter {
4887 parameter.unclosed()?;
4888 }
4889 Ok(())
4890 }
4891 RuntimeOp::ParameterizedAggregate {
4894 input, parameter, ..
4895 } => {
4896 input.unclosed()?;
4897 if let Some(parameter) = parameter {
4898 parameter.unclosed()?;
4899 }
4900 Ok(())
4901 }
4902 RuntimeOp::ParameterizedHistogram {
4903 input,
4904 parameters,
4905 vector,
4906 state,
4907 ..
4908 } => {
4909 vector
4910 .input
4911 .ensure_closed(Reader::Vector)
4912 .map_err(|e| state.context(e))?;
4913 input.unclosed()?;
4914 parameters
4915 .iter()
4916 .flatten()
4917 .try_for_each(RuntimeNode::unclosed)
4918 }
4919 RuntimeOp::Binary {
4920 left,
4921 right,
4922 binary,
4923 state,
4924 } => {
4925 binary.closed().map_err(|error| state.context(error))?;
4926 left.unclosed()?;
4927 right.unclosed()
4928 }
4929 RuntimeOp::Broadcast { left, right, .. } => {
4930 left.unclosed()?;
4931 right.unclosed()
4932 }
4933 RuntimeOp::Vector {
4934 input,
4935 vector,
4936 state,
4937 } => {
4938 vector
4939 .input
4940 .ensure_closed(Reader::Vector)
4941 .map_err(|error| state.context(error))?;
4942 input.unclosed()
4943 }
4944 }
4945 }
4946
4947 fn finish_windows(&mut self) -> Result<()> {
4952 match &mut self.op {
4953 RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => Ok(()),
4954 RuntimeOp::ScalarOf { input, .. } => input.finish_windows(),
4955 RuntimeOp::ParameterizedMap {
4956 input, parameters, ..
4957 } => {
4958 let first = input.finish_windows();
4960 parameters
4961 .iter_mut()
4962 .map(RuntimeNode::finish_windows)
4963 .fold(first, Result::and)
4964 }
4965 RuntimeOp::Instant { input, .. }
4966 | RuntimeOp::Map { input, .. }
4967 | RuntimeOp::Timestamp { input, .. }
4968 | RuntimeOp::Aggregate { input, .. }
4969 | RuntimeOp::Vector { input, .. }
4970 | RuntimeOp::VectorOf { input, .. }
4971 | RuntimeOp::Merge { input, .. } => input.finish_windows(),
4972 RuntimeOp::ParameterizedTopK {
4973 input, parameter, ..
4974 }
4975 | RuntimeOp::ParameterizedAggregate {
4976 input, parameter, ..
4977 } => {
4978 let first = input.finish_windows();
4979 let parameter = parameter.as_mut().map_or(Ok(()), |p| p.finish_windows());
4980 first.and(parameter)
4981 }
4982 RuntimeOp::ParameterizedHistogram {
4983 input, parameters, ..
4984 } => {
4985 let first = input.finish_windows();
4986 parameters
4987 .iter_mut()
4988 .flatten()
4989 .map(RuntimeNode::finish_windows)
4990 .fold(first, Result::and)
4991 }
4992 RuntimeOp::Binary { left, right, .. } | RuntimeOp::Broadcast { left, right, .. } => {
4993 let first = left.finish_windows();
4996 let second = right.finish_windows();
4997 first.and(second)
4998 }
4999 RuntimeOp::Window {
5000 input,
5001 window,
5002 state,
5003 ..
5004 } => {
5005 let child = input.finish_windows();
5006 let own = window
5008 .take()
5009 .map_or(Ok(()), |evaluator| {
5010 state.buffer.reserve_grid(evaluator.grid())?;
5011 RangeEvaluator::finish(evaluator)
5012 })
5013 .map_err(|error| state.context(error));
5014 child.and(own)
5015 }
5016 }
5017 }
5018}
5019
5020#[derive(Clone, Debug, Default)]
5028pub struct SourceFacts {
5029 tags: Vec<Vec<String>>,
5031 metrics: Vec<Option<Arc<str>>>,
5034}
5035
5036impl SourceFacts {
5037 pub fn none() -> Self {
5039 Self::default()
5040 }
5041
5042 pub fn uniform(tags: Vec<String>, metric: Option<Arc<str>>, sources: usize) -> Self {
5048 Self {
5049 tags: vec![tags; sources],
5050 metrics: vec![metric; sources],
5051 }
5052 }
5053}
5054
5055impl NativeExecutionState {
5056 pub fn try_new(
5057 tree: &NativeTree,
5058 pool: Arc<dyn MemoryPool>,
5059 duplicate_evidence: Option<Arc<DuplicateEvidence>>,
5060 ) -> Result<Self> {
5061 Self::try_new_with_sources(tree, pool, duplicate_evidence, &SourceFacts::none())
5062 }
5063
5064 pub fn try_new_with_sources(
5069 tree: &NativeTree,
5070 pool: Arc<dyn MemoryPool>,
5071 duplicate_evidence: Option<Arc<DuplicateEvidence>>,
5072 sources: &SourceFacts,
5073 ) -> Result<Self> {
5074 let mut inputs = Vec::new();
5075 let mut binary_before = 0usize;
5076 let root = RuntimeNode::build(
5077 tree.root(),
5078 &pool,
5079 &mut inputs,
5080 &mut binary_before,
5081 "root".to_string(),
5082 duplicate_evidence.clone(),
5083 sources,
5084 )?;
5085 let scalar_root = match (&tree.root().expr, &tree.root().output) {
5087 (NativeExpr::Scalar(BoundScalar { value }), NativeType::Scalar(grid)) => Some((
5088 Arc::clone(grid),
5089 *value,
5090 NodeState::new(
5091 "native.scalar at root".to_string(),
5092 Arc::clone(&root.metrics),
5093 &pool,
5094 ),
5095 )),
5096 _ => None,
5097 };
5098 match &tree.root().output {
5099 NativeType::Scalar(_) => {}
5100 NativeType::Samples(schema) if schema.eval_grid.is_some() => {}
5101 NativeType::Samples(_) => {
5102 return Err(DataFusionError::Execution(
5103 "native runtime root produces raw samples".to_string(),
5104 ));
5105 }
5106 NativeType::AggregateState(_) => {}
5110 }
5111 Ok(Self {
5112 live: Some(LiveExecution {
5113 root,
5114 inputs,
5115 scalar_root,
5116 }),
5117 })
5118 }
5119
5120 pub fn set_annotations(&mut self, collector: Option<PromqlAnnotationCollector>) {
5121 if let (Some(live), Some(collector)) = (&mut self.live, collector) {
5122 live.root.set_annotations(collector);
5123 }
5124 }
5125
5126 pub(crate) fn register_metrics(&self, set: &ExecutionPlanMetricsSet, partition: usize) {
5131 if let Some(live) = &self.live {
5132 live.root.register_metrics("root", set, partition);
5133 }
5134 }
5135
5136 pub fn input_ids(&self, source_index: usize) -> impl Iterator<Item = InputId> + '_ {
5138 self.live
5139 .iter()
5140 .flat_map(|live| live.inputs.iter())
5141 .enumerate()
5142 .filter(move |(_, slot)| slot.source_index == source_index)
5143 .map(|(index, _)| InputId::new(index))
5144 }
5145
5146 pub fn reserved_bytes(&self) -> usize {
5147 self.live.as_ref().map_or(0, |live| {
5148 live.inputs
5149 .iter()
5150 .map(|slot| slot.state.buffer.reservation.size())
5151 .fold(0usize, usize::saturating_add)
5152 .saturating_add(live.root.reserved_bytes())
5153 .saturating_add(
5154 live.scalar_root
5155 .as_ref()
5156 .map_or(0, |(_, _, state)| state.buffer.reservation.size()),
5157 )
5158 })
5159 }
5160}
5161
5162impl LiveExecution {
5164 fn pull(&mut self, inputs_finished: bool) -> Result<Option<NativeChunk>> {
5167 if let Some((grid, value, mut state)) = self.scalar_root.take() {
5168 let bytes = grid_chunk_bytes(&grid).map_err(|error| state.context(error))?;
5169 state
5170 .buffer
5171 .grow(bytes)
5172 .map_err(|error| state.context(error))?;
5173 let chunk = scalar_chunk(grid, value).map_err(|error| state.context(error))?;
5174 state.buffer.metrics.record_completed_series(1);
5175 state
5176 .queued
5177 .push_back((NativeChunk::Evaluated(chunk), bytes));
5178 return state.pop_queued(evaluated_values);
5179 }
5180 self.root.pull(&mut self.inputs, inputs_finished)
5181 }
5182
5183 fn unclosed(&self) -> Result<()> {
5189 if let Some(index) = self.inputs.iter().position(InputSlot::ends_open) {
5190 let slot = &self.inputs[index];
5191 return Err(slot.state.context(truncated_input(InputId::new(index))));
5192 }
5193 self.root.unclosed()
5194 }
5195
5196 fn flush_ready_merges(&mut self) -> Result<bool> {
5198 self.root.flush_ready_merges(&self.inputs)
5199 }
5200
5201 fn any_merge_pending(&self) -> bool {
5203 self.root.any_merge_pending()
5204 }
5205
5206 fn close(mut self) -> Result<()> {
5208 self.root.finish_windows()
5209 }
5210}
5211
5212impl NodeState {
5213 fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> {
5217 let positions = chunk.positions();
5218 let bytes = chunk.bytes();
5219 self.buffer.grow(bytes)?;
5222 self.queued.push_back((chunk, bytes));
5223 self.buffer.metrics.record_input(1, positions);
5224 Ok(())
5225 }
5226
5227 fn pop_queued(&mut self, values: fn(&NativeChunk) -> usize) -> Result<Option<NativeChunk>> {
5233 let Some((mut chunk, bytes)) = self.queued.pop_front() else {
5234 return Ok(None);
5235 };
5236 let moved = match &mut chunk {
5239 NativeChunk::AggregateState(StateChunk::Series { reservation, .. }) => {
5240 debug_assert!(
5241 reservation.is_none(),
5242 "a handed-over state chunk was charged to a queue twice"
5243 );
5244 let transferred = self.buffer.transfer(bytes)?;
5245 let moved = transferred.size();
5246 *reservation = Some(transferred);
5247 moved
5248 }
5249 _ => 0,
5250 };
5251 let metrics = Arc::clone(&self.buffer.metrics);
5252 {
5253 let _timer = metrics.timer();
5257 self.buffer.shrink(bytes - moved)?;
5258 self.release_queued_tables()?;
5259 }
5260 metrics.record_output(1, values(&chunk));
5261 if let NativeChunk::Evaluated(chunk) = &chunk {
5264 metrics.record_grid_points(chunk.series.time.len());
5265 }
5266 Ok(Some(chunk))
5267 }
5268
5269 fn map(&mut self, map: &MapRuntime, chunk: EvaluatedChunk) -> Result<Option<EvaluatedChunk>> {
5273 let (positions, closing) = (chunk.series.time.len(), chunk.is_last);
5274 let workspace = map_workspace_bytes(&map.ops, &chunk.series)?;
5277 self.buffer.grow(evaluated_bytes(&chunk))?;
5278 self.buffer.grow(workspace)?;
5279 let metrics = Arc::clone(&self.buffer.metrics);
5280 let outcome = {
5281 let _timer = metrics.timer();
5284 map_chunk(&map.schema, &chunk, &map.ops, &mut |bytes| {
5285 self.buffer.grow(bytes)
5286 })
5287 };
5288 metrics.record_input(1, positions);
5289 if closing {
5290 metrics.record_completed_series(1);
5291 }
5292 let output = match outcome {
5295 Ok(output) => output,
5296 Err(error) => {
5297 self.buffer.resize(0)?;
5298 return Err(error);
5299 }
5300 };
5301 if let Some(output) = &output {
5302 metrics.record_grid_points(output.series.time.len());
5303 metrics.record_output(1, valid_values(output));
5304 }
5305 self.buffer.resize(0)?;
5309 Ok(output)
5310 }
5311
5312 fn parameterized_map(
5317 &mut self,
5318 map: &ParameterizedMapRuntime,
5319 chunk: EvaluatedChunk,
5320 ) -> Result<Option<EvaluatedChunk>> {
5321 let (positions, closing) = (chunk.series.time.len(), chunk.is_last);
5322 let workspace = built_series_workspace_bytes(&chunk.series)?;
5323 self.buffer.grow(evaluated_bytes(&chunk))?;
5324 self.buffer.grow(workspace)?;
5325 let metrics = Arc::clone(&self.buffer.metrics);
5326 let outcome = {
5327 let _timer = metrics.timer();
5328 map.apply(&chunk)
5329 };
5330 metrics.record_input(1, positions);
5331 if closing {
5332 metrics.record_completed_series(1);
5333 }
5334 let outcome = match outcome {
5336 Ok(outcome) => outcome,
5337 Err(error) => {
5338 self.buffer.resize(map.parameter_bytes)?;
5339 return Err(error);
5340 }
5341 };
5342 let output = match outcome {
5343 Some(series) => Some(EvaluatedChunk::try_new(series, closing)?),
5344 None if closing => {
5347 let metric = drop_metric_name(&chunk.series.metric)?;
5348 let empty = no_row_series(&map.schema, &chunk.series, metric)?;
5349 Some(EvaluatedChunk::try_new(empty, true)?)
5350 }
5351 None => None,
5352 };
5353 if let Some(output) = &output {
5354 metrics.record_grid_points(output.series.time.len());
5355 metrics.record_output(1, valid_values(output));
5356 }
5357 self.buffer.resize(map.parameter_bytes)?;
5359 Ok(output)
5360 }
5361
5362 fn timestamp(
5364 &mut self,
5365 schema: &Arc<SeriesSchema>,
5366 chunk: EvaluatedChunk,
5367 ) -> Result<Option<EvaluatedChunk>> {
5368 let positions = chunk.series.time.len();
5369 let closing = chunk.is_last;
5370 if let Some(grid) = schema.eval_grid.as_deref() {
5375 self.buffer.reserve_grid(grid)?;
5376 }
5377 let workspace = built_series_workspace_bytes(&chunk.series)?;
5378 self.buffer.grow(evaluated_bytes(&chunk))?;
5379 self.buffer.grow(workspace)?;
5380 let labels = drop_metric_name(&chunk.series.metric)?;
5381 let metrics = Arc::clone(&self.buffer.metrics);
5382 let result = {
5383 let _timer = metrics.timer();
5384 timestamp_of_evaluated(schema, &chunk.series)
5385 };
5386 metrics.record_input(1, positions);
5387 if closing {
5388 metrics.record_completed_series(1);
5389 }
5390 let result = match result {
5392 Ok(result) => result,
5393 Err(error) => {
5394 self.buffer.resize(0)?;
5395 return Err(error);
5396 }
5397 };
5398 let output = match result {
5399 Some(series) => Some(EvaluatedChunk::try_new(series, closing)?),
5400 None if closing => Some(no_row_chunk(schema, labels)?),
5401 None => None,
5402 };
5403 if let Some(output) = &output {
5404 metrics.record_grid_points(output.series.time.len());
5405 metrics.record_output(1, valid_values(output));
5406 }
5407 self.buffer.resize(0)?;
5408 Ok(output)
5409 }
5410
5411 fn broadcast(
5416 &mut self,
5417 broadcast: &BroadcastRuntime,
5418 chunk: NativeChunk,
5419 ) -> Result<Option<EvaluatedChunk>> {
5420 let NativeChunk::Evaluated(chunk) = chunk else {
5421 return Err(DataFusionError::Execution(
5422 "the binary node broadcasts over an evaluated vector, not raw samples".to_string(),
5423 ));
5424 };
5425 let (positions, closing) = (chunk.series.time.len(), chunk.is_last);
5426 let workspace = match (&broadcast.scalar, broadcast.op) {
5430 (BroadcastScalar::Literal(_), BroadcastOp::Arithmetic(_)) => {
5431 mapped_workspace_bytes(&chunk.series)?
5432 }
5433 _ => built_series_workspace_bytes(&chunk.series)?,
5434 };
5435 self.buffer.grow(evaluated_bytes(&chunk))?;
5436 self.buffer.grow(workspace)?;
5437 let metrics = Arc::clone(&self.buffer.metrics);
5438 let outcome = {
5439 let _timer = metrics.timer();
5442 broadcast.apply(&chunk)
5443 };
5444 metrics.record_input(1, positions);
5445 if closing {
5446 metrics.record_completed_series(1);
5449 }
5450 let output = match outcome {
5452 Ok(output) => output,
5453 Err(error) => {
5454 self.buffer.resize(broadcast.scalar_bytes)?;
5455 return Err(error);
5456 }
5457 };
5458 let output = match output {
5459 Some(series) => Some(EvaluatedChunk::try_new(series, closing)?),
5460 None => None,
5461 };
5462 if let Some(output) = &output {
5463 metrics.record_grid_points(output.series.time.len());
5464 metrics.record_output(1, valid_values(output));
5465 }
5466 self.buffer.resize(broadcast.scalar_bytes)?;
5468 Ok(output)
5469 }
5470
5471 fn hold_scalar(
5473 &mut self,
5474 held: &mut usize,
5475 slot: &mut Option<Series>,
5476 chunk: NativeChunk,
5477 ) -> Result<()> {
5478 let NativeChunk::Evaluated(EvaluatedChunk { series, is_last }) = chunk else {
5479 return Err(DataFusionError::Execution(
5480 "a scalar operand is an evaluated series, not raw samples".to_string(),
5481 ));
5482 };
5483 if slot.is_some() || !is_last {
5484 return Err(DataFusionError::Execution(
5485 "a scalar operand hands over exactly one closed chunk".to_string(),
5486 ));
5487 }
5488 let bytes = series_bytes(&series);
5489 self.buffer.grow(bytes)?;
5490 *held = held.saturating_add(bytes);
5491 *slot = Some(series);
5492 Ok(())
5493 }
5494
5495 fn hold_constant(
5497 &mut self,
5498 held: &mut usize,
5499 slot: &mut Option<Series>,
5500 grid: Arc<EvalGrid>,
5501 value: f64,
5502 ) -> Result<()> {
5503 let bytes = grid_chunk_bytes(&grid)?;
5504 self.buffer.grow(bytes)?;
5505 *held = held.saturating_add(bytes);
5506 *slot = Some(scalar_chunk(grid, value)?.series);
5507 Ok(())
5508 }
5509
5510 fn produce(&mut self, grid: &EvalGrid, series: impl FnOnce() -> Result<Series>) -> Result<()> {
5513 let bytes = grid_chunk_bytes(grid)?;
5514 self.buffer.grow(bytes)?;
5515 let chunk = EvaluatedChunk::try_new(series()?, true)?;
5516 self.buffer.metrics.record_completed_series(1);
5517 self.queued
5518 .push_back((NativeChunk::Evaluated(chunk), bytes));
5519 Ok(())
5520 }
5521
5522 fn window(
5528 &mut self,
5529 window: &mut RangeEvaluator,
5530 merge: &mut Option<MergeInput>,
5531 chunk: NativeChunk,
5532 ) -> Result<Option<EvaluatedChunk>> {
5533 self.buffer.reserve_grid(window.grid())?;
5536 if let Some(merge) = merge.as_mut() {
5537 let NativeChunk::Evaluated(chunk) = chunk else {
5538 return Err(DataFusionError::Execution(
5539 "the window collects evaluated fragments, but it was handed raw samples"
5540 .to_string(),
5541 ));
5542 };
5543 return self.collect(merge, window, chunk);
5544 }
5545 let (positions, closing) = (chunk.positions(), chunk.is_last());
5546 let (fields, metric) = match &chunk {
5550 NativeChunk::Raw(chunk) => (&chunk.fields, chunk.metric.as_ref()),
5551 NativeChunk::Evaluated(chunk) => (&chunk.series.fields, Some(&chunk.series.metric)),
5552 NativeChunk::AggregateState(_) => {
5553 return Err(DataFusionError::Execution(
5554 "an aggregate state chunk reached a node that reads values or samples"
5555 .to_string(),
5556 ));
5557 }
5558 };
5559 let workspace = match metric {
5560 Some(metric) => {
5561 window_workspace_bytes(window, last_sample_ms(&chunk)?, closing, fields, metric)?
5562 }
5563 None => 0,
5565 };
5566 self.buffer.grow(chunk.bytes())?;
5567 self.buffer.grow(workspace)?;
5568 let metrics = Arc::clone(&self.buffer.metrics);
5569 let outcome = {
5570 let _timer = metrics.timer();
5571 match &chunk {
5572 NativeChunk::Raw(chunk) => window.push(chunk),
5574 NativeChunk::Evaluated(chunk) => window.push_series(&chunk.series, chunk.is_last),
5578 NativeChunk::AggregateState(_) => {
5579 return Err(DataFusionError::Execution(
5580 "an aggregate state chunk reached a node that reads values or samples"
5581 .to_string(),
5582 ));
5583 }
5584 }
5585 };
5586 metrics.record_input(1, positions);
5587 if closing {
5588 metrics.record_completed_series(1);
5591 }
5592 let output = match outcome {
5594 Ok(output) => output,
5595 Err(error) => {
5596 self.buffer.resize(window.retained_bytes())?;
5597 return Err(error);
5598 }
5599 };
5600 if let Some(output) = &output {
5601 metrics.record_grid_points(output.series.time.len());
5602 metrics.record_output(1, valid_values(output));
5603 }
5604 self.buffer.resize(window.retained_bytes())?;
5609 Ok(output)
5610 }
5611
5612 fn retain_binary(
5617 &mut self,
5618 binary: &mut BinaryRuntime,
5619 side: usize,
5620 chunk: NativeChunk,
5621 ) -> Result<()> {
5622 let NativeChunk::Evaluated(chunk) = chunk else {
5623 return Err(DataFusionError::Execution(format!(
5624 "{} consumes evaluated chunks, not raw samples",
5625 binary.kernel.node()
5626 )));
5627 };
5628 let pending = binary.pending(side, &chunk)?;
5631 let positions = chunk.series.time.len();
5632 self.buffer.grow(pending)?;
5633 let metrics = Arc::clone(&self.buffer.metrics);
5634 {
5635 let _timer = metrics.timer();
5636 binary.retain(side, chunk)?;
5637 let retained = binary.retained_bytes();
5638 self.buffer.resize(retained)?;
5639 }
5640 metrics.record_input(1, positions);
5641 Ok(())
5642 }
5643
5644 fn compute_binary(&mut self, binary: &mut BinaryRuntime) -> Result<()> {
5646 let output = binary.compute(&mut self.buffer)?;
5647 let Some(output) = output else {
5650 return Ok(());
5651 };
5652 self.queue_results(output, false, 0)
5653 }
5654
5655 fn settle_vector(&mut self, vector: &VectorRuntime) -> Result<()> {
5659 let held = vector.input.held.saturating_add(vector.parameter_bytes);
5660 self.buffer.resize(held)
5661 }
5662
5663 fn retain_vector(&mut self, vector: &mut VectorRuntime, chunk: NativeChunk) -> Result<()> {
5666 let NativeChunk::Evaluated(chunk) = chunk else {
5667 return Err(DataFusionError::Execution(
5668 "the vector operation consumes evaluated chunks, not raw samples".to_string(),
5669 ));
5670 };
5671 validate_binary_operand(vector.schema.as_ref(), std::slice::from_ref(&chunk.series))
5674 .map_err(|error| {
5675 DataFusionError::Execution(format!(
5676 "the vector operation rejected its input: {error}"
5677 ))
5678 })?;
5679 let pending = vector.input.pending(&chunk);
5680 let positions = chunk.series.time.len();
5681 self.buffer.grow(pending)?;
5682 let metrics = Arc::clone(&self.buffer.metrics);
5683 {
5684 let _timer = metrics.timer();
5685 vector.input.retain(chunk, Reader::Vector)?;
5686 self.settle_vector(vector)?;
5689 }
5690 metrics.record_input(1, positions);
5691 Ok(())
5692 }
5693
5694 fn compute_histogram(
5696 &mut self,
5697 vector: &mut VectorRuntime,
5698 parameters: &[&[Option<f64>]],
5699 ) -> Result<()> {
5700 let output = vector.compute_with_histogram_parameters(&mut self.buffer, parameters)?;
5701 if let Some(output) = output {
5702 self.queue_results(output, false, vector.parameter_bytes)?;
5703 }
5704 Ok(())
5705 }
5706
5707 fn compute_vector(&mut self, vector: &mut VectorRuntime) -> Result<()> {
5708 let shares_input = matches!(vector.op, BoundVectorOp::Sort(_));
5709 let output = vector.compute(&mut self.buffer)?;
5710 let Some(output) = output else {
5711 return Ok(());
5712 };
5713 self.queue_results(output, shares_input, vector.parameter_bytes)
5714 }
5715
5716 fn queue_results(
5725 &mut self,
5726 output: Vec<Series>,
5727 shares_input: bool,
5728 beside: usize,
5729 ) -> Result<()> {
5730 let mut tables = HashSet::new();
5731 let mut closed = 0usize;
5734 for series in output {
5735 let bytes = if shares_input {
5738 let (fresh, table_bytes) = unbilled_tables(&series, &tables);
5739 tables.extend(fresh);
5740 self.queued_tables = self.queued_tables.saturating_add(table_bytes);
5741 operand_chunk_bytes(&series)
5742 } else {
5743 series_bytes(&series)
5744 };
5745 let chunk = NativeChunk::Evaluated(EvaluatedChunk::try_new(series, true)?);
5746 self.queued.push_back((chunk, bytes));
5747 closed += 1;
5748 }
5749 self.buffer.metrics.record_completed_series(closed);
5753 let queued = self
5757 .queued
5758 .iter()
5759 .fold(self.queued_tables, |total, (_, bytes)| {
5760 total.saturating_add(*bytes)
5761 });
5762 self.buffer.resize(queued.saturating_add(beside))
5763 }
5764
5765 fn retain_aggregate(
5770 &mut self,
5771 aggregate: &mut AggregateRuntime,
5772 chunk: NativeChunk,
5773 ) -> Result<()> {
5774 if let NativeChunk::AggregateState(chunk) = chunk {
5778 let pending = aggregate.pending_state(&chunk);
5779 let positions = match &chunk {
5780 StateChunk::Series { series, .. } => {
5781 series.iter().map(|series| series.time.len()).sum()
5782 }
5783 StateChunk::Row(row) => row.time.len(),
5784 };
5785 self.buffer.grow(pending)?;
5786 let metrics = Arc::clone(&self.buffer.metrics);
5787 {
5788 let _timer = metrics.timer();
5789 aggregate.accumulate_state(chunk, &mut self.buffer, pending)?;
5790 }
5791 metrics.record_input(1, positions);
5792 return Ok(());
5793 }
5794 let NativeChunk::Evaluated(chunk) = chunk else {
5795 return Err(DataFusionError::Execution(
5796 "the aggregate consumes evaluated chunks, not raw samples".to_string(),
5797 ));
5798 };
5799 let pending = aggregate.pending(&chunk);
5802 let positions = chunk.series.time.len();
5803 self.buffer.grow(pending)?;
5804 let metrics = Arc::clone(&self.buffer.metrics);
5805 {
5806 let _timer = metrics.timer();
5807 aggregate.accumulate(chunk, &mut self.buffer, pending)?;
5808 }
5809 metrics.record_input(1, positions);
5810 Ok(())
5814 }
5815
5816 fn compute_aggregate(&mut self, aggregate: &mut AggregateRuntime) -> Result<()> {
5821 let metrics = Arc::clone(&self.buffer.metrics);
5822 let _timer = metrics.timer();
5823 let groups = aggregate.groups();
5824 let queue_capacity = self.queued.capacity();
5825 let queue_target = self.queued.len().saturating_add(groups);
5826 let queue_growth = queue_target
5827 .saturating_sub(queue_capacity)
5828 .saturating_mul(std::mem::size_of::<(NativeChunk, usize)>());
5829 self.buffer.grow(queue_growth)?;
5830 if groups > 0 {
5831 self.queued.try_reserve_exact(groups).map_err(|error| {
5832 DataFusionError::Execution(format!(
5833 "cannot reserve aggregate output queue: {error}"
5834 ))
5835 })?;
5836 }
5837 let queue_bytes = queue_target
5838 .max(queue_capacity)
5839 .saturating_mul(std::mem::size_of::<(NativeChunk, usize)>());
5840 let output = aggregate.compute(&mut self.buffer, queue_bytes)?;
5841 let Some(output) = output else {
5843 return Ok(());
5844 };
5845 let mut closed = 0usize;
5846 match output {
5847 AggregateOutput::Samples(series) => {
5848 for series in series {
5849 let bytes = series_bytes(&series);
5850 let chunk = NativeChunk::Evaluated(EvaluatedChunk::try_new(series, true)?);
5851 self.queued.push_back((chunk, bytes));
5852 closed += 1;
5853 }
5854 }
5855 AggregateOutput::State(chunk) => {
5859 let StateChunk::Series { series, .. } = &chunk else {
5860 return Err(DataFusionError::Internal(
5861 "Partial aggregate produced row state".into(),
5862 ));
5863 };
5864 closed = series.len();
5865 let bytes = state_bytes(&chunk);
5866 self.queued
5867 .push_back((NativeChunk::AggregateState(chunk), bytes));
5868 }
5869 }
5870 self.buffer.metrics.record_completed_series(closed);
5873 let queued_bytes = self
5875 .queued
5876 .iter()
5877 .fold(0usize, |total, (_, bytes)| total.saturating_add(*bytes));
5878 let queue_backing = self
5879 .queued
5880 .capacity()
5881 .saturating_mul(std::mem::size_of::<(NativeChunk, usize)>());
5882 self.buffer
5883 .resize(queued_bytes.saturating_add(queue_backing))
5884 }
5885
5886 fn instant(
5888 &mut self,
5889 instant: &mut InstantRuntime,
5890 chunk: NativeChunk,
5891 ) -> Result<Option<EvaluatedChunk>> {
5892 let NativeChunk::Raw(chunk) = chunk else {
5893 return Err(DataFusionError::Execution(
5894 "the instant selection consumes raw samples, not an evaluated chunk".to_string(),
5895 ));
5896 };
5897 let (positions, closing) = (chunk.time.len(), chunk.is_last);
5898 if instant.selection.value != InstantValue::Sample {
5901 self.buffer.reserve_grid(&instant.selection.output_grid)?;
5902 }
5903 self.buffer.grow(raw_bytes(&chunk))?;
5906 let scratch = if closing {
5911 instant.gather_bytes(&chunk)
5912 } else {
5913 0
5914 };
5915 self.buffer.grow(scratch)?;
5916 let metrics = Arc::clone(&self.buffer.metrics);
5917 let outcome = {
5918 let _timer = metrics.timer();
5921 instant.push(chunk)
5922 };
5923 metrics.record_input(1, positions);
5924 if closing {
5925 metrics.record_completed_series(1);
5928 }
5929 let output = match outcome {
5932 Ok(output) => output,
5933 Err(error) => {
5934 self.settle_buffered(instant)?;
5935 return Err(error);
5936 }
5937 };
5938 if let Some(output) = &output {
5939 metrics.record_grid_points(output.series.time.len());
5940 metrics.record_output(1, valid_values(output));
5941 }
5942 self.settle_buffered(instant)?;
5946 Ok(output)
5947 }
5948
5949 fn settle_buffered(&mut self, instant: &InstantRuntime) -> Result<()> {
5951 self.buffer.resize(instant.buffered_bytes())
5952 }
5953
5954 fn collect_merge(&mut self, merge: &mut MergeInput, chunk: EvaluatedChunk) -> Result<()> {
5956 let EvaluatedChunk { series, is_last } = chunk;
5957 merge.check(&series, is_last)?;
5958 let bytes = series_bytes(&series);
5959 self.buffer.grow(bytes)?;
5960 merge.bytes = merge.bytes.saturating_add(bytes);
5961 merge.fragments.push(series);
5962 self.buffer
5963 .metrics
5964 .record_input(1, merge.fragments.last().map_or(0, |s| s.time.len()));
5965 if is_last {
5966 self.buffer.metrics.record_completed_series(1);
5967 }
5968 Ok(())
5969 }
5970
5971 fn flush_canonical_merge(&mut self, merge: &mut Option<MergeInput>) -> Result<()> {
5973 let Some(merge) = merge.take() else {
5974 return Ok(());
5975 };
5976 if merge.fragments.is_empty() {
5977 return self.buffer.shrink(merge.bytes);
5978 }
5979 let workspace = merge.workspace_bytes();
5980 self.buffer.grow(workspace)?;
5981 let held = merge.bytes.saturating_add(workspace);
5982 let merged = merge_same_labelset(&merge.schema, merge.fragments)?;
5983 for series in merged {
5984 let chunk = EvaluatedChunk::try_new(series, true)?;
5985 self.buffer
5986 .metrics
5987 .record_grid_points(chunk.series.time.len());
5988 self.buffer.metrics.record_output(1, valid_values(&chunk));
5989 let bytes = series_bytes(&chunk.series);
5990 self.buffer.grow(bytes)?;
5991 self.queued
5992 .push_back((NativeChunk::Evaluated(chunk), bytes));
5993 }
5994 self.buffer.shrink(held)
5995 }
5996
5997 fn collect(
6002 &mut self,
6003 merge: &mut MergeInput,
6004 window: &RangeEvaluator,
6005 chunk: EvaluatedChunk,
6006 ) -> Result<Option<EvaluatedChunk>> {
6007 self.collect_merge(merge, chunk)?;
6008 let retained = window.retained_bytes();
6010 self.buffer.resize(retained.saturating_add(merge.bytes))?;
6011 Ok(None)
6012 }
6013
6014 fn flush_merge(
6020 &mut self,
6021 window: &mut RangeEvaluator,
6022 merge: &mut Option<MergeInput>,
6023 ) -> Result<()> {
6024 let Some(merge) = merge.take() else {
6025 return Ok(());
6026 };
6027 if merge.fragments.is_empty() {
6028 return self.buffer.shrink(merge.bytes);
6031 }
6032 self.buffer.reserve_grid(window.grid())?;
6034 let workspace = merge.workspace_bytes();
6037 let held = merge.bytes.saturating_add(workspace);
6038 let schema = Arc::clone(&merge.schema);
6039 self.buffer.grow(workspace)?;
6040 let mut queued_bytes = self
6043 .queued
6044 .iter()
6045 .fold(self.queued_tables, |total, (_, bytes)| {
6046 total.saturating_add(*bytes)
6047 });
6048 let merged = merge_same_labelset(&schema, merge.fragments)?;
6052 for series in merged {
6053 let workspace = window_workspace_bytes(
6054 window,
6055 last_series_ms(&series),
6056 true,
6057 &series.fields,
6058 &series.metric,
6059 )?;
6060 self.buffer.grow(workspace)?;
6061 let output = {
6062 let metrics = Arc::clone(&self.buffer.metrics);
6063 let _timer = metrics.timer();
6064 window.push_series(&series, true)?
6065 };
6066 let Some(output) = output else {
6067 self.buffer.shrink(workspace)?;
6068 continue;
6069 };
6070 self.buffer
6071 .metrics
6072 .record_grid_points(output.series.time.len());
6073 self.buffer.metrics.record_output(1, valid_values(&output));
6074 let retained = window.retained_bytes();
6075 self.buffer
6076 .resize(retained.saturating_add(held).saturating_add(queued_bytes))?;
6077 let bytes = evaluated_bytes(&output);
6078 self.enqueue_output(output)?;
6079 queued_bytes = queued_bytes.saturating_add(bytes);
6080 }
6081 self.buffer.shrink(held)
6084 }
6085
6086 fn enqueue_output(&mut self, chunk: EvaluatedChunk) -> Result<()> {
6089 let bytes = evaluated_bytes(&chunk);
6090 self.buffer.grow(bytes)?;
6091 self.queued
6092 .push_back((NativeChunk::Evaluated(chunk), bytes));
6093 Ok(())
6094 }
6095
6096 fn take_output(&mut self) -> Result<Option<NativeChunk>> {
6098 let Some((chunk, bytes)) = self.queued.pop_front() else {
6099 return Ok(None);
6100 };
6101 self.buffer.shrink(bytes)?;
6102 self.release_queued_tables()?;
6103 Ok(Some(chunk))
6104 }
6105
6106 fn release_queued_tables(&mut self) -> Result<()> {
6108 if self.queued.is_empty() && self.queued_tables > 0 {
6109 self.buffer
6110 .shrink(std::mem::take(&mut self.queued_tables))?;
6111 }
6112 Ok(())
6113 }
6114}
6115
6116impl InputSlot {
6117 fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> {
6122 if !self.kind.accepts(&chunk) {
6123 return Err(self.state.context(DataFusionError::Execution(format!(
6124 "the native source is bound to {}, but {} was queued at it",
6125 self.kind.describe(),
6126 chunk.describe(),
6127 ))));
6128 }
6129 let closing = chunk.is_last();
6134 self.state
6135 .enqueue(chunk)
6136 .map_err(|error| self.state.context(error))?;
6137 self.open_queued_series = !closing;
6138 Ok(())
6139 }
6140
6141 fn pop_source(&mut self) -> Result<Option<NativeChunk>> {
6147 let Some(chunk) = self.state.pop_queued(NativeChunk::positions)? else {
6148 return Ok(None);
6149 };
6150 self.open_source_series = !chunk.is_last();
6153 if chunk.is_last() {
6154 self.state.buffer.metrics.record_completed_series(1);
6155 }
6156 Ok(Some(chunk))
6157 }
6158}
6159
6160pub struct NativeExecutor {
6169 state: NativeExecutionState,
6170 phase: Phase,
6171 inputs_finished: bool,
6177 ended: bool,
6183}
6184
6185#[derive(Clone, Debug, PartialEq, Eq)]
6187enum Phase {
6188 Running,
6190 Finished,
6192 Failed(String),
6194}
6195
6196impl NativeExecutor {
6197 pub fn new(state: NativeExecutionState) -> Self {
6199 Self {
6200 state,
6201 phase: Phase::Running,
6202 inputs_finished: false,
6203 ended: false,
6204 }
6205 }
6206
6207 pub fn state(&self) -> &NativeExecutionState {
6209 &self.state
6210 }
6211
6212 fn live(&self) -> Result<&LiveExecution> {
6213 self.state.live.as_ref().ok_or_else(no_live_execution)
6214 }
6215
6216 fn live_mut(&mut self) -> Result<&mut LiveExecution> {
6217 self.state.live.as_mut().ok_or_else(no_live_execution)
6218 }
6219
6220 pub fn push_raw(&mut self, input: InputId, chunk: RawSeriesChunk) -> Result<()> {
6225 self.push_source(input, NativeChunk::Raw(chunk))
6226 }
6227
6228 pub fn push_evaluated(&mut self, input: InputId, chunk: EvaluatedChunk) -> Result<()> {
6230 self.push_source(input, NativeChunk::Evaluated(chunk))
6231 }
6232
6233 pub(crate) fn push_state(&mut self, input: InputId, chunk: StateChunk) -> Result<()> {
6237 self.push_source(input, NativeChunk::AggregateState(chunk))
6238 }
6239
6240 pub fn next_chunk(&mut self) -> Result<Option<EvaluatedChunk>> {
6251 match self.next_output()? {
6252 Some(NativeChunk::Evaluated(chunk)) => Ok(Some(chunk)),
6253 Some(NativeChunk::Raw(_)) => {
6254 let error = DataFusionError::Execution(
6255 "the native runtime produces evaluated chunks, but its root produced raw \
6256 samples"
6257 .to_string(),
6258 );
6259 self.stop(&error);
6260 Err(error)
6261 }
6262 Some(NativeChunk::AggregateState(_)) => {
6263 let error = DataFusionError::Execution(
6264 "the native runtime produces evaluated chunks, but its root produced \
6265 aggregate state"
6266 .to_string(),
6267 );
6268 self.stop(&error);
6269 Err(error)
6270 }
6271 None => Ok(None),
6272 }
6273 }
6274
6275 pub(crate) fn next_state(&mut self) -> Result<Option<StateChunk>> {
6280 match self.next_output()? {
6281 Some(NativeChunk::AggregateState(chunk)) => Ok(Some(chunk)),
6282 Some(other) => {
6283 let error = DataFusionError::Execution(format!(
6284 "the native runtime produces aggregate state, but its root produced {}",
6285 other.describe()
6286 ));
6287 self.stop(&error);
6288 Err(error)
6289 }
6290 None => Ok(None),
6291 }
6292 }
6293
6294 fn next_output(&mut self) -> Result<Option<NativeChunk>> {
6297 self.check_running()?;
6298 loop {
6302 let inputs_finished = self.inputs_finished;
6305 match self.live_mut()?.pull(inputs_finished) {
6306 Ok(Some(chunk)) => return Ok(Some(chunk)),
6307 Ok(None) => {}
6309 Err(error) => {
6310 self.stop(&error);
6311 return Err(error);
6312 }
6313 }
6314 if !self.ended {
6318 return Ok(None);
6319 }
6320 if !self.inputs_finished {
6321 if let Err(error) = self.live()?.unclosed() {
6325 self.stop(&error);
6326 return Err(error);
6327 }
6328 self.inputs_finished = true;
6329 continue;
6330 }
6331 match self.live_mut()?.flush_ready_merges() {
6334 Ok(true) => continue,
6337 Ok(false) => {}
6338 Err(error) => {
6339 self.stop(&error);
6340 return Err(error);
6341 }
6342 }
6343 if self.live()?.any_merge_pending() {
6344 continue;
6347 }
6348 let live = self.state.live.take().ok_or_else(no_live_execution)?;
6352 return match live.close() {
6353 Ok(()) => {
6354 self.phase = Phase::Finished;
6355 Ok(None)
6356 }
6357 Err(error) => {
6358 self.stop(&error);
6359 Err(error)
6360 }
6361 };
6362 }
6363 }
6364
6365 pub fn end_of_input(&mut self) -> Result<()> {
6370 if self.ended {
6371 return Err(DataFusionError::Execution(
6372 "the native execution already ended its input".to_string(),
6373 ));
6374 }
6375 self.ended = true;
6376 Ok(())
6377 }
6378
6379 pub fn finish(&mut self) -> Result<Vec<EvaluatedChunk>> {
6382 self.end_of_input()?;
6383 self.drain()
6384 }
6385
6386 fn drain(&mut self) -> Result<Vec<EvaluatedChunk>> {
6388 let mut drained = Vec::new();
6389 loop {
6390 match self.next_chunk() {
6391 Ok(Some(chunk)) => drained.push(chunk),
6392 Ok(None) => return Ok(drained),
6393 Err(error) => return Err(error),
6394 }
6395 }
6396 }
6397
6398 fn push_source(&mut self, input: InputId, chunk: NativeChunk) -> Result<()> {
6400 self.check_running()?;
6401 if self.ended {
6404 return Err(DataFusionError::Execution(
6405 "the native execution already ended its input, so no chunk can be queued at it"
6406 .to_string(),
6407 ));
6408 }
6409 let result = self.queue_source(input, chunk);
6410 if let Err(error) = &result {
6411 self.stop(error);
6412 }
6413 result
6414 }
6415
6416 fn queue_source(&mut self, input: InputId, chunk: NativeChunk) -> Result<()> {
6418 let live = self.live_mut()?;
6422 let count = live.inputs.len();
6423 let slot = live
6424 .inputs
6425 .get_mut(input.index())
6426 .ok_or_else(|| no_input(count, input))?;
6427 slot.enqueue(chunk)
6428 }
6429
6430 fn check_running(&self) -> Result<()> {
6432 match &self.phase {
6433 Phase::Running => Ok(()),
6434 Phase::Finished => Err(DataFusionError::Execution(
6435 "the native execution already finished".to_string(),
6436 )),
6437 Phase::Failed(reason) => Err(DataFusionError::Execution(format!(
6438 "the native execution stopped after an earlier error: {reason}"
6439 ))),
6440 }
6441 }
6442
6443 fn stop(&mut self, error: &DataFusionError) {
6447 self.state.live = None;
6448 self.phase = Phase::Failed(error.to_string());
6449 }
6450}
6451
6452fn map_chunk(
6463 schema: &Arc<SeriesSchema>,
6464 chunk: &EvaluatedChunk,
6465 ops: &[MapOp],
6466 admit: &mut dyn FnMut(usize) -> Result<()>,
6467) -> Result<Option<EvaluatedChunk>> {
6468 let mut series = chunk.series.clone();
6469 for (index, op) in ops.iter().enumerate() {
6470 let mapped = match op {
6471 MapOp::Label(rewrite) => {
6472 admit(rewrite.written_bytes(&series.metric))?;
6473 rewrite.apply(&mut series.metric)?;
6474 continue;
6475 }
6476 MapOp::Math(math) => map_math(schema, &series, *math)?,
6477 MapOp::Histogram(function) => map_native_histogram(*function, schema, &series)?,
6478 };
6479 if let Some(mapped) = mapped {
6480 series = mapped;
6481 continue;
6482 }
6483 if !chunk.is_last {
6486 return Ok(None);
6487 }
6488 let mut metric = series.metric.clone();
6491 for op in &ops[index..] {
6492 match op {
6493 MapOp::Label(rewrite) => {
6494 admit(rewrite.written_bytes(&metric))?;
6495 rewrite.apply(&mut metric)?;
6496 }
6497 MapOp::Math(_) => metric = drop_metric_name(&metric)?,
6498 MapOp::Histogram(_) => metric.remove("__name__"),
6500 }
6501 }
6502 let empty = no_row_series(schema, &series, metric)?;
6503 return EvaluatedChunk::try_new(empty, true).map(Some);
6504 }
6505 EvaluatedChunk::try_new(series, chunk.is_last).map(Some)
6506}
6507
6508fn no_row_series(schema: &SeriesSchema, series: &Series, metric: SeriesLabels) -> Result<Series> {
6513 let grid = series.time.grid().ok_or_else(|| {
6514 DataFusionError::Execution("a mapped chunk must be addressed on a grid".to_string())
6515 })?;
6516 let fields = (0..schema.fields.len())
6517 .map(|_| Samples::from_float(Float64Array::from(Vec::<f64>::new())))
6518 .collect();
6519 let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?;
6520 let at = series.time.last_position().map_or(0, |last| last + 1);
6521 let time = GridRange::try_new(Arc::clone(grid), at, 0).map_err(series_error)?;
6522 Series::try_new(schema, metric, TimeAxis::Grid(time), fields).map_err(series_error)
6523}
6524
6525fn valid_values(chunk: &EvaluatedChunk) -> usize {
6527 chunk
6528 .series
6529 .fields
6530 .iter()
6531 .map(|field| {
6532 field
6533 .iter()
6534 .filter(|sample| !matches!(sample, SampleRef::Missing))
6535 .count()
6536 })
6537 .sum()
6538}
6539
6540fn evaluated_values(chunk: &NativeChunk) -> usize {
6542 match chunk {
6543 NativeChunk::Evaluated(chunk) => valid_values(chunk),
6544 NativeChunk::Raw(chunk) => chunk.time.len(),
6545 NativeChunk::AggregateState(StateChunk::Series { series, .. }) => {
6546 series.iter().map(|series| series.time.len()).sum()
6547 }
6548 NativeChunk::AggregateState(StateChunk::Row(row)) => row.time.len(),
6549 }
6550}
6551
6552fn series_changed() -> DataFusionError {
6556 DataFusionError::Execution(
6557 "the instant selection combines one series into one axis, and a chunk of another series \
6558 arrived before the first one ended"
6559 .to_string(),
6560 )
6561}
6562
6563fn no_labels() -> DataFusionError {
6565 DataFusionError::Execution(
6566 "the instant selection requires materialized series labels".to_string(),
6567 )
6568}
6569
6570fn missing_row(index: usize) -> DataFusionError {
6572 DataFusionError::Execution(format!(
6573 "the instant selection selected the source row {index}, which the series it read does not \
6574 hold"
6575 ))
6576}
6577
6578fn truncated_input(input: InputId) -> DataFusionError {
6584 DataFusionError::Execution(format!(
6585 "the input at routing slot {} ended before the last chunk of a series: the last chunk it \
6586 handed over did not say `is_last`",
6587 input.index()
6588 ))
6589}
6590
6591fn no_input(inputs: usize, input: InputId) -> DataFusionError {
6594 DataFusionError::Execution(format!(
6595 "the native execution has {inputs} inputs, and no input {} was queued at",
6596 input.index()
6597 ))
6598}
6599
6600fn invalid_binary_operand() -> DataFusionError {
6602 DataFusionError::Internal("invalid binary operand index".to_string())
6603}
6604
6605fn no_live_execution() -> DataFusionError {
6607 DataFusionError::Internal("the running native execution has no state".to_string())
6608}
6609
6610fn no_window() -> DataFusionError {
6612 DataFusionError::Execution("the node holds no window evaluator".to_string())
6613}
6614
6615fn matched_scalar() -> DataFusionError {
6620 DataFusionError::NotImplemented(
6621 "the native runtime does not execute a scalar broadcast whose constant carries matching \
6622 modifiers: a constant has no labels to match, so the operation this Binary describes is \
6623 not the one it would compute"
6624 .to_string(),
6625 )
6626}
6627
6628fn unsupported_binary(operands: &str) -> DataFusionError {
6633 DataFusionError::NotImplemented(format!(
6634 "the native runtime does not execute this Binary node: it reads {operands}, and this \
6635 runtime reads two evaluated vectors or one evaluated vector and one constant"
6636 ))
6637}
6638
6639fn broadcast_runtime(
6648 left: &NativeNode,
6649 right: &NativeNode,
6650 matching: &BinaryMatching,
6651) -> Result<BroadcastRuntime> {
6652 let literal = |node: &NativeNode| match &node.expr {
6653 NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
6654 _ => None,
6655 };
6656 let (vector_left, sample_schema) = match (&left.output, &right.output) {
6657 (NativeType::Samples(vector), NativeType::Scalar(_)) if vector.eval_grid.is_some() => {
6658 (true, Arc::clone(vector))
6659 }
6660 (NativeType::Scalar(_), NativeType::Samples(vector)) if vector.eval_grid.is_some() => {
6661 (false, Arc::clone(vector))
6662 }
6663 (NativeType::Scalar(grid), NativeType::Scalar(_)) => {
6664 if literal(left).is_some() && literal(right).is_some() {
6668 return Err(unsupported_binary(
6669 "two constants, which broadcast over no vector",
6670 ));
6671 }
6672 (
6673 literal(left).is_none(),
6674 Arc::new(scalar_schema(Arc::clone(grid))),
6675 )
6676 }
6677 (_, _) => {
6678 return Err(unsupported_binary(
6679 "an operand that is neither evaluated samples nor a scalar, which no validated \
6680 tree binds as a binary operand",
6681 ));
6682 }
6683 };
6684 let scalar_side = if vector_left { right } else { left };
6685 let scalar = match literal(scalar_side) {
6686 Some(value) if vector_left => BroadcastScalar::Literal(ScalarOperand::Right(value)),
6687 Some(value) => BroadcastScalar::Literal(ScalarOperand::Left(value)),
6688 None => BroadcastScalar::Dynamic {
6689 left: !vector_left,
6690 value: None,
6691 },
6692 };
6693 if matching.labels != MatchingLabels::Ignoring(Vec::new())
6696 || matching.cardinality != Cardinality::OneToOne
6697 || matching.fill != FillValues::default()
6698 {
6699 return Err(matched_scalar());
6700 }
6701 Ok(BroadcastRuntime {
6702 scalar,
6703 vector_left,
6704 op: broadcast_op(matching)?,
6705 sample_schema,
6706 scalar_bytes: 0,
6707 annotations: None,
6708 })
6709}
6710
6711fn broadcast_op(matching: &BinaryMatching) -> Result<BroadcastOp> {
6717 let arithmetic = |op: ArithmeticOp| {
6718 if matching.return_bool {
6719 Err(DataFusionError::Execution(
6720 "the binary node carries `bool` on an arithmetic operator, which has no bool form"
6721 .to_string(),
6722 ))
6723 } else {
6724 Ok(BroadcastOp::Arithmetic(op))
6725 }
6726 };
6727 let comparison = |op: ComparisonOp| {
6728 if matching.return_bool {
6729 Ok(BroadcastOp::Compare(Comparison::Bool(op)))
6730 } else {
6731 Ok(BroadcastOp::Compare(Comparison::Filter(op)))
6732 }
6733 };
6734 match matching.op.kind() {
6735 BinaryKind::Arithmetic(op) => arithmetic(op),
6736 BinaryKind::Comparison(op) => comparison(op),
6737 }
6738}
6739
6740fn reservation_overflow(node: &str) -> DataFusionError {
6743 DataFusionError::Execution(format!(
6744 "the operands and the kernel's workspace of {node} do not fit one address space: the bytes \
6745 it would reserve overflow"
6746 ))
6747}
6748
6749fn series_error(error: datatypes::error::Error) -> DataFusionError {
6750 DataFusionError::External(Box::new(error))
6751}