diff --git a/src/promql/src/extension_plan/row_series_source.rs b/src/promql/src/extension_plan/row_series_source.rs index 93823d90352..0acfb023bda 100644 --- a/src/promql/src/extension_plan/row_series_source.rs +++ b/src/promql/src/extension_plan/row_series_source.rs @@ -19,7 +19,8 @@ //! `(tags, time index)`, which the physical optimizer provides with a `RepartitionExec` //! and a `SortExec` that spills under memory pressure, and cuts the sorted rows into series chunks //! that carry their complete labels. Numeric fields are read as `Float64` and native histogram -//! fields as histogram samples. +//! fields as histogram samples. Timestamps are handed over in the time index's own unit; the +//! consumer is bound to that unit (`crate::raw_time`). //! //! A raw series holds one sample per timestamp, as Prometheus storage does. Each field is its own //! value series, so rows that share labels and a timestamp are reduced field by field: each field @@ -41,13 +42,11 @@ use common_query::series_frame::{ PendingBatching, pack_raw_series_with, raw_series_frame_schema_with_ordering, }; use datafusion::arrow::array::{ - Array, ArrayRef, AsArray, DynComparator, StringArray, UInt32Array, make_comparator, + Array, ArrayRef, AsArray, DynComparator, Int64Array, StringArray, UInt32Array, make_comparator, }; use datafusion::arrow::buffer::Buffer; use datafusion::arrow::compute::{cast, concat_batches, take, take_record_batch}; -use datafusion::arrow::datatypes::{ - DataType, Float64Type, SchemaRef, TimeUnit, TimestampMillisecondType, -}; +use datafusion::arrow::datatypes::{DataType, Float64Type, Int64Type, SchemaRef}; use datafusion::arrow::record_batch::RecordBatch; use datafusion::common::tree_node::TreeNodeRecursion; use datafusion::common::{DFSchema, DFSchemaRef}; @@ -67,6 +66,7 @@ use datatypes::compute::SortOptions; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{FieldSpec, Samples, SeriesFields, SeriesSchema}; use datatypes::series::{Label, SeriesLabels, SeriesOrdering}; +use datatypes::timestamp::timestamp_array_to_primitive; use futures::{Stream, StreamExt}; use store_api::region_engine::{RawLabelSource, RawSeriesStream}; @@ -258,12 +258,9 @@ impl RowColumns { .map(|tag| index_of(tag)) .collect::>>()?; let time = index_of(time_index)?; - if !matches!( - schema.field(time).data_type(), - DataType::Timestamp(TimeUnit::Millisecond, _) - ) { + if !matches!(schema.field(time).data_type(), DataType::Timestamp(_, _)) { return Err(DataFusionError::Plan(format!( - "RowSeriesSource time index {time_index:?} is {}, not a millisecond timestamp", + "RowSeriesSource time index {time_index:?} is {}, not a timestamp", schema.field(time).data_type() ))); } @@ -563,11 +560,9 @@ impl RowSeriesStream { Ok(tag) }) .collect::>>()?; - let time = batch - .column(self.columns.time) - .as_primitive_opt::() - .ok_or_else(|| { - DataFusionError::Execution("RowSeriesSource time index is not milliseconds".into()) + let (time, _) = + timestamp_array_to_primitive(batch.column(self.columns.time)).ok_or_else(|| { + DataFusionError::Execution("RowSeriesSource time index is not a timestamp".into()) })?; if time.null_count() > 0 { return Err(DataFusionError::Execution( @@ -622,7 +617,7 @@ impl RowSeriesStream { .as_ref() .is_some_and(|open| open.holds(&tags, row)) { - self.publish(&kept, &field_rows, time, &fields)?; + self.publish(&kept, &field_rows, &time, &fields)?; kept.clear(); field_rows.iter_mut().for_each(Vec::clear); self.close(); @@ -662,7 +657,7 @@ impl RowSeriesStream { winners.dedup(); self.tail = Some(take_record_batch(&batch, &UInt32Array::from(winners))?); } - self.publish(&kept, &field_rows, time, &fields) + self.publish(&kept, &field_rows, &time, &fields) } /// Makes the samples at the rows `kept` of the current batch the open series' latest chunk; @@ -671,7 +666,7 @@ impl RowSeriesStream { &mut self, kept: &[u32], field_rows: &[Vec], - time: &datafusion::arrow::array::TimestampMillisecondArray, + time: &Int64Array, fields: &[ArrayRef], ) -> DataFusionResult<()> { let Some(open) = &mut self.open else { @@ -682,12 +677,8 @@ impl RowSeriesStream { } let indices = UInt32Array::from(kept.to_vec()); let time = take(time, &indices, None)?; - let time = RawTimestamps::try_new( - time.as_primitive::() - .values() - .clone(), - ) - .map_err(|error| DataFusionError::External(Box::new(error)))?; + let time = RawTimestamps::try_new(time.as_primitive::().values().clone()) + .map_err(|error| DataFusionError::External(Box::new(error)))?; let samples = fields .iter() .zip(field_rows) @@ -821,7 +812,7 @@ impl RawSeriesStream for RowSeriesStream { mod tests { use common_query::series_frame::unpack_raw_series; use datafusion::arrow::array::{Float64Array, TimestampMillisecondArray}; - use datafusion::arrow::datatypes::{Field, Schema}; + use datafusion::arrow::datatypes::{Field, Schema, TimeUnit}; use datafusion::datasource::memory::MemorySourceConfig; use datafusion::prelude::SessionContext; use datatypes::series::samples::SampleRef; diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 98d9cc3f78f..94feed47c0c 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -361,17 +361,20 @@ impl PromPlanner { input = LogicalPlan::TableScan(scan.clone()); scan } - None => match &input { - LogicalPlan::TableScan(scan) => scan.clone(), - // A time index in another unit than milliseconds is read through a projection that - // casts it. A row source reads that projection; the raw series scan reads the - // column as stored, so that route takes the scan below it once the engine is known. - LogicalPlan::Projection(projection) => match projection.input.as_ref() { + None => { + // The existing plan reads a time index in another unit than milliseconds under a + // projection that casts or reorders it. The raw series scan and a row source read + // the column as stored, so this route takes the scan below it. + if let LogicalPlan::Projection(projection) = &input + && let LogicalPlan::TableScan(scan) = projection.input.as_ref() + { + input = LogicalPlan::TableScan(scan.clone()); + } + match &input { LogicalPlan::TableScan(scan) => scan.clone(), _ => return Ok(declined("selector_plan_is_not_a_table_scan")), - }, - _ => return Ok(declined("selector_plan_is_not_a_table_scan")), - }, + } + } }; let table = self.table_from_source(&scan.source)?; let table_meta = &table.table_info().meta; @@ -409,42 +412,24 @@ impl PromPlanner { { return Ok(declined("engine_without_raw_series_scanner")); } - // A row source names its series by its tag columns and the metric name by the table, so a tag - // column named `__name__` has no label to be read as, and dropping it would merge the series - // it tells apart. - if reads_rows && tags.iter().any(|tag| tag == METRIC_NAME) { - return Ok(declined("row_source_tag_named_metric_name")); + // This route names every series it reads by the table, so a tag column named `__name__` has no + // label to be read as, and dropping it would merge the series it tells apart. + if tags.iter().any(|tag| tag == METRIC_NAME) { + return Ok(declined("tag_named_metric_name")); } - let time_index_unit = table_meta + let sub_millisecond_time_index = table_meta .schema .timestamp_column() - .map(|column| column.data_type.as_arrow_type()); - // A row source reads milliseconds, and a second-precision time index as the milliseconds - // it is exactly. - if reads_rows - && !matches!( - time_index_unit, - Some(ArrowDataType::Timestamp( - ArrowTimeUnit::Millisecond | ArrowTimeUnit::Second, - _ - )) - ) - { - return Ok(declined("row_source_sub_millisecond_time_index")); - } - let sub_millisecond_time_index = matches!( - time_index_unit, - Some(ArrowDataType::Timestamp( - ArrowTimeUnit::Microsecond | ArrowTimeUnit::Nanosecond, - _ - )) - ); - if !reads_rows - && let LogicalPlan::Projection(projection) = &input - && let LogicalPlan::TableScan(scan) = projection.input.as_ref() - { - input = LogicalPlan::TableScan(scan.clone()); - } + .map(|column| column.data_type.as_arrow_type()) + .is_some_and(|data_type| { + matches!( + data_type, + ArrowDataType::Timestamp( + ArrowTimeUnit::Microsecond | ArrowTimeUnit::Nanosecond, + _ + ) + ) + }); // Admitted: such inputs are read through a raw source, which reconciles the fragments. let split_series = !table_meta .partition_column_names() @@ -1538,12 +1523,10 @@ impl PromPlanner { } else if let LogicalPlan::Extension(extension) = scan && let Some(source) = extension.node.as_any().downcast_ref::() { - // A row source hands over milliseconds, whatever unit its file stores. - let filter = - scan_time_filter(start, end, inclusive, time, ArrowTimeUnit::Millisecond); - *scan = bind_row_source_filters(source, filter, time) + let (bound, unit) = bind_row_source_filters(source, start, end, inclusive, time) .context(DataFusionPlanningSnafu)?; - input_time_units.push(RawTimeUnit::Millisecond); + *scan = bound; + input_time_units.push(RawTimeUnit::from(unit)); } else if let LogicalPlan::TableScan(table_scan) = scan { let unit = self.scan_time_unit(table_scan)?; table_scan @@ -2151,27 +2134,37 @@ fn row_source_input( .context(DataFusionPlanningSnafu) } -/// Filters a row source by the selector's time range, also pushed into a scan whose time index is -/// in milliseconds so the file engine can prune files and row groups. +/// Filters a row source by the selector's time range, in milliseconds, and returns the source with +/// the unit of its time index. The range is also pushed into the scan so the file engine can prune +/// files and row groups. fn bind_row_source_filters( source: &RowSeriesSource, - time_filter: DfExpr, + start: i64, + end: i64, + inclusive: bool, time: &str, -) -> std::result::Result { +) -> std::result::Result<(LogicalPlan, ArrowTimeUnit), DataFusionError> { use datafusion::common::tree_node::{Transformed, TreeNode}; - let millis = - ArrowDataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None); + let unit = match source + .input() + .schema() + .field_with_unqualified_name(time)? + .data_type() + { + ArrowDataType::Timestamp(unit, _) => *unit, + other => { + return Err(DataFusionError::Internal(format!( + "row source time index {time:?} is {other}, not a timestamp" + ))); + } + }; + let time_filter = scan_time_filter(start, end, inclusive, time, unit); let input = source .input() .clone() .transform_down(|plan| match plan { - LogicalPlan::TableScan(mut scan) - if scan - .projected_schema - .field_with_unqualified_name(time) - .is_ok_and(|field| field.data_type() == &millis) => - { + LogicalPlan::TableScan(mut scan) => { scan.filters.push(time_filter.clone()); Ok(Transformed::yes(LogicalPlan::TableScan(scan))) } @@ -2181,7 +2174,7 @@ fn bind_row_source_filters( let input = LogicalPlanBuilder::from(input) .filter(time_filter)? .build()?; - Ok(LogicalPlan::Extension(Extension { + let source = LogicalPlan::Extension(Extension { node: Arc::new( datafusion::logical_expr::UserDefinedLogicalNodeCore::with_exprs_and_inputs( source, @@ -2189,7 +2182,8 @@ fn bind_row_source_filters( vec![input], )?, ), - })) + }); + Ok((source, unit)) } /// `millis` from the Unix epoch, negative included; `None` when [`SystemTime`] cannot represent it. diff --git a/tests-integration/src/tests/native_file_engine_test.rs b/tests-integration/src/tests/native_file_engine_test.rs index 63cd92ea832..5c080ca4e8c 100644 --- a/tests-integration/src/tests/native_file_engine_test.rs +++ b/tests-integration/src/tests/native_file_engine_test.rs @@ -15,21 +15,30 @@ //! Native PromQL over file-engine tables. //! //! `fe_metric` reads two CSV files whose rows are in no particular order, and one sample of series -//! `{job="api", instance="a"}` is present in both files with different values; `fe_metric_s` reads -//! the same files with a second-precision time index. `fe_labels` holds a tag that is `NULL` on some +//! `{job="api", instance="a"}` is present in both files with different values; `fe_metric_s`, +//! `fe_metric_us` and `fe_metric_ns` read the same files with a second, microsecond and nanosecond +//! time index. `fe_sub_us` and `fe_sub_ns` read one file whose samples are less than a millisecond +//! off whole milliseconds and from each other. `fe_labels` holds a tag that is `NULL` on some //! rows and `''` on others, and an integer tag. `fe_histogram` mirrors the sqlness case //! `promql/delta_exponential_histogram`. Expected answers are worked out by hand from Prometheus //! semantics, which keep one sample per timestamp per series, read an empty label as an absent one -//! and compare label values as strings. +//! and compare label values as strings. `fe_wide` is a Parquet file with two `DOUBLE` fields and a +//! microsecond time index, where each row holds a stale marker in one of them. use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; +use api::v1::value::ValueData; +use api::v1::{ + ColumnDataType, ColumnSchema, RowInsertRequest, RowInsertRequests, Rows, SemanticType, +}; use common_base::Plugins; use common_datasource::object_store::LocalFileAccess; use common_query::OutputData; +use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS; use common_recordbatch::util::collect_batches; use common_test_util::find_workspace_path; +use datafusion::arrow::util::display::array_value_to_string; use datafusion::physical_plan::ExecutionPlan; use datatypes::arrow::array::{Array, Float64Array, Int64Array, StringArray}; use datatypes::arrow::compute::cast; @@ -116,6 +125,8 @@ struct Case { /// sample its sort leaves last, keeps `NULL` and `''` apart, and fails on an integer tag /// (`Unsupported tag column type: Int64`). legacy_differs: bool, + /// The lookback delta of the statement, when not the default. + lookback: Option<&'static str>, } fn row(offset_secs: i64, labels: &str, value: f64) -> Row { @@ -129,6 +140,7 @@ fn instant(promql: impl Into, offset_secs: i64, expected: Vec) -> C end: BASE_SECS + offset_secs, expected, legacy_differs: false, + lookback: None, } } @@ -214,6 +226,7 @@ fn metric_cases(table: &str) -> Vec { end: BASE_SECS + 240, expected: range_selector, legacy_differs: true, + lookback: None, }, Case { promql: q("sum by (job) (fe_metric)"), @@ -221,10 +234,62 @@ fn metric_cases(table: &str) -> Vec { end: BASE_SECS + 240, expected: range_sum, legacy_differs: true, + lookback: None, }, ] } +/// `(offset_micros, value)` of the one series `{host="h"}` of `fe_sub_us` and `fe_sub_ns`. +const SUB_MILLISECOND: &[(i64, f64)] = &[ + (59_999_500, 1.0), + (60_000_500, 2.0), + (61_000_000, 4.0), + (61_000_200, 8.0), +]; + +/// Windows and lookbacks are decided on the stored time, so a bound at a whole millisecond falls +/// between two samples that share that millisecond once truncated, and samples less than a +/// millisecond apart stay two samples. A kernel reads the time truncated to milliseconds. +fn sub_millisecond_cases(table: &str) -> Vec { + let q = |promql: &str| promql.replace("fe_sub", table); + let h = "host=h"; + vec![ + // 60.0005s is after 60s, so 59.9995s is the latest sample at 60s. + instant(q("fe_sub"), 60, vec![row(60, h, 1.0)]), + instant( + q("timestamp(fe_sub)"), + 60, + vec![row(60, h, (BASE_SECS * 1000 + 59_999) as f64 / 1000.0)], + ), + // 61.0002s is after 61s. + instant(q("fe_sub"), 61, vec![row(61, h, 4.0)]), + instant( + q("timestamp(fe_sub)"), + 62, + vec![row(62, h, (BASE_SECS + 61) as f64)], + ), + // (60s, 61s] holds 60.0005s and 61s. + instant(q("count_over_time(fe_sub[1s])"), 61, vec![row(61, h, 2.0)]), + // (60s, 62s] holds 60.0005s, 61s and 61.0002s. + instant(q("sum_over_time(fe_sub[2s])"), 62, vec![row(62, h, 14.0)]), + // The last two samples in (59s, 61s] are 60.0005s and 61s. + instant(q("idelta(fe_sub[2s])"), 61, vec![row(61, h, 2.0)]), + // The last two samples in (60s, 62s] share the millisecond 61000, so there is no interval + // to take a difference over. + instant(q("idelta(fe_sub[2s])"), 62, vec![]), + // A zero lookback selects a sample stored exactly at the instant: 59.9995s is not at 60s. + zero_lookback(instant(q("fe_sub"), 60, vec![])), + zero_lookback(instant(q("fe_sub"), 61, vec![row(61, h, 4.0)])), + ] +} + +fn zero_lookback(case: Case) -> Case { + Case { + lookback: Some("0"), + ..case + } +} + /// `fe_labels`: `{code="200"}` holds 1 at offset 0 with `instance` NULL, 2 at 60 with `instance` /// `''`, and at 120 both a NULL row (3) and a `''` row (4); `{code="500", instance="x"}` holds 10, /// 20, 30. The first is one series without an `instance` label, whose sample at 120 is 3. @@ -238,6 +303,7 @@ fn label_cases() -> Vec { end: BASE_SECS + 120, expected: vec![row(0, ok, 1.0), row(60, ok, 2.0), row(120, ok, 3.0)], legacy_differs: true, + lookback: None, }, differs(instant("count(fe_labels)", 120, vec![row(120, "", 2.0)])), differs(instant( @@ -275,6 +341,7 @@ fn histogram_cases() -> Vec { .map(|value| vec![(secs * 1000, String::new(), value)]) .unwrap_or_default(), legacy_differs: false, + lookback: None, }; vec![ at( @@ -339,7 +406,12 @@ async fn create_tables(instance: &Arc, dir: &std::path::Path) { std::fs::create_dir(&metric_dir).unwrap(); write_csv(&metric_dir.join("a.csv"), FILE_A); write_csv(&metric_dir.join("b.csv"), FILE_B); - for (table, precision) in [("fe_metric", 3), ("fe_metric_s", 0)] { + for (table, precision) in [ + ("fe_metric", 3), + ("fe_metric_s", 0), + ("fe_metric_us", 6), + ("fe_metric_ns", 9), + ] { execute( instance, &format!( @@ -356,6 +428,34 @@ async fn create_tables(instance: &Arc, dir: &std::path::Path) { .await; } + let sub_dir = dir.join("sub"); + std::fs::create_dir(&sub_dir).unwrap(); + let mut text = String::from("ts,host,val\n"); + for (offset_micros, value) in SUB_MILLISECOND { + let ts = + chrono::DateTime::from_timestamp_micros(BASE_SECS * 1_000_000 + offset_micros).unwrap(); + text.push_str(&format!( + "{},h,{value}\n", + ts.format("%Y-%m-%dT%H:%M:%S%.6f") + )); + } + std::fs::write(sub_dir.join("rows.csv"), text).unwrap(); + for (table, precision) in [("fe_sub_us", 6), ("fe_sub_ns", 9)] { + execute( + instance, + &format!( + "CREATE EXTERNAL TABLE {table} ( + ts TIMESTAMP({precision}) TIME INDEX, + host STRING, + val DOUBLE, + PRIMARY KEY (host) + ) WITH (location = '{}', format = 'csv')", + location(&sub_dir) + ), + ) + .await; + } + let labels_dir = dir.join("labels"); std::fs::create_dir(&labels_dir).unwrap(); let mut lines = String::new(); @@ -416,6 +516,77 @@ async fn create_tables(instance: &Arc, dir: &std::path::Path) { ) .await; + let wide_file = prepare_path(&format!("{}/wide.parquet", dir.display())); + execute( + instance, + "CREATE TABLE fe_wide_source ( + ts TIMESTAMP(6) TIME INDEX, host STRING PRIMARY KEY, a DOUBLE, b DOUBLE + )", + ) + .await; + let stale = f64::from_bits(PROMETHEUS_STALE_NAN_BITS); + let column = |name: &str, datatype: ColumnDataType, semantic_type: SemanticType| ColumnSchema { + column_name: name.into(), + datatype: datatype as i32, + semantic_type: semantic_type as i32, + ..Default::default() + }; + instance + .handle_row_inserts( + RowInsertRequests { + inserts: vec![RowInsertRequest { + table_name: "fe_wide_source".into(), + rows: Some(Rows { + schema: vec![ + column("host", ColumnDataType::String, SemanticType::Tag), + column( + "ts", + ColumnDataType::TimestampMicrosecond, + SemanticType::Timestamp, + ), + column("a", ColumnDataType::Float64, SemanticType::Field), + column("b", ColumnDataType::Float64, SemanticType::Field), + ], + rows: [("a_stale", stale, 1.0), ("b_stale", 1.0, stale)] + .into_iter() + .map(|(host, a, b)| api::v1::Row { + values: vec![ + ValueData::StringValue(host.into()).into(), + ValueData::TimestampMicrosecondValue(BASE_SECS * 1_000_000) + .into(), + ValueData::F64Value(a).into(), + ValueData::F64Value(b).into(), + ], + }) + .collect(), + }), + }], + }, + QueryContext::arc(), + false, + false, + ) + .await + .unwrap(); + execute( + instance, + &format!("COPY (SELECT ts, host, a, b FROM fe_wide_source) TO '{wide_file}'"), + ) + .await; + execute( + instance, + &format!( + "CREATE EXTERNAL TABLE fe_wide ( + ts TIMESTAMP(6) TIME INDEX, + host STRING, + a DOUBLE, + b DOUBLE, + PRIMARY KEY (host) + ) WITH (location = '{wide_file}', format = 'parquet')" + ), + ) + .await; + // The fixture of `promql/delta_exponential_histogram`. let histogram_file = prepare_path(&format!("{}/histogram.parquet", dir.display())); execute( @@ -476,8 +647,12 @@ async fn create_tables(instance: &Arc, dir: &std::path::Path) { } async fn run(instance: &Arc, case: &Case, native: bool) -> Result, String> { + let lookback = case + .lookback + .map(|lookback| format!(", '{lookback}'")) + .unwrap_or_default(); let sql = format!( - "TQL EVAL ({}, {}, '60s') {}", + "TQL EVAL ({}, {}, '60s'{lookback}) {}", case.start, case.end, case.promql ); let mut ctx = QueryContext::with_db_name(None); @@ -551,6 +726,10 @@ async fn check_native_answers(instance: &Arc, observer: &PlanObserver) let cases = metric_cases("fe_metric") .into_iter() .chain(metric_cases("fe_metric_s")) + .chain(metric_cases("fe_metric_us")) + .chain(metric_cases("fe_metric_ns")) + .chain(sub_millisecond_cases("fe_sub_us")) + .chain(sub_millisecond_cases("fe_sub_ns")) .chain(label_cases()) .chain(histogram_cases()); let mut failures = Vec::new(); @@ -614,11 +793,77 @@ async fn check_metric_name_tag_declines(instance: &Arc, observer: &Pla panic!("a `__name__` tag column is refused: {answer:?}"); }; assert!( - error.contains("declined this expression: row_source_tag_named_metric_name"), + error.contains("declined this expression: tag_named_metric_name"), "the refusal names the tag column it cannot read: {error}" ); } +/// The rows of a multi-field answer as `(time, labels, values)`, without the metric name. +async fn wide_rows( + instance: &Arc, + sql: &str, + native: bool, +) -> Vec<(i64, Vec, Vec)> { + let mut ctx = QueryContext::with_db_name(None); + ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, native.to_string()); + let output = instance + .do_query(sql, Arc::new(ctx)) + .await + .remove(0) + .unwrap_or_else(|error| panic!("`{sql}` (native={native}) failed: {error:?}")); + let batches = match output.data { + OutputData::Stream(stream) => collect_batches(stream).await.unwrap(), + OutputData::RecordBatches(batches) => batches, + other => panic!("`{sql}` returned {other:?}"), + }; + let mut rows = Vec::new(); + for batch in batches.iter() { + let df = batch.df_record_batch(); + let schema = df.schema(); + let text = |index: usize, row: usize| array_value_to_string(df.column(index), row).unwrap(); + for row in 0..df.num_rows() { + let (mut time, mut labels, mut values) = (None, Vec::new(), Vec::new()); + for (index, field) in schema.fields().iter().enumerate() { + match field.data_type() { + DataType::Timestamp(_, _) => { + let ts = cast(df.column(index), &DataType::Int64).unwrap(); + time = Some(ts.as_any().downcast_ref::().unwrap().value(row)); + } + _ if field.name() == "__name__" => {} + DataType::Utf8 => labels.push(format!("{}={}", field.name(), text(index, row))), + _ => values.push(text(index, row)), + } + } + rows.push((time.expect("a time column"), labels, values)); + } + } + rows.sort(); + rows +} + +/// The existing plan reads a stale marker from the first field only, so of `fe_wide` it drops +/// `a_stale` and keeps `b_stale`, whose stale marker is in the second field. +async fn check_stale_second_field(instance: &Arc, observer: &PlanObserver) { + for query in ["fe_wide", "timestamp(fe_wide)"] { + let sql = format!("TQL EVAL ({BASE_SECS}, {BASE_SECS}, '60s') {query}"); + observer.take_node_names(); + let native = wide_rows(instance, &sql, true).await; + let nodes = observer.take_node_names(); + assert!( + nodes.iter().any(|node| node == "FusedSeriesExec") + && nodes.iter().any(|node| node == "RowSeriesSourceExec"), + "`{query}` did not run on the native route: {nodes:?}" + ); + let legacy = wide_rows(instance, &sql, false).await; + assert_eq!(native, legacy, "`{query}`"); + let hosts = native + .iter() + .map(|(_, labels, _)| labels.join(",")) + .collect::>(); + assert_eq!(vec!["host=b_stale"], hosts, "`{query}`"); + } +} + fn observer_plugins() -> (Arc, Plugins) { let observer = Arc::new(PlanObserver::default()); let plugins = Plugins::new(); @@ -647,6 +892,7 @@ async fn native_promql_over_file_engine_standalone() { create_tables(&instance, dir.path()).await; check_native_answers(&instance, &observer).await; check_metric_name_tag_declines(&instance, &observer).await; + check_stale_second_field(&instance, &observer).await; } #[tokio::test(flavor = "multi_thread")] @@ -665,4 +911,5 @@ async fn native_promql_over_file_engine_distributed() { create_tables(&instance, dir.path()).await; check_native_answers(&instance, &observer).await; check_metric_name_tag_declines(&instance, &observer).await; + check_stale_second_field(&instance, &observer).await; } diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 750861988e8..7c12fbfac64 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -13941,6 +13941,44 @@ async fn native_promql_declines_a_tree_the_runtime_cannot_execute() { assert_native_decline(&instance, &sql, "runtime_refuses_the_tree", query).await; } +/// A tag column named `__name__` contradicts the metric name the table gives every series it holds, +/// and the native route has no label to read it as: it would merge the series the column tells +/// apart. The route refuses such a table instead. +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_declines_a_tag_named_metric_name() { + common_telemetry::init_default_ut_logging(); + let (standalone, _observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + "native_promql_tag_named_metric_name", + )) + .await; + let instance = standalone.fe_instance().clone(); + execute_all( + &instance, + r#"CREATE TABLE native_named ( + ts TIMESTAMP TIME INDEX, + "__name__" STRING, + host STRING, + val DOUBLE, + PRIMARY KEY ("__name__", host) + ); + INSERT INTO native_named VALUES (0, 'a', 'h', 1), (0, 'b', 'h', 2);"#, + QueryContext::arc(), + ) + .await; + + for query in [ + "native_named", + "sum by (__name__) (native_named)", + "count_over_time(native_named[1m])", + ] { + let sql = format!("TQL EVAL (0, 0, '1s') {query}"); + let (_, legacy_rows) = + native_labelled_rows(native_tql_output(&instance, &sql, false).await).await; + assert_eq!(legacy_rows.len(), 2, "{query}: {legacy_rows:?}"); + assert_native_decline(&instance, &sql, "tag_named_metric_name", query).await; + } +} + /// A `quantile` over one logical table, divided by a `sum` over another, answers natively and the /// rows are the existing plan's. ///