diff --git a/config/config.md b/config/config.md
index 6faae09c347..f486cbeeee2 100644
--- a/config/config.md
+++ b/config/config.md
@@ -141,6 +141,7 @@
| `procedure.max_running_procedures` | Integer | `128` | Max running procedures. The maximum number of procedures that can be running at the same time. If the number of running procedures exceeds this limit, the procedure will be rejected. |
| `query` | -- | -- | The query engine options. |
| `query.parallelism` | Integer | `0` | Parallelism of the query engine. Default to 0, which means the number of CPU cores. |
+| `query.experimental_native_promql` | Bool | `false` | Enables bounded native raw-series instant-vector execution. Unsupported queries retain ordinary execution before native consumption. |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join). Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%"). Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`. When this limit is reached, queries will fail with ResourceExhausted error. NOTE: This does NOT limit memory used by table scans. |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy: - "greedy" (default): first-come-first-served allocation; preserves current behavior. - "fair": divides available memory among spillable operators and may spill earlier. Only effective when `memory_pool_size` is bounded (>0). |
| `query.experimental_spill_mode` | String | `default` | Spill mode: - "default": preserve DataFusion built-in OS temp directory (default). - "custom": explicitly configure spill path, quota, and compression. - "disabled": explicitly disable disk spilling. Set this to "custom" before using the path/quota/compression keys below. |
@@ -384,6 +385,7 @@
| `meta_client.metadata_cache_tti` | String | `5m` | -- |
| `query` | -- | -- | The query engine options. |
| `query.parallelism` | Integer | `0` | Parallelism of the query engine. Default to 0, which means the number of CPU cores. |
+| `query.experimental_native_promql` | Bool | `false` | Enables bounded native raw-series instant-vector execution. Unsupported queries retain ordinary execution before native consumption. This frontend option does not configure datanodes. |
| `query.allow_query_fallback` | Bool | `false` | Whether to allow query fallback when push down optimize fails. Default to false, meaning when push down optimize failed, return error msg |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join). Supports absolute size (e.g., "4GB", "8GB") or percentage of system memory (e.g., "30%"). Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`. When this limit is reached, queries will fail with ResourceExhausted error. NOTE: This does NOT limit memory used by table scans (only applies to datanodes). |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy: - "greedy" (default): first-come-first-served allocation; preserves current behavior. - "fair": divides available memory among spillable operators and may spill earlier. Only effective when `memory_pool_size` is bounded (>0). |
@@ -614,6 +616,7 @@
| `wal.on_corrupted_segment` | String | `skip` | What a read does with a segment that still does not decode after a second fetch, because its checksum does not match or its content disagrees with its footer entry. - `skip`: the segment is skipped and recorded as a WAL hole of its region, a metric is incremented and a warning is logged; the other regions of the object are unaffected (the default). - `fail`: the read fails, so the region does not open. **It's only used when the provider is `experimental_object_store`**. |
| `query` | -- | -- | The query engine options. |
| `query.parallelism` | Integer | `0` | Parallelism of the query engine. Default to 0, which means the number of CPU cores. |
+| `query.experimental_native_promql` | Bool | `false` | Enables bounded native raw-series instant-vector execution. Unsupported queries retain ordinary execution before native consumption. |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join). Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%"). Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`. When this limit is reached, queries will fail with ResourceExhausted error. NOTE: This does NOT limit memory used by table scans. |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy: - "greedy" (default): first-come-first-served allocation; preserves current behavior. - "fair": divides available memory among spillable operators and may spill earlier. Only effective when `memory_pool_size` is bounded (>0). |
| `query.experimental_spill_mode` | String | `default` | Spill mode: - "default": preserve DataFusion built-in OS temp directory (default). - "custom": explicitly configure spill path, quota, and compression. - "disabled": explicitly disable disk spilling. Set this to "custom" before using the path/quota/compression keys below. |
@@ -800,6 +803,7 @@
| `tracing.tokio_console_addr` | String | Unset | The tokio console address. |
| `query` | -- | -- | -- |
| `query.parallelism` | Integer | `1` | Parallelism of the query engine for query sent by flownode. Default to 1, so it won't use too much cpu or memory |
+| `query.experimental_native_promql` | Bool | `false` | Enables bounded native raw-series instant-vector execution. Unsupported queries retain ordinary execution before native consumption. |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join). Supports absolute size (e.g., "1GB", "2GB") or percentage of system memory (e.g., "20%"). Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`. When this limit is reached, queries will fail with ResourceExhausted error. NOTE: This does NOT limit memory used by table scans. |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy: - "greedy" (default): first-come-first-served allocation; preserves current behavior. - "fair": divides available memory among spillable operators and may spill earlier. Only effective when `memory_pool_size` is bounded (>0). |
| `query.experimental_spill_mode` | String | `default` | Spill mode: - "default": preserve DataFusion built-in OS temp directory (default). - "custom": explicitly configure spill path, quota, and compression. - "disabled": explicitly disable disk spilling. Set this to "custom" before using the path/quota/compression keys below. |
diff --git a/config/datanode.example.toml b/config/datanode.example.toml
index 2d72f795189..74c85116715 100644
--- a/config/datanode.example.toml
+++ b/config/datanode.example.toml
@@ -330,6 +330,9 @@ overwrite_entry_start_id = false
## Default to 0, which means the number of CPU cores.
parallelism = 0
+## Enables bounded native raw-series instant-vector execution. Unsupported queries retain ordinary execution before native consumption.
+experimental_native_promql = false
+
## Memory pool size for query execution operators (aggregation, sorting, join).
## Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").
## Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
diff --git a/config/flownode.example.toml b/config/flownode.example.toml
index fab31fed510..0d35e404642 100644
--- a/config/flownode.example.toml
+++ b/config/flownode.example.toml
@@ -155,6 +155,9 @@ default_ratio = 1.0
## Default to 1, so it won't use too much cpu or memory
parallelism = 1
+## Enables bounded native raw-series instant-vector execution. Unsupported queries retain ordinary execution before native consumption.
+experimental_native_promql = false
+
## Memory pool size for query execution operators (aggregation, sorting, join).
## Supports absolute size (e.g., "1GB", "2GB") or percentage of system memory (e.g., "20%").
## Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
diff --git a/config/frontend.example.toml b/config/frontend.example.toml
index c42d254671c..9d2d00d0ce3 100644
--- a/config/frontend.example.toml
+++ b/config/frontend.example.toml
@@ -362,6 +362,9 @@ metadata_cache_tti = "5m"
## Parallelism of the query engine.
## Default to 0, which means the number of CPU cores.
parallelism = 0
+## Enables bounded native raw-series instant-vector execution. Unsupported queries retain ordinary execution before native consumption.
+## This frontend option does not configure datanodes.
+experimental_native_promql = false
## Whether to allow query fallback when push down optimize fails.
## Default to false, meaning when push down optimize failed, return error msg
allow_query_fallback = false
diff --git a/config/standalone.example.toml b/config/standalone.example.toml
index 82fb3d2c489..0ab55de32cc 100644
--- a/config/standalone.example.toml
+++ b/config/standalone.example.toml
@@ -541,6 +541,9 @@ max_running_procedures = 128
## Default to 0, which means the number of CPU cores.
parallelism = 0
+## Enables bounded native raw-series instant-vector execution. Unsupported queries retain ordinary execution before native consumption.
+experimental_native_promql = false
+
## Memory pool size for query execution operators (aggregation, sorting, join).
## Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").
## Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
diff --git a/src/datatypes/src/series/raw.rs b/src/datatypes/src/series/raw.rs
index 2bad48e7b3b..1d8db5db675 100644
--- a/src/datatypes/src/series/raw.rs
+++ b/src/datatypes/src/series/raw.rs
@@ -120,7 +120,8 @@ pub struct RawSeriesChunk {
pub time: RawTimeAxis,
/// Field values aligned with the source timestamps.
pub fields: SeriesFields,
- /// Whether this is the final chunk for this input stream's series, not all regions.
+ /// Whether this is the final chunk for this series in the stream exposing it.
+ /// A merge must recompute this marker across all of its inputs.
pub is_last: bool,
}
diff --git a/src/promql/src/extension_plan/instant_manipulate.rs b/src/promql/src/extension_plan/instant_manipulate.rs
index 9b7a2a44349..96060ceab57 100644
--- a/src/promql/src/extension_plan/instant_manipulate.rs
+++ b/src/promql/src/extension_plan/instant_manipulate.rs
@@ -12,6 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+mod native;
+mod native_exec;
+
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
diff --git a/src/promql/src/extension_plan/instant_manipulate/native.rs b/src/promql/src/extension_plan/instant_manipulate/native.rs
new file mode 100644
index 00000000000..cb113bed024
--- /dev/null
+++ b/src/promql/src/extension_plan/instant_manipulate/native.rs
@@ -0,0 +1,307 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use std::sync::Arc;
+
+use datafusion::arrow::array::{ArrayRef, Float64Array, StringArray, TimestampMillisecondArray};
+use datafusion::arrow::datatypes::{DataType, SchemaRef, TimeUnit};
+use datafusion::arrow::record_batch::RecordBatch;
+use datafusion::error::{DataFusionError, Result as DataFusionResult};
+use datatypes::series::MetricName;
+use datatypes::series::raw::RawTimeAxis;
+use datatypes::series::samples::{SampleRef, Samples, SeriesFields, SeriesSchema};
+
+#[cfg(test)]
+#[path = "native_tests.rs"]
+mod tests;
+
+use crate::instant_eval::{MAX_INSTANT_MANIPULATE_OUTPUT_POINTS, select_instants};
+
+use super::InstantManipulate;
+
+#[derive(Clone)]
+enum Column {
+ Time,
+ Field(usize),
+ Tag(String),
+}
+
+/// Preflighted mapping from a complete typed series to the original query schema.
+pub(crate) struct NativeInstantMapping {
+ schema: SchemaRef,
+ series_schema: Arc,
+ columns: Vec,
+ fields: Vec,
+ start: i64,
+ end: i64,
+ step: i64,
+ lookback: i64,
+}
+
+impl NativeInstantMapping {
+ /// Returns `None` when the node/schema is outside the bounded native subset.
+ pub(crate) fn try_new(
+ node: &InstantManipulate,
+ schema: SchemaRef,
+ series_schema: Arc,
+ logical_tags: &[String],
+ ) -> DataFusionResult> {
+ if node.offset != 0 || node.unfix.is_some() || node.start >= node.end {
+ return Ok(None);
+ }
+ if node.interval <= 0 {
+ return Err(DataFusionError::Execution(
+ "InstantManipulate interval must be positive".into(),
+ ));
+ }
+ if node.lookback_delta < 0 {
+ return Err(DataFusionError::Execution(
+ "InstantManipulate lookback must be non-negative".into(),
+ ));
+ }
+ if series_schema.eval_grid.is_some() {
+ return Ok(None);
+ }
+
+ let mut names = std::collections::HashSet::new();
+ for field in series_schema.fields.iter() {
+ if !names.insert(field.name.as_ref()) {
+ return Ok(None);
+ }
+ }
+ if logical_tags.iter().any(|name| !names.insert(name.as_str())) {
+ return Ok(None);
+ }
+
+ let stale_field_names = node.staleness_field_columns().collect::>();
+ if stale_field_names.iter().any(|name| {
+ series_schema
+ .fields
+ .iter()
+ .all(|field| field.name.as_ref() != *name)
+ }) || series_schema.fields.iter().any(|field| {
+ node.field_column
+ .as_deref()
+ .is_some_and(|selected| selected != field.name.as_ref())
+ }) {
+ return Ok(None);
+ }
+
+ let mut columns = Vec::with_capacity(schema.fields().len());
+ let mut seen_fields = vec![false; series_schema.fields.len()];
+ let mut seen_tags = vec![false; logical_tags.len()];
+ let mut seen_time = false;
+ for field in schema.fields() {
+ let name = field.name();
+ let column = if name == node.time_index_column.as_str() {
+ if seen_time
+ || field.data_type() != &DataType::Timestamp(TimeUnit::Millisecond, None)
+ {
+ return Ok(None);
+ }
+ seen_time = true;
+ Column::Time
+ } else if let Some(index) = series_schema
+ .fields
+ .iter()
+ .position(|v| v.name.as_ref() == name)
+ {
+ if seen_fields[index] || field.data_type() != &DataType::Float64 {
+ return Ok(None);
+ }
+ seen_fields[index] = true;
+ Column::Field(index)
+ } else if let Some(index) = logical_tags.iter().position(|tag| tag == name) {
+ if seen_tags[index] || !is_string_type(field.data_type()) {
+ return Ok(None);
+ }
+ seen_tags[index] = true;
+ Column::Tag(name.clone())
+ } else {
+ return Ok(None);
+ };
+ columns.push(column);
+ }
+ if !seen_time || seen_fields.iter().any(|seen| !seen) || seen_tags.iter().any(|seen| !seen)
+ {
+ return Ok(None);
+ }
+
+ let fields = stale_field_names
+ .iter()
+ .filter_map(|name| {
+ series_schema
+ .fields
+ .iter()
+ .position(|field| field.name.as_ref() == *name)
+ })
+ .collect();
+ Ok(Some(Self {
+ schema,
+ series_schema,
+ columns,
+ fields,
+ start: node.start,
+ end: node.end,
+ step: node.interval,
+ lookback: node.lookback_delta,
+ }))
+ }
+
+ /// The original output schema retained by this mapping.
+ pub(crate) fn schema(&self) -> SchemaRef {
+ self.schema.clone()
+ }
+
+ /// Estimates the clipped evaluation grid for complete source timestamp bounds.
+ pub(crate) fn estimated_points(&self, first: i64, last: i64) -> DataFusionResult {
+ let first = first as i128;
+ let last = last as i128;
+ let useful_last = if self.lookback == 0 {
+ last
+ } else {
+ last + self.lookback as i128 - 1
+ };
+ let query_start = self.start as i128;
+ let query_end = self.end as i128;
+ let max_start = first.max(query_start);
+ let min_end = useful_last.min(query_end);
+ let (aligned_start, aligned_end) = if max_start > min_end {
+ (1_i128, 0_i128)
+ } else {
+ (
+ query_start + (max_start - query_start) / self.step as i128 * self.step as i128,
+ query_end - (query_end - min_end) / self.step as i128 * self.step as i128,
+ )
+ };
+ let points = if aligned_end >= aligned_start {
+ (aligned_end - aligned_start) / self.step as i128 + 1
+ } else {
+ 0
+ };
+ if points > MAX_INSTANT_MANIPULATE_OUTPUT_POINTS as i128 {
+ return Err(DataFusionError::Execution(format!(
+ "InstantManipulate output points exceed limit: {points} > {MAX_INSTANT_MANIPULATE_OUTPUT_POINTS}"
+ )));
+ }
+ usize::try_from(points).map_err(|_| {
+ DataFusionError::ResourcesExhausted("native instant point count overflow".into())
+ })
+ }
+
+ /// Selects instants against typed samples, then maps only selected values to Arrow.
+ pub(crate) fn evaluate(
+ &self,
+ metric: &MetricName,
+ time: &RawTimeAxis,
+ fields: &SeriesFields,
+ ) -> DataFusionResult {
+ if fields.len() != self.series_schema.fields.len() {
+ return Err(DataFusionError::Execution(
+ "native instant field count mismatch".into(),
+ ));
+ }
+ let checked_fields = self
+ .fields
+ .iter()
+ .map(|i| fields.as_slice()[*i].clone())
+ .collect::>();
+ let checked_fields = if checked_fields.is_empty() {
+ vec![Samples::from_float(Float64Array::new_null(time.len()))]
+ } else {
+ checked_fields
+ };
+ let checked = SeriesFields::try_from_vec(checked_fields)
+ .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+ let (indices, timestamps) = select_instants(
+ time,
+ &checked,
+ self.start..=self.end,
+ self.step,
+ self.lookback,
+ 0,
+ )?;
+ if indices.is_empty() {
+ return Ok(RecordBatch::new_empty(self.schema.clone()));
+ }
+
+ let arrays: DataFusionResult> = self
+ .columns
+ .iter()
+ .enumerate()
+ .map(|(output_index, column)| match column {
+ Column::Time => {
+ Ok(Arc::new(TimestampMillisecondArray::from(timestamps.clone())) as ArrayRef)
+ }
+ Column::Field(index) => {
+ let source = fields.get(*index).ok_or_else(|| {
+ DataFusionError::Execution("native instant field missing".into())
+ })?;
+ let mut samples = source.iter();
+ let mut cursor = 0usize;
+ let mut selected_index = None;
+ let mut selected_value = None;
+ let mut values = Vec::with_capacity(indices.len());
+ for index in &indices {
+ let index = *index as usize;
+ if selected_index != Some(index) {
+ while cursor <= index {
+ selected_value = Some(
+ match samples.next().ok_or_else(|| {
+ DataFusionError::Execution(
+ "native instant sample iterator ended before selected index"
+ .into(),
+ )
+ })? {
+ SampleRef::Float(value) => Some(value),
+ SampleRef::Missing => None,
+ SampleRef::Histogram(_) => {
+ return Err(DataFusionError::Execution(
+ "native instant expected Float64 sample".into(),
+ ));
+ }
+ },
+ );
+ selected_index = Some(cursor);
+ cursor += 1;
+ }
+ }
+ values.push(selected_value.ok_or_else(|| {
+ DataFusionError::Execution(
+ "native instant selected sample was not initialized".into(),
+ )
+ })?);
+ }
+ Ok(Arc::new(Float64Array::from(values)) as ArrayRef)
+ }
+ Column::Tag(name) => {
+ let values = std::iter::repeat_with(|| metric.get(name))
+ .take(indices.len())
+ .collect::();
+ let target = self.schema.field(output_index).data_type();
+ let cast = datafusion::arrow::compute::cast(&values, target)?;
+ Ok(cast)
+ }
+ })
+ .collect();
+ Ok(RecordBatch::try_new(self.schema.clone(), arrays?)?)
+ }
+}
+
+fn is_string_type(data_type: &DataType) -> bool {
+ matches!(
+ data_type,
+ DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
+ ) || matches!(data_type, DataType::Dictionary(key, value) if key.as_ref() == &DataType::UInt32 && value.as_ref() == &DataType::Utf8)
+}
diff --git a/src/promql/src/extension_plan/instant_manipulate/native_exec.rs b/src/promql/src/extension_plan/instant_manipulate/native_exec.rs
new file mode 100644
index 00000000000..dfc46429605
--- /dev/null
+++ b/src/promql/src/extension_plan/instant_manipulate/native_exec.rs
@@ -0,0 +1,482 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use common_query::series_frame::{raw_series_frame_ordering, unpack_raw_series};
+use datafusion::arrow::array::Array;
+use datafusion::arrow::datatypes::SchemaRef;
+use datafusion::arrow::record_batch::RecordBatch;
+use datafusion::common::tree_node::TreeNodeRecursion;
+use datafusion::error::{DataFusionError, Result as DfResult};
+use datafusion::execution::context::TaskContext;
+use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation};
+use datafusion::physical_expr::EquivalenceProperties;
+use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
+use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
+use datafusion::physical_plan::{
+ DisplayAs, DisplayFormatType, ExecutionPlan, PhysicalExpr, PlanProperties, RecordBatchStream,
+ SendableRecordBatchStream,
+};
+use datatypes::series::raw::{RawSeriesChunk, RawSeriesOrdering, RawTimeAxis};
+use datatypes::series::samples::{DenseSamplesRef, Samples, SeriesFields, SeriesSchema};
+use futures::{Stream, ready};
+use store_api::region_engine::{RawLabelSource, SendableRawSeriesStream};
+
+use crate::extension_plan::instant_manipulate::InstantManipulate;
+use crate::extension_plan::instant_manipulate::native::NativeInstantMapping;
+use crate::source::materialize_raw_labels;
+
+#[cfg(test)]
+#[path = "native_exec_tests.rs"]
+mod tests;
+
+impl InstantManipulate {
+ /// Builds the bounded native execution path for a prepared raw-series frame.
+ pub fn try_to_native_execution_plan(
+ &self,
+ input: Arc,
+ output_schema: SchemaRef,
+ label_source: RawLabelSource,
+ series_schema: Arc,
+ logical_tags: &[String],
+ ) -> DfResult>> {
+ let Some(mapping) = NativeInstantMapping::try_new(
+ self,
+ output_schema,
+ series_schema.clone(),
+ logical_tags,
+ )?
+ else {
+ return Ok(None);
+ };
+ if input.properties().partitioning.partition_count() != 1 {
+ return Ok(None);
+ }
+ let declared_schema = input.schema();
+ let ordering = raw_series_frame_ordering(declared_schema.as_ref())?;
+ // Validate the declared raw-frame schema without executing the child.
+ unpack_raw_series(
+ Box::pin(RecordBatchStreamAdapter::new(
+ declared_schema.clone(),
+ futures::stream::empty(),
+ )),
+ series_schema.clone(),
+ label_source.clone(),
+ ordering,
+ )?;
+ Ok(Some(Arc::new(NativeInstantManipulateExec::new(
+ input,
+ Arc::new(mapping),
+ declared_schema,
+ series_schema,
+ label_source,
+ ordering,
+ ))))
+ }
+}
+
+struct NativeInstantManipulateExec {
+ input: Arc,
+ mapping: Arc,
+ raw_schema: SchemaRef,
+ series_schema: Arc,
+ label_source: RawLabelSource,
+ ordering: RawSeriesOrdering,
+ properties: Arc,
+}
+impl NativeInstantManipulateExec {
+ fn new(
+ input: Arc,
+ mapping: Arc,
+ raw_schema: SchemaRef,
+ series_schema: Arc,
+ label_source: RawLabelSource,
+ ordering: RawSeriesOrdering,
+ ) -> Self {
+ let properties = Arc::new(PlanProperties::new(
+ EquivalenceProperties::new(mapping.schema()),
+ datafusion::physical_plan::Partitioning::UnknownPartitioning(1),
+ EmissionType::Incremental,
+ Boundedness::Bounded,
+ ));
+ Self {
+ input,
+ mapping,
+ raw_schema,
+ series_schema,
+ label_source,
+ ordering,
+ properties,
+ }
+ }
+}
+impl std::fmt::Debug for NativeInstantManipulateExec {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("NativeInstantManipulateExec").finish()
+ }
+}
+impl DisplayAs for NativeInstantManipulateExec {
+ fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ write!(f, "NativeInstantManipulateExec")
+ }
+}
+impl ExecutionPlan for NativeInstantManipulateExec {
+ fn name(&self) -> &str {
+ "NativeInstantManipulateExec"
+ }
+ fn schema(&self) -> SchemaRef {
+ self.mapping.schema()
+ }
+ fn apply_expressions(
+ &self,
+ _f: &mut dyn FnMut(&Arc) -> DfResult,
+ ) -> DfResult {
+ Ok(TreeNodeRecursion::Continue)
+ }
+ fn properties(&self) -> &Arc {
+ &self.properties
+ }
+ fn children(&self) -> Vec<&Arc> {
+ vec![&self.input]
+ }
+ fn with_new_children(
+ self: Arc,
+ children: Vec>,
+ ) -> DfResult> {
+ if children.len() != 1
+ || children[0].schema() != self.raw_schema
+ || children[0].properties().partitioning.partition_count() != 1
+ {
+ return Err(DataFusionError::Plan(
+ "NativeInstantManipulateExec requires one unchanged one-partition raw child".into(),
+ ));
+ }
+ Ok(Arc::new(Self::new(
+ children[0].clone(),
+ self.mapping.clone(),
+ self.raw_schema.clone(),
+ self.series_schema.clone(),
+ self.label_source.clone(),
+ self.ordering,
+ )))
+ }
+ fn execute(
+ &self,
+ partition: usize,
+ context: Arc,
+ ) -> DfResult {
+ if partition != 0 {
+ return Err(DataFusionError::Execution(
+ "native instant partition must be zero".into(),
+ ));
+ }
+ let frame = self.input.execute(partition, context.clone())?;
+ let source = unpack_raw_series(
+ frame,
+ self.series_schema.clone(),
+ self.label_source.clone(),
+ self.ordering,
+ )?;
+ let source = materialize_raw_labels(source)
+ .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+ let reservation =
+ MemoryConsumer::new("NativeInstantStream").register(&context.runtime_env().memory_pool);
+ Ok(Box::pin(NativeInstantStream {
+ source: Some(source),
+ mapping: self.mapping.clone(),
+ schema: self.mapping.schema(),
+ series_schema: self.series_schema.clone(),
+ pending: Vec::new(),
+ reservation,
+ }))
+ }
+}
+
+struct NativeInstantStream {
+ source: Option,
+ mapping: Arc,
+ schema: SchemaRef,
+ series_schema: Arc,
+ pending: Vec,
+ reservation: MemoryReservation,
+}
+impl NativeInstantStream {
+ fn fail(&mut self, error: DataFusionError) -> Poll>> {
+ self.source = None;
+ self.pending = Vec::new();
+ self.reservation.free();
+ Poll::Ready(Some(Err(error)))
+ }
+ fn finish_series(&mut self) -> DfResult {
+ let chunks = std::mem::take(&mut self.pending);
+ let rows = chunks
+ .iter()
+ .try_fold(0usize, |n, c| n.checked_add(c.time.len()))
+ .ok_or_else(|| {
+ DataFusionError::ResourcesExhausted("native instant row count overflow".into())
+ })?;
+ let first = chunks
+ .first()
+ .and_then(|c| c.time.timestamp(0))
+ .ok_or_else(|| {
+ DataFusionError::Execution("native instant series has no timestamps".into())
+ })?;
+ let last = chunks
+ .last()
+ .and_then(|c| c.time.timestamp(c.time.len().saturating_sub(1)))
+ .ok_or_else(|| {
+ DataFusionError::Execution("native instant series has no timestamps".into())
+ })?;
+ let points = self.mapping.estimated_points(first, last)?;
+ let label_bytes = chunks
+ .first()
+ .and_then(|c| c.metric.as_ref())
+ .map(|m| {
+ m.name().map_or(0, str::len)
+ + m.tags()
+ .iter()
+ .map(|l| l.name.len() + l.value.len() + 16)
+ .sum::()
+ })
+ .unwrap_or(0);
+ // Reserve timestamp concatenation by row count, but field descriptors by their
+ // actual chunk/segment counts: a dense chunk is still one field descriptor.
+ let field_count = self.series_schema.fields.len();
+ let chunk_count = chunks.len();
+ let segment_count = chunks
+ .iter()
+ .flat_map(|chunk| chunk.fields.as_slice())
+ .try_fold(0usize, |count, field| {
+ count.checked_add(field.segments().len())
+ })
+ .ok_or_else(|| {
+ DataFusionError::ResourcesExhausted("native instant segment count overflow".into())
+ })?;
+ let chunk_field_descriptors = chunk_count
+ .checked_mul(field_count)
+ .and_then(|n| n.checked_mul(std::mem::size_of::()))
+ .ok_or_else(|| {
+ DataFusionError::ResourcesExhausted(
+ "native instant descriptor estimate overflow".into(),
+ )
+ })?;
+ // Flattening and converting to Arc can transiently retain the target descriptors and
+ // two source/flattened vectors; three segment-counts conservatively cover those owners.
+ let flattened_descriptors = segment_count
+ .checked_mul(3)
+ .and_then(|n| n.checked_mul(std::mem::size_of::()))
+ .ok_or_else(|| {
+ DataFusionError::ResourcesExhausted(
+ "native instant segment estimate overflow".into(),
+ )
+ })?;
+ let scratch = rows
+ .checked_mul(16)
+ .and_then(|n| n.checked_add(chunk_field_descriptors))
+ .and_then(|n| n.checked_add(flattened_descriptors))
+ .and_then(|n| {
+ n.checked_add(field_count.checked_mul(std::mem::size_of::>())?)
+ })
+ .and_then(|n| {
+ points
+ .checked_mul(
+ self.schema
+ .fields()
+ .len()
+ .checked_mul(24)?
+ .checked_add(label_bytes)?
+ .checked_add(48)?,
+ )?
+ .checked_add(n)
+ })
+ .ok_or_else(|| {
+ DataFusionError::ResourcesExhausted(
+ "native instant scratch estimate overflow".into(),
+ )
+ })?;
+ self.reservation
+ .try_grow(scratch)
+ .map_err(|e| DataFusionError::ResourcesExhausted(e.to_string()))?;
+ let metric = chunks
+ .first()
+ .and_then(|c| c.metric.clone())
+ .ok_or_else(|| {
+ DataFusionError::Execution("native instant series has no metric labels".into())
+ })?;
+ let mut times = Vec::new();
+ times
+ .try_reserve_exact(rows)
+ .map_err(|e| DataFusionError::ResourcesExhausted(e.to_string()))?;
+ let mut field_chunks = (0..field_count).map(|_| Vec::new()).collect::>();
+ for field in &mut field_chunks {
+ field
+ .try_reserve_exact(chunk_count)
+ .map_err(|e| DataFusionError::ResourcesExhausted(e.to_string()))?;
+ }
+ for chunk in chunks {
+ for i in 0..chunk.time.len() {
+ times.push(chunk.time.timestamp(i).ok_or_else(|| {
+ DataFusionError::Execution("native instant timestamp missing".into())
+ })?);
+ }
+ for (target, field) in field_chunks.iter_mut().zip(chunk.fields.as_slice()) {
+ target.push(field.clone());
+ }
+ }
+ let time = RawTimeAxis::try_new(times.into())
+ .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+ let fields = field_chunks
+ .into_iter()
+ .map(Samples::try_from_chunks)
+ .collect::, _>>()
+ .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+ let fields = SeriesFields::try_from_vec(fields)
+ .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+ self.mapping.evaluate(&metric, &time, &fields)
+ }
+}
+fn retained_chunk_bytes(chunk: &RawSeriesChunk) -> Option {
+ let timestamp_bytes = chunk.time.as_explicit()?.inner().capacity();
+ let labels = chunk
+ .metric
+ .as_ref()
+ .map(|metric| {
+ metric
+ .tags()
+ .iter()
+ .try_fold(metric.name().map_or(0, str::len), |total, label| {
+ total
+ .checked_add(label.name.len())?
+ .checked_add(label.value.len())?
+ .checked_add(std::mem::size_of::())?
+ .checked_add(2 * std::mem::size_of::())
+ })
+ })
+ .unwrap_or(Some(0))?;
+ let field_descriptors = std::mem::size_of::()
+ .checked_add(std::mem::size_of::())?
+ .checked_add(
+ chunk
+ .fields
+ .as_slice()
+ .len()
+ .checked_mul(std::mem::size_of::())?,
+ )?;
+ let (segment_descriptors, sample_buffers) = chunk
+ .fields
+ .as_slice()
+ .iter()
+ .flat_map(|field| field.segments())
+ .try_fold((0usize, 0usize), |(descriptors, buffers), segment| {
+ let bytes = match segment.dense()? {
+ DenseSamplesRef::Float(array) => array.get_buffer_memory_size(),
+ _ => return None,
+ };
+ Some((
+ descriptors.checked_add(std::mem::size_of::())?,
+ buffers.checked_add(bytes)?,
+ ))
+ })?;
+ timestamp_bytes
+ .checked_add(chunk.read_key.capacity())?
+ .checked_add(labels)?
+ .checked_add(field_descriptors)?
+ .checked_add(segment_descriptors)?
+ .checked_add(sample_buffers)
+}
+
+impl Stream for NativeInstantStream {
+ type Item = DfResult;
+ fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {
+ for _ in 0..64 {
+ let Some(source) = self.source.as_mut() else {
+ self.pending = Vec::new();
+ self.reservation.free();
+ return Poll::Ready(None);
+ };
+ match ready!(source.as_mut().poll_next(cx)) {
+ Some(Err(error)) => {
+ return self.fail(DataFusionError::Execution(error.to_string()));
+ }
+ None if !self.pending.is_empty() => {
+ return self.fail(DataFusionError::Execution(
+ "raw series ended without final chunk".into(),
+ ));
+ }
+ None => {
+ self.source = None;
+ self.pending = Vec::new();
+ self.reservation.free();
+ return Poll::Ready(None);
+ }
+ Some(Ok(chunk)) => {
+ let Some(bytes) = retained_chunk_bytes(&chunk) else {
+ return self.fail(DataFusionError::ResourcesExhausted(
+ "native instant retained-byte estimate overflow".into(),
+ ));
+ };
+ if self.pending.len() == self.pending.capacity() {
+ let old_capacity = self.pending.capacity();
+ let new_capacity = old_capacity.checked_mul(2).unwrap_or(usize::MAX).max(4);
+ let slot_growth =
+ new_capacity.checked_sub(old_capacity).and_then(|slots| {
+ slots.checked_mul(std::mem::size_of::())
+ });
+ let Some(slot_growth) = slot_growth else {
+ return self.fail(DataFusionError::ResourcesExhausted(
+ "native instant pending capacity overflow".into(),
+ ));
+ };
+ let Some(growth) = bytes.checked_add(slot_growth) else {
+ return self.fail(DataFusionError::ResourcesExhausted(
+ "native instant chunk estimate overflow".into(),
+ ));
+ };
+ if let Err(e) = self.reservation.try_grow(growth) {
+ return self.fail(DataFusionError::ResourcesExhausted(e.to_string()));
+ }
+ let additional = new_capacity - self.pending.capacity();
+ if let Err(e) = self.pending.try_reserve_exact(additional) {
+ return self.fail(DataFusionError::ResourcesExhausted(e.to_string()));
+ }
+ } else if let Err(e) = self.reservation.try_grow(bytes) {
+ return self.fail(DataFusionError::ResourcesExhausted(e.to_string()));
+ }
+ let last = chunk.is_last;
+ self.pending.push(chunk);
+ if last {
+ match self.finish_series() {
+ Ok(batch) => {
+ self.pending = Vec::new();
+ self.reservation.free();
+ return Poll::Ready(Some(Ok(batch)));
+ }
+ Err(e) => return self.fail(e),
+ }
+ }
+ }
+ }
+ }
+ cx.waker().wake_by_ref();
+ Poll::Pending
+ }
+}
+impl RecordBatchStream for NativeInstantStream {
+ fn schema(&self) -> SchemaRef {
+ self.schema.clone()
+ }
+}
diff --git a/src/promql/src/extension_plan/instant_manipulate/native_exec_tests.rs b/src/promql/src/extension_plan/instant_manipulate/native_exec_tests.rs
new file mode 100644
index 00000000000..e99e20304f6
--- /dev/null
+++ b/src/promql/src/extension_plan/instant_manipulate/native_exec_tests.rs
@@ -0,0 +1,413 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use std::collections::VecDeque;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::task::{Context, Poll};
+
+use common_error::ext::{BoxedError, PlainError};
+use common_error::status_code::StatusCode;
+use datafusion::arrow::array::{Array, Float64Array, TimestampMillisecondArray};
+use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
+use datafusion::common::DFSchema;
+use datafusion::error::DataFusionError;
+use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};
+use datafusion::logical_expr::{EmptyRelation, LogicalPlan};
+use datatypes::arrow::buffer::ScalarBuffer;
+use datatypes::series::MetricName;
+use datatypes::series::raw::{RawSeriesChunk, RawSeriesOrdering, RawTimeAxis};
+use datatypes::series::samples::{FieldSpec, Samples, SeriesFields, SeriesSchema};
+use futures::Stream;
+use store_api::region_engine::{RawLabelSource, RawSeriesStream, SendableRawSeriesStream};
+
+use super::*;
+
+fn raw_schema() -> Arc {
+ Arc::new(SeriesSchema {
+ fields: Arc::from([FieldSpec {
+ name: Arc::from("value"),
+ }]),
+ eval_grid: None,
+ })
+}
+
+fn output_schema() -> Arc {
+ Arc::new(Schema::new(vec![
+ Field::new("value", DataType::Float64, true),
+ Field::new(
+ "time",
+ DataType::Timestamp(TimeUnit::Millisecond, None),
+ false,
+ ),
+ ]))
+}
+
+fn mapping_for(
+ start: i64,
+ end: i64,
+ step: i64,
+ lookback: i64,
+) -> (Arc, Arc) {
+ let logical = LogicalPlan::EmptyRelation(EmptyRelation {
+ produce_one_row: false,
+ schema: Arc::new(DFSchema::empty()),
+ });
+ let node = InstantManipulate::new(
+ start,
+ end,
+ lookback,
+ step,
+ 0,
+ "time".into(),
+ vec![],
+ Some("value".into()),
+ logical,
+ );
+ let series = raw_schema();
+ let mapping = NativeInstantMapping::try_new(&node, output_schema(), series.clone(), &[])
+ .unwrap()
+ .unwrap();
+ (Arc::new(mapping), series)
+}
+
+fn chunk(time: &[i64], values: &[f64], last: bool) -> RawSeriesChunk {
+ RawSeriesChunk::try_new(
+ &raw_schema(),
+ datatypes::arrow::buffer::Buffer::from(vec![1, 2, 3]),
+ Some(MetricName::try_new(None, vec![]).unwrap()),
+ RawTimeAxis::try_new(ScalarBuffer::from(time.to_vec())).unwrap(),
+ SeriesFields::one(Samples::from_float(Float64Array::from(values.to_vec()))),
+ last,
+ )
+ .unwrap()
+}
+
+struct RawMock {
+ schema: Arc,
+ labels: RawLabelSource,
+ items: VecDeque>>>,
+ polls: Arc,
+ drops: Arc,
+}
+impl Stream for RawMock {
+ type Item = std::result::Result;
+ fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> {
+ self.polls.fetch_add(1, Ordering::SeqCst);
+ self.items.pop_front().unwrap_or(Poll::Ready(None))
+ }
+}
+impl Drop for RawMock {
+ fn drop(&mut self) {
+ self.drops.fetch_add(1, Ordering::SeqCst);
+ }
+}
+impl RawSeriesStream for RawMock {
+ fn schema(&self) -> &Arc {
+ &self.schema
+ }
+ fn label_source(&self) -> &RawLabelSource {
+ &self.labels
+ }
+ fn ordering(&self) -> RawSeriesOrdering {
+ RawSeriesOrdering::Contiguous
+ }
+}
+
+fn raw(
+ items: impl IntoIterator- >>>,
+) -> (SendableRawSeriesStream, Arc
, Arc) {
+ let polls = Arc::new(AtomicUsize::new(0));
+ let drops = Arc::new(AtomicUsize::new(0));
+ (
+ Box::pin(RawMock {
+ schema: raw_schema(),
+ labels: RawLabelSource::Explicit,
+ items: items.into_iter().collect(),
+ polls: polls.clone(),
+ drops: drops.clone(),
+ }),
+ polls,
+ drops,
+ )
+}
+
+fn stream(source: SendableRawSeriesStream, pool: &Arc) -> NativeInstantStream {
+ stream_for(source, pool, 10, 30, 10, 10)
+}
+
+fn stream_for(
+ source: SendableRawSeriesStream,
+ pool: &Arc,
+ start: i64,
+ end: i64,
+ step: i64,
+ lookback: i64,
+) -> NativeInstantStream {
+ let (mapping, schema) = mapping_for(start, end, step, lookback);
+ NativeInstantStream {
+ source: Some(source),
+ mapping: mapping.clone(),
+ schema: mapping.schema(),
+ series_schema: schema,
+ pending: Vec::new(),
+ reservation: MemoryConsumer::new("NativeInstantStreamTest").register(pool),
+ }
+}
+
+fn poll(stream: &mut NativeInstantStream) -> Poll>> {
+ let waker = futures::task::noop_waker();
+ let mut cx = Context::from_waker(&waker);
+ Pin::new(stream).poll_next(&mut cx)
+}
+
+#[test]
+fn emits_complete_series_before_polling_later_pending_input() {
+ let (input, polls, _) = raw([
+ Poll::Ready(Some(Ok(chunk(&[10], &[1.0], false)))),
+ Poll::Ready(Some(Ok(chunk(&[20], &[2.0], true)))),
+ Poll::Pending,
+ ]);
+ let pool = Arc::new(GreedyMemoryPool::new(1_000_000)) as Arc;
+ let mut stream = stream(input, &pool);
+ let Poll::Ready(Some(Ok(batch))) = poll(&mut stream) else {
+ panic!("completed series should emit")
+ };
+ assert_eq!(polls.load(Ordering::SeqCst), 2);
+ assert_eq!(
+ batch
+ .column(0)
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .values(),
+ &[1.0, 2.0]
+ );
+ assert_eq!(
+ batch
+ .column(1)
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .values(),
+ &[10, 20]
+ );
+ assert!(matches!(poll(&mut stream), Poll::Pending));
+ assert_eq!(polls.load(Ordering::SeqCst), 3);
+}
+
+#[test]
+fn source_error_after_prefix_is_returned_once_and_clears_reservation_and_input() {
+ let failure = BoxedError::new(PlainError::new(
+ "mock source error".into(),
+ StatusCode::Internal,
+ ));
+ let (input, polls, drops) = raw([
+ Poll::Ready(Some(Ok(chunk(&[10], &[1.0], true)))),
+ Poll::Ready(Some(Err(failure))),
+ ]);
+ let pool = Arc::new(GreedyMemoryPool::new(1_000_000)) as Arc;
+ let mut stream = stream(input, &pool);
+ assert!(matches!(poll(&mut stream), Poll::Ready(Some(Ok(_)))));
+ assert!(matches!(poll(&mut stream), Poll::Ready(Some(Err(_)))));
+ assert!(matches!(poll(&mut stream), Poll::Ready(None)));
+ assert!(matches!(poll(&mut stream), Poll::Ready(None)));
+ assert_eq!(polls.load(Ordering::SeqCst), 2);
+ assert_eq!(drops.load(Ordering::SeqCst), 1);
+ assert_eq!(pool.reserved(), 0);
+}
+
+#[test]
+fn unfinished_series_eof_is_error_once_and_drops_partial_chunks() {
+ let (input, _, drops) = raw([Poll::Ready(Some(Ok(chunk(&[10], &[1.0], false))))]);
+ let pool = Arc::new(GreedyMemoryPool::new(1_000_000)) as Arc;
+ let mut stream = stream(input, &pool);
+ assert!(matches!(poll(&mut stream), Poll::Ready(Some(Err(_)))));
+ assert_eq!(stream.pending.len(), 0);
+ assert_eq!(drops.load(Ordering::SeqCst), 1);
+ assert_eq!(pool.reserved(), 0);
+ assert!(matches!(poll(&mut stream), Poll::Ready(None)));
+}
+
+#[test]
+fn dropping_pending_stream_releases_source_chunks_and_memory() {
+ let array = Arc::new(Float64Array::from(vec![1.0]));
+ let samples = Samples::from_float(array.as_ref().clone());
+ drop(array);
+ let pending_chunk = RawSeriesChunk::try_new(
+ &raw_schema(),
+ datatypes::arrow::buffer::Buffer::from(vec![1]),
+ Some(MetricName::try_new(None, vec![]).unwrap()),
+ RawTimeAxis::try_new(ScalarBuffer::from(vec![10])).unwrap(),
+ SeriesFields::one(samples),
+ false,
+ )
+ .unwrap();
+ let (input, _, drops) = raw([Poll::Ready(Some(Ok(pending_chunk))), Poll::Pending]);
+ let pool = Arc::new(GreedyMemoryPool::new(1_000_000)) as Arc;
+ let mut stream = stream(input, &pool);
+ assert!(matches!(poll(&mut stream), Poll::Pending));
+ assert!(pool.reserved() > 0);
+ drop(stream);
+ assert_eq!(drops.load(Ordering::SeqCst), 1);
+ assert_eq!(pool.reserved(), 0);
+}
+
+#[test]
+fn reservation_failure_is_terminal_and_releases_input_and_partial_series() {
+ let (input, _, drops) = raw([Poll::Ready(Some(Ok(chunk(&[10], &[1.0], false))))]);
+ let pool = Arc::new(GreedyMemoryPool::new(1)) as Arc;
+ let mut stream = stream(input, &pool);
+ assert!(matches!(
+ poll(&mut stream),
+ Poll::Ready(Some(Err(DataFusionError::ResourcesExhausted(_))))
+ ));
+ assert_eq!(drops.load(Ordering::SeqCst), 1);
+ assert_eq!(stream.pending.len(), 0);
+ assert_eq!(stream.pending.capacity(), 0);
+ assert_eq!(pool.reserved(), 0);
+ assert!(matches!(poll(&mut stream), Poll::Ready(None)));
+}
+
+#[test]
+fn source_error_drops_unfinished_series_without_emitting_it() {
+ let failure = BoxedError::new(PlainError::new(
+ "mock source error".into(),
+ StatusCode::Internal,
+ ));
+ let (input, polls, drops) = raw([
+ Poll::Ready(Some(Ok(chunk(&[10], &[1.0], false)))),
+ Poll::Ready(Some(Err(failure))),
+ ]);
+ let pool = Arc::new(GreedyMemoryPool::new(1_000_000)) as Arc;
+ let mut stream = stream(input, &pool);
+ assert!(matches!(poll(&mut stream), Poll::Ready(Some(Err(_)))));
+ assert!(stream.pending.is_empty());
+ assert_eq!(stream.pending.capacity(), 0);
+ assert!(matches!(poll(&mut stream), Poll::Ready(None)));
+ assert_eq!(polls.load(Ordering::SeqCst), 2);
+ assert_eq!(drops.load(Ordering::SeqCst), 1);
+ assert_eq!(pool.reserved(), 0);
+}
+
+#[test]
+fn descriptor_heavy_series_fails_reservation_before_accumulating_unbounded_chunks() {
+ let items = (0..512)
+ .map(|i| Poll::Ready(Some(Ok(chunk(&[i], &[i as f64], false)))))
+ .chain([Poll::Pending]);
+ let (input, polls, drops) = raw(items);
+ let pool = Arc::new(GreedyMemoryPool::new(32 * 1024)) as Arc;
+ let mut stream = stream(input, &pool);
+ assert!(matches!(
+ poll(&mut stream),
+ Poll::Ready(Some(Err(DataFusionError::ResourcesExhausted(_))))
+ ));
+ assert!(stream.pending.is_empty());
+ assert_eq!(stream.pending.capacity(), 0);
+ assert!(matches!(poll(&mut stream), Poll::Ready(None)));
+ assert!(polls.load(Ordering::SeqCst) < 512);
+ assert_eq!(drops.load(Ordering::SeqCst), 1);
+ assert_eq!(pool.reserved(), 0);
+}
+
+#[test]
+fn dense_large_chunk_uses_segment_count_not_row_count_for_descriptors() {
+ let count = 100_000usize;
+ let timestamps = (0..count).map(|i| i as i64).collect::>();
+ let values = Float64Array::from(vec![7.0; count]);
+ let dense_chunk = RawSeriesChunk::try_new(
+ &raw_schema(),
+ datatypes::arrow::buffer::Buffer::from(vec![1]),
+ Some(MetricName::try_new(None, vec![]).unwrap()),
+ RawTimeAxis::try_new(ScalarBuffer::from(timestamps)).unwrap(),
+ SeriesFields::one(Samples::from_float(values)),
+ true,
+ )
+ .unwrap();
+ let (input, _, _) = raw([Poll::Ready(Some(Ok(dense_chunk)))]);
+ // Input timestamp/field buffers and concatenation scratch fit; row-scaled Samples
+ // descriptors would exceed this pool despite there being only one dense segment.
+ let pool = Arc::new(GreedyMemoryPool::new(4 * 1024 * 1024)) as Arc;
+ let mut stream = stream_for(input, &pool, 10, 11, 1, 0);
+ let Poll::Ready(Some(Ok(batch))) = poll(&mut stream) else {
+ panic!("dense chunk should fit its bounded pool")
+ };
+ assert_eq!(batch.num_rows(), 2);
+ assert_eq!(
+ batch
+ .column(0)
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .values(),
+ &[7.0, 7.0]
+ );
+ assert_eq!(
+ batch
+ .column(1)
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .values(),
+ &[10, 11]
+ );
+ assert_eq!(pool.reserved(), 0);
+}
+
+#[test]
+fn output_grid_scratch_is_reserved_before_large_evaluation() {
+ let (input, polls, drops) = raw([Poll::Ready(Some(Ok(chunk(&[0], &[7.0], true))))]);
+ let pool = Arc::new(GreedyMemoryPool::new(128 * 1024)) as Arc;
+ // One source point with a long lookback produces a large grid despite the tiny source.
+ let mut stream = stream_for(input, &pool, 0, 900_000, 1, 900_001);
+ assert!(matches!(
+ poll(&mut stream),
+ Poll::Ready(Some(Err(DataFusionError::ResourcesExhausted(_))))
+ ));
+ assert_eq!(polls.load(Ordering::SeqCst), 1);
+ assert_eq!(drops.load(Ordering::SeqCst), 1);
+ assert!(stream.pending.is_empty());
+ assert_eq!(pool.reserved(), 0);
+ assert!(matches!(poll(&mut stream), Poll::Ready(None)));
+}
+
+#[test]
+fn larger_pool_completes_one_point_many_evaluation_grid() {
+ let (input, _, _) = raw([Poll::Ready(Some(Ok(chunk(&[0], &[7.0], true))))]);
+ let pool = Arc::new(GreedyMemoryPool::new(32 * 1024 * 1024)) as Arc;
+ let mut stream = stream_for(input, &pool, 0, 4, 1, 5);
+ let Poll::Ready(Some(Ok(batch))) = poll(&mut stream) else {
+ panic!("sufficient reservation should evaluate")
+ };
+ assert_eq!(
+ batch
+ .column(0)
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .values(),
+ &[7.0; 5]
+ );
+ assert_eq!(
+ batch
+ .column(1)
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .values(),
+ &[0, 1, 2, 3, 4]
+ );
+ assert_eq!(pool.reserved(), 0);
+}
diff --git a/src/promql/src/extension_plan/instant_manipulate/native_tests.rs b/src/promql/src/extension_plan/instant_manipulate/native_tests.rs
new file mode 100644
index 00000000000..bfa9363689b
--- /dev/null
+++ b/src/promql/src/extension_plan/instant_manipulate/native_tests.rs
@@ -0,0 +1,369 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
+use datafusion::arrow::array::{Array, Float64Array, StringArray, TimestampMillisecondArray};
+use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
+use datafusion::common::DFSchema;
+use datafusion::logical_expr::{EmptyRelation, LogicalPlan};
+use datatypes::arrow::buffer::ScalarBuffer;
+use datatypes::series::raw::RawTimeAxis;
+use datatypes::series::samples::{FieldSpec, Samples, SeriesFields, SeriesSchema};
+use datatypes::series::{Label, MetricName};
+
+use super::*;
+
+fn node() -> InstantManipulate {
+ let input = LogicalPlan::EmptyRelation(EmptyRelation {
+ produce_one_row: false,
+ schema: Arc::new(DFSchema::empty()),
+ });
+ InstantManipulate::new(
+ 10,
+ 20,
+ 10,
+ 10,
+ 0,
+ "time".into(),
+ vec![],
+ Some("value".into()),
+ input,
+ )
+}
+
+fn schema(tag_type: DataType) -> SchemaRef {
+ let mut metadata = HashMap::new();
+ metadata.insert("schema".to_string(), "kept".to_string());
+ Arc::new(Schema::new_with_metadata(
+ vec![
+ Field::new("value", DataType::Float64, true)
+ .with_metadata([("field-key".to_string(), "field-value".to_string())].into()),
+ Field::new(
+ "time",
+ DataType::Timestamp(TimeUnit::Millisecond, None),
+ false,
+ ),
+ Field::new("zone", tag_type, true),
+ ],
+ metadata,
+ ))
+}
+
+fn series_schema() -> Arc {
+ Arc::new(SeriesSchema {
+ fields: Arc::from([FieldSpec {
+ name: Arc::from("value"),
+ }]),
+ eval_grid: None,
+ })
+}
+
+fn metric(zone: Option<&str>) -> MetricName {
+ let labels = zone
+ .map(|value| {
+ vec![Label {
+ name: Arc::from("zone"),
+ value: Arc::from(value),
+ }]
+ })
+ .unwrap_or_default();
+ MetricName::try_new(None, labels).unwrap()
+}
+
+#[test]
+fn evaluates_sliced_chunked_samples_and_preserves_original_schema() {
+ let output_schema = schema(DataType::Dictionary(
+ Box::new(DataType::UInt32),
+ Box::new(DataType::Utf8),
+ ));
+ let mapping = NativeInstantMapping::try_new(
+ &node(),
+ output_schema.clone(),
+ series_schema(),
+ &["zone".into()],
+ )
+ .unwrap()
+ .unwrap();
+ let a = Float64Array::from(vec![Some(99.0), Some(1.0), None]);
+ let b = Float64Array::from(vec![Some(2.0), Some(3.0)]);
+ let samples = Samples::try_from_chunks(vec![
+ Samples::from_float(
+ a.slice(1, 2)
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .clone(),
+ ),
+ Samples::from_float(b),
+ ])
+ .unwrap();
+ let fields = SeriesFields::one(samples);
+ let time = RawTimeAxis::try_new(ScalarBuffer::from(vec![0, 10, 20, 30])).unwrap();
+ let batch = mapping.evaluate(&metric(Some("")), &time, &fields).unwrap();
+ assert_eq!(batch.num_rows(), 2);
+ assert_eq!(batch.schema(), output_schema);
+ let output_values = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ assert!(output_values.is_null(0));
+ assert_eq!(output_values.value(1), 2.0);
+ assert_eq!(
+ batch
+ .column(1)
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .values(),
+ &[10, 20]
+ );
+ let tag_values = datafusion::arrow::compute::cast(batch.column(2), &DataType::Utf8).unwrap();
+ let tag_values = tag_values.as_any().downcast_ref::().unwrap();
+ assert_eq!(tag_values.value(0), "");
+ assert_eq!(tag_values.value(1), "");
+}
+
+#[test]
+fn selected_repeated_indices_across_sliced_chunks_preserve_missing_and_nan() {
+ let mut query = node();
+ query.end = 30;
+ query.lookback_delta = 20;
+ let mapping = NativeInstantMapping::try_new(
+ &query,
+ schema(DataType::Utf8),
+ series_schema(),
+ &["zone".into()],
+ )
+ .unwrap()
+ .unwrap();
+ let first = Float64Array::from(vec![Some(99.0), None]).slice(1, 1);
+ let second = Float64Array::from(vec![Some(f64::NAN), Some(88.0)]).slice(0, 1);
+ let samples = Samples::try_from_chunks(vec![
+ Samples::from_float(
+ first
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .clone(),
+ ),
+ Samples::from_float(
+ second
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .clone(),
+ ),
+ ])
+ .unwrap();
+ let fields = SeriesFields::one(samples);
+ let time = RawTimeAxis::try_new(ScalarBuffer::from(vec![10, 30])).unwrap();
+
+ let batch = mapping.evaluate(&metric(None), &time, &fields).unwrap();
+ let values = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ assert_eq!(batch.num_rows(), 3);
+ assert!(values.is_null(0));
+ assert!(values.is_null(1));
+ assert!(!values.is_null(2));
+ assert!(values.value(2).is_nan());
+}
+
+#[test]
+fn maps_all_supported_string_types_and_distinguishes_missing_from_empty() {
+ let tag_types = [
+ DataType::Utf8,
+ DataType::LargeUtf8,
+ DataType::Utf8View,
+ DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
+ ];
+ let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
+ Some(1.0),
+ Some(2.0),
+ ])));
+ let time = RawTimeAxis::try_new(ScalarBuffer::from(vec![10, 20])).unwrap();
+
+ for tag_type in tag_types {
+ let output_schema = schema(tag_type);
+ let mapping = NativeInstantMapping::try_new(
+ &node(),
+ output_schema.clone(),
+ series_schema(),
+ &["zone".into()],
+ )
+ .unwrap()
+ .unwrap();
+
+ for (label, expected) in [(Some(""), Some("")), (None, None)] {
+ let batch = mapping.evaluate(&metric(label), &time, &fields).unwrap();
+ assert_eq!(batch.schema(), output_schema);
+ let values =
+ datafusion::arrow::compute::cast(batch.column(2), &DataType::Utf8).unwrap();
+ let values = values.as_any().downcast_ref::().unwrap();
+ match expected {
+ Some(value) => {
+ assert_eq!(values.value(0), value);
+ assert_eq!(values.value(1), value);
+ assert_eq!(values.null_count(), 0);
+ }
+ None => assert_eq!(values.null_count(), 2),
+ }
+ }
+ }
+}
+
+#[test]
+fn selected_field_staleness_and_no_field_semantics_match_existing_selector_contract() {
+ let stale = f64::from_bits(PROMETHEUS_STALE_NAN_BITS);
+ let times = RawTimeAxis::try_new(ScalarBuffer::from(vec![10, 20])).unwrap();
+ let values = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
+ Some(1.0),
+ Some(stale),
+ ])));
+ let mapping = NativeInstantMapping::try_new(
+ &node(),
+ schema(DataType::Utf8),
+ series_schema(),
+ &["zone".into()],
+ )
+ .unwrap()
+ .unwrap();
+ let batch = mapping.evaluate(&metric(None), ×, &values).unwrap();
+ assert_eq!(batch.num_rows(), 1);
+ assert_eq!(
+ batch
+ .column(1)
+ .as_any()
+ .downcast_ref::()
+ .unwrap()
+ .value(0),
+ 10
+ );
+
+ let mut no_staleness_node = node();
+ no_staleness_node.field_column = None;
+ let no_staleness_mapping = NativeInstantMapping::try_new(
+ &no_staleness_node,
+ schema(DataType::Utf8),
+ series_schema(),
+ &["zone".into()],
+ )
+ .unwrap()
+ .unwrap();
+ let batch = no_staleness_mapping
+ .evaluate(&metric(None), ×, &values)
+ .unwrap();
+ let output = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ assert_eq!(output.len(), 2);
+ assert_eq!(output.value(1).to_bits(), PROMETHEUS_STALE_NAN_BITS);
+}
+
+#[test]
+fn rejects_unmapped_missing_duplicate_and_non_millisecond_schema_columns() {
+ let valid = schema(DataType::Utf8);
+ let mut cases = Vec::new();
+
+ cases.push(Arc::new(Schema::new(vec![
+ valid.field(0).clone(),
+ valid.field(1).clone(),
+ valid.field(2).clone(),
+ Field::new("helper", DataType::UInt64, true),
+ ])));
+ cases.push(Arc::new(Schema::new(vec![
+ valid.field(0).clone(),
+ valid.field(1).clone(),
+ valid.field(2).clone(),
+ Field::new("__tsid", DataType::UInt64, true),
+ ])));
+ cases.push(Arc::new(Schema::new(vec![
+ valid.field(0).clone(),
+ valid.field(1).clone(),
+ ])));
+ cases.push(Arc::new(Schema::new(vec![
+ valid.field(1).clone(),
+ valid.field(2).clone(),
+ ])));
+ cases.push(Arc::new(Schema::new(vec![
+ valid.field(0).clone(),
+ valid.field(1).clone(),
+ valid.field(2).clone(),
+ valid.field(0).clone(),
+ ])));
+ cases.push(Arc::new(Schema::new(vec![
+ valid.field(0).clone(),
+ Field::new(
+ "time",
+ DataType::Timestamp(TimeUnit::Microsecond, None),
+ false,
+ ),
+ valid.field(2).clone(),
+ ])));
+ cases.push(Arc::new(Schema::new(vec![
+ Field::new("value", DataType::Int64, true),
+ valid.field(1).clone(),
+ valid.field(2).clone(),
+ ])));
+
+ for output_schema in cases {
+ assert!(
+ NativeInstantMapping::try_new(
+ &node(),
+ output_schema,
+ series_schema(),
+ &["zone".into()],
+ )
+ .unwrap()
+ .is_none()
+ );
+ }
+}
+
+#[test]
+fn absent_tag_is_null_and_nonzero_offset_is_rejected() {
+ let output_schema = schema(DataType::Utf8);
+ let mapping =
+ NativeInstantMapping::try_new(&node(), output_schema, series_schema(), &["zone".into()])
+ .unwrap()
+ .unwrap();
+ let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
+ Some(1.0),
+ Some(2.0),
+ ])));
+ let time = RawTimeAxis::try_new(ScalarBuffer::from(vec![10, 20])).unwrap();
+ let batch = mapping.evaluate(&metric(None), &time, &fields).unwrap();
+ assert_eq!(batch.column(2).null_count(), 2);
+
+ let mut unsupported = node();
+ unsupported.offset = 1;
+ assert!(
+ NativeInstantMapping::try_new(
+ &unsupported,
+ schema(DataType::Utf8),
+ series_schema(),
+ &["zone".into()],
+ )
+ .unwrap()
+ .is_none()
+ );
+}
diff --git a/src/query/src/datafusion.rs b/src/query/src/datafusion.rs
index 7219ac19268..d36c324a23c 100644
--- a/src/query/src/datafusion.rs
+++ b/src/query/src/datafusion.rs
@@ -16,6 +16,7 @@
mod error;
mod json_expr_planner;
+pub(crate) mod native_promql;
mod pg_oid_alias_expr_planner;
mod planner;
@@ -97,7 +98,7 @@ pub const QUERY_PARALLELISM_HINT: &str = "query_parallelism";
/// Whether to fallback to the original plan when failed to push down.
pub const QUERY_FALLBACK_HINT: &str = "query_fallback";
-fn raw_expr_supported(expr: &Expr) -> bool {
+pub(crate) fn raw_expr_supported(expr: &Expr) -> bool {
let mut supported = true;
let _ = expr.apply(|node| {
match node {
@@ -604,6 +605,11 @@ impl DatafusionQueryEngine {
.query_planner()
.create_physical_plan(&optimized_plan, state)
.await?;
+ let physical_plan = if self.state.experimental_native_promql() {
+ native_promql::try_select(&optimized_plan, physical_plan)?
+ } else {
+ physical_plan
+ };
logger.phy_plan = Some(physical_plan.clone());
drop(logger);
diff --git a/src/query/src/datafusion/native_promql.rs b/src/query/src/datafusion/native_promql.rs
new file mode 100644
index 00000000000..a20aae2c40f
--- /dev/null
+++ b/src/query/src/datafusion/native_promql.rs
@@ -0,0 +1,307 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use std::sync::Arc;
+
+use api::v1::SemanticType;
+use datafusion::arrow::datatypes::{DataType, SchemaRef, TimeUnit};
+use datafusion::datasource::DefaultTableSource;
+use datafusion::physical_plan::ExecutionPlan;
+use datafusion_expr::{Extension, LogicalPlan};
+use datatypes::data_type::ConcreteDataType;
+use promql::extension_plan::{InstantManipulate, InstantManipulateExec, SeriesDivideExec};
+use store_api::metric_engine_consts::is_metric_engine_internal_column;
+use table::table::scan::RegionScanExec;
+
+use crate::datafusion::raw_expr_supported;
+use crate::dummy_catalog::DummyTableProvider;
+
+/// Selects native execution only for the bounded, unmodified instant-over-divide shape.
+pub(crate) fn try_select(
+ logical: &LogicalPlan,
+ original: Arc,
+) -> datafusion::error::Result> {
+ let Some((instant, divide, scan_node)) = logical_shape(logical) else {
+ return Ok(original);
+ };
+ let Some((instant_exec_schema, scan_exec, root_cooperative, scan_cooperative)) =
+ physical_shape(&original)
+ else {
+ return Ok(original);
+ };
+ if scan_node.fetch.is_some()
+ || !scan_node.statistics_requests.is_empty()
+ || scan_node
+ .filters
+ .iter()
+ .any(|filter| !raw_expr_supported(filter))
+ {
+ return Ok(original);
+ }
+ let Some(source) = scan_node.source.downcast_ref::() else {
+ return Ok(original);
+ };
+ let Some(provider) = source.table_provider.downcast_ref::() else {
+ return Ok(original);
+ };
+
+ let metadata = provider.region_metadata();
+ let table_name = scan_node.table_name.table().to_string();
+ let logical_tags = metadata
+ .column_metadatas
+ .iter()
+ .filter(|column| {
+ column.semantic_type == SemanticType::Tag
+ && !is_metric_engine_internal_column(&column.column_schema.name)
+ })
+ .map(|column| column.column_schema.name.clone())
+ .collect::>();
+ let logical_output = scan_node.projected_schema.as_ref();
+ let physical_output = scan_exec.schema();
+ if logical_output.fields().len() != physical_output.fields().len()
+ || logical_output
+ .fields()
+ .iter()
+ .zip(physical_output.fields())
+ .any(|(logical, physical)| {
+ logical.name() != physical.name() || logical.data_type() != physical.data_type()
+ })
+ {
+ return Ok(original);
+ }
+ let mut fields = Vec::new();
+ let mut tags_found = std::collections::HashSet::new();
+ let mut time_found = false;
+ for field in logical_output.fields() {
+ let Some(column) = metadata.column_by_name(field.name()) else {
+ return Ok(original);
+ };
+ match column.semantic_type {
+ SemanticType::Tag if logical_tags.iter().any(|tag| tag == field.name()) => {
+ tags_found.insert(field.name().clone());
+ }
+ SemanticType::Timestamp
+ if field.data_type() == &DataType::Timestamp(TimeUnit::Millisecond, None) =>
+ {
+ time_found = true;
+ }
+ SemanticType::Field
+ if column.column_schema.data_type == ConcreteDataType::float64_datatype()
+ && field.data_type() == &DataType::Float64 =>
+ {
+ fields.push(field.name().clone());
+ }
+ _ => return Ok(original),
+ }
+ }
+ // First slice preserves the ordinary selector's single-field staleness semantics.
+ if !time_found
+ || logical_output.fields().len() != logical_tags.len() + fields.len() + 1
+ || tags_found.len() != logical_tags.len()
+ || fields.len() != 1
+ || (!divide.tags().is_empty() && divide.tags() != logical_tags)
+ {
+ return Ok(original);
+ }
+
+ let Some(native_scan) =
+ scan_exec
+ .clone()
+ .try_to_named_series_scan(&table_name, &logical_tags, &fields)?
+ else {
+ return Ok(original);
+ };
+ let label_source = native_scan.label_source().clone();
+ let series_schema = Arc::clone(native_scan.series_schema());
+ let mut native_child: Arc = native_scan;
+ if scan_cooperative {
+ native_child = Arc::new(datafusion::physical_plan::coop::CooperativeExec::new(
+ native_child,
+ ));
+ }
+ let native = instant.try_to_native_execution_plan(
+ native_child,
+ instant_exec_schema,
+ label_source,
+ series_schema,
+ &logical_tags,
+ )?;
+ let Some(native) = native else {
+ return Ok(original);
+ };
+ if root_cooperative {
+ original.replace_children(
+ vec![native],
+ datafusion::physical_plan::ReplaceChildrenOptions::new(
+ datafusion::physical_plan::ChildrenPropertiesMode::Recompute,
+ ),
+ )
+ } else {
+ Ok(native)
+ }
+}
+
+fn logical_shape(
+ plan: &LogicalPlan,
+) -> Option<(
+ &InstantManipulate,
+ &promql::extension_plan::SeriesDivide,
+ &datafusion_expr::logical_plan::TableScan,
+)> {
+ let LogicalPlan::Extension(Extension { node }) = plan else {
+ return None;
+ };
+ let instant = node.as_any().downcast_ref::()?;
+ if instant.is_single_evaluation() {
+ return None;
+ }
+ let instant_inputs = node.inputs();
+ let [input] = instant_inputs.as_slice() else {
+ return None;
+ };
+ let LogicalPlan::Extension(Extension { node: divide_node }) = input else {
+ return None;
+ };
+ let divide = divide_node
+ .as_any()
+ .downcast_ref::()?;
+ let divide_inputs = divide_node.inputs();
+ let [input] = divide_inputs.as_slice() else {
+ return None;
+ };
+ let scan = table_scan_through_safe_nodes(input)?;
+ Some((instant, divide, scan))
+}
+
+fn table_scan_through_safe_nodes(
+ plan: &LogicalPlan,
+) -> Option<&datafusion_expr::logical_plan::TableScan> {
+ match plan {
+ LogicalPlan::TableScan(scan) => Some(scan),
+ LogicalPlan::Sort(sort) if sort.fetch.is_none() => {
+ table_scan_through_safe_nodes(&sort.input)
+ }
+ LogicalPlan::Filter(filter) if raw_expr_supported(&filter.predicate) => {
+ table_scan_through_safe_nodes(&filter.input)
+ }
+ LogicalPlan::Projection(projection)
+ if projection.expr.len() == projection.input.schema().fields().len()
+ && projection.expr.iter().enumerate().all(|(index, expr)| {
+ matches!(expr, datafusion_expr::Expr::Column(column)
+ if column.name.as_str() == projection.input.schema().field(index).name())
+ }) =>
+ {
+ table_scan_through_safe_nodes(&projection.input)
+ }
+ _ => None,
+ }
+}
+
+fn physical_shape(
+ plan: &Arc,
+) -> Option<(SchemaRef, Arc, bool, bool)> {
+ let (plan, root_cooperative) = if let Some(wrapper) =
+ plan.downcast_ref::()
+ {
+ (wrapper.input(), true)
+ } else {
+ (plan, false)
+ };
+ let instant = plan.downcast_ref::()?;
+ let output_schema = instant.schema();
+ let instant_children = instant.children();
+ let [divide] = instant_children.as_slice() else {
+ return None;
+ };
+ let divide = divide.downcast_ref::()?;
+ let divide_children = divide.children();
+ let [scan] = divide_children.as_slice() else {
+ return None;
+ };
+ let (scan, scan_cooperative) = if let Some(wrapper) =
+ scan.downcast_ref::()
+ {
+ (wrapper.input(), true)
+ } else {
+ (*scan, false)
+ };
+ let scan = scan.downcast_ref::()?;
+ if scan.properties().output_partitioning().partition_count() != 1 {
+ return None;
+ }
+ Some((
+ output_schema,
+ Arc::new(scan.clone()),
+ root_cooperative,
+ scan_cooperative,
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use datafusion::datasource::DefaultTableSource;
+ use datafusion_expr::{Extension, LogicalPlan, LogicalPlanBuilder};
+ use promql::extension_plan::{InstantManipulate, SeriesDivide};
+ use store_api::storage::RegionId;
+
+ use super::{logical_shape, table_scan_through_safe_nodes};
+
+ #[test]
+ fn native_instant_admission_rejects_non_instant_root() {
+ let plan = LogicalPlanBuilder::empty(false).build().unwrap();
+ assert!(logical_shape(&plan).is_none());
+ }
+
+ #[test]
+ fn native_instant_admission_accepts_one_bounded_instant_scan() {
+ let provider = Arc::new(crate::optimizer::test_util::mock_table_provider(
+ RegionId::new(1, 1),
+ ));
+ let source = Arc::new(DefaultTableSource::new(provider));
+ let scan = LogicalPlanBuilder::scan("metric", source, None)
+ .unwrap()
+ .build()
+ .unwrap();
+ let divide = LogicalPlan::Extension(Extension {
+ node: Arc::new(SeriesDivide::new(vec!["k0".into()], "ts".into(), scan)),
+ });
+ let instant = LogicalPlan::Extension(Extension {
+ node: Arc::new(InstantManipulate::new(
+ 1000,
+ 2000,
+ 30000,
+ 1000,
+ 0,
+ "ts".into(),
+ vec!["k0".into()],
+ Some("v0".into()),
+ divide,
+ )),
+ });
+ assert!(logical_shape(&instant).is_some());
+ }
+
+ #[test]
+ fn native_instant_scan_path_rejects_uncontrolled_operators() {
+ let plan = LogicalPlanBuilder::empty(false)
+ .limit(0, Some(1))
+ .unwrap()
+ .build()
+ .unwrap();
+ assert!(table_scan_through_safe_nodes(&plan).is_none());
+ assert!(matches!(plan, LogicalPlan::Limit(_)));
+ }
+}
diff --git a/src/query/src/options.rs b/src/query/src/options.rs
index a49021f2f15..acec284455a 100644
--- a/src/query/src/options.rs
+++ b/src/query/src/options.rs
@@ -91,6 +91,9 @@ pub struct QueryOptions {
/// Whether to expose per-region query load metrics.
#[serde(skip)]
pub enable_per_region_metrics: bool,
+ /// Enables bounded native raw-series instant-vector execution. Defaults to `false`;
+ /// unsupported queries retain ordinary execution before native consumption.
+ pub experimental_native_promql: bool,
/// Experimental: spill-to-disk mode.
/// - `default`: preserve DataFusion built-in OS temp directory behavior.
/// - `custom`: explicitly configure spill path, max directory size, and compression.
@@ -120,6 +123,7 @@ impl Default for QueryOptions {
allow_query_fallback: false,
memory_pool_size: MemoryLimit::default(),
enable_per_region_metrics: false,
+ experimental_native_promql: false,
experimental_spill_mode: QuerySpillMode::Default,
experimental_spill_path: None,
experimental_spill_max_temp_directory_size: ReadableSize::gb(1),
@@ -831,6 +835,25 @@ mod flow_extension_tests {
mod query_options_tests {
use super::*;
+ #[test]
+ fn test_experimental_native_promql_option() {
+ assert!(!QueryOptions::default().experimental_native_promql);
+
+ let enabled: QueryOptions = toml::from_str("experimental_native_promql = true").unwrap();
+ assert!(enabled.experimental_native_promql);
+
+ for value in [false, true] {
+ let options = QueryOptions {
+ experimental_native_promql: value,
+ ..Default::default()
+ };
+ let serialized = toml::to_string(&options).unwrap();
+ assert!(serialized.contains(&format!("experimental_native_promql = {value}")));
+ let parsed: QueryOptions = toml::from_str(&serialized).unwrap();
+ assert_eq!(parsed.experimental_native_promql, value);
+ }
+ }
+
#[test]
fn test_parse_spill_options_from_toml() {
let toml_str = r#"
diff --git a/src/query/src/query_engine/state.rs b/src/query/src/query_engine/state.rs
index be681cfcf57..c8a3f5cb8b4 100644
--- a/src/query/src/query_engine/state.rs
+++ b/src/query/src/query_engine/state.rs
@@ -91,6 +91,7 @@ use crate::region_query::RegionQueryHandlerRef;
#[derive(Clone)]
pub struct QueryEngineState {
df_context: SessionContext,
+ experimental_native_promql: bool,
catalog_manager: CatalogManagerRef,
dyn_filter_registry_manager: Arc,
function_state: Arc,
@@ -284,6 +285,7 @@ impl QueryEngineState {
Ok(Self {
df_context,
+ experimental_native_promql: options.experimental_native_promql,
catalog_manager: catalog_list,
dyn_filter_registry_manager: Arc::new(DynFilterRegistryManager::default()),
function_state: Arc::new(FunctionState {
@@ -484,6 +486,10 @@ impl QueryEngineState {
.unwrap_or(false)
}
+ pub(crate) fn experimental_native_promql(&self) -> bool {
+ self.experimental_native_promql
+ }
+
pub fn session_state(&self) -> SessionState {
self.df_context.state()
}
diff --git a/src/standalone/src/options.rs b/src/standalone/src/options.rs
index 05d929cc7da..92b5b90ce65 100644
--- a/src/standalone/src/options.rs
+++ b/src/standalone/src/options.rs
@@ -382,8 +382,13 @@ flow_notification_queue_capacity = 17
fn test_query_options_propagated_to_components() {
let mut options = StandaloneOptions::default();
options.query.parallelism = 4;
+ options.query.experimental_native_promql = true;
- assert_eq!(options.frontend_options().query.parallelism, 4);
- assert_eq!(options.datanode_options().query.parallelism, 4);
+ let frontend_options = options.frontend_options();
+ let datanode_options = options.datanode_options();
+ assert_eq!(frontend_options.query.parallelism, 4);
+ assert!(frontend_options.query.experimental_native_promql);
+ assert_eq!(datanode_options.query.parallelism, 4);
+ assert!(datanode_options.query.experimental_native_promql);
}
}
diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs
index 282c86e9673..dad227759a4 100644
--- a/src/table/src/table/scan.rs
+++ b/src/table/src/table/scan.rs
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use std::collections::HashSet;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
@@ -19,7 +20,7 @@ use std::time::Instant;
use api::v1::SemanticType;
use common_error::ext::BoxedError;
-use common_query::request::RawSeriesRequest;
+use common_query::request::{RawSeriesRequest, RawSeriesTag};
use common_query::series_frame::{pack_raw_series, raw_series_frame_schema_with_ordering};
use common_recordbatch::adapter::{
RecordBatchStreamAdapter, RegionQueryStatCounters, SERIES_SCAN_EXEC_NAME,
@@ -415,6 +416,92 @@ impl RegionScanExec {
.query_stat_counters()
}
+ /// Resolves authorized logical names against this prepared scanner's physical metadata,
+ /// then selects a native raw-series leaf through the existing binding path.
+ ///
+ /// The caller is responsible for authorizing the logical table and supplying its complete
+ /// logical tag names and requested field names. This method does not discover logical schema
+ /// or authorize names; it resolves them only against this scanner's metadata snapshot.
+ pub fn try_to_named_series_scan(
+ self: Arc,
+ metric_name: &str,
+ logical_tags: &[String],
+ field_names: &[String],
+ ) -> DfResult>> {
+ if !self.is_partition_set || field_names.is_empty() {
+ return Ok(None);
+ }
+
+ if !self.pushed_dyn_filters.lock().unwrap().is_empty() {
+ return Ok(None);
+ }
+ let binding = {
+ let scanner = self.scanner.lock().unwrap();
+ let metadata = scanner.metadata();
+ if scanner.properties().num_partitions().max(1) != 1 {
+ return Ok(None);
+ }
+
+ let primary_key_ids = metadata
+ .primary_key_columns()
+ .map(|column| column.column_id)
+ .collect::>();
+ let mut names = HashSet::new();
+ let mut column_ids = HashSet::new();
+ let mut tags = Vec::with_capacity(logical_tags.len());
+ for name in logical_tags {
+ if !names.insert(name.as_str())
+ || name == "__name__"
+ || store_api::metric_engine_consts::is_metric_engine_internal_column(name)
+ || store_api::storage::consts::is_internal_column(name)
+ {
+ return Ok(None);
+ }
+ let Some(column) = metadata.column_by_name(name) else {
+ return Ok(None);
+ };
+ if column.semantic_type != SemanticType::Tag
+ || store_api::storage::consts::ReservedColumnId::is_reserved(column.column_id)
+ || !primary_key_ids.contains(&column.column_id)
+ || !column_ids.insert(column.column_id)
+ {
+ return Ok(None);
+ }
+ tags.push(RawSeriesTag {
+ column_id: column.column_id,
+ name: name.clone(),
+ });
+ }
+
+ let mut fields = Vec::with_capacity(field_names.len());
+ for name in field_names {
+ if !names.insert(name.as_str()) {
+ return Ok(None);
+ }
+ let Some(column) = metadata.column_by_name(name) else {
+ return Ok(None);
+ };
+ if column.semantic_type != SemanticType::Field
+ || store_api::storage::consts::ReservedColumnId::is_reserved(column.column_id)
+ || !column_ids.insert(column.column_id)
+ {
+ return Ok(None);
+ }
+ fields.push(column.column_id);
+ }
+
+ RawSeriesRequest {
+ version: 1,
+ physical_metadata: metadata.as_ref().clone(),
+ metric_name: metric_name.to_string(),
+ logical_tags: tags,
+ field_ids: fields,
+ }
+ };
+
+ self.try_to_bound_series_scan(&binding)
+ }
+
/// Selects a native raw-series leaf only when the prepared scanner matches the binding.
pub fn try_to_bound_series_scan(
self: Arc,
@@ -1200,6 +1287,39 @@ mod test {
)
}
+ #[test]
+ fn named_series_scan_requires_prepared_single_partition() {
+ let (_, plan) = dynamic_filter_fixture(5686);
+ let plan = Arc::new(plan);
+ assert!(
+ plan.clone()
+ .try_to_named_series_scan("cpu", &[], &["a".to_string()])
+ .unwrap()
+ .is_none()
+ );
+
+ let prepared = Arc::new(
+ plan.with_new_partitions(vec![vec![]], 1)
+ .expect("prepare scanner partitions"),
+ );
+ for (tags, fields) in [
+ (vec![], vec!["missing".to_string()]),
+ (vec!["a".to_string()], vec!["a".to_string()]),
+ (
+ vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME.to_string()],
+ vec!["a".to_string()],
+ ),
+ ] {
+ assert!(
+ prepared
+ .clone()
+ .try_to_named_series_scan("cpu", &tags, &fields)
+ .unwrap()
+ .is_none()
+ );
+ }
+ }
+
#[test]
fn test_per_series_partitioning_requires_all_primary_keys() {
let full_schema = Arc::new(Schema::new(vec![
diff --git a/src/table/src/table/scan/series_tests.rs b/src/table/src/table/scan/series_tests.rs
index 08d5cc78982..1c414f48d19 100644
--- a/src/table/src/table/scan/series_tests.rs
+++ b/src/table/src/table/scan/series_tests.rs
@@ -288,6 +288,88 @@ fn fixture(
)
}
+fn named_fixture() -> (
+ Arc,
+ Arc>,
+ store_api::metadata::RegionMetadataRef,
+) {
+ let schema = Arc::new(Schema::new(vec![
+ ColumnSchema::new("host", ConcreteDataType::string_datatype(), false),
+ ColumnSchema::new("aux", ConcreteDataType::float64_datatype(), false),
+ ColumnSchema::new("value", ConcreteDataType::float64_datatype(), false),
+ ColumnSchema::new(
+ "ts",
+ ConcreteDataType::timestamp_millisecond_datatype(),
+ false,
+ ),
+ ]));
+ let batch = RecordBatch::new(
+ schema.clone(),
+ vec![
+ Arc::new(datatypes::vectors::StringVector::from_slice(&["node"])) as VectorRef,
+ Arc::new(datatypes::vectors::Float64Vector::from_slice([2.0])) as VectorRef,
+ Arc::new(datatypes::vectors::Float64Vector::from_slice([1.0])) as VectorRef,
+ Arc::new(TimestampMillisecondVector::from_slice([42])) as VectorRef,
+ ],
+ )
+ .unwrap();
+ let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
+ let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2));
+ builder
+ .push_column_metadata(ColumnMetadata {
+ column_schema: ColumnSchema::new("host", ConcreteDataType::string_datatype(), false),
+ semantic_type: SemanticType::Tag,
+ column_id: 7,
+ })
+ .push_column_metadata(ColumnMetadata {
+ column_schema: ColumnSchema::new("aux", ConcreteDataType::float64_datatype(), false),
+ semantic_type: SemanticType::Field,
+ column_id: 11,
+ })
+ .push_column_metadata(ColumnMetadata {
+ column_schema: ColumnSchema::new("value", ConcreteDataType::float64_datatype(), false),
+ semantic_type: SemanticType::Field,
+ column_id: 12,
+ })
+ .push_column_metadata(ColumnMetadata {
+ column_schema: ColumnSchema::new(
+ "ts",
+ ConcreteDataType::timestamp_millisecond_datatype(),
+ false,
+ ),
+ semantic_type: SemanticType::Timestamp,
+ column_id: 13,
+ })
+ .primary_key(vec![7]);
+ let metadata = Arc::new(builder.build().unwrap());
+ let raw_schema = Arc::new(SeriesSchema {
+ fields: vec![
+ FieldSpec {
+ name: Arc::from("aux"),
+ },
+ FieldSpec {
+ name: Arc::from("value"),
+ },
+ ]
+ .into(),
+ eval_grid: None,
+ });
+ let state = Arc::new(Mutex::new(State::default()));
+ let scanner = TestScanner {
+ properties: ScannerProperties::default(),
+ metadata: metadata.clone(),
+ batches,
+ raw_schema: Some(raw_schema),
+ chunks: vec![],
+ state: state.clone(),
+ };
+ (
+ Arc::new(RegionScanExec::new(Box::new(scanner), ScanRequest::default(), None).unwrap()),
+ state,
+ metadata,
+ )
+}
+
fn series_schema() -> Arc {
Arc::new(SeriesSchema {
fields: vec![FieldSpec {
@@ -315,6 +397,102 @@ fn context() -> Arc {
datafusion::prelude::SessionContext::new().task_ctx()
}
+#[test]
+fn named_series_scan_uses_actual_metadata_and_requested_field_order() {
+ let (scan, state, metadata) = named_fixture();
+ let scan = Arc::new(scan.with_new_partitions(vec![vec![]], 1).unwrap());
+ let native = scan
+ .try_to_named_series_scan(
+ "cpu",
+ &["host".to_string()],
+ &["aux".to_string(), "value".to_string()],
+ )
+ .unwrap()
+ .unwrap();
+ let RawLabelSource::PrimaryKey {
+ physical_metadata,
+ logical_tags,
+ ..
+ } = native.label_source()
+ else {
+ panic!("expected primary-key label source");
+ };
+ assert!(Arc::ptr_eq(&metadata, physical_metadata));
+ assert_eq!(logical_tags.len(), 1);
+ assert_eq!(logical_tags[0].column_id, 7);
+ assert_ne!(logical_tags[0].column_id, 1);
+ assert_eq!(logical_tags[0].name.as_ref(), "host");
+ assert_eq!(
+ native
+ .series_schema
+ .fields
+ .iter()
+ .map(|field| field.name.as_ref())
+ .collect::>(),
+ ["aux", "value"]
+ );
+ let state = state.lock().unwrap();
+ assert_eq!(state.preflights, 1);
+ assert_eq!(state.raw_calls, 0);
+ assert_eq!(state.legacy_calls, 0);
+}
+
+#[test]
+fn named_series_scan_declines_invalid_names_before_raw_preflight() {
+ let (scan, state, _) = named_fixture();
+ let scan = Arc::new(scan.with_new_partitions(vec![vec![]], 1).unwrap());
+ for (tags, fields) in [
+ (vec!["missing"], vec!["value"]),
+ (vec!["aux"], vec!["value"]),
+ (vec!["ts"], vec!["value"]),
+ (vec!["host", "host"], vec!["value"]),
+ (vec!["__sequence"], vec!["value"]),
+ (vec!["__table_id"], vec!["value"]),
+ (vec!["host"], vec!["missing"]),
+ (vec!["host"], vec!["ts"]),
+ (vec!["host"], vec!["value", "value"]),
+ ] {
+ let tags = tags.into_iter().map(str::to_string).collect::>();
+ let fields = fields.into_iter().map(str::to_string).collect::>();
+ assert!(
+ scan.clone()
+ .try_to_named_series_scan("cpu", &tags, &fields)
+ .unwrap()
+ .is_none()
+ );
+ }
+ let state = state.lock().unwrap();
+ assert_eq!(state.preflights, 0);
+ assert_eq!(state.raw_calls, 0);
+}
+
+#[tokio::test]
+async fn named_series_scan_raw_capability_declines_and_legacy_scan_is_unchanged() {
+ let (scan, state, _) = named_fixture();
+ state.lock().unwrap().raw_schema = Some(None);
+ let scan = Arc::new(scan.with_new_partitions(vec![vec![]], 1).unwrap());
+ assert!(
+ scan.clone()
+ .try_to_named_series_scan(
+ "cpu",
+ &["host".to_string()],
+ &["aux".to_string(), "value".to_string()]
+ )
+ .unwrap()
+ .is_none()
+ );
+ assert_eq!(state.lock().unwrap().preflights, 1);
+ assert_eq!(state.lock().unwrap().raw_calls, 0);
+ let rows = scan
+ .execute(0, context())
+ .unwrap()
+ .try_collect::>()
+ .await
+ .unwrap();
+ assert_eq!(rows.iter().map(|batch| batch.num_rows()).sum::(), 1);
+ assert_eq!(state.lock().unwrap().legacy_calls, 1);
+}
+
#[tokio::test]
async fn unsupported_native_scan_preserves_ordinary_data() {
let (scan, state) = fixture(None, vec![]);
diff --git a/tests-integration/src/standalone.rs b/tests-integration/src/standalone.rs
index 802e6668cb7..f0f5300722b 100644
--- a/tests-integration/src/standalone.rs
+++ b/tests-integration/src/standalone.rs
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+#[cfg(test)]
+#[path = "standalone/native_promql_tests.rs"]
+mod native_promql_tests;
+
use std::sync::Arc;
use std::time::Duration;
@@ -91,6 +95,7 @@ pub struct GreptimeDbStandaloneBuilder {
logical_batcher: Option,
table_batcher: BatcherOptions,
mito_config: Option,
+ query_options: Option,
}
impl GreptimeDbStandaloneBuilder {
@@ -112,9 +117,17 @@ impl GreptimeDbStandaloneBuilder {
logical_batcher: None,
table_batcher: BatcherOptions::default(),
mito_config: None,
+ query_options: None,
}
}
+ /// Overrides the query options for this test instance.
+ #[must_use]
+ pub fn with_query_options(mut self, options: query::options::QueryOptions) -> Self {
+ self.query_options = Some(options);
+ self
+ }
+
/// Overrides the Mito configuration for this test instance.
#[must_use]
pub fn with_mito_config(mut self, config: mito2::config::MitoConfig) -> Self {
@@ -401,6 +414,10 @@ impl GreptimeDbStandaloneBuilder {
..StandaloneOptions::default()
};
+ if let Some(query_options) = &self.query_options {
+ standalone_opts.query = query_options.clone();
+ }
+
if let Some(config) = &self.mito_config {
for engine in &mut standalone_opts.region_engine {
if let datanode::config::RegionEngineConfig::Mito(mito) = engine {
diff --git a/tests-integration/src/standalone/native_promql_tests.rs b/tests-integration/src/standalone/native_promql_tests.rs
new file mode 100644
index 00000000000..e06dc8d5730
--- /dev/null
+++ b/tests-integration/src/standalone/native_promql_tests.rs
@@ -0,0 +1,321 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use std::sync::Arc;
+
+use common_query::OutputData;
+use common_recordbatch::RecordBatches;
+use datafusion::arrow::array::{Array, Float64Array, StringArray, TimestampMillisecondArray};
+use datafusion::arrow::datatypes::{DataType, TimeUnit};
+use frontend::instance::Instance;
+use query::options::QueryOptions;
+use servers::query_handler::sql::SqlQueryHandler;
+use session::context::QueryContext;
+
+use super::GreptimeDbStandaloneBuilder;
+use crate::test_util::execute_sql;
+
+const QUERY: &str = "TQL EVAL (1, 3, '1s') baseline_native";
+const FILTERED_QUERY: &str = "TQL EVAL (1, 3, '1s') baseline_native > 6";
+const CREATE_TABLE: &str = "CREATE TABLE baseline_native (ts TIMESTAMP(3), host STRING, val DOUBLE, TIME INDEX (ts), PRIMARY KEY (host)) ENGINE=mito";
+const INSERT_ROWS: &str = "INSERT INTO baseline_native VALUES (1000, 'alpha', 1.5), (2000, 'alpha', NULL), (3000, 'alpha', 3.5), (1000, '', 4.5), (2000, '', 5.5), (3000, '', 6.5), (1000, NULL, 10.5), (2000, NULL, 11.5), (3000, NULL, 12.5), (1000, 'beta', 7.5), (3000, 'beta', 9.5)";
+
+async fn run_query(instance: &Arc, sql: &str) -> String {
+ let output = SqlQueryHandler::do_query(instance.as_ref(), sql, QueryContext::arc())
+ .await
+ .remove(0)
+ .unwrap();
+ output.data.pretty_print().await
+}
+
+async fn query_batches(instance: &Arc, sql: &str) -> RecordBatches {
+ let output = SqlQueryHandler::do_query(instance.as_ref(), sql, QueryContext::arc())
+ .await
+ .remove(0)
+ .unwrap();
+ match output.data {
+ OutputData::RecordBatches(batches) => batches,
+ OutputData::Stream(stream) => RecordBatches::try_collect(stream).await.unwrap(),
+ OutputData::AffectedRows(_) => panic!("expected query batches"),
+ }
+}
+
+async fn create_seeded_instance(
+ name: &str,
+ options: QueryOptions,
+) -> crate::standalone::GreptimeDbStandalone {
+ let standalone = GreptimeDbStandaloneBuilder::new(name)
+ .with_query_options(options)
+ .build()
+ .await;
+ let instance = &standalone.frontend.instance;
+ execute_sql(instance, CREATE_TABLE).await;
+ execute_sql(instance, INSERT_ROWS).await;
+ standalone
+}
+
+fn rows(batches: &RecordBatches) -> Vec<(i64, Option, Option)> {
+ let mut rows = Vec::new();
+ for batch in batches.iter() {
+ let batch = batch.df_record_batch();
+ let ts = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ let val = batch
+ .column(1)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ let host = batch
+ .column(2)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ for index in 0..batch.num_rows() {
+ rows.push((
+ ts.value(index),
+ (!host.is_null(index)).then(|| host.value(index).to_string()),
+ (!val.is_null(index)).then(|| val.value(index)),
+ ));
+ }
+ }
+ rows.sort_by(|left, right| {
+ left.0.cmp(&right.0).then_with(|| {
+ left.1
+ .is_none()
+ .cmp(&right.1.is_none())
+ .then_with(|| left.1.cmp(&right.1))
+ })
+ });
+ rows
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn test_native_promql_standalone_executes_with_real_tql_query() {
+ let disabled_options = QueryOptions {
+ parallelism: 1,
+ ..Default::default()
+ };
+ let enabled_options = QueryOptions {
+ experimental_native_promql: true,
+ ..disabled_options.clone()
+ };
+ let enabled = create_seeded_instance("native_promql_enabled", enabled_options).await;
+ let ordinary = create_seeded_instance("native_promql_disabled", disabled_options).await;
+ let instance = &enabled.frontend.instance;
+ let baseline_instance = &ordinary.frontend.instance;
+
+ let analyzed = run_query(instance, "TQL ANALYZE VERBOSE (1, 3, '1s') baseline_native").await;
+ assert!(
+ analyzed.contains("NativeInstantManipulateExec"),
+ "experimental plan did not execute via native instant manipulation:\n{analyzed}"
+ );
+ assert!(
+ analyzed.contains("SeriesScanExec: source=primary_key"),
+ "native plan omitted the primary-key raw-series scan:\n{analyzed}"
+ );
+ let ordinary_plan = run_query(
+ baseline_instance,
+ "TQL ANALYZE VERBOSE (1, 3, '1s') baseline_native",
+ )
+ .await;
+ assert!(
+ !ordinary_plan.contains("NativeInstantManipulateExec"),
+ "{ordinary_plan}"
+ );
+
+ let enabled_batches = query_batches(instance, QUERY).await;
+ let ordinary_batches = query_batches(baseline_instance, QUERY).await;
+ assert_eq!(enabled_batches.schema(), ordinary_batches.schema());
+ let arrow_schema = enabled_batches.schema().arrow_schema().clone();
+ assert_eq!(
+ arrow_schema
+ .fields()
+ .iter()
+ .map(|field| field.name().as_str())
+ .collect::>(),
+ vec!["ts", "val", "host"]
+ );
+ assert_eq!(
+ arrow_schema.field(0).data_type(),
+ &DataType::Timestamp(TimeUnit::Millisecond, None)
+ );
+ assert_eq!(arrow_schema.field(1).data_type(), &DataType::Float64);
+ assert_eq!(arrow_schema.field(2).data_type(), &DataType::Utf8);
+ assert_eq!(rows(&enabled_batches), rows(&ordinary_batches));
+ assert_eq!(
+ vec![
+ (1_000, Some(String::new()), Some(4.5)),
+ (1_000, Some("alpha".to_string()), Some(1.5)),
+ (1_000, Some("beta".to_string()), Some(7.5)),
+ (1_000, None, Some(10.5)),
+ (2_000, Some(String::new()), Some(5.5)),
+ (2_000, Some("alpha".to_string()), None),
+ (2_000, Some("beta".to_string()), Some(7.5)),
+ (2_000, None, Some(11.5)),
+ (3_000, Some(String::new()), Some(6.5)),
+ (3_000, Some("alpha".to_string()), Some(3.5)),
+ (3_000, Some("beta".to_string()), Some(9.5)),
+ (3_000, None, Some(12.5)),
+ ],
+ rows(&enabled_batches)
+ );
+
+ let single_eval = "TQL ANALYZE VERBOSE (1, 1, '1s') baseline_native";
+ let unsupported_plan = run_query(instance, single_eval).await;
+ assert!(
+ !unsupported_plan.contains("NativeInstantManipulateExec"),
+ "{unsupported_plan}"
+ );
+ let unsupported_result = query_batches(instance, "TQL EVAL (1, 1, '1s') baseline_native").await;
+ assert_eq!(
+ vec![
+ (1_000, Some(String::new()), Some(4.5)),
+ (1_000, Some("alpha".to_string()), Some(1.5)),
+ (1_000, Some("beta".to_string()), Some(7.5)),
+ (1_000, None, Some(10.5)),
+ ],
+ rows(&unsupported_result)
+ );
+
+ for test_instance in [instance, baseline_instance] {
+ execute_sql(
+ test_instance,
+ "CREATE TABLE native_tag_parts (ts TIMESTAMP(3), host STRING, val DOUBLE, TIME INDEX (ts), PRIMARY KEY (host)) PARTITION ON COLUMNS (host) (host < 'm', host >= 'm') ENGINE=mito",
+ )
+ .await;
+ execute_sql(
+ test_instance,
+ "INSERT INTO native_tag_parts VALUES (1000, 'alpha', 1), (3000, 'alpha', 3), (1000, 'zeta', 10), (3000, 'zeta', 30)",
+ )
+ .await;
+ let table = test_instance
+ .catalog_manager()
+ .table("greptime", "public", "native_tag_parts", None)
+ .await
+ .unwrap()
+ .unwrap();
+ let table_id = table.table_info().ident.table_id;
+ let partitions = test_instance
+ .partition_manager()
+ .batch_find_table_partitions(&[table_id])
+ .await
+ .unwrap()[&table_id]
+ .clone();
+ assert_eq!(2, partitions.len(), "native_tag_parts");
+ execute_sql(
+ test_instance,
+ "CREATE TABLE native_time_parts (ts TIMESTAMP(3), host STRING, val DOUBLE, TIME INDEX (ts), PRIMARY KEY (host)) PARTITION ON COLUMNS (ts) (ts < '1970-01-01 00:00:02', ts >= '1970-01-01 00:00:02') ENGINE=mito",
+ )
+ .await;
+ execute_sql(
+ test_instance,
+ "INSERT INTO native_time_parts VALUES (1000, 'alpha', 1), (3000, 'alpha', 3)",
+ )
+ .await;
+ let table = test_instance
+ .catalog_manager()
+ .table("greptime", "public", "native_time_parts", None)
+ .await
+ .unwrap()
+ .unwrap();
+ let table_id = table.table_info().ident.table_id;
+ let partitions = test_instance
+ .partition_manager()
+ .batch_find_table_partitions(&[table_id])
+ .await
+ .unwrap()[&table_id]
+ .clone();
+ assert_eq!(2, partitions.len(), "native_time_parts");
+ }
+
+ let tag_query = "TQL EVAL (1, 3, '1s') native_tag_parts";
+ let tag_plan = run_query(
+ instance,
+ "TQL ANALYZE VERBOSE (1, 3, '1s') native_tag_parts",
+ )
+ .await;
+ assert!(
+ tag_plan.contains("NativeInstantManipulateExec"),
+ "tag-partitioned plan did not use native instant manipulation:\n{tag_plan}"
+ );
+ let tag_enabled = query_batches(instance, tag_query).await;
+ let tag_ordinary =
+ query_batches(baseline_instance, "TQL EVAL (1, 3, '1s') native_tag_parts").await;
+ assert_eq!(tag_enabled.schema(), tag_ordinary.schema());
+ assert_eq!(rows(&tag_enabled), rows(&tag_ordinary));
+ assert_eq!(
+ vec![
+ (1_000, Some("alpha".to_string()), Some(1.0)),
+ (1_000, Some("zeta".to_string()), Some(10.0)),
+ (2_000, Some("alpha".to_string()), Some(1.0)),
+ (2_000, Some("zeta".to_string()), Some(10.0)),
+ (3_000, Some("alpha".to_string()), Some(3.0)),
+ (3_000, Some("zeta".to_string()), Some(30.0)),
+ ],
+ rows(&tag_enabled)
+ );
+
+ let time_query = "TQL EVAL (1, 3, '1s') native_time_parts";
+ let time_plan = run_query(
+ instance,
+ "TQL ANALYZE VERBOSE (1, 3, '1s') native_time_parts",
+ )
+ .await;
+ assert!(
+ !time_plan.contains("NativeInstantManipulateExec"),
+ "time-partitioned plan unexpectedly used native instant manipulation:\n{time_plan}"
+ );
+ let time_enabled = query_batches(instance, time_query).await;
+ let time_ordinary =
+ query_batches(baseline_instance, "TQL EVAL (1, 3, '1s') native_time_parts").await;
+ assert_eq!(time_enabled.schema(), time_ordinary.schema());
+ assert_eq!(rows(&time_enabled), rows(&time_ordinary));
+ assert_eq!(
+ vec![
+ (1_000, Some("alpha".to_string()), Some(1.0)),
+ (2_000, Some("alpha".to_string()), Some(1.0)),
+ (3_000, Some("alpha".to_string()), Some(3.0)),
+ ],
+ rows(&time_enabled)
+ );
+
+ let filtered_plan = run_query(
+ instance,
+ "TQL ANALYZE VERBOSE (1, 3, '1s') baseline_native > 6",
+ )
+ .await;
+ assert!(
+ !filtered_plan.contains("NativeInstantManipulateExec"),
+ "unsupported filtered plan unexpectedly used native instant manipulation:\n{filtered_plan}"
+ );
+ let filtered_enabled = query_batches(instance, FILTERED_QUERY).await;
+ let filtered_ordinary = query_batches(baseline_instance, FILTERED_QUERY).await;
+ assert_eq!(filtered_enabled.schema(), filtered_ordinary.schema());
+ assert_eq!(rows(&filtered_enabled), rows(&filtered_ordinary));
+ assert_eq!(
+ vec![
+ (1_000, Some("beta".to_string()), Some(7.5)),
+ (1_000, None, Some(10.5)),
+ (2_000, Some("beta".to_string()), Some(7.5)),
+ (2_000, None, Some(11.5)),
+ (3_000, Some(String::new()), Some(6.5)),
+ (3_000, Some("beta".to_string()), Some(9.5)),
+ (3_000, None, Some(12.5)),
+ ],
+ rows(&filtered_enabled)
+ );
+}