Skip to main content

promql/extension_plan/
instant_manipulate.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::pin::Pin;
16use std::sync::Arc;
17use std::task::{Context, Poll};
18
19use common_query::prelude::{greptime_native_histogram, greptime_value};
20use datafusion::arrow::array::{
21    Array, ArrayRef, Float64Array, LargeListArray, LargeStringArray, ListArray, StringArray,
22    StringViewArray, StructArray, TimestampMillisecondArray, UInt64Array,
23};
24use datafusion::arrow::datatypes::{DataType, SchemaRef};
25use datafusion::arrow::record_batch::RecordBatch;
26use datafusion::common::stats::Precision;
27use datafusion::common::tree_node::TreeNodeRecursion;
28use datafusion::common::{DFSchema, DFSchemaRef, ScalarValue};
29use datafusion::error::{DataFusionError, Result as DataFusionResult};
30use datafusion::execution::context::TaskContext;
31use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation};
32use datafusion::logical_expr::{
33    EmptyRelation, Expr, Extension, LogicalPlan, UserDefinedLogicalNodeCore,
34};
35use datafusion::physical_expr::EquivalenceProperties;
36use datafusion::physical_plan::metrics::{
37    BaselineMetrics, Count, ExecutionPlanMetricsSet, MetricBuilder, MetricValue, MetricsSet,
38};
39use datafusion::physical_plan::{
40    ChildStats, DisplayAs, DisplayFormatType, ExecutionPlan, InputDistributionRequirements,
41    PhysicalExpr, PlanProperties, RecordBatchStream, SendableRecordBatchStream, Statistics,
42    StatisticsArgs,
43};
44use datafusion_expr::ident;
45use datatypes::arrow::compute;
46use datatypes::series::raw::RawTimestamps;
47use datatypes::series::samples::{Samples, SeriesFields};
48use datatypes::timestamp::timestamp_array_to_primitive;
49use futures::{Stream, StreamExt, ready};
50use greptime_proto::substrait_extension as pb;
51use prost::Message;
52use snafu::ResultExt;
53
54use crate::error::{DeserializeSnafu, Result};
55use crate::extension_plan::range_manipulate::{Nanoseconds, ScanNanoseconds, narrow_scan};
56use crate::extension_plan::series_divide::SeriesDivide;
57use crate::extension_plan::{
58    METRIC_NUM_SERIES, Millisecond, is_prometheus_stale_sample, local_offset,
59    nanoseconds_per_native_tick, prometheus_stale_sample_column, resolve_column_name,
60    serialize_column_index, timestamp_unit,
61};
62use crate::instant_eval::select_instants;
63use crate::metrics::PROMQL_SERIES_COUNT;
64
65fn mixed_sample_fields(field: Option<&str>) -> [Option<&str>; 2] {
66    let companion = match field {
67        Some(field) if field == greptime_value() => Some(greptime_native_histogram()),
68        Some(field) if field == greptime_native_histogram() => Some(greptime_value()),
69        _ => None,
70    };
71    [field, companion]
72}
73
74/// Manipulate the input record batch to make it suitable for Instant Operator.
75///
76/// This plan will try to align the input time series, for every timestamp between
77/// `start` and `end` with step `interval`. Find in the `lookback` range if data
78/// is missing at the given timestamp.
79///
80/// The memory pool admits this operator's per-series selection workspace: the execution reserves
81/// the estimate before allocating that workspace and a pool that cannot meet it refuses the
82/// operation with `ResourcesExhausted` (see [`InstantManipulateStream::manipulate_reserved`]).
83/// The reservation is released as soon as the output batch is built; it does not bound the child's
84/// input, the returned output batch, or total memory retained by an instant query. Its effect also
85/// depends on the attached pool: an unbounded pool always accepts the reservation.
86#[derive(Debug, PartialEq, Eq, Hash)]
87pub struct InstantManipulate {
88    start: Millisecond,
89    end: Millisecond,
90    lookback_delta: Millisecond,
91    interval: Millisecond,
92    offset: Millisecond,
93    time_index_column: String,
94    // Planner-provided tag-column hint for execution fast paths.
95    tag_columns: Vec<String>,
96    /// Primary sample column used to derive the columns checked for staleness.
97    field_column: Option<String>,
98    input: LogicalPlan,
99    output_schema: DFSchemaRef,
100    unfix: Option<UnfixIndices>,
101}
102
103impl PartialOrd for InstantManipulate {
104    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
105        (
106            self.start,
107            self.end,
108            self.lookback_delta,
109            self.interval,
110            self.offset,
111            &self.time_index_column,
112            &self.tag_columns,
113            &self.field_column,
114            &self.input,
115            &self.unfix,
116        )
117            .partial_cmp(&(
118                other.start,
119                other.end,
120                other.lookback_delta,
121                other.interval,
122                other.offset,
123                &other.time_index_column,
124                &other.tag_columns,
125                &other.field_column,
126                &other.input,
127                &other.unfix,
128            ))
129    }
130}
131
132#[derive(Debug, PartialEq, Eq, Hash, PartialOrd)]
133struct UnfixIndices {
134    pub time_index_idx: u64,
135    pub field_index_idx: u64,
136}
137
138impl UserDefinedLogicalNodeCore for InstantManipulate {
139    fn name(&self) -> &str {
140        Self::name()
141    }
142
143    fn inputs(&self) -> Vec<&LogicalPlan> {
144        vec![&self.input]
145    }
146
147    fn schema(&self) -> &DFSchemaRef {
148        &self.output_schema
149    }
150
151    fn expressions(&self) -> Vec<Expr> {
152        if self.unfix.is_some() {
153            return vec![];
154        }
155
156        let mut exprs = vec![ident(&self.time_index_column)];
157        exprs.extend(self.staleness_field_columns().map(ident));
158        exprs
159    }
160
161    fn necessary_children_exprs(&self, output_columns: &[usize]) -> Option<Vec<Vec<usize>>> {
162        if self.unfix.is_some() {
163            return None;
164        }
165
166        let input_schema = self.input.schema();
167        if output_columns.is_empty() {
168            let indices = (0..input_schema.fields().len()).collect::<Vec<_>>();
169            return Some(vec![indices]);
170        }
171
172        let mut required = output_columns.to_vec();
173        required.push(input_schema.index_of_column_by_name(None, &self.time_index_column)?);
174        for field in self.staleness_field_columns() {
175            required.push(input_schema.index_of_column_by_name(None, field)?);
176        }
177
178        required.sort_unstable();
179        required.dedup();
180        Some(vec![required])
181    }
182
183    fn fmt_for_explain(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
184        write!(
185            f,
186            "PromInstantManipulate: range=[{}..{}], lookback=[{}], interval=[{}], time index=[{}]",
187            self.start, self.end, self.lookback_delta, self.interval, self.time_index_column
188        )
189    }
190
191    fn with_exprs_and_inputs(
192        &self,
193        _exprs: Vec<Expr>,
194        inputs: Vec<LogicalPlan>,
195    ) -> DataFusionResult<Self> {
196        if inputs.len() != 1 {
197            return Err(DataFusionError::Internal(
198                "InstantManipulate should have exact one input".to_string(),
199            ));
200        }
201
202        let input: LogicalPlan = inputs.into_iter().next().unwrap();
203        let input_schema = input.schema();
204
205        if let Some(unfix) = &self.unfix {
206            // transform indices to names
207            let time_index_column = resolve_column_name(
208                unfix.time_index_idx,
209                input_schema,
210                "InstantManipulate",
211                "time index",
212            )?;
213
214            let field_column = if unfix.field_index_idx == u64::MAX {
215                None
216            } else {
217                Some(resolve_column_name(
218                    unfix.field_index_idx,
219                    input_schema,
220                    "InstantManipulate",
221                    "field",
222                )?)
223            };
224
225            Ok(Self {
226                start: self.start,
227                end: self.end,
228                lookback_delta: self.lookback_delta,
229                interval: self.interval,
230                offset: local_offset(&input, &time_index_column),
231                output_schema: Self::calculate_output_schema(&input, &time_index_column)?,
232                time_index_column,
233                tag_columns: Self::resolve_tag_columns(&input, &self.tag_columns),
234                field_column,
235                input,
236                unfix: None,
237            })
238        } else {
239            Ok(Self {
240                start: self.start,
241                end: self.end,
242                lookback_delta: self.lookback_delta,
243                interval: self.interval,
244                offset: self.offset,
245                time_index_column: self.time_index_column.clone(),
246                tag_columns: Self::resolve_tag_columns(&input, &self.tag_columns),
247                field_column: self.field_column.clone(),
248                output_schema: Self::calculate_output_schema(&input, &self.time_index_column)?,
249                input,
250                unfix: None,
251            })
252        }
253    }
254}
255
256impl InstantManipulate {
257    fn calculate_output_schema(
258        input: &LogicalPlan,
259        time_index_column: &str,
260    ) -> DataFusionResult<DFSchemaRef> {
261        let input_schema = input.schema();
262        let time_index = input_schema
263            .index_of_column_by_name(None, time_index_column)
264            .ok_or_else(|| {
265                DataFusionError::Internal(format!(
266                    "InstantManipulate time index {time_index_column} not found"
267                ))
268            })?;
269        let mut fields = (0..input_schema.fields().len())
270            .map(|index| {
271                let (qualifier, field) = input_schema.qualified_field(index);
272                (qualifier.cloned(), field.clone())
273            })
274            .collect::<Vec<_>>();
275        let (qualifier, field) = input_schema.qualified_field(time_index);
276        fields[time_index] = (
277            qualifier.cloned(),
278            Arc::new(field.as_ref().clone().with_data_type(DataType::Timestamp(
279                datafusion::arrow::datatypes::TimeUnit::Millisecond,
280                None,
281            ))),
282        );
283        Ok(Arc::new(DFSchema::new_with_metadata(
284            fields,
285            input_schema.metadata().clone(),
286        )?))
287    }
288
289    #[allow(clippy::too_many_arguments)]
290    pub fn new(
291        start: Millisecond,
292        end: Millisecond,
293        lookback_delta: Millisecond,
294        interval: Millisecond,
295        offset: Millisecond,
296        time_index_column: String,
297        tag_columns: Vec<String>,
298        field_column: Option<String>,
299        input: LogicalPlan,
300    ) -> Self {
301        Self {
302            start,
303            end,
304            lookback_delta,
305            interval,
306            offset,
307            output_schema: Self::calculate_output_schema(&input, &time_index_column)
308                .unwrap_or_else(|_| input.schema().clone()),
309            time_index_column,
310            tag_columns,
311            field_column,
312            input,
313            unfix: None,
314        }
315    }
316
317    pub const fn name() -> &'static str {
318        "InstantManipulate"
319    }
320
321    /// Returns whether this node evaluates a single timestamp rather than a range.
322    pub fn is_single_evaluation(&self) -> bool {
323        self.start == self.end
324    }
325
326    fn staleness_field_columns(&self) -> impl Iterator<Item = &str> {
327        let [field, companion] = mixed_sample_fields(self.field_column.as_deref());
328        [
329            field,
330            companion.filter(|companion| {
331                self.input
332                    .schema()
333                    .index_of_column_by_name(None, companion)
334                    .is_some()
335            }),
336        ]
337        .into_iter()
338        .flatten()
339    }
340
341    fn resolve_tag_columns(input: &LogicalPlan, tag_columns: &[String]) -> Vec<String> {
342        if !tag_columns.is_empty() {
343            return tag_columns.to_vec();
344        }
345
346        Self::find_series_divide_tags(input).unwrap_or_default()
347    }
348
349    fn find_series_divide_tags(plan: &LogicalPlan) -> Option<Vec<String>> {
350        if let LogicalPlan::Extension(Extension { node }) = plan
351            && let Some(series_divide) = node.as_any().downcast_ref::<SeriesDivide>()
352        {
353            return Some(series_divide.tags().to_vec());
354        }
355
356        plan.inputs()
357            .into_iter()
358            .find_map(Self::find_series_divide_tags)
359    }
360
361    pub fn to_execution_plan(&self, exec_input: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {
362        let reuse_tsid_column = matches!(self.tag_columns.as_slice(), [tag] if tag == "__tsid");
363
364        let mut fields = exec_input.schema().fields().to_vec();
365        let time_index = exec_input
366            .schema()
367            .index_of(&self.time_index_column)
368            .expect("time index column not found");
369        fields[time_index] = Arc::new(fields[time_index].as_ref().clone().with_data_type(
370            DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
371        ));
372        let output_schema = Arc::new(datafusion::arrow::datatypes::Schema::new_with_metadata(
373            fields,
374            exec_input.schema().metadata().clone(),
375        ));
376        let input_properties = exec_input.properties();
377        let properties = Arc::new(PlanProperties::new(
378            EquivalenceProperties::new(output_schema.clone()),
379            input_properties.partitioning.clone(),
380            input_properties.emission_type,
381            input_properties.boundedness,
382        ));
383        Arc::new(InstantManipulateExec {
384            offset: self.offset,
385            start: self.start,
386            end: self.end,
387            lookback_delta: self.lookback_delta,
388            interval: self.interval,
389            time_index_column: self.time_index_column.clone(),
390            field_column: self.field_column.clone(),
391            reuse_tsid_column,
392            input: exec_input,
393            output_schema,
394            properties,
395            metric: ExecutionPlanMetricsSet::new(),
396        })
397    }
398
399    pub fn serialize(&self) -> Vec<u8> {
400        let time_index_idx = serialize_column_index(self.input.schema(), &self.time_index_column);
401
402        let field_index_idx = self
403            .field_column
404            .as_ref()
405            .map(|name| serialize_column_index(self.input.schema(), name))
406            .unwrap_or(u64::MAX);
407
408        pb::InstantManipulate {
409            start: self.start,
410            end: self.end,
411            interval: self.interval,
412            lookback_delta: self.lookback_delta,
413            time_index_idx,
414            field_index_idx,
415            ..Default::default()
416        }
417        .encode_to_vec()
418    }
419
420    pub fn deserialize(bytes: &[u8]) -> Result<Self> {
421        let pb_instant_manipulate =
422            pb::InstantManipulate::decode(bytes).context(DeserializeSnafu)?;
423        let empty_schema = Arc::new(DFSchema::empty());
424        let placeholder_plan = LogicalPlan::EmptyRelation(EmptyRelation {
425            produce_one_row: false,
426            schema: empty_schema.clone(),
427        });
428
429        let unfix = UnfixIndices {
430            time_index_idx: pb_instant_manipulate.time_index_idx,
431            field_index_idx: pb_instant_manipulate.field_index_idx,
432        };
433
434        Ok(Self {
435            start: pb_instant_manipulate.start,
436            end: pb_instant_manipulate.end,
437            lookback_delta: pb_instant_manipulate.lookback_delta,
438            interval: pb_instant_manipulate.interval,
439            offset: 0,
440            time_index_column: String::new(),
441            tag_columns: Vec::new(),
442            field_column: None,
443            output_schema: empty_schema,
444            input: placeholder_plan,
445            unfix: Some(unfix),
446        })
447    }
448}
449
450#[derive(Debug)]
451pub struct InstantManipulateExec {
452    offset: Millisecond,
453    start: Millisecond,
454    end: Millisecond,
455    lookback_delta: Millisecond,
456    interval: Millisecond,
457    time_index_column: String,
458    field_column: Option<String>,
459    reuse_tsid_column: bool,
460
461    input: Arc<dyn ExecutionPlan>,
462    output_schema: SchemaRef,
463    properties: Arc<PlanProperties>,
464    metric: ExecutionPlanMetricsSet,
465}
466
467impl ExecutionPlan for InstantManipulateExec {
468    fn apply_expressions(
469        &self,
470        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> datafusion_common::Result<TreeNodeRecursion>,
471    ) -> DataFusionResult<TreeNodeRecursion> {
472        Ok(TreeNodeRecursion::Continue)
473    }
474
475    fn schema(&self) -> SchemaRef {
476        self.output_schema.clone()
477    }
478
479    fn properties(&self) -> &Arc<PlanProperties> {
480        &self.properties
481    }
482
483    fn input_distribution_requirements(&self) -> InputDistributionRequirements {
484        self.input.input_distribution_requirements()
485    }
486
487    // Prevent reordering of input
488    fn maintains_input_order(&self) -> Vec<bool> {
489        vec![false; self.children().len()]
490    }
491
492    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
493        vec![&self.input]
494    }
495
496    fn with_new_children(
497        self: Arc<Self>,
498        children: Vec<Arc<dyn ExecutionPlan>>,
499    ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
500        assert!(!children.is_empty());
501        let input = children[0].clone();
502        // The child may expose native timestamps, but our output schema uses ms.
503        // Retain its execution properties, not its schema equivalences or ordering.
504        let input_properties = input.properties();
505        let properties = Arc::new(PlanProperties::new(
506            EquivalenceProperties::new(self.output_schema.clone()),
507            input_properties.partitioning.clone(),
508            input_properties.emission_type,
509            input_properties.boundedness,
510        ));
511        Ok(Arc::new(Self {
512            offset: self.offset,
513            start: self.start,
514            end: self.end,
515            lookback_delta: self.lookback_delta,
516            interval: self.interval,
517            time_index_column: self.time_index_column.clone(),
518            field_column: self.field_column.clone(),
519            reuse_tsid_column: self.reuse_tsid_column,
520            input,
521            output_schema: self.output_schema.clone(),
522            properties,
523            metric: self.metric.clone(),
524        }))
525    }
526
527    fn execute(
528        &self,
529        partition: usize,
530        context: Arc<TaskContext>,
531    ) -> DataFusionResult<SendableRecordBatchStream> {
532        let baseline_metric = BaselineMetrics::new(&self.metric, partition);
533        let num_series = Count::new();
534        MetricBuilder::new(&self.metric)
535            .with_partition(partition)
536            .build(MetricValue::Count {
537                name: METRIC_NUM_SERIES.into(),
538                count: num_series.clone(),
539            });
540
541        // The reservation is the operator's own, registered before the child is polled so that a
542        // pool which cannot hold one series' workspace refuses it rather than the child's memory.
543        let reservation =
544            MemoryConsumer::new("InstantManipulateStream").register(context.memory_pool());
545        let input = self.input.execute(partition, context)?;
546        let schema = input.schema();
547        let time_index = schema
548            .column_with_name(&self.time_index_column)
549            .expect("time index column not found")
550            .0;
551        let time_unit = timestamp_unit(schema.field(time_index).data_type())?;
552        let field_indices = mixed_sample_fields(self.field_column.as_deref()).map(|field| {
553            field.and_then(|field| schema.column_with_name(field).map(|(index, _)| index))
554        });
555        let tsid_index = schema
556            .column_with_name("__tsid")
557            .filter(|(_, field)| field.data_type() == &DataType::UInt64)
558            .map(|(index, _)| index);
559        Ok(Box::pin(InstantManipulateStream {
560            offset: self.offset,
561            start: self.start,
562            end: self.end,
563            lookback_delta: self.lookback_delta,
564            interval: self.interval,
565            time_index,
566            time_unit,
567            field_indices,
568            tsid_index,
569            reuse_tsid_column: self.reuse_tsid_column && tsid_index.is_some(),
570            schema: self.output_schema.clone(),
571            input,
572            metric: baseline_metric,
573            num_series,
574            reservation,
575        }))
576    }
577
578    fn metrics(&self) -> Option<MetricsSet> {
579        Some(self.metric.clone_inner())
580    }
581
582    fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
583        vec![ChildStats::At(partition)]
584    }
585
586    fn statistics_from_inputs(
587        &self,
588        input_stats: &[Arc<Statistics>],
589        _args: &StatisticsArgs,
590    ) -> DataFusionResult<Arc<Statistics>> {
591        let input_stats = &input_stats[0];
592
593        let estimated_row_num = (self.end - self.start) as f64 / self.interval as f64;
594        let estimated_total_bytes = input_stats
595            .total_byte_size
596            .get_value()
597            .zip(input_stats.num_rows.get_value())
598            .map(|(size, rows)| {
599                Precision::Inexact(((*size as f64 / *rows as f64) * estimated_row_num).floor() as _)
600            })
601            .unwrap_or(Precision::Absent);
602
603        Ok(Arc::new(Statistics {
604            num_rows: Precision::Inexact(estimated_row_num.floor() as _),
605            total_byte_size: estimated_total_bytes,
606            // TODO(ruihang): support this column statistics
607            column_statistics: Statistics::unknown_column(&self.schema()),
608        }))
609    }
610
611    fn name(&self) -> &str {
612        "InstantManipulateExec"
613    }
614}
615
616impl DisplayAs for InstantManipulateExec {
617    fn fmt_as(&self, t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
618        match t {
619            DisplayFormatType::Default
620            | DisplayFormatType::Verbose
621            | DisplayFormatType::TreeRender => {
622                write!(
623                    f,
624                    "PromInstantManipulateExec: range=[{}..{}], lookback=[{}], interval=[{}], time index=[{}]",
625                    self.start,
626                    self.end,
627                    self.lookback_delta,
628                    self.interval,
629                    self.time_index_column
630                )
631            }
632        }
633    }
634}
635
636pub struct InstantManipulateStream {
637    offset: Millisecond,
638    start: Millisecond,
639    end: Millisecond,
640    lookback_delta: Millisecond,
641    interval: Millisecond,
642    // Column index of TIME INDEX column's position in schema
643    time_index: usize,
644    time_unit: datafusion::arrow::datatypes::TimeUnit,
645    field_indices: [Option<usize>; 2],
646    tsid_index: Option<usize>,
647    reuse_tsid_column: bool,
648
649    schema: SchemaRef,
650    input: SendableRecordBatchStream,
651    metric: BaselineMetrics,
652    /// Number of series processed.
653    num_series: Count,
654    /// What the workspace of the selection being built holds, reserved before it is allocated.
655    reservation: MemoryReservation,
656}
657
658impl RecordBatchStream for InstantManipulateStream {
659    fn schema(&self) -> SchemaRef {
660        self.schema.clone()
661    }
662}
663
664impl Stream for InstantManipulateStream {
665    type Item = DataFusionResult<RecordBatch>;
666
667    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
668        let poll = match ready!(self.input.poll_next_unpin(cx)) {
669            Some(Ok(batch)) => {
670                let timer = std::time::Instant::now();
671                if batch.num_rows() != 0 {
672                    self.num_series.add(1);
673                }
674                let result = self.manipulate_reserved(batch);
675                self.metric.elapsed_compute().add_elapsed(timer);
676                Poll::Ready(Some(result))
677            }
678            None => {
679                PROMQL_SERIES_COUNT.observe(self.num_series.value() as f64);
680                Poll::Ready(None)
681            }
682            Some(Err(e)) => Poll::Ready(Some(Err(e))),
683        };
684        self.metric.record_poll(poll)
685    }
686}
687
688impl InstantManipulateStream {
689    /// Manipulates one complete series with the workspace the selection allocates reserved first.
690    ///
691    /// One grid point of the selection is decided per selected sample position, so the workspace is
692    /// proportional to the points of the clipped grid rather than to the samples of the series: the
693    /// two arrays [`select_instants`] returns, the take indices the batch is built with, and one
694    /// value per point for every column of the batch. That is what the point-count limit this
695    /// operator used to carry stood for, and [`Self::workspace_bytes`] derives it term by term.
696    ///
697    /// The reservation goes back as soon as the batch is built, because what it covers is this
698    /// operator's workspace and not its output: the batch belongs to whoever reads it from here and
699    /// is charged to the pool there, as the output of any operator is.
700    fn manipulate_reserved(&mut self, input: RecordBatch) -> DataFusionResult<RecordBatch> {
701        self.reservation.try_grow(self.workspace_bytes(&input))?;
702        let result = self.manipulate(input);
703        self.reservation.free();
704        result
705    }
706
707    /// Manipulates one complete series sorted by timestamp. The planner enforces
708    /// this input contract with a sort followed by [`SeriesDivide`].
709    ///
710    /// Prometheus `v3.9.1`'s `vectorSelectorSingle` uses a start-exclusive
711    /// lookback window `(eval_ts - lookback_delta, eval_ts]`; a sample at exactly
712    /// `eval_ts - lookback_delta` is too old.
713    pub fn manipulate(&self, input: RecordBatch) -> DataFusionResult<RecordBatch> {
714        let ts_column = input.column(self.time_index);
715        if ts_column.is_empty() {
716            // Returning Pending after consuming a ready batch without a wake can stall the stream.
717            return Ok(RecordBatch::new_empty(self.schema.clone()));
718        }
719        if let Some(timestamps) = ts_column
720            .as_any()
721            .downcast_ref::<TimestampMillisecondArray>()
722            .filter(|timestamps| timestamps.null_count() == 0)
723        {
724            let values = timestamps.values();
725            let float_fields: Option<Vec<_>> = self
726                .field_indices
727                .iter()
728                .flatten()
729                .map(|index| {
730                    input
731                        .column(*index)
732                        .as_any()
733                        .downcast_ref::<Float64Array>()
734                        .cloned()
735                })
736                .collect();
737            if let Some(float_fields) = float_fields
738                && !float_fields.is_empty()
739                && values.windows(2).all(|pair| pair[0] < pair[1])
740            {
741                let time = RawTimestamps::try_new(values.clone())
742                    .map_err(|error| DataFusionError::Execution(error.to_string()))?;
743                let fields = SeriesFields::try_from_vec(
744                    float_fields.into_iter().map(Samples::from_float).collect(),
745                )
746                .map_err(|error| DataFusionError::Execution(error.to_string()))?;
747                let (indices, evaluation_timestamps) = select_instants(
748                    &time,
749                    &fields,
750                    self.start..=self.end,
751                    self.interval,
752                    self.lookback_delta,
753                    self.offset,
754                )?;
755                return self.take_record_batch_optional(input, indices, evaluation_timestamps);
756            }
757        }
758        let stale_sample_columns = self.field_indices.map(|index| {
759            index.and_then(|index| prometheus_stale_sample_column(input.column(index).as_ref()))
760        });
761        let is_stale = |row| {
762            stale_sample_columns
763                .iter()
764                .flatten()
765                .any(|column| is_prometheus_stale_sample(*column, row))
766        };
767        let (timestamps, _) = timestamp_array_to_primitive(ts_column).ok_or_else(|| {
768            DataFusionError::Execution("Time index column is not a timestamp".into())
769        })?;
770        let timestamp_null_count = timestamps.null_count();
771        let timestamps = timestamps.values();
772        let len = timestamps.len();
773        let (aligned_start, aligned_end) = self.clipped_range(timestamps);
774        let estimated_points = self.range_points(aligned_start, aligned_end);
775        // Narrow `i64` nanoseconds whenever the batch fits them, exact `i128` otherwise.
776        let narrow = (timestamp_null_count == 0)
777            .then(|| {
778                narrow_scan(
779                    self.time_unit,
780                    self.offset,
781                    self.lookback_delta,
782                    timestamps,
783                    aligned_start,
784                    aligned_end,
785                )
786            })
787            .flatten();
788        if let Some(scan) = &narrow {
789            // The clip converted the series bounds to milliseconds; this asserts the scan the
790            // selection walks agrees with them on those two samples.
791            let scale = nanoseconds_per_native_tick(self.time_unit);
792            let to_nanoseconds =
793                |timestamp: i64| (timestamp as i128) * scale + (self.offset as i128) * 1_000_000;
794            debug_assert_eq!(
795                i64::try_from(to_nanoseconds(timestamps[0])),
796                Ok(scan.shift(timestamps[0]))
797            );
798            debug_assert_eq!(
799                i64::try_from(to_nanoseconds(timestamps[len - 1])),
800                Ok(scan.shift(timestamps[len - 1]))
801            );
802        }
803        let (take_indices, aligned_ts) = match narrow {
804            Some(scan) => self.scan_instants::<i64>(
805                timestamps,
806                aligned_start,
807                aligned_end,
808                &scan,
809                estimated_points,
810                &is_stale,
811            ),
812            None => self.scan_instants::<i128>(
813                timestamps,
814                aligned_start,
815                aligned_end,
816                &ScanNanoseconds::<i128>::wide(self.time_unit, self.offset, self.lookback_delta),
817                estimated_points,
818                &is_stale,
819            ),
820        };
821        self.take_record_batch_optional(input, take_indices, aligned_ts)
822    }
823
824    /// Chooses the sample of every aligned evaluation instant, in `Ns` nanoseconds.
825    ///
826    /// Keeps the first row among exact timestamp ties and the latest preceding row
827    /// otherwise; zero lookback admits only exact samples. Staleness is tested after
828    /// choosing: a selected stale marker suppresses this evaluation rather than
829    /// falling back to an older finite value.
830    fn scan_instants<Ns: Nanoseconds>(
831        &self,
832        timestamps: &[i64],
833        start: Millisecond,
834        end: Millisecond,
835        scan: &ScanNanoseconds<Ns>,
836        capacity: usize,
837        is_stale: impl Fn(usize) -> bool,
838    ) -> (Vec<u64>, Vec<Millisecond>) {
839        let len = timestamps.len();
840        let mut cursor = 0usize;
841        let mut take_indices = Vec::with_capacity(capacity);
842        let mut aligned_ts = Vec::with_capacity(capacity);
843        for expected_ms in (start..=end).step_by(self.interval as usize) {
844            let expected = scan.instant(expected_ms);
845            let mut exact_candidate = None;
846            while cursor < len && scan.shift(timestamps[cursor]) <= expected {
847                if scan.shift(timestamps[cursor]) == expected && exact_candidate.is_none() {
848                    exact_candidate = Some(cursor);
849                }
850                cursor += 1;
851            }
852            let Some(candidate) = exact_candidate.or_else(|| cursor.checked_sub(1)) else {
853                continue;
854            };
855            let candidate_ts = scan.shift(timestamps[candidate]);
856            if (candidate_ts == expected || candidate_ts > scan.window_start(expected))
857                && candidate_ts <= expected
858                && !is_stale(candidate)
859            {
860                take_indices.push(candidate as u64);
861                aligned_ts.push(expected_ms);
862            }
863        }
864        (take_indices, aligned_ts)
865    }
866
867    /// Helper function to apply "take" on record batch.
868    fn take_record_batch_optional(
869        &self,
870        record_batch: RecordBatch,
871        take_indices: Vec<u64>,
872        aligned_ts: Vec<Millisecond>,
873    ) -> DataFusionResult<RecordBatch> {
874        assert_eq!(take_indices.len(), aligned_ts.len());
875
876        let output_len = aligned_ts.len();
877        let mut indices_array = None;
878        let mut arrays = Vec::with_capacity(record_batch.num_columns());
879        let aligned_ts = Arc::new(TimestampMillisecondArray::from(aligned_ts)) as Arc<dyn Array>;
880
881        for (index, array) in record_batch.columns().iter().enumerate() {
882            if index == self.time_index {
883                arrays.push(aligned_ts.clone());
884                continue;
885            }
886
887            if self.reuse_tsid_column && self.tsid_index == Some(index) {
888                arrays.push(reuse_constant_column(array, output_len)?);
889                continue;
890            }
891
892            let indices_array =
893                indices_array.get_or_insert_with(|| UInt64Array::from(take_indices.clone()));
894            arrays.push(compute::take(array, indices_array, None)?);
895        }
896
897        let result = RecordBatch::try_new(self.schema.clone(), arrays)
898            .map_err(|e| DataFusionError::ArrowError(Box::new(e), None))?;
899        Ok(result)
900    }
901
902    /// What one selected series' workspace holds, in bytes, before it is allocated.
903    ///
904    /// The figure follows the reasoning of `InstantRuntime::gather_bytes` in `native::execute`: a
905    /// selection decides one point of its grid per sample position it reads, so what it allocates
906    /// grows with the points of the
907    /// clipped grid and not with the samples of the series. Each term below is one allocation, and
908    /// the ones this path shares with those are named as they are there.
909    ///
910    /// Per selected point, [`Self::clipped_points`] points being the most it can decide:
911    ///
912    /// - A `u64` source row index and an `i64` evaluation timestamp: the two vectors
913    ///   [`select_instants`] returns, and the scan of [`Self::scan_instants`] returns the same pair.
914    ///   This is that node's "two arrays [`select_instants`] returns" term.
915    /// - The same indices again, for the `UInt64Array` [`Self::take_record_batch_optional`] takes
916    ///   the column values with: `take_indices.clone()` is a second copy of them.
917    /// - The timestamps again, as an allowance for the output's time column: they are moved into it
918    ///   when they fit and copied when they do not, and a move costs nothing to bound.
919    ///
920    /// Per column, one row per point: `take` allocates a row of the column for every point, so a
921    /// column costs its widest row per point -- the same term as that node's "one `f64` per field"
922    /// -- and one byte per point for the validity buffer it allocates, charged a byte for a bit so
923    /// that the figure stays an upper bound. A reused TSID column is sliced instead of taken
924    /// whenever the output is no longer than it and materialized a row per point otherwise, so the
925    /// same row bounds both. [`row_bytes`] gives the width, and a column of a type the series
926    /// frames of this path do not carry is charged for the bytes it already occupies once rather
927    /// than as a row per point.
928    ///
929    /// Per native histogram column, the widest row is not one value: a histogram row is a struct of
930    /// scalar columns whose values are copied and bucket lists whose values are copied for the row
931    /// the point selects, so a point costs the scalars, the list offsets and the widest payload the
932    /// column holds. That node charges its histogram payload the same way, "at the largest one the
933    /// field holds and per *point* rather than per row", because one source row can be selected by
934    /// every point of the grid and still be copied for each of them.
935    ///
936    /// Not charged, deliberately: the headers this selection builds per batch rather than per point
937    /// (the sample iterators and `Samples` clones of the fast path are constant per field), the
938    /// `Arc` bumps of a shared column, and the input batch, which belongs to the child. No term
939    /// doubles: every vector here is created with its exact capacity and `take` sizes its output by
940    /// the point count, unlike the builders that node charges twice.
941    fn workspace_bytes(&self, input: &RecordBatch) -> usize {
942        let points = self.clipped_points(input);
943        let mut bytes = points.saturating_mul(4 * std::mem::size_of::<u64>());
944        for (index, column) in input.columns().iter().enumerate() {
945            // The time column of the output is built from the timestamps counted above.
946            if index == self.time_index {
947                continue;
948            }
949            bytes = bytes.saturating_add(match row_bytes(column.as_ref()) {
950                Some(width) => {
951                    let output_offsets = match column.data_type() {
952                        DataType::Utf8 => points
953                            .saturating_add(1)
954                            .saturating_mul(std::mem::size_of::<i32>()),
955                        DataType::LargeUtf8 => points
956                            .saturating_add(1)
957                            .saturating_mul(std::mem::size_of::<i64>()),
958                        _ => 0,
959                    };
960                    points
961                        .saturating_mul(width.saturating_add(1))
962                        .saturating_add(output_offsets)
963                }
964                None => column.get_buffer_memory_size(),
965            });
966        }
967        // The `Arc<[ArrayRef]>` this batch is assembled from, one pointer per column.
968        bytes.saturating_add(
969            input
970                .num_columns()
971                .saturating_mul(std::mem::size_of::<ArrayRef>()),
972        )
973    }
974
975    /// The points [`select_instants`] decides for the series `input` holds.
976    ///
977    /// That selection clips this operator's `start..=end` to the series it reads before it walks
978    /// the grid, so the points it allocates for are the ones of the clipped range and not the ones
979    /// of the whole planned grid: a series whose samples end long before the query does reaches no
980    /// later point, yet stepping the whole planned range by the interval reserved the workspace of
981    /// every point of it, and a pool that could hold everything such a series selects refused the
982    /// query before selecting anything.
983    ///
984    /// The bounds, the clip and the alignment below are [`select_instants`]'s, kept the same line
985    /// for line because the reservation must cover what that function allocates: a point it misses
986    /// is memory no reservation bounds, and a point it invents is memory reserved for nothing.
987    ///
988    /// This batch holds one complete series -- [`SeriesDivide`] upstream guarantees it -- so the
989    /// first and last timestamp of its time column are the series bounds and reading them is
990    /// constant work, no matter how many samples the series holds.
991    fn clipped_points(&self, input: &RecordBatch) -> usize {
992        if self.end < self.start || self.interval <= 0 {
993            return 0;
994        }
995        let time = input.column(self.time_index);
996        if time.is_empty() {
997            return 0;
998        }
999        let Some((timestamps, _)) = timestamp_array_to_primitive(time) else {
1000            return 0;
1001        };
1002        let (start, end) = self.clipped_range(timestamps.values());
1003        self.range_points(start, end)
1004    }
1005
1006    /// This operator's grid clipped to the instants one series is selected at.
1007    ///
1008    /// `ticks` are that series' sample times in the operator's native tick unit, sorted and
1009    /// non-empty, and the interval must be positive. The lower bound moves to the first instant at
1010    /// or after the first sample and the upper bound to the last instant at or before the last
1011    /// sample widened by the lookback, both rounded onto the grid. An instant outside the returned
1012    /// range has no sample to select, so [`Self::scan_instants`] never walks it and nothing is
1013    /// allocated for it. Returns `(1, 0)` -- an empty range -- when nothing is left.
1014    ///
1015    /// [`Self::manipulate`] and [`Self::clipped_points`] both call this. They used to carry the
1016    /// same arithmetic twice, on the reasoning that the reservation must mirror the selection; one
1017    /// copy is the stronger guarantee, because the two cannot drift apart at all.
1018    fn clipped_range(&self, ticks: &[i64]) -> (Millisecond, Millisecond) {
1019        // Shift the native-tick timeline in i128 before comparing samples. Doing this in the Arrow
1020        // storage unit can overflow even when the shifted PromQL millisecond evaluation time is
1021        // representable.
1022        let scale = nanoseconds_per_native_tick(self.time_unit);
1023        let to_nanoseconds =
1024            |timestamp: i64| (timestamp as i128) * scale + (self.offset as i128) * 1_000_000;
1025        let first_ns = to_nanoseconds(ticks[0]);
1026        let last_ns = to_nanoseconds(ticks[ticks.len() - 1]);
1027        // An exact sample remains useful with zero lookback. Otherwise the lower boundary is
1028        // exclusive, so subtract one nanosecond from its final window.
1029        let last_useful = if self.lookback_delta == 0 {
1030            last_ns
1031        } else {
1032            last_ns + (self.lookback_delta as i128) * 1_000_000 - 1
1033        };
1034        let first_ms = (first_ns + 999_999).div_euclid(1_000_000);
1035        let last_ms = last_useful.div_euclid(1_000_000);
1036        let query_start = self.start as i128;
1037        let query_end = self.end as i128;
1038        let interval = self.interval as i128;
1039        let max_start = first_ms.max(query_start);
1040        let min_end = last_ms.min(query_end);
1041        if max_start > min_end {
1042            return (1, 0);
1043        }
1044        (
1045            (query_start + (max_start - query_start) / interval * interval) as i64,
1046            (query_end - (query_end - min_end) / interval * interval) as i64,
1047        )
1048    }
1049
1050    /// The number of instants in `start..=end`, stepping by the interval.
1051    fn range_points(&self, start: Millisecond, end: Millisecond) -> usize {
1052        if end < start || self.interval <= 0 {
1053            return 0;
1054        }
1055        usize::try_from((end as i128 - start as i128) / self.interval as i128 + 1)
1056            .unwrap_or(usize::MAX)
1057    }
1058}
1059
1060/// The bytes one selected point copies out of `column`, `None` for a column type this path does not
1061/// carry.
1062///
1063/// `take` allocates one row of the column per point, so one point costs the widest row the column
1064/// holds: the width of its value for a fixed-width column; value bytes for Utf8 or LargeUtf8 (the
1065/// output offsets buffer is accounted once in `workspace_bytes`), a view descriptor plus value
1066/// bytes for Utf8View (a conservative allowance because short views may point into shared buffers),
1067/// dictionary key bytes for string dictionaries (whose values remain shared),
1068/// and the whole row for a struct such as a native histogram -- its scalar columns, the offsets of
1069/// its list columns and their widest values.
1070fn row_bytes(column: &dyn Array) -> Option<usize> {
1071    if let Some(width) = column.data_type().primitive_width() {
1072        return Some(width);
1073    }
1074    // `primitive_width` reports a `Boolean` as unknown, and its values are one byte wide.
1075    if let DataType::Boolean = column.data_type() {
1076        return Some(1);
1077    }
1078    if let Some(values) = column.as_any().downcast_ref::<StringArray>() {
1079        return Some(values.offsets().lengths().max().unwrap_or(0));
1080    }
1081    if let Some(values) = column.as_any().downcast_ref::<LargeStringArray>() {
1082        return Some(values.offsets().lengths().max().unwrap_or(0));
1083    }
1084    if let Some(values) = column.as_any().downcast_ref::<StringViewArray>() {
1085        return Some(
1086            std::mem::size_of::<u128>().saturating_add(
1087                values
1088                    .iter()
1089                    .map(|value| value.map_or(0, str::len))
1090                    .max()
1091                    .unwrap_or(0),
1092            ),
1093        );
1094    }
1095    if let DataType::Dictionary(key_type, value_type) = column.data_type() {
1096        // `take` copies dictionary keys per output row and shares the dictionary values.
1097        // Instant tags supported by the producer use string dictionary values.
1098        if matches!(
1099            value_type.as_ref(),
1100            DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
1101        ) {
1102            return key_type.primitive_width();
1103        }
1104        return None;
1105    }
1106    let values = column.as_any().downcast_ref::<StructArray>()?;
1107    Some(
1108        values
1109            .columns()
1110            .iter()
1111            .map(|child| match child.data_type() {
1112                // One offset per row of a list column, and the values the widest row holds.
1113                DataType::List(_) => {
1114                    std::mem::size_of::<i32>().saturating_add(widest_list_row(child))
1115                }
1116                DataType::LargeList(_) => {
1117                    std::mem::size_of::<i64>().saturating_add(widest_list_row(child))
1118                }
1119                // The scalars of a row are fixed width; a nested column counted at the width of the
1120                // widest value this crate stores keeps the sum an upper bound.
1121                _ => child
1122                    .data_type()
1123                    .primitive_width()
1124                    .unwrap_or(std::mem::size_of::<f64>()),
1125            })
1126            .fold(0usize, usize::saturating_add),
1127    )
1128}
1129
1130/// The values the widest row of a list column holds, in bytes.
1131///
1132/// A list column of a histogram row is one bucket side or one bucket list of it, so one row of it
1133/// is one list's values: the widest row times the width of a value bounds what a point copies.
1134fn widest_list_row(column: &dyn Array) -> usize {
1135    let (widest, values) = if let Some(list) = column.as_any().downcast_ref::<ListArray>() {
1136        (list.offsets().lengths().max().unwrap_or(0), list.values())
1137    } else if let Some(list) = column.as_any().downcast_ref::<LargeListArray>() {
1138        (list.offsets().lengths().max().unwrap_or(0), list.values())
1139    } else {
1140        return 0;
1141    };
1142    widest.saturating_mul(
1143        values
1144            .data_type()
1145            .primitive_width()
1146            .unwrap_or(std::mem::size_of::<f64>()),
1147    )
1148}
1149
1150fn reuse_constant_column(array: &Arc<dyn Array>, len: usize) -> DataFusionResult<Arc<dyn Array>> {
1151    if len <= array.len() {
1152        return Ok(array.slice(0, len));
1153    }
1154
1155    if array.is_empty() {
1156        return Ok(array.slice(0, 0));
1157    }
1158
1159    ScalarValue::try_from_array(array.as_ref(), 0)?.to_array_of_size(len)
1160}
1161
1162#[cfg(test)]
1163#[path = "instant_manipulate/typed_tests.rs"]
1164mod typed_tests;
1165
1166#[cfg(test)]
1167mod test {
1168    use common_query::native_histogram::build_histogram_array;
1169    use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
1170    use datafusion::arrow::array::{
1171        Float64Array, LargeStringArray, StringArray, StringViewArray, TimestampMicrosecondArray,
1172        TimestampNanosecondArray, TimestampSecondArray,
1173    };
1174    use datafusion::arrow::buffer::NullBuffer;
1175    use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
1176    use datafusion::common::ToDFSchema;
1177    use datafusion::datasource::memory::MemorySourceConfig;
1178    use datafusion::datasource::source::DataSourceExec;
1179    use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool, UnboundedMemoryPool};
1180    use datafusion::execution::runtime_env::RuntimeEnvBuilder;
1181    use datafusion::logical_expr::{
1182        EmptyRelation, Extension, LogicalPlan, Projection, UserDefinedLogicalNodeCore,
1183    };
1184    use datafusion::physical_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions};
1185    use datafusion::prelude::SessionContext;
1186    use datafusion_expr::col;
1187
1188    use super::*;
1189    use crate::extension_plan::test_util::{
1190        TIME_INDEX_COLUMN, native_histogram, prepare_test_data, prepare_test_data_with_stale_marker,
1191    };
1192
1193    /// An unbounded reservation, for the streams built outside an operator's `execute`.
1194    fn unbounded() -> MemoryReservation {
1195        let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
1196        MemoryConsumer::new("InstantManipulateStreamTest").register(&pool)
1197    }
1198
1199    /// A task context whose pool holds `bytes`, so a reservation larger than that is refused.
1200    fn bounded_task_context(bytes: usize) -> Arc<TaskContext> {
1201        let runtime = RuntimeEnvBuilder::new()
1202            .with_memory_pool(Arc::new(GreedyMemoryPool::new(bytes)))
1203            .build()
1204            .unwrap();
1205        Arc::new(TaskContext::default().with_runtime(Arc::new(runtime)))
1206    }
1207
1208    async fn do_normalize_test(
1209        start: Millisecond,
1210        end: Millisecond,
1211        lookback_delta: Millisecond,
1212        interval: Millisecond,
1213        expected: String,
1214        contains_stale_marker: bool,
1215    ) {
1216        let memory_exec = if contains_stale_marker {
1217            Arc::new(prepare_test_data_with_stale_marker())
1218        } else {
1219            Arc::new(prepare_test_data())
1220        };
1221        let normalize_exec = Arc::new(InstantManipulateExec {
1222            offset: 0,
1223            start,
1224            end,
1225            lookback_delta,
1226            interval,
1227            time_index_column: TIME_INDEX_COLUMN.to_string(),
1228            field_column: Some("value".to_string()),
1229            reuse_tsid_column: false,
1230            output_schema: memory_exec.schema(),
1231            properties: memory_exec.properties().clone(),
1232            input: memory_exec,
1233            metric: ExecutionPlanMetricsSet::new(),
1234        });
1235        let session_context = SessionContext::default();
1236        let result = datafusion::physical_plan::collect(normalize_exec, session_context.task_ctx())
1237            .await
1238            .unwrap();
1239        let result_literal = datatypes::arrow::util::pretty::pretty_format_batches(&result)
1240            .unwrap()
1241            .to_string();
1242
1243        assert_eq!(result_literal, expected);
1244    }
1245
1246    #[tokio::test]
1247    async fn native_timestamps_select_exact_samples_and_keep_ms_output() {
1248        for (unit, ticks_per_ms) in [
1249            (TimeUnit::Microsecond, 1_000_i64),
1250            (TimeUnit::Nanosecond, 1_000_000_i64),
1251        ] {
1252            let lower = 1_000 * ticks_per_ms;
1253            let upper = 1_001 * ticks_per_ms;
1254            let stale = f64::from_bits(PROMETHEUS_STALE_NAN_BITS);
1255            for (name, timestamps, values, expected_timestamps, expected_values) in [
1256                (
1257                    "exact upper sample",
1258                    vec![lower + 1, upper],
1259                    vec![1.0, 2.0],
1260                    vec![1_001],
1261                    vec![2.0],
1262                ),
1263                (
1264                    "exclusive lower boundary and future sample",
1265                    vec![lower, upper + 1],
1266                    vec![1.0, 2.0],
1267                    vec![1_000],
1268                    vec![1.0],
1269                ),
1270                (
1271                    "one native tick above lower boundary",
1272                    vec![lower + 1, upper + 1],
1273                    vec![1.0, 2.0],
1274                    vec![1_001],
1275                    vec![1.0],
1276                ),
1277                (
1278                    "future stale marker does not suppress",
1279                    vec![lower + 1, upper + 1],
1280                    vec![1.0, stale],
1281                    vec![1_001],
1282                    vec![1.0],
1283                ),
1284                (
1285                    "latest in-window stale marker suppresses",
1286                    vec![lower + 1, lower + 2, upper + 1],
1287                    vec![1.0, stale, 3.0],
1288                    vec![],
1289                    vec![],
1290                ),
1291            ] {
1292                let schema = Arc::new(Schema::new(vec![
1293                    Field::new(TIME_INDEX_COLUMN, DataType::Timestamp(unit, None), false),
1294                    Field::new("value", DataType::Float64, true),
1295                ]));
1296                let time: Arc<dyn Array> = match unit {
1297                    TimeUnit::Microsecond => Arc::new(TimestampMicrosecondArray::from(timestamps)),
1298                    TimeUnit::Nanosecond => Arc::new(TimestampNanosecondArray::from(timestamps)),
1299                    _ => unreachable!(),
1300                };
1301                let batch = RecordBatch::try_new(
1302                    schema.clone(),
1303                    vec![time, Arc::new(Float64Array::from(values))],
1304                )
1305                .unwrap();
1306                let logical_input = LogicalPlan::EmptyRelation(EmptyRelation {
1307                    produce_one_row: false,
1308                    schema: schema.clone().to_dfschema_ref().unwrap(),
1309                });
1310                let plan = InstantManipulate::new(
1311                    1_000,
1312                    1_001,
1313                    1,
1314                    1,
1315                    0,
1316                    TIME_INDEX_COLUMN.to_string(),
1317                    Vec::new(),
1318                    Some("value".to_string()),
1319                    logical_input.clone(),
1320                );
1321                let output_schema = Arc::new(Schema::new(vec![
1322                    Field::new(
1323                        TIME_INDEX_COLUMN,
1324                        DataType::Timestamp(TimeUnit::Millisecond, None),
1325                        false,
1326                    ),
1327                    Field::new("value", DataType::Float64, true),
1328                ]));
1329                assert_eq!(plan.schema().as_arrow(), output_schema.as_ref());
1330
1331                let rebuilt = InstantManipulate::deserialize(&plan.serialize())
1332                    .unwrap()
1333                    .with_exprs_and_inputs(vec![], vec![logical_input])
1334                    .unwrap();
1335                assert_eq!(rebuilt.schema(), plan.schema());
1336                assert_eq!(rebuilt.input.schema().as_arrow(), schema.as_ref());
1337
1338                let input = Arc::new(DataSourceExec::new(Arc::new(
1339                    MemorySourceConfig::try_new(&[vec![batch]], schema.clone(), None).unwrap(),
1340                )));
1341                let exec = rebuilt.to_execution_plan(input);
1342                assert_eq!(exec.schema(), output_schema);
1343                assert_eq!(exec.children()[0].schema(), schema);
1344
1345                let batches =
1346                    datafusion::physical_plan::collect(exec, SessionContext::default().task_ctx())
1347                        .await
1348                        .unwrap();
1349                assert_eq!(batches.len(), 1, "{unit:?}: {name}");
1350                let output = &batches[0];
1351                assert_eq!(output.schema(), output_schema);
1352                let timestamps = output
1353                    .column(0)
1354                    .as_any()
1355                    .downcast_ref::<TimestampMillisecondArray>()
1356                    .unwrap();
1357                let values = output
1358                    .column(1)
1359                    .as_any()
1360                    .downcast_ref::<Float64Array>()
1361                    .unwrap();
1362                assert_eq!(
1363                    timestamps.values().as_ref(),
1364                    expected_timestamps.as_slice(),
1365                    "{unit:?}: {name}"
1366                );
1367                assert_eq!(
1368                    values.values().as_ref(),
1369                    expected_values.as_slice(),
1370                    "{unit:?}: {name}"
1371                );
1372                assert_eq!(values.null_count(), 0, "{unit:?}: {name}");
1373            }
1374        }
1375    }
1376
1377    #[tokio::test]
1378    async fn logical_normalize_offset_survives_rebuild_and_executes() {
1379        for (name, time_unit, raw, offset, start, lookback_delta) in [
1380            (
1381                "millisecond offset",
1382                TimeUnit::Millisecond,
1383                0,
1384                1_000,
1385                1_000,
1386                0,
1387            ),
1388            (
1389                "second timestamp with negative fractional offset",
1390                TimeUnit::Second,
1391                1,
1392                -500,
1393                500,
1394                0,
1395            ),
1396        ] {
1397            let schema = Arc::new(Schema::new(vec![
1398                Field::new(
1399                    TIME_INDEX_COLUMN,
1400                    DataType::Timestamp(time_unit, None),
1401                    false,
1402                ),
1403                Field::new("value", DataType::Float64, true),
1404            ]));
1405            let input = LogicalPlan::EmptyRelation(EmptyRelation {
1406                produce_one_row: false,
1407                schema: schema.clone().to_dfschema_ref().unwrap(),
1408            });
1409            let normalize = crate::extension_plan::SeriesNormalize::new(
1410                offset,
1411                TIME_INDEX_COLUMN,
1412                false,
1413                Vec::new(),
1414                input.clone(),
1415            );
1416            let normalize =
1417                crate::extension_plan::SeriesNormalize::deserialize(&normalize.serialize())
1418                    .unwrap()
1419                    .with_exprs_and_inputs(vec![], vec![input.clone()])
1420                    .unwrap();
1421            let normalized = LogicalPlan::Projection(
1422                Projection::try_new(
1423                    vec![col(TIME_INDEX_COLUMN), col("value")],
1424                    Arc::new(LogicalPlan::Extension(Extension {
1425                        node: Arc::new(normalize),
1426                    })),
1427                )
1428                .unwrap(),
1429            );
1430            let fresh = InstantManipulate::new(
1431                start,
1432                start,
1433                lookback_delta,
1434                1,
1435                offset,
1436                TIME_INDEX_COLUMN.to_string(),
1437                Vec::new(),
1438                Some("value".to_string()),
1439                input.clone(),
1440            )
1441            .with_exprs_and_inputs(vec![], vec![input.clone()])
1442            .unwrap();
1443            let serialized = InstantManipulate::new(
1444                start,
1445                start,
1446                lookback_delta,
1447                1,
1448                offset,
1449                TIME_INDEX_COLUMN.to_string(),
1450                Vec::new(),
1451                Some("value".to_string()),
1452                normalized.clone(),
1453            );
1454            let decoded = InstantManipulate::deserialize(&serialized.serialize())
1455                .unwrap()
1456                .with_exprs_and_inputs(vec![], vec![normalized])
1457                .unwrap();
1458            let timestamp: Arc<dyn Array> = match time_unit {
1459                TimeUnit::Millisecond => Arc::new(TimestampMillisecondArray::from(vec![raw])),
1460                TimeUnit::Second => Arc::new(TimestampSecondArray::from(vec![raw])),
1461                _ => unreachable!(),
1462            };
1463            let batch = RecordBatch::try_new(
1464                schema.clone(),
1465                vec![timestamp, Arc::new(Float64Array::from(vec![7.0]))],
1466            )
1467            .unwrap();
1468            for (mode, rebuilt) in [("fresh", fresh), ("decoded", decoded)] {
1469                let rebuilt = rebuilt
1470                    .with_exprs_and_inputs(vec![], vec![input.clone()])
1471                    .unwrap();
1472                assert_eq!(rebuilt.offset, offset, "{name}: {mode}");
1473                assert_eq!(rebuilt.input.schema(), input.schema(), "{name}: {mode}");
1474
1475                let empty_exec_input = Arc::new(DataSourceExec::new(Arc::new(
1476                    MemorySourceConfig::try_new(&[vec![]], schema.clone(), None).unwrap(),
1477                )));
1478                let exec_input = Arc::new(DataSourceExec::new(Arc::new(
1479                    MemorySourceConfig::try_new(&[vec![batch.clone()]], schema.clone(), None)
1480                        .unwrap(),
1481                )));
1482                let exec = rebuilt
1483                    .to_execution_plan(empty_exec_input)
1484                    .replace_children(
1485                        vec![exec_input],
1486                        ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
1487                    )
1488                    .unwrap();
1489                let output =
1490                    datafusion::physical_plan::collect(exec, SessionContext::default().task_ctx())
1491                        .await
1492                        .unwrap();
1493                let output = &output[0];
1494                assert_eq!(output.num_rows(), 1, "{name}: {mode}");
1495                assert_eq!(
1496                    output
1497                        .column(0)
1498                        .as_any()
1499                        .downcast_ref::<TimestampMillisecondArray>()
1500                        .unwrap()
1501                        .value(0),
1502                    start,
1503                    "{name}: {mode}"
1504                );
1505                assert_eq!(
1506                    output
1507                        .column(1)
1508                        .as_any()
1509                        .downcast_ref::<Float64Array>()
1510                        .unwrap()
1511                        .value(0),
1512                    7.0,
1513                    "{name}: {mode}"
1514                );
1515            }
1516        }
1517    }
1518
1519    #[test]
1520    fn deserialized_ordering_preserves_column_indices() {
1521        let mut wire = pb::InstantManipulate::default();
1522        let first = InstantManipulate::deserialize(&wire.encode_to_vec()).unwrap();
1523        wire.time_index_idx = 1;
1524        let second = InstantManipulate::deserialize(&wire.encode_to_vec()).unwrap();
1525        assert_ne!(first, second);
1526        assert_eq!(first.partial_cmp(&second), Some(std::cmp::Ordering::Less));
1527        wire.field_index_idx = 2;
1528        let third = InstantManipulate::deserialize(&wire.encode_to_vec()).unwrap();
1529        assert_ne!(second, third);
1530        assert_eq!(second.partial_cmp(&third), Some(std::cmp::Ordering::Less));
1531
1532        let input = LogicalPlan::EmptyRelation(EmptyRelation {
1533            produce_one_row: false,
1534            schema: prepare_test_data().schema().to_dfschema_ref().unwrap(),
1535        });
1536        let first = InstantManipulate::new(
1537            0,
1538            0,
1539            0,
1540            0,
1541            0,
1542            TIME_INDEX_COLUMN.to_string(),
1543            Vec::new(),
1544            Some("value".to_string()),
1545            input.clone(),
1546        );
1547        let second = InstantManipulate::new(
1548            0,
1549            0,
1550            0,
1551            0,
1552            1,
1553            TIME_INDEX_COLUMN.to_string(),
1554            Vec::new(),
1555            Some("value".to_string()),
1556            input,
1557        );
1558        assert_ne!(first, second);
1559        assert_eq!(first.partial_cmp(&second), Some(std::cmp::Ordering::Less));
1560    }
1561
1562    #[test]
1563    fn pruning_should_keep_time_and_field_columns_for_exec() {
1564        let df_schema = prepare_test_data().schema().to_dfschema_ref().unwrap();
1565        let input = LogicalPlan::EmptyRelation(EmptyRelation {
1566            produce_one_row: false,
1567            schema: df_schema,
1568        });
1569        let plan = InstantManipulate::new(
1570            0,
1571            0,
1572            0,
1573            0,
1574            0,
1575            TIME_INDEX_COLUMN.to_string(),
1576            Vec::new(),
1577            Some("value".to_string()),
1578            input,
1579        );
1580
1581        // Simulate a parent projection requesting only the `path` column.
1582        let output_columns = [2usize];
1583        let required = plan.necessary_children_exprs(&output_columns).unwrap();
1584        let required = &required[0];
1585        assert_eq!(required.as_slice(), &[0, 1, 2]);
1586    }
1587
1588    #[test]
1589    fn rebuild_should_recover_tag_columns_from_series_divide_input() {
1590        let df_schema = prepare_test_data().schema().to_dfschema_ref().unwrap();
1591        let input = LogicalPlan::EmptyRelation(EmptyRelation {
1592            produce_one_row: false,
1593            schema: df_schema,
1594        });
1595        let series_divide = LogicalPlan::Extension(Extension {
1596            node: Arc::new(SeriesDivide::new(
1597                vec!["__tsid".to_string()],
1598                TIME_INDEX_COLUMN.to_string(),
1599                input,
1600            )),
1601        });
1602        let bytes = InstantManipulate::new(
1603            0,
1604            0,
1605            0,
1606            0,
1607            0,
1608            TIME_INDEX_COLUMN.to_string(),
1609            vec!["__tsid".to_string()],
1610            Some("value".to_string()),
1611            series_divide.clone(),
1612        )
1613        .serialize();
1614        let plan = InstantManipulate::deserialize(&bytes)
1615            .unwrap()
1616            .with_exprs_and_inputs(vec![], vec![series_divide])
1617            .unwrap();
1618
1619        assert_eq!(plan.tag_columns, vec!["__tsid".to_string()]);
1620    }
1621
1622    #[test]
1623    fn rebuild_should_recover_tag_columns_from_series_normalize_input() {
1624        let df_schema = prepare_test_data().schema().to_dfschema_ref().unwrap();
1625        let input = LogicalPlan::EmptyRelation(EmptyRelation {
1626            produce_one_row: false,
1627            schema: df_schema,
1628        });
1629        let series_divide = LogicalPlan::Extension(Extension {
1630            node: Arc::new(SeriesDivide::new(
1631                vec!["__tsid".to_string()],
1632                TIME_INDEX_COLUMN.to_string(),
1633                input,
1634            )),
1635        });
1636        let series_normalize = LogicalPlan::Extension(Extension {
1637            node: Arc::new(crate::extension_plan::SeriesNormalize::new(
1638                0,
1639                TIME_INDEX_COLUMN,
1640                false,
1641                vec!["__tsid".to_string()],
1642                series_divide,
1643            )),
1644        });
1645        let bytes = InstantManipulate::new(
1646            0,
1647            0,
1648            0,
1649            0,
1650            0,
1651            TIME_INDEX_COLUMN.to_string(),
1652            vec!["__tsid".to_string()],
1653            Some("value".to_string()),
1654            series_normalize.clone(),
1655        )
1656        .serialize();
1657        let plan = InstantManipulate::deserialize(&bytes)
1658            .unwrap()
1659            .with_exprs_and_inputs(vec![], vec![series_normalize])
1660            .unwrap();
1661
1662        assert_eq!(plan.tag_columns, vec!["__tsid".to_string()]);
1663    }
1664
1665    #[test]
1666    fn to_execution_plan_enables_tsid_fast_path() {
1667        let schema = Arc::new(Schema::new(vec![
1668            Field::new(
1669                TIME_INDEX_COLUMN,
1670                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
1671                false,
1672            ),
1673            Field::new("value", DataType::Float64, true),
1674        ]));
1675        let exec_input: Arc<dyn ExecutionPlan> = Arc::new(DataSourceExec::new(Arc::new(
1676            MemorySourceConfig::try_new(&[], schema, None).unwrap(),
1677        )));
1678
1679        let exec = InstantManipulate::new(
1680            0,
1681            0,
1682            0,
1683            0,
1684            0,
1685            TIME_INDEX_COLUMN.to_string(),
1686            vec!["__tsid".to_string()],
1687            Some("value".to_string()),
1688            LogicalPlan::EmptyRelation(EmptyRelation {
1689                produce_one_row: false,
1690                schema: Arc::new(datafusion::common::DFSchema::empty()),
1691            }),
1692        )
1693        .to_execution_plan(exec_input);
1694
1695        assert!(format!("{exec:?}").contains("reuse_tsid_column: true"));
1696    }
1697
1698    #[tokio::test]
1699    async fn tsid_fast_path_reuses_tsid_column_when_output_grows() {
1700        let schema = Arc::new(Schema::new(vec![
1701            Field::new(
1702                TIME_INDEX_COLUMN,
1703                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
1704                false,
1705            ),
1706            Field::new("value", DataType::Float64, true),
1707            Field::new("host", DataType::Utf8, true),
1708            Field::new("__tsid", DataType::UInt64, false),
1709        ]));
1710        let batch = RecordBatch::try_new(
1711            schema.clone(),
1712            vec![
1713                Arc::new(TimestampMillisecondArray::from(vec![0, 1_000])),
1714                Arc::new(Float64Array::from(vec![1.0, 2.0])),
1715                Arc::new(datafusion::arrow::array::StringArray::from(vec![
1716                    "foo", "foo",
1717                ])),
1718                Arc::new(UInt64Array::from(vec![42, 42])),
1719            ],
1720        )
1721        .unwrap();
1722        let input = Arc::new(DataSourceExec::new(Arc::new(
1723            MemorySourceConfig::try_new(&[vec![batch]], schema, None).unwrap(),
1724        )));
1725        let normalize_exec = Arc::new(InstantManipulateExec {
1726            offset: 0,
1727            start: 0,
1728            end: 1_500,
1729            lookback_delta: 1_000,
1730            interval: 500,
1731            time_index_column: TIME_INDEX_COLUMN.to_string(),
1732            field_column: Some("value".to_string()),
1733            reuse_tsid_column: true,
1734            output_schema: input.schema(),
1735            properties: input.properties().clone(),
1736            input,
1737            metric: ExecutionPlanMetricsSet::new(),
1738        });
1739        let session_context = SessionContext::default();
1740        let result = datafusion::physical_plan::collect(normalize_exec, session_context.task_ctx())
1741            .await
1742            .unwrap();
1743        let result_literal = datatypes::arrow::util::pretty::pretty_format_batches(&result)
1744            .unwrap()
1745            .to_string();
1746
1747        assert_eq!(
1748            result_literal,
1749            "+-------------------------+-------+------+--------+\
1750            \n| timestamp               | value | host | __tsid |\
1751            \n+-------------------------+-------+------+--------+\
1752            \n| 1970-01-01T00:00:00     | 1.0   | foo  | 42     |\
1753            \n| 1970-01-01T00:00:00.500 | 1.0   | foo  | 42     |\
1754            \n| 1970-01-01T00:00:01     | 2.0   | foo  | 42     |\
1755            \n| 1970-01-01T00:00:01.500 | 2.0   | foo  | 42     |\
1756            \n+-------------------------+-------+------+--------+"
1757        );
1758    }
1759
1760    #[tokio::test]
1761    async fn tsid_fast_path_still_takes_additional_field_columns() {
1762        let schema = Arc::new(Schema::new(vec![
1763            Field::new(
1764                TIME_INDEX_COLUMN,
1765                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
1766                false,
1767            ),
1768            Field::new("value", DataType::Float64, true),
1769            Field::new("value_2", DataType::Float64, true),
1770            Field::new("host", DataType::Utf8, true),
1771            Field::new("__tsid", DataType::UInt64, false),
1772        ]));
1773        let batch = RecordBatch::try_new(
1774            schema.clone(),
1775            vec![
1776                Arc::new(TimestampMillisecondArray::from(vec![0, 1_000])),
1777                Arc::new(Float64Array::from(vec![1.0, 2.0])),
1778                Arc::new(Float64Array::from(vec![10.0, 20.0])),
1779                Arc::new(datafusion::arrow::array::StringArray::from(vec![
1780                    "foo", "foo",
1781                ])),
1782                Arc::new(UInt64Array::from(vec![42, 42])),
1783            ],
1784        )
1785        .unwrap();
1786        let input = Arc::new(DataSourceExec::new(Arc::new(
1787            MemorySourceConfig::try_new(&[vec![batch]], schema, None).unwrap(),
1788        )));
1789        let normalize_exec = Arc::new(InstantManipulateExec {
1790            offset: 0,
1791            start: 0,
1792            end: 1_500,
1793            lookback_delta: 1_000,
1794            interval: 500,
1795            time_index_column: TIME_INDEX_COLUMN.to_string(),
1796            field_column: Some("value".to_string()),
1797            reuse_tsid_column: true,
1798            output_schema: input.schema(),
1799            properties: input.properties().clone(),
1800            input,
1801            metric: ExecutionPlanMetricsSet::new(),
1802        });
1803        let session_context = SessionContext::default();
1804        let result = datafusion::physical_plan::collect(normalize_exec, session_context.task_ctx())
1805            .await
1806            .unwrap();
1807        let result_literal = datatypes::arrow::util::pretty::pretty_format_batches(&result)
1808            .unwrap()
1809            .to_string();
1810
1811        assert_eq!(
1812            result_literal,
1813            "+-------------------------+-------+---------+------+--------+\
1814            \n| timestamp               | value | value_2 | host | __tsid |\
1815            \n+-------------------------+-------+---------+------+--------+\
1816            \n| 1970-01-01T00:00:00     | 1.0   | 10.0    | foo  | 42     |\
1817            \n| 1970-01-01T00:00:00.500 | 1.0   | 10.0    | foo  | 42     |\
1818            \n| 1970-01-01T00:00:01     | 2.0   | 20.0    | foo  | 42     |\
1819            \n| 1970-01-01T00:00:01.500 | 2.0   | 20.0    | foo  | 42     |\
1820            \n+-------------------------+-------+---------+------+--------+"
1821        );
1822    }
1823
1824    /// One series of one `value` column holding `rows` of `(timestamp, value)` decided over
1825    /// `start..=end` by `interval` with `lookback`.
1826    fn one_series(
1827        rows: Vec<(Millisecond, f64)>,
1828        start: Millisecond,
1829        end: Millisecond,
1830        interval: Millisecond,
1831        lookback: Millisecond,
1832    ) -> Arc<InstantManipulateExec> {
1833        let schema = Arc::new(Schema::new(vec![
1834            Field::new(
1835                TIME_INDEX_COLUMN,
1836                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
1837                false,
1838            ),
1839            Field::new("value", DataType::Float64, true),
1840        ]));
1841        let (timestamps, values): (Vec<Millisecond>, Vec<f64>) = rows.into_iter().unzip();
1842        let batch = RecordBatch::try_new(
1843            schema.clone(),
1844            vec![
1845                Arc::new(TimestampMillisecondArray::from(timestamps)),
1846                Arc::new(Float64Array::from(values)),
1847            ],
1848        )
1849        .unwrap();
1850        let input = Arc::new(DataSourceExec::new(Arc::new(
1851            MemorySourceConfig::try_new(&[vec![batch]], schema, None).unwrap(),
1852        )));
1853        Arc::new(InstantManipulateExec {
1854            offset: 0,
1855            start,
1856            end,
1857            lookback_delta: lookback,
1858            interval,
1859            time_index_column: TIME_INDEX_COLUMN.to_string(),
1860            field_column: Some("value".to_string()),
1861            reuse_tsid_column: false,
1862            output_schema: input.schema(),
1863            properties: input.properties().clone(),
1864            input,
1865            metric: ExecutionPlanMetricsSet::new(),
1866        })
1867    }
1868
1869    /// A single row of one series selected at every point of a grid `points` long, with `lookback`
1870    /// wide enough that the row answers all of them.
1871    fn one_row_selected_everywhere(points: Millisecond) -> Arc<InstantManipulateExec> {
1872        one_series(vec![(0, 1.0)], 0, points, 1, points + 1)
1873    }
1874
1875    /// A grid of a million and one points used to be refused by a point count of the kernel's own.
1876    /// What refuses it now is the pool, which cannot hold the workspace of the selection.
1877    #[tokio::test]
1878    async fn manipulate_reports_the_pool_that_cannot_hold_the_workspace() {
1879        let points = 1_000_001;
1880        let err = datafusion::physical_plan::collect(
1881            one_row_selected_everywhere(points),
1882            bounded_task_context(1024),
1883        )
1884        .await
1885        .unwrap_err();
1886
1887        assert!(
1888            matches!(err, DataFusionError::ResourcesExhausted(_)),
1889            "the pool did not refuse the workspace: {err}"
1890        );
1891        assert!(
1892            !err.to_string().contains("exceed limit"),
1893            "a point limit answered in the pool's place: {err}"
1894        );
1895    }
1896
1897    /// The same grid, past what the removed limit allowed, is decided against a pool that holds it.
1898    #[tokio::test]
1899    async fn manipulate_decides_a_grid_past_the_removed_point_limit() {
1900        let points = 1_000_001;
1901        let batches = datafusion::physical_plan::collect(
1902            one_row_selected_everywhere(points),
1903            // This series' one sample answers every point of the grid under that wide lookback, so
1904            // its clipped grid is the whole grid. The estimate of `manipulate_reserved` for this
1905            // schema is 41 bytes per point (four `u64`, one `f64` and a validity bit), so this
1906            // holds the million-odd points it reserves for with room to spare.
1907            bounded_task_context(64 * 1024 * 1024),
1908        )
1909        .await
1910        .unwrap();
1911
1912        let rows: usize = batches.iter().map(|batch| batch.num_rows()).sum();
1913        assert_eq!(
1914            rows,
1915            points as usize + 1,
1916            "the grid the removed limit refused was not decided"
1917        );
1918    }
1919
1920    /// A series that ends at its first sample is charged for the points it selects, not for the
1921    /// grid of the whole query range.
1922    ///
1923    /// Seven days at a 60 s step is 10 081 grid points, and the whole-grid figure of this schema is
1924    /// 41 bytes per point: 413 337 bytes, which a 256 KiB pool refuses. The series holds one sample
1925    /// at `t=0` and its lookback is 5 min, so `select_instants` clips it to the six-point grid
1926    /// `0..=300 s`, from which the five points `0, 60, ..., 240 s` are selected; the reservation
1927    /// covers those six points -- 262 bytes -- and the pool holds it. Before the reservation
1928    /// followed the clipped range, the query was refused before anything was selected.
1929    #[tokio::test]
1930    async fn series_that_ends_at_its_first_sample_is_not_charged_for_the_grid() {
1931        let batches = datafusion::physical_plan::collect(
1932            one_series(
1933                vec![(0, 1.0)],
1934                0,
1935                7 * 24 * 60 * 60 * 1_000,
1936                60_000,
1937                5 * 60 * 1_000,
1938            ),
1939            bounded_task_context(256 * 1024),
1940        )
1941        .await
1942        .unwrap();
1943
1944        let timestamps: Vec<Millisecond> = batches
1945            .iter()
1946            .flat_map(|batch| {
1947                batch
1948                    .column(0)
1949                    .as_any()
1950                    .downcast_ref::<TimestampMillisecondArray>()
1951                    .expect("the output time column is in milliseconds")
1952                    .values()
1953                    .to_vec()
1954            })
1955            .collect();
1956        assert_eq!(timestamps, vec![0, 60_000, 120_000, 180_000, 240_000]);
1957    }
1958
1959    /// A series whose samples span the whole query range is still charged for the whole grid, so
1960    /// the clipped figure is a bound on what is selected and not a reservation of nothing.
1961    #[tokio::test]
1962    async fn series_that_spans_the_whole_grid_is_still_charged_for_it() {
1963        let end = 7 * 24 * 60 * 60 * 1_000;
1964        let spanning = || one_series(vec![(0, 1.0), (end, 2.0)], 0, end, 60_000, 5 * 60 * 1_000);
1965
1966        let err = datafusion::physical_plan::collect(spanning(), bounded_task_context(256 * 1024))
1967            .await
1968            .unwrap_err();
1969        assert!(
1970            matches!(err, DataFusionError::ResourcesExhausted(_)),
1971            "a pool below the clipped grid's workspace did not refuse it: {err}"
1972        );
1973
1974        let batches =
1975            datafusion::physical_plan::collect(spanning(), bounded_task_context(1024 * 1024))
1976                .await
1977                .unwrap();
1978        // A sample answers only the points of its own lookback window, so the two samples decide
1979        // six rows: the five of the first 5 min and the point of the second sample. The grid they
1980        // reach, and the one the reservation covers, is the whole 10 081 points.
1981        let rows: usize = batches.iter().map(|batch| batch.num_rows()).sum();
1982        assert_eq!(
1983            rows, 6,
1984            "the series spanning the whole grid was not decided"
1985        );
1986    }
1987
1988    #[test]
1989    fn row_bytes_accounts_for_string_representation_storage() {
1990        use datafusion::arrow::array::{DictionaryArray, Int8Array};
1991        use datafusion::arrow::datatypes::Int8Type;
1992
1993        let utf8 = StringArray::from(vec!["a", "long"]);
1994        // `row_bytes` is the per-row value width; workspace offsets are charged separately.
1995        assert_eq!(row_bytes(&utf8), Some(4));
1996
1997        let large_utf8 = LargeStringArray::from(vec!["a", "long"]);
1998        assert_eq!(row_bytes(&large_utf8), Some(4));
1999
2000        let view = StringViewArray::from(vec!["a", "long"]);
2001        assert_eq!(row_bytes(&view), Some(16 + 4));
2002
2003        let dictionary = DictionaryArray::<Int8Type>::try_new(
2004            Int8Array::from(vec![Some(0), Some(1)]),
2005            Arc::new(StringArray::from(vec!["a", "long"])),
2006        )
2007        .unwrap();
2008        assert_eq!(row_bytes(&dictionary), Some(std::mem::size_of::<i8>()));
2009    }
2010
2011    #[test]
2012    fn workspace_bytes_charges_utf8_output_offsets_once() {
2013        let schema = Arc::new(Schema::new(vec![
2014            Field::new(
2015                TIME_INDEX_COLUMN,
2016                DataType::Timestamp(TimeUnit::Millisecond, None),
2017                false,
2018            ),
2019            Field::new("utf8", DataType::Utf8, false),
2020        ]));
2021        let batch = RecordBatch::try_new(
2022            schema.clone(),
2023            vec![
2024                Arc::new(TimestampMillisecondArray::from(vec![0, 1])),
2025                Arc::new(StringArray::from(vec!["payload", "payload"])),
2026            ],
2027        )
2028        .unwrap();
2029        let stream = InstantManipulateStream {
2030            offset: 0,
2031            start: 0,
2032            end: 1,
2033            lookback_delta: 1,
2034            interval: 1,
2035            time_index: 0,
2036            time_unit: TimeUnit::Millisecond,
2037            field_indices: [None, None],
2038            tsid_index: None,
2039            reuse_tsid_column: false,
2040            schema,
2041            input: Box::pin(
2042                datafusion::physical_plan::memory::MemoryStream::try_new(
2043                    vec![],
2044                    batch.schema(),
2045                    None,
2046                )
2047                .unwrap(),
2048            ),
2049            metric: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
2050            num_series: Count::new(),
2051            reservation: unbounded(),
2052        };
2053        let points = stream.clipped_points(&batch);
2054        assert_eq!(points, 2);
2055        let estimate = stream.workspace_bytes(&batch);
2056        let output = stream.manipulate(batch.clone()).unwrap();
2057        let output_buffers = output
2058            .columns()
2059            .iter()
2060            .map(|column| column.get_buffer_memory_size())
2061            .sum::<usize>();
2062        assert!(estimate >= output_buffers);
2063    }
2064
2065    /// The figure `manipulate_reserved` grows is the clipped one: 262 bytes for a series that ends
2066    /// at its first sample, 413 337 bytes for one that spans the same seven-day grid of 10 081
2067    /// points at a 60 s step. Per point it is the four `u64` of the two index vectors and the
2068    /// timestamp allowance, the `f64` and validity bit `take` allocates for `value`, and one
2069    /// `ArrayRef` per column.
2070    #[test]
2071    fn workspace_bytes_follows_the_clipped_grid_not_the_planned_one() {
2072        let schema = Arc::new(Schema::new(vec![
2073            Field::new(
2074                TIME_INDEX_COLUMN,
2075                DataType::Timestamp(TimeUnit::Millisecond, None),
2076                false,
2077            ),
2078            Field::new("value", DataType::Float64, true),
2079        ]));
2080        let end = 7 * 24 * 60 * 60 * 1_000;
2081        let stream = InstantManipulateStream {
2082            offset: 0,
2083            start: 0,
2084            end,
2085            lookback_delta: 5 * 60 * 1_000,
2086            interval: 60_000,
2087            time_index: 0,
2088            time_unit: TimeUnit::Millisecond,
2089            field_indices: [Some(1), None],
2090            tsid_index: None,
2091            reuse_tsid_column: false,
2092            schema: schema.clone(),
2093            input: Box::pin(
2094                datafusion::physical_plan::memory::MemoryStream::try_new(
2095                    vec![],
2096                    schema.clone(),
2097                    None,
2098                )
2099                .unwrap(),
2100            ),
2101            metric: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
2102            num_series: Count::new(),
2103            reservation: unbounded(),
2104        };
2105        let series = |timestamps: Vec<Millisecond>| {
2106            RecordBatch::try_new(
2107                schema.clone(),
2108                vec![
2109                    Arc::new(TimestampMillisecondArray::from(timestamps.clone())),
2110                    Arc::new(Float64Array::from(vec![1.0; timestamps.len()])),
2111                ],
2112            )
2113            .unwrap()
2114        };
2115
2116        // One sample at `t=0` under a 5 min lookback clips to the six points `0, 60, ..., 300 s`;
2117        // the exclusive lower bound leaves five of them selected.
2118        let short = series(vec![0]);
2119        assert_eq!(stream.clipped_points(&short), 6);
2120        assert_eq!(
2121            stream.workspace_bytes(&short),
2122            6 * 32 + 6 * 9 + 2 * std::mem::size_of::<ArrayRef>()
2123        );
2124        // Samples at both ends reach every point of the planned grid, and are charged for it.
2125        let long = series(vec![0, end]);
2126        assert_eq!(stream.clipped_points(&long), 10_081);
2127        assert_eq!(
2128            stream.workspace_bytes(&long),
2129            10_081 * 32 + 10_081 * 9 + 2 * std::mem::size_of::<ArrayRef>()
2130        );
2131        // An input without samples selects nothing and reserves nothing beyond the batch's columns.
2132        let empty = series(vec![]);
2133        assert_eq!(stream.clipped_points(&empty), 0);
2134        assert_eq!(
2135            stream.workspace_bytes(&empty),
2136            2 * std::mem::size_of::<ArrayRef>()
2137        );
2138    }
2139
2140    #[tokio::test]
2141    async fn lookback_10s_interval_30s() {
2142        let expected = String::from(
2143            "+---------------------+-------+------+\
2144            \n| timestamp           | value | path |\
2145            \n+---------------------+-------+------+\
2146            \n| 1970-01-01T00:00:00 | 1.0   | foo  |\
2147            \n| 1970-01-01T00:00:30 | 1.0   | foo  |\
2148            \n| 1970-01-01T00:01:00 | 1.0   | foo  |\
2149            \n| 1970-01-01T00:01:30 | 1.0   | foo  |\
2150            \n| 1970-01-01T00:02:00 | 1.0   | foo  |\
2151            \n| 1970-01-01T00:03:00 | 1.0   | foo  |\
2152            \n| 1970-01-01T00:04:00 | 1.0   | foo  |\
2153            \n| 1970-01-01T00:05:00 | 1.0   | foo  |\
2154            \n+---------------------+-------+------+",
2155        );
2156        do_normalize_test(0, 310_000, 10_000, 30_000, expected, false).await;
2157    }
2158
2159    #[tokio::test]
2160    async fn lookback_10s_interval_10s() {
2161        let expected = String::from(
2162            "+---------------------+-------+------+\
2163            \n| timestamp           | value | path |\
2164            \n+---------------------+-------+------+\
2165            \n| 1970-01-01T00:00:00 | 1.0   | foo  |\
2166            \n| 1970-01-01T00:00:30 | 1.0   | foo  |\
2167            \n| 1970-01-01T00:01:00 | 1.0   | foo  |\
2168            \n| 1970-01-01T00:01:30 | 1.0   | foo  |\
2169            \n| 1970-01-01T00:02:00 | 1.0   | foo  |\
2170            \n| 1970-01-01T00:03:00 | 1.0   | foo  |\
2171            \n| 1970-01-01T00:04:00 | 1.0   | foo  |\
2172            \n| 1970-01-01T00:04:10 | 1.0   | foo  |\
2173            \n| 1970-01-01T00:04:40 | 1.0   | foo  |\
2174            \n| 1970-01-01T00:05:00 | 1.0   | foo  |\
2175            \n+---------------------+-------+------+",
2176        );
2177        do_normalize_test(0, 300_000, 10_000, 10_000, expected, false).await;
2178    }
2179
2180    #[tokio::test]
2181    async fn lookback_30s_interval_30s() {
2182        let expected = String::from(
2183            "+---------------------+-------+------+\
2184            \n| timestamp           | value | path |\
2185            \n+---------------------+-------+------+\
2186            \n| 1970-01-01T00:00:00 | 1.0   | foo  |\
2187            \n| 1970-01-01T00:00:30 | 1.0   | foo  |\
2188            \n| 1970-01-01T00:01:00 | 1.0   | foo  |\
2189            \n| 1970-01-01T00:01:30 | 1.0   | foo  |\
2190            \n| 1970-01-01T00:02:00 | 1.0   | foo  |\
2191            \n| 1970-01-01T00:03:00 | 1.0   | foo  |\
2192            \n| 1970-01-01T00:04:00 | 1.0   | foo  |\
2193            \n| 1970-01-01T00:04:30 | 1.0   | foo  |\
2194            \n| 1970-01-01T00:05:00 | 1.0   | foo  |\
2195            \n+---------------------+-------+------+",
2196        );
2197        do_normalize_test(0, 300_000, 30_000, 30_000, expected, false).await;
2198    }
2199
2200    #[tokio::test]
2201    async fn lookback_30s_interval_10s() {
2202        let expected = String::from(
2203            "+---------------------+-------+------+\
2204            \n| timestamp           | value | path |\
2205            \n+---------------------+-------+------+\
2206            \n| 1970-01-01T00:00:00 | 1.0   | foo  |\
2207            \n| 1970-01-01T00:00:10 | 1.0   | foo  |\
2208            \n| 1970-01-01T00:00:20 | 1.0   | foo  |\
2209            \n| 1970-01-01T00:00:30 | 1.0   | foo  |\
2210            \n| 1970-01-01T00:00:40 | 1.0   | foo  |\
2211            \n| 1970-01-01T00:00:50 | 1.0   | foo  |\
2212            \n| 1970-01-01T00:01:00 | 1.0   | foo  |\
2213            \n| 1970-01-01T00:01:10 | 1.0   | foo  |\
2214            \n| 1970-01-01T00:01:20 | 1.0   | foo  |\
2215            \n| 1970-01-01T00:01:30 | 1.0   | foo  |\
2216            \n| 1970-01-01T00:01:40 | 1.0   | foo  |\
2217            \n| 1970-01-01T00:01:50 | 1.0   | foo  |\
2218            \n| 1970-01-01T00:02:00 | 1.0   | foo  |\
2219            \n| 1970-01-01T00:02:10 | 1.0   | foo  |\
2220            \n| 1970-01-01T00:02:20 | 1.0   | foo  |\
2221            \n| 1970-01-01T00:03:00 | 1.0   | foo  |\
2222            \n| 1970-01-01T00:03:10 | 1.0   | foo  |\
2223            \n| 1970-01-01T00:03:20 | 1.0   | foo  |\
2224            \n| 1970-01-01T00:04:00 | 1.0   | foo  |\
2225            \n| 1970-01-01T00:04:10 | 1.0   | foo  |\
2226            \n| 1970-01-01T00:04:20 | 1.0   | foo  |\
2227            \n| 1970-01-01T00:04:30 | 1.0   | foo  |\
2228            \n| 1970-01-01T00:04:40 | 1.0   | foo  |\
2229            \n| 1970-01-01T00:04:50 | 1.0   | foo  |\
2230            \n| 1970-01-01T00:05:00 | 1.0   | foo  |\
2231            \n+---------------------+-------+------+",
2232        );
2233        do_normalize_test(0, 300_000, 30_000, 10_000, expected, false).await;
2234    }
2235
2236    #[tokio::test]
2237    async fn lookback_60s_interval_10s() {
2238        let expected = String::from(
2239            "+---------------------+-------+------+\
2240            \n| timestamp           | value | path |\
2241            \n+---------------------+-------+------+\
2242            \n| 1970-01-01T00:00:00 | 1.0   | foo  |\
2243            \n| 1970-01-01T00:00:10 | 1.0   | foo  |\
2244            \n| 1970-01-01T00:00:20 | 1.0   | foo  |\
2245            \n| 1970-01-01T00:00:30 | 1.0   | foo  |\
2246            \n| 1970-01-01T00:00:40 | 1.0   | foo  |\
2247            \n| 1970-01-01T00:00:50 | 1.0   | foo  |\
2248            \n| 1970-01-01T00:01:00 | 1.0   | foo  |\
2249            \n| 1970-01-01T00:01:10 | 1.0   | foo  |\
2250            \n| 1970-01-01T00:01:20 | 1.0   | foo  |\
2251            \n| 1970-01-01T00:01:30 | 1.0   | foo  |\
2252            \n| 1970-01-01T00:01:40 | 1.0   | foo  |\
2253            \n| 1970-01-01T00:01:50 | 1.0   | foo  |\
2254            \n| 1970-01-01T00:02:00 | 1.0   | foo  |\
2255            \n| 1970-01-01T00:02:10 | 1.0   | foo  |\
2256            \n| 1970-01-01T00:02:20 | 1.0   | foo  |\
2257            \n| 1970-01-01T00:02:30 | 1.0   | foo  |\
2258            \n| 1970-01-01T00:02:40 | 1.0   | foo  |\
2259            \n| 1970-01-01T00:02:50 | 1.0   | foo  |\
2260            \n| 1970-01-01T00:03:00 | 1.0   | foo  |\
2261            \n| 1970-01-01T00:03:10 | 1.0   | foo  |\
2262            \n| 1970-01-01T00:03:20 | 1.0   | foo  |\
2263            \n| 1970-01-01T00:03:30 | 1.0   | foo  |\
2264            \n| 1970-01-01T00:03:40 | 1.0   | foo  |\
2265            \n| 1970-01-01T00:03:50 | 1.0   | foo  |\
2266            \n| 1970-01-01T00:04:00 | 1.0   | foo  |\
2267            \n| 1970-01-01T00:04:10 | 1.0   | foo  |\
2268            \n| 1970-01-01T00:04:20 | 1.0   | foo  |\
2269            \n| 1970-01-01T00:04:30 | 1.0   | foo  |\
2270            \n| 1970-01-01T00:04:40 | 1.0   | foo  |\
2271            \n| 1970-01-01T00:04:50 | 1.0   | foo  |\
2272            \n| 1970-01-01T00:05:00 | 1.0   | foo  |\
2273            \n+---------------------+-------+------+",
2274        );
2275        do_normalize_test(0, 300_000, 60_000, 10_000, expected, false).await;
2276    }
2277
2278    #[tokio::test]
2279    async fn lookback_60s_interval_30s() {
2280        let expected = String::from(
2281            "+---------------------+-------+------+\
2282            \n| timestamp           | value | path |\
2283            \n+---------------------+-------+------+\
2284            \n| 1970-01-01T00:00:00 | 1.0   | foo  |\
2285            \n| 1970-01-01T00:00:30 | 1.0   | foo  |\
2286            \n| 1970-01-01T00:01:00 | 1.0   | foo  |\
2287            \n| 1970-01-01T00:01:30 | 1.0   | foo  |\
2288            \n| 1970-01-01T00:02:00 | 1.0   | foo  |\
2289            \n| 1970-01-01T00:02:30 | 1.0   | foo  |\
2290            \n| 1970-01-01T00:03:00 | 1.0   | foo  |\
2291            \n| 1970-01-01T00:03:30 | 1.0   | foo  |\
2292            \n| 1970-01-01T00:04:00 | 1.0   | foo  |\
2293            \n| 1970-01-01T00:04:30 | 1.0   | foo  |\
2294            \n| 1970-01-01T00:05:00 | 1.0   | foo  |\
2295            \n+---------------------+-------+------+",
2296        );
2297        do_normalize_test(0, 300_000, 60_000, 30_000, expected, false).await;
2298    }
2299
2300    #[tokio::test]
2301    async fn small_range_lookback_0s_interval_1s() {
2302        let expected = String::from(
2303            "+---------------------+-------+------+\
2304            \n| timestamp           | value | path |\
2305            \n+---------------------+-------+------+\
2306            \n| 1970-01-01T00:04:00 | 1.0   | foo  |\
2307            \n| 1970-01-01T00:04:01 | 1.0   | foo  |\
2308            \n+---------------------+-------+------+",
2309        );
2310        do_normalize_test(230_000, 245_000, 0, 1_000, expected, false).await;
2311    }
2312
2313    #[tokio::test]
2314    async fn small_range_lookback_10s_interval_10s() {
2315        let expected = String::from(
2316            "+---------------------+-------+------+\
2317            \n| timestamp           | value | path |\
2318            \n+---------------------+-------+------+\
2319            \n| 1970-01-01T00:00:00 | 1.0   | foo  |\
2320            \n| 1970-01-01T00:00:30 | 1.0   | foo  |\
2321            \n+---------------------+-------+------+",
2322        );
2323        do_normalize_test(0, 30_000, 10_000, 10_000, expected, false).await;
2324    }
2325
2326    #[tokio::test]
2327    async fn large_range_lookback_30s_interval_60s() {
2328        let expected = String::from(
2329            "+---------------------+-------+------+\
2330            \n| timestamp           | value | path |\
2331            \n+---------------------+-------+------+\
2332            \n| 1970-01-01T00:00:00 | 1.0   | foo  |\
2333            \n| 1970-01-01T00:01:00 | 1.0   | foo  |\
2334            \n| 1970-01-01T00:02:00 | 1.0   | foo  |\
2335            \n| 1970-01-01T00:03:00 | 1.0   | foo  |\
2336            \n| 1970-01-01T00:04:00 | 1.0   | foo  |\
2337            \n| 1970-01-01T00:05:00 | 1.0   | foo  |\
2338            \n+---------------------+-------+------+",
2339        );
2340        do_normalize_test(-900_000, 900_000, 30_000, 60_000, expected, false).await;
2341    }
2342
2343    #[tokio::test]
2344    async fn small_range_lookback_30s_interval_30s() {
2345        let expected = String::from(
2346            "+---------------------+-------+------+\
2347            \n| timestamp           | value | path |\
2348            \n+---------------------+-------+------+\
2349            \n| 1970-01-01T00:03:10 | 1.0   | foo  |\
2350            \n| 1970-01-01T00:03:20 | 1.0   | foo  |\
2351            \n| 1970-01-01T00:04:00 | 1.0   | foo  |\
2352            \n| 1970-01-01T00:04:10 | 1.0   | foo  |\
2353            \n| 1970-01-01T00:04:20 | 1.0   | foo  |\
2354            \n| 1970-01-01T00:04:30 | 1.0   | foo  |\
2355            \n| 1970-01-01T00:04:40 | 1.0   | foo  |\
2356            \n| 1970-01-01T00:04:50 | 1.0   | foo  |\
2357            \n| 1970-01-01T00:05:00 | 1.0   | foo  |\
2358            \n+---------------------+-------+------+",
2359        );
2360        do_normalize_test(190_000, 300_000, 30_000, 10_000, expected, false).await;
2361    }
2362
2363    #[tokio::test]
2364    async fn lookback_10s_interval_10s_with_stale_marker() {
2365        let expected = String::from(
2366            "+---------------------+-------+\
2367            \n| timestamp           | value |\
2368            \n+---------------------+-------+\
2369            \n| 1970-01-01T00:00:00 | 0.0   |\
2370            \n| 1970-01-01T00:01:00 | 6.0   |\
2371            \n| 1970-01-01T00:02:00 | 12.0  |\
2372            \n+---------------------+-------+",
2373        );
2374        do_normalize_test(0, 300_000, 10_000, 10_000, expected, true).await;
2375    }
2376
2377    #[tokio::test]
2378    async fn lookback_10s_interval_10s_with_stale_marker_unaligned() {
2379        let expected = String::from(
2380            "+-------------------------+-------+\
2381            \n| timestamp               | value |\
2382            \n+-------------------------+-------+\
2383            \n| 1970-01-01T00:00:00.001 | 0.0   |\
2384            \n| 1970-01-01T00:01:00.001 | 6.0   |\
2385            \n| 1970-01-01T00:02:00.001 | 12.0  |\
2386            \n+-------------------------+-------+",
2387        );
2388        do_normalize_test(1, 300_001, 10_000, 10_000, expected, true).await;
2389    }
2390
2391    #[tokio::test]
2392    async fn ultra_large_range() {
2393        let expected = String::from(
2394            "+-------------------------+-------+\
2395            \n| timestamp               | value |\
2396            \n+-------------------------+-------+\
2397            \n| 1970-01-01T00:00:00.001 | 0.0   |\
2398            \n| 1970-01-01T00:01:00.001 | 6.0   |\
2399            \n| 1970-01-01T00:02:00.001 | 12.0  |\
2400            \n+-------------------------+-------+",
2401        );
2402        do_normalize_test(
2403            -900_000_000_000_000 + 1,
2404            900_000_000_000_000,
2405            10_000,
2406            10_000,
2407            expected,
2408            true,
2409        )
2410        .await;
2411    }
2412
2413    #[test]
2414    fn nullable_interior_timestamp_matches_wide_scan() {
2415        let schema = Arc::new(Schema::new(vec![
2416            Field::new(
2417                TIME_INDEX_COLUMN,
2418                DataType::Timestamp(TimeUnit::Second, None),
2419                true,
2420            ),
2421            Field::new("value", DataType::Float64, false),
2422        ]));
2423        let timestamps = [0, i64::MAX, 1];
2424        let array = TimestampSecondArray::new(
2425            timestamps.to_vec().into(),
2426            Some(NullBuffer::from(vec![false, false, true])),
2427        );
2428        let input = RecordBatch::try_new(
2429            schema.clone(),
2430            vec![
2431                Arc::new(array),
2432                Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0])),
2433            ],
2434        )
2435        .unwrap();
2436        let stream = InstantManipulateStream {
2437            offset: 0,
2438            start: 0,
2439            end: 1_000,
2440            lookback_delta: 1_000,
2441            interval: 1_000,
2442            time_index: 0,
2443            time_unit: TimeUnit::Second,
2444            field_indices: [Some(1), None],
2445            tsid_index: None,
2446            reuse_tsid_column: false,
2447            schema: Arc::new(Schema::new(vec![
2448                Field::new(
2449                    TIME_INDEX_COLUMN,
2450                    DataType::Timestamp(TimeUnit::Millisecond, None),
2451                    false,
2452                ),
2453                Field::new("value", DataType::Float64, false),
2454            ])),
2455            input: Box::pin(
2456                datafusion::physical_plan::memory::MemoryStream::try_new(vec![], schema, None)
2457                    .unwrap(),
2458            ),
2459            metric: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
2460            num_series: Count::new(),
2461            reservation: unbounded(),
2462        };
2463
2464        let output = stream.manipulate(input).unwrap();
2465        let output_timestamps = output
2466            .column(0)
2467            .as_any()
2468            .downcast_ref::<TimestampMillisecondArray>()
2469            .unwrap();
2470        let output_values = output
2471            .column(1)
2472            .as_any()
2473            .downcast_ref::<Float64Array>()
2474            .unwrap();
2475        let wide = stream.scan_instants::<i128>(
2476            &timestamps,
2477            0,
2478            1_000,
2479            &ScanNanoseconds::<i128>::wide(TimeUnit::Second, 0, 1_000),
2480            2,
2481            |_| false,
2482        );
2483        assert_eq!(output_timestamps.values(), &[0]);
2484        assert_eq!(output_values.values(), &[1.0]);
2485        assert_eq!(wide, (vec![0], vec![0]));
2486        assert_eq!(wide.1, output_timestamps.values().to_vec());
2487    }
2488
2489    #[test]
2490    fn exact_ties_select_first_and_lookback_uses_latest() {
2491        for (values, expected_timestamp) in [
2492            (vec![42.0, f64::from_bits(PROMETHEUS_STALE_NAN_BITS)], 1_000),
2493            (vec![f64::from_bits(PROMETHEUS_STALE_NAN_BITS), 42.0], 1_050),
2494        ] {
2495            let schema = Arc::new(Schema::new(vec![
2496                Field::new(
2497                    TIME_INDEX_COLUMN,
2498                    DataType::Timestamp(TimeUnit::Millisecond, None),
2499                    false,
2500                ),
2501                Field::new("value", DataType::Float64, true),
2502            ]));
2503            let input = RecordBatch::try_new(
2504                schema.clone(),
2505                vec![
2506                    Arc::new(TimestampMillisecondArray::from(vec![1_000, 1_000])),
2507                    Arc::new(Float64Array::from(values)),
2508                ],
2509            )
2510            .unwrap();
2511            let stream = InstantManipulateStream {
2512                offset: 0,
2513                start: 1_000,
2514                end: 1_050,
2515                lookback_delta: 100,
2516                interval: 50,
2517                time_index: 0,
2518                time_unit: TimeUnit::Millisecond,
2519                field_indices: [Some(1), None],
2520                tsid_index: None,
2521                reuse_tsid_column: false,
2522                schema: schema.clone(),
2523                input: Box::pin(
2524                    datafusion::physical_plan::memory::MemoryStream::try_new(vec![], schema, None)
2525                        .unwrap(),
2526                ),
2527                metric: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
2528                num_series: Count::new(),
2529                reservation: unbounded(),
2530            };
2531
2532            let output = stream.manipulate(input).unwrap();
2533            let timestamps = output
2534                .column(0)
2535                .as_any()
2536                .downcast_ref::<TimestampMillisecondArray>()
2537                .unwrap();
2538            let values = output
2539                .column(1)
2540                .as_any()
2541                .downcast_ref::<Float64Array>()
2542                .unwrap();
2543            assert_eq!(timestamps.values(), &[expected_timestamp]);
2544            assert_eq!(values.values(), &[42.0]);
2545        }
2546    }
2547
2548    #[test]
2549    fn empty_batches_preserve_stream_progression_and_output_schema() {
2550        use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
2551        use futures::stream;
2552        use futures::task::noop_waker_ref;
2553
2554        let input_schema = Arc::new(Schema::new(vec![Field::new(
2555            TIME_INDEX_COLUMN,
2556            DataType::Timestamp(TimeUnit::Second, None),
2557            false,
2558        )]));
2559        let output_schema = Arc::new(Schema::new(vec![Field::new(
2560            TIME_INDEX_COLUMN,
2561            DataType::Timestamp(TimeUnit::Millisecond, None),
2562            false,
2563        )]));
2564        let empty = RecordBatch::new_empty(input_schema.clone());
2565        let valid = RecordBatch::try_new(
2566            input_schema.clone(),
2567            vec![Arc::new(TimestampSecondArray::from(vec![1]))],
2568        )
2569        .unwrap();
2570        let input = RecordBatchStreamAdapter::new(
2571            input_schema,
2572            stream::iter(vec![
2573                Ok(empty.clone()),
2574                Ok(empty.clone()),
2575                Ok(valid),
2576                Ok(empty),
2577                Err(DataFusionError::Execution("injected input error".into())),
2578            ]),
2579        );
2580        let mut stream = InstantManipulateStream {
2581            offset: 0,
2582            start: 1_000,
2583            end: 1_000,
2584            lookback_delta: 0,
2585            interval: 1,
2586            time_index: 0,
2587            time_unit: TimeUnit::Second,
2588            field_indices: [None, None],
2589            tsid_index: None,
2590            reuse_tsid_column: false,
2591            schema: output_schema.clone(),
2592            input: Box::pin(input),
2593            metric: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
2594            num_series: Count::new(),
2595            reservation: unbounded(),
2596        };
2597        let waker = noop_waker_ref();
2598        let mut cx = Context::from_waker(waker);
2599
2600        for _ in 0..2 {
2601            let Poll::Ready(Some(Ok(batch))) = Pin::new(&mut stream).poll_next(&mut cx) else {
2602                panic!("empty batch must be returned immediately");
2603            };
2604            assert_eq!(batch.num_rows(), 0);
2605            assert_eq!(batch.schema(), output_schema);
2606        }
2607
2608        let Poll::Ready(Some(Ok(valid))) = Pin::new(&mut stream).poll_next(&mut cx) else {
2609            panic!("valid batch must follow empty batches");
2610        };
2611        assert_eq!(valid.schema(), output_schema);
2612        assert_eq!(
2613            valid.column(0).data_type(),
2614            &DataType::Timestamp(TimeUnit::Millisecond, None)
2615        );
2616        assert_eq!(
2617            valid
2618                .column(0)
2619                .as_any()
2620                .downcast_ref::<TimestampMillisecondArray>()
2621                .unwrap()
2622                .values(),
2623            &[1_000]
2624        );
2625
2626        let Poll::Ready(Some(Ok(empty))) = Pin::new(&mut stream).poll_next(&mut cx) else {
2627            panic!("empty batch after valid batch must be returned immediately");
2628        };
2629        assert_eq!(empty.num_rows(), 0);
2630        assert_eq!(empty.schema(), output_schema);
2631
2632        let Poll::Ready(Some(Err(error))) = Pin::new(&mut stream).poll_next(&mut cx) else {
2633            panic!("input error must propagate");
2634        };
2635        assert!(error.to_string().contains("injected input error"));
2636        assert!(matches!(
2637            Pin::new(&mut stream).poll_next(&mut cx),
2638            Poll::Ready(None)
2639        ));
2640        assert_eq!(stream.num_series.value(), 1);
2641    }
2642
2643    #[test]
2644    fn extreme_alignment_retains_exact_sample() {
2645        let schema = Arc::new(Schema::new(vec![
2646            Field::new(
2647                TIME_INDEX_COLUMN,
2648                DataType::Timestamp(TimeUnit::Millisecond, None),
2649                false,
2650            ),
2651            Field::new("value", DataType::Float64, true),
2652        ]));
2653        let input = RecordBatch::try_new(
2654            schema.clone(),
2655            vec![
2656                Arc::new(TimestampMillisecondArray::from(vec![i64::MAX])),
2657                Arc::new(Float64Array::from(vec![7.0])),
2658            ],
2659        )
2660        .unwrap();
2661        let stream = InstantManipulateStream {
2662            offset: 0,
2663            start: i64::MIN + 1,
2664            end: i64::MAX,
2665            lookback_delta: 0,
2666            interval: i64::MAX,
2667            time_index: 0,
2668            time_unit: TimeUnit::Millisecond,
2669            field_indices: [Some(1), None],
2670            tsid_index: None,
2671            reuse_tsid_column: false,
2672            schema: schema.clone(),
2673            input: Box::pin(
2674                datafusion::physical_plan::memory::MemoryStream::try_new(vec![], schema, None)
2675                    .unwrap(),
2676            ),
2677            metric: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
2678            num_series: Count::new(),
2679            reservation: unbounded(),
2680        };
2681
2682        let output = stream.manipulate(input).unwrap();
2683        let timestamps = output
2684            .column(0)
2685            .as_any()
2686            .downcast_ref::<TimestampMillisecondArray>()
2687            .unwrap();
2688        let values = output
2689            .column(1)
2690            .as_any()
2691            .downcast_ref::<Float64Array>()
2692            .unwrap();
2693        assert_eq!(timestamps.values(), &[i64::MAX]);
2694        assert_eq!(values.values(), &[7.0]);
2695    }
2696
2697    #[test]
2698    fn native_nanosecond_offset_uses_wide_shifted_timeline() {
2699        for (raw, offset, eval) in [
2700            (
2701                9_223_112_837_000_000_000_i64,
2702                259_200_000,
2703                9_223_372_037_000,
2704            ),
2705            (
2706                -9_223_112_837_000_000_000_i64,
2707                -259_200_000,
2708                -9_223_372_037_000,
2709            ),
2710        ] {
2711            let schema = Arc::new(Schema::new(vec![
2712                Field::new(
2713                    TIME_INDEX_COLUMN,
2714                    DataType::Timestamp(TimeUnit::Nanosecond, None),
2715                    false,
2716                ),
2717                Field::new("value", DataType::Float64, true),
2718            ]));
2719            let input = RecordBatch::try_new(
2720                schema.clone(),
2721                vec![
2722                    Arc::new(TimestampNanosecondArray::from(vec![raw])),
2723                    Arc::new(Float64Array::from(vec![7.0])),
2724                ],
2725            )
2726            .unwrap();
2727            let stream = InstantManipulateStream {
2728                offset,
2729                start: eval,
2730                end: eval,
2731                lookback_delta: 300_000,
2732                interval: 1,
2733                time_index: 0,
2734                time_unit: TimeUnit::Nanosecond,
2735                field_indices: [Some(1), None],
2736                tsid_index: None,
2737                reuse_tsid_column: false,
2738                schema: Arc::new(Schema::new(vec![
2739                    Field::new(
2740                        TIME_INDEX_COLUMN,
2741                        DataType::Timestamp(TimeUnit::Millisecond, None),
2742                        false,
2743                    ),
2744                    Field::new("value", DataType::Float64, true),
2745                ])),
2746                input: Box::pin(
2747                    datafusion::physical_plan::memory::MemoryStream::try_new(vec![], schema, None)
2748                        .unwrap(),
2749                ),
2750                metric: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
2751                num_series: Count::new(),
2752                reservation: unbounded(),
2753            };
2754            let output = stream.manipulate(input).unwrap();
2755            assert_eq!(output.num_rows(), 1);
2756            assert_eq!(
2757                output
2758                    .column(0)
2759                    .as_any()
2760                    .downcast_ref::<TimestampMillisecondArray>()
2761                    .unwrap()
2762                    .value(0),
2763                eval
2764            );
2765            assert_eq!(
2766                output
2767                    .column(1)
2768                    .as_any()
2769                    .downcast_ref::<Float64Array>()
2770                    .unwrap()
2771                    .value(0),
2772                7.0
2773            );
2774        }
2775    }
2776
2777    #[tokio::test]
2778    async fn ordinary_nan_is_selected_for_exact_and_lookback() {
2779        let schema = Arc::new(Schema::new(vec![
2780            Field::new(
2781                TIME_INDEX_COLUMN,
2782                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
2783                false,
2784            ),
2785            Field::new("value", DataType::Float64, true),
2786        ]));
2787        let batch = RecordBatch::try_new(
2788            schema.clone(),
2789            vec![
2790                Arc::new(TimestampMillisecondArray::from(vec![1_000])),
2791                Arc::new(Float64Array::from(vec![f64::NAN])),
2792            ],
2793        )
2794        .unwrap();
2795        let input = Arc::new(DataSourceExec::new(Arc::new(
2796            MemorySourceConfig::try_new(&[vec![batch]], schema, None).unwrap(),
2797        )));
2798        let exec = Arc::new(InstantManipulateExec {
2799            offset: 0,
2800            start: 1_000,
2801            end: 1_500,
2802            lookback_delta: 1_000,
2803            interval: 500,
2804            time_index_column: TIME_INDEX_COLUMN.to_string(),
2805            field_column: Some("value".to_string()),
2806            reuse_tsid_column: false,
2807            output_schema: input.schema(),
2808            properties: input.properties().clone(),
2809            input,
2810            metric: ExecutionPlanMetricsSet::new(),
2811        });
2812
2813        let context = SessionContext::default();
2814        let batches = datafusion::physical_plan::collect(exec, context.task_ctx())
2815            .await
2816            .unwrap();
2817        let values = batches
2818            .iter()
2819            .flat_map(|batch| {
2820                batch
2821                    .column(1)
2822                    .as_any()
2823                    .downcast_ref::<Float64Array>()
2824                    .unwrap()
2825                    .values()
2826                    .iter()
2827                    .copied()
2828            })
2829            .collect::<Vec<_>>();
2830        let timestamps = batches
2831            .iter()
2832            .flat_map(|batch| {
2833                batch
2834                    .column(0)
2835                    .as_any()
2836                    .downcast_ref::<TimestampMillisecondArray>()
2837                    .unwrap()
2838                    .values()
2839                    .iter()
2840                    .copied()
2841            })
2842            .collect::<Vec<_>>();
2843
2844        assert_eq!(values.len(), 2);
2845        assert_eq!(timestamps, vec![1_000, 1_500]);
2846        assert!(values.iter().all(|value| value.is_nan()));
2847        assert_eq!(
2848            values
2849                .iter()
2850                .map(|value| value.to_bits())
2851                .collect::<Vec<_>>(),
2852            vec![f64::NAN.to_bits(); 2]
2853        );
2854    }
2855
2856    #[tokio::test]
2857    async fn prometheus_stale_nan_selects_before_and_suppresses_after_marker() {
2858        let schema = Arc::new(Schema::new(vec![
2859            Field::new(
2860                TIME_INDEX_COLUMN,
2861                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
2862                false,
2863            ),
2864            Field::new("value", DataType::Float64, true),
2865        ]));
2866        let batch = RecordBatch::try_new(
2867            schema.clone(),
2868            vec![
2869                Arc::new(TimestampMillisecondArray::from(vec![500, 1_000])),
2870                Arc::new(Float64Array::from(vec![
2871                    42.0,
2872                    f64::from_bits(0x7ff0_0000_0000_0002),
2873                ])),
2874            ],
2875        )
2876        .unwrap();
2877        let input = Arc::new(DataSourceExec::new(Arc::new(
2878            MemorySourceConfig::try_new(&[vec![batch]], schema, None).unwrap(),
2879        )));
2880        let exec = Arc::new(InstantManipulateExec {
2881            offset: 0,
2882            start: 750,
2883            end: 1_500,
2884            lookback_delta: 1_001,
2885            interval: 250,
2886            time_index_column: TIME_INDEX_COLUMN.to_string(),
2887            field_column: Some("value".to_string()),
2888            reuse_tsid_column: false,
2889            output_schema: input.schema(),
2890            properties: input.properties().clone(),
2891            input,
2892            metric: ExecutionPlanMetricsSet::new(),
2893        });
2894
2895        let context = SessionContext::default();
2896        let batches = datafusion::physical_plan::collect(exec, context.task_ctx())
2897            .await
2898            .unwrap();
2899
2900        let row_count = batches.iter().map(RecordBatch::num_rows).sum::<usize>();
2901        let batch = batches.iter().find(|batch| batch.num_rows() > 0).unwrap();
2902        let timestamp = batch
2903            .column(0)
2904            .as_any()
2905            .downcast_ref::<TimestampMillisecondArray>()
2906            .unwrap()
2907            .value(0);
2908        let value = batch
2909            .column(1)
2910            .as_any()
2911            .downcast_ref::<Float64Array>()
2912            .unwrap()
2913            .value(0);
2914        assert_eq!(
2915            (row_count, timestamp, value),
2916            (1, 750, 42.0),
2917            "only the evaluation before the stale marker should select 42.0"
2918        );
2919    }
2920
2921    #[tokio::test]
2922    async fn native_histogram_stale_nan_suppresses_exact_and_lookback() {
2923        let histograms = build_histogram_array(&[
2924            Some(native_histogram(42.0)),
2925            Some(native_histogram(f64::from_bits(PROMETHEUS_STALE_NAN_BITS))),
2926        ]);
2927        let schema = Arc::new(Schema::new(vec![
2928            Field::new(
2929                TIME_INDEX_COLUMN,
2930                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
2931                false,
2932            ),
2933            Field::new("value", histograms.data_type().clone(), true),
2934        ]));
2935        let batch = RecordBatch::try_new(
2936            schema.clone(),
2937            vec![
2938                Arc::new(TimestampMillisecondArray::from(vec![500, 1_000])),
2939                histograms,
2940            ],
2941        )
2942        .unwrap();
2943        let input = Arc::new(DataSourceExec::new(Arc::new(
2944            MemorySourceConfig::try_new(&[vec![batch]], schema, None).unwrap(),
2945        )));
2946        let exec = Arc::new(InstantManipulateExec {
2947            offset: 0,
2948            start: 1_000,
2949            end: 1_500,
2950            lookback_delta: 1_001,
2951            interval: 500,
2952            time_index_column: TIME_INDEX_COLUMN.to_string(),
2953            field_column: Some("value".to_string()),
2954            reuse_tsid_column: false,
2955            output_schema: input.schema(),
2956            properties: input.properties().clone(),
2957            input,
2958            metric: ExecutionPlanMetricsSet::new(),
2959        });
2960
2961        let context = SessionContext::default();
2962        let batches = datafusion::physical_plan::collect(exec, context.task_ctx())
2963            .await
2964            .unwrap();
2965
2966        assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 0);
2967    }
2968
2969    #[tokio::test]
2970    async fn null_value_backed_by_stale_bits_is_selected_for_exact_and_lookback() {
2971        let schema = Arc::new(Schema::new(vec![
2972            Field::new(
2973                TIME_INDEX_COLUMN,
2974                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
2975                false,
2976            ),
2977            Field::new("value", DataType::Float64, true),
2978        ]));
2979        let field_column = Float64Array::new(
2980            vec![f64::from_bits(0x7ff0_0000_0000_0002)].into(),
2981            Some(NullBuffer::from(vec![false])),
2982        );
2983        assert!(!field_column.is_valid(0));
2984        assert_eq!(field_column.value(0).to_bits(), 0x7ff0_0000_0000_0002);
2985        let batch = RecordBatch::try_new(
2986            schema.clone(),
2987            vec![
2988                Arc::new(TimestampMillisecondArray::from(vec![1_000])),
2989                Arc::new(field_column),
2990            ],
2991        )
2992        .unwrap();
2993        let input = Arc::new(DataSourceExec::new(Arc::new(
2994            MemorySourceConfig::try_new(&[vec![batch]], schema, None).unwrap(),
2995        )));
2996        let exec = Arc::new(InstantManipulateExec {
2997            offset: 0,
2998            start: 1_000,
2999            end: 1_500,
3000            lookback_delta: 1_000,
3001            interval: 500,
3002            time_index_column: TIME_INDEX_COLUMN.to_string(),
3003            field_column: Some("value".to_string()),
3004            reuse_tsid_column: false,
3005            output_schema: input.schema(),
3006            properties: input.properties().clone(),
3007            input,
3008            metric: ExecutionPlanMetricsSet::new(),
3009        });
3010
3011        let context = SessionContext::default();
3012        let batches = datafusion::physical_plan::collect(exec, context.task_ctx())
3013            .await
3014            .unwrap();
3015        assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 2);
3016        let batch = batches.iter().find(|batch| batch.num_rows() == 2).unwrap();
3017        let timestamps = batch
3018            .column(0)
3019            .as_any()
3020            .downcast_ref::<TimestampMillisecondArray>()
3021            .unwrap();
3022        let values = batch
3023            .column(1)
3024            .as_any()
3025            .downcast_ref::<Float64Array>()
3026            .unwrap();
3027
3028        assert_eq!(timestamps.values(), &[1_000, 1_500]);
3029        assert!(!values.is_valid(0));
3030        assert!(!values.is_valid(1));
3031    }
3032}