feat(promql): read sub-millisecond file-engine time indexes natively (#10703)

* feat(promql): read second, microsecond and nanosecond time indexes natively

The native route declined every selector over a time index that is not
in milliseconds. The existing plan wraps such a scan in a cast
projection, so the decline surfaced as selector_plan_is_not_a_table_scan,
and the region's raw series preflight refused the unit as well.

The raw series path now hands ticks over in the stored unit, and each
raw input of the native tree records that unit. Evaluation keeps the
existing plan's semantics: windows and lookbacks are decided on the
stored ticks, a kernel reads the time truncated toward zero to
milliseconds after the offset, and samples less than a millisecond
apart remain distinct samples. Since every bound is a whole
millisecond, deciding membership on ceil(tick) in milliseconds is
exact, so the evaluators keep a window time beside the payload only for
microsecond and nanosecond inputs. Scan filters are built in the
stored unit.

Histogram fields and range modifiers over a sub-millisecond time index
still decline. The append-mode decline is kept and renamed to
append_mode_table.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): decline a discovered selector over mixed time index units

Logical metrics on different physical tables can store their time
index in different units, while the union a nameless selector reads is
one native input bound to one unit. The union took the first source's
unit and read the other sources' ticks in it, so a series stored in
microseconds next to one in milliseconds dropped out of its windows.
Such a selector now declines.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): run native PromQL over file-engine tables

File-engine tables have no raw series scanner, so the native route
declined them and they fell back to the legacy planner.

Read such a table through a new RowSeriesSource node: an ordinary scan,
filtered by the selector's matchers and time range, hash-partitioned by
tags and sorted by (tags, time index, fields), then cut into
explicit-label raw series chunks with Float64 values. The node declares
its input distribution and ordering, so the physical optimizer inserts
the repartition and a spillable SortExec. It stays above the merge scan,
so it runs on the frontend in both standalone and distributed mode.

Rows sharing labels and a timestamp keep one sample, as Prometheus
storage does: the row whose field values sort lowest (nulls last).
Non-string tags and histogram fields keep the existing plan.

The cluster test builder can now pass the local file sandbox to
datanodes and install frontend-only plugins, so the distributed case is
covered.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): read file-engine tags as Prometheus label values

A row source now reads every tag column as text with NULL read as '',
so a NULL and an empty tag are one series from the start and an empty
value carries no label, as in Prometheus. Rows of that series at one
timestamp keep one sample by the existing rule. Matchers apply to the
text form above the scan, so an integer tag matches "200" but not
"0200". This drops the row_source_tag_is_not_a_string decline.

The legacy planner fails on such a table with "Unsupported tag column
type: Int64".

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): read native histogram fields from file-engine tables

A row source passes a native histogram field on as histogram samples,
converted with the same histogram_samples_from_arrow the mito raw scan
uses, instead of casting every field to Float64. This drops the
row_source_reads_floats_only decline, so the fixture of the sqlness
case promql/delta_exponential_histogram runs natively; the integration
test mirrors its statements and answers.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): read second-precision file-engine time indexes natively

The existing scan plan already promotes a second-precision time index to
milliseconds through a projection, which is exact. A row source now
reads that projection instead of declining, and pushes the time range
into the scan only when the scan's time index is in milliseconds.
Microsecond and nanosecond time indexes still keep the existing plan.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): decline file-engine tables with a `__name__` tag column

A row source dropped a tag column named `__name__` from its labels, sort
key and partition key, so rows that differed only in that column merged
into one series and lost samples. Mito's raw scan refuses such a tag.
Decline it at planning time instead, and make RowSeriesSource reject the
tag rather than filter it out.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): dedupe file-engine samples per field

A row source reduced rows sharing labels and a timestamp to one whole
row picked by the first field, so a NULL in another field of that row
dropped the value a discarded row held there. Each field is its own
value series: at a duplicated timestamp every field now keeps its own
lowest non-null value (NaN above numbers, histograms by struct order).

The sort key drops the fields, and the rows of the last timestamp of a
batch are held back until the next batch, so every duplicated timestamp
is reduced within one batch.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): read microsecond and nanosecond file-engine time indexes natively

A row source read its time index through the existing plan's cast to
milliseconds, which truncates a finer one, so it declined microsecond
and nanosecond time indexes.

It now reads the column as stored, as the raw series scan does, and the
input it feeds is bound to the time index's unit. Evaluation then
follows the rules mito tables already have: windows and lookbacks are
decided on the stored ticks, a kernel reads the time truncated to
milliseconds, and samples less than a millisecond apart stay distinct.
Histogram fields and range modifiers over such a time index decline as
they do for mito. The time range is pushed into the scan in the stored
unit for pruning. A second-precision time index takes the same path.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): decline every table with a `__name__` tag column

The native route names each series it reads by its table and has no
label to read a tag column named `__name__` as. Only file-engine tables
were declined; a mito table with such a column ran natively and lost
the column: two series that differ only in it came back as two rows
with one label set, and `sum by (__name__)` folded them into one. The
existing plan reads the column's values as the metric name instead.

Such a schema has no Prometheus reading: a series has one `__name__`,
and the table name already is the metric name. Decline it on every
engine so the statement keeps the existing plan's answer.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): keep a window open until its last millisecond has been read

A sample finer than a millisecond is placed in the window ending at the
millisecond above it. A chunk that ends on such a sample has not read
the rest of that millisecond, so treating that millisecond as settled
closed the window before a later sample in the same millisecond arrived
in the next chunk. Settle only up to the millisecond the last sample lies
in, rounded down.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): select only an exact sample under a zero lookback

A zero lookback admits only a sample exactly at the instant. The window
time of a sample less than a millisecond before the instant rounds up to
the instant, so the native selection picked it where the existing route
returns nothing. Compare the stored tick with the instant when the
lookback is zero, on the grid and anchored paths.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): cover zero lookback on microsecond and nanosecond file-engine tables

A zero lookback selects only a sample stored exactly at the instant. A
row source hands its time index over as stored, so a sample 0.5ms before
the instant shares that instant's window time and was selected. The
exact-match rule from the time index precision branch covers the row
source as well; these cases pin it for file-engine tables in both
precisions and check that legacy gives the same answer.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): cover a stale marker in the second field of a wide file-engine table

A Parquet file-engine table with a microsecond time index and two DOUBLE
fields: a row whose first field is valid and whose second holds a stale
marker is selected on both routes, and a row stale in the first field is
dropped on both, as the existing plan reads staleness from the first field
only.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
dennis zhuang
2026-12-02 04:32:09 +00:00
committed by GitHub
parent 66ef0e3d67
commit 4d44909217
4 changed files with 362 additions and 92 deletions
@@ -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::<DataFusionResult<Vec<_>>>()?;
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::<DataFusionResult<Vec<StringArray>>>()?;
let time = batch
.column(self.columns.time)
.as_primitive_opt::<TimestampMillisecondType>()
.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<u32>],
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::<TimestampMillisecondType>()
.values()
.clone(),
)
.map_err(|error| DataFusionError::External(Box::new(error)))?;
let time = RawTimestamps::try_new(time.as_primitive::<Int64Type>().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;
+55 -61
View File
@@ -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::<RowSeriesSource>()
{
// 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<LogicalPlan, DataFusionError> {
) -> 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.
@@ -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<String>, offset_secs: i64, expected: Vec<Row>) -> C
end: BASE_SECS + offset_secs,
expected,
legacy_differs: false,
lookback: None,
}
}
@@ -214,6 +226,7 @@ fn metric_cases(table: &str) -> Vec<Case> {
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<Case> {
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<Case> {
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<Case> {
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<Case> {
.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<Instance>, 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<Instance>, 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<Instance>, 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<Instance>, dir: &std::path::Path) {
}
async fn run(instance: &Arc<Instance>, case: &Case, native: bool) -> Result<Vec<Row>, 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<Instance>, 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<Instance>, 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<Instance>,
sql: &str,
native: bool,
) -> Vec<(i64, Vec<String>, Vec<String>)> {
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::<Int64Array>().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<Instance>, 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::<Vec<_>>();
assert_eq!(vec!["host=b_stale"], hosts, "`{query}`");
}
}
fn observer_plugins() -> (Arc<PlanObserver>, 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;
}
@@ -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.
///