mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 13:44:03 +00:00
fix(promql): reconcile a discovered union of raw series
A nameless selector reads its matches as one `Union`, and `UnionExec` reports the frame metadata of its last child. A time-partitioned metric sorted before a host-partitioned one therefore looked contiguous, and the fused node skipped the reconciliation of the fragmented member's series, silently folding region fragments as separate series. Lower the declaration on the fused edge to the weakest ordering any member declares, before the fused node reads it. The union itself is unchanged; the fused node's existing interleaved-input path inserts the router. A projection carries the lowered declaration because the pinned physical planner ignores a union's own schema. Cover it with a planner regression for both member orders and an all-complete control, and with a real two-datanode acceptance case that mixes a time-partitioned and a host-partitioned metric and checks the extrapolated increase per series. Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -22,6 +22,10 @@ use datafusion::error::{DataFusionError, Result as DfResult};
|
||||
use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
|
||||
use datafusion::logical_expr::{LogicalPlan, UserDefinedLogicalNode};
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datafusion::physical_plan::PhysicalExpr;
|
||||
use datafusion::physical_plan::expressions::Column;
|
||||
use datafusion::physical_plan::projection::ProjectionExec;
|
||||
use datafusion::physical_plan::union::UnionExec;
|
||||
use datafusion::physical_planner::{ExtensionPlanner, PhysicalPlanner};
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::frame::{FrameLabelMode, SeriesFrameDeclaration};
|
||||
@@ -122,7 +126,11 @@ fn plan_fused_series(
|
||||
.to_execution_plan_with_parallelism(Vec::new(), target_partitions)
|
||||
.map(Some);
|
||||
}
|
||||
if let Some(inputs) = physical_inputs
|
||||
let explicit_inputs = physical_inputs
|
||||
.iter()
|
||||
.map(normalize_raw_union)
|
||||
.collect::<DfResult<Vec<_>>>()?;
|
||||
if let Some(inputs) = explicit_inputs
|
||||
.iter()
|
||||
.map(|input| {
|
||||
explicit_label_frame_ordering(input.schema().as_ref())
|
||||
@@ -250,6 +258,65 @@ fn series_scan(
|
||||
}
|
||||
|
||||
/// The ordering an input declares when it produces raw frames that carry their own labels.
|
||||
/// Restate a raw union's ordering as the weakest guarantee its members make.
|
||||
///
|
||||
/// `UnionExec` reports the frame metadata of its last child, so a fragmented member beside one
|
||||
/// whose series are complete can look contiguous, and the fused node would skip the reconciliation
|
||||
/// of the fragments. The union itself is not rewritten; only the declaration on this edge is
|
||||
/// lowered, and the fused node's own interleaved-input path inserts the router.
|
||||
fn normalize_raw_union(input: &Arc<dyn ExecutionPlan>) -> DfResult<Arc<dyn ExecutionPlan>> {
|
||||
let Some(union) = input.downcast_ref::<UnionExec>() else {
|
||||
return Ok(Arc::clone(input));
|
||||
};
|
||||
if explicit_label_frame_ordering(input.schema().as_ref()) != Some(SeriesOrdering::Contiguous)
|
||||
|| weakest_union_ordering(union) != SeriesOrdering::Interleaved
|
||||
{
|
||||
return Ok(Arc::clone(input));
|
||||
}
|
||||
let mut metadata = input.schema().metadata().clone();
|
||||
metadata.insert(RAW_SERIES_ORDERING_KEY.into(), "interleaved".into());
|
||||
let schema = Arc::new(Schema::new_with_metadata(
|
||||
input.schema().fields().clone(),
|
||||
metadata,
|
||||
));
|
||||
let exprs = input
|
||||
.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, field)| {
|
||||
(
|
||||
Arc::new(Column::new(field.name(), index)) as Arc<dyn PhysicalExpr>,
|
||||
field.name().clone(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(Arc::new(ProjectionExec::try_new_with_schema_metadata(
|
||||
exprs,
|
||||
Arc::clone(input),
|
||||
schema.as_ref(),
|
||||
)?))
|
||||
}
|
||||
|
||||
/// The schema metadata key a frame's ordering is declared under; see
|
||||
/// [`common_query::series_frame`].
|
||||
const RAW_SERIES_ORDERING_KEY: &str = "greptime.series.ordering";
|
||||
|
||||
/// The weakest ordering any member of this union declares. A member that is itself a union is
|
||||
/// asked the same question; a member that already reconciles keeps its own guarantee.
|
||||
fn weakest_union_ordering(union: &UnionExec) -> SeriesOrdering {
|
||||
union
|
||||
.children()
|
||||
.iter()
|
||||
.map(|child| match child.downcast_ref::<UnionExec>() {
|
||||
Some(nested) => weakest_union_ordering(nested),
|
||||
None => explicit_label_frame_ordering(child.schema().as_ref())
|
||||
.unwrap_or(SeriesOrdering::Contiguous),
|
||||
})
|
||||
.find(|ordering| *ordering == SeriesOrdering::Interleaved)
|
||||
.unwrap_or(SeriesOrdering::Contiguous)
|
||||
}
|
||||
|
||||
fn explicit_label_frame_ordering(schema: &Schema) -> Option<SeriesOrdering> {
|
||||
let declaration = SeriesFrameDeclaration::parse(schema).ok()?;
|
||||
if declaration.labels() != FrameLabelMode::Explicit {
|
||||
@@ -257,3 +324,79 @@ fn explicit_label_frame_ordering(schema: &Schema) -> Option<SeriesOrdering> {
|
||||
}
|
||||
series_frame_ordering(schema).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_query::series_frame::{
|
||||
raw_series_frame_schema_with_ordering, series_frame_ordering,
|
||||
};
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datafusion::physical_plan::empty::EmptyExec;
|
||||
use datafusion::physical_plan::union::UnionExec;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
|
||||
use super::normalize_raw_union;
|
||||
|
||||
fn raw_frame(ordering: SeriesOrdering) -> Arc<datafusion::arrow::datatypes::Schema> {
|
||||
let series = SeriesSchema {
|
||||
fields: vec![FieldSpec {
|
||||
name: Arc::from("val"),
|
||||
}]
|
||||
.into(),
|
||||
eval_grid: None,
|
||||
};
|
||||
raw_series_frame_schema_with_ordering(
|
||||
&series,
|
||||
&store_api::region_engine::RawLabelSource::Explicit,
|
||||
ordering,
|
||||
)
|
||||
.expect("a raw schema declares an explicit-label frame")
|
||||
}
|
||||
|
||||
fn union(children: &[SeriesOrdering]) -> Arc<dyn ExecutionPlan> {
|
||||
let children = children
|
||||
.iter()
|
||||
.map(|ordering| {
|
||||
Arc::new(EmptyExec::new(raw_frame(*ordering))) as Arc<dyn ExecutionPlan>
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
UnionExec::try_new(children).expect("two framed children")
|
||||
}
|
||||
|
||||
/// A union reports the ordering of its last child. The declaration this edge hands to the
|
||||
/// fused node must instead be the weakest of the members, in either order, and must stay the
|
||||
/// union's own when every member is complete.
|
||||
#[test]
|
||||
fn raw_union_declaration_lowers_to_the_weakest_member() {
|
||||
for members in [
|
||||
vec![SeriesOrdering::Interleaved, SeriesOrdering::Contiguous],
|
||||
vec![SeriesOrdering::Contiguous, SeriesOrdering::Interleaved],
|
||||
] {
|
||||
let union = union(&members);
|
||||
assert_eq!(
|
||||
series_frame_ordering(union.schema().as_ref()).unwrap(),
|
||||
*members.last().unwrap(),
|
||||
"the union itself keeps its last child's declaration"
|
||||
);
|
||||
let normalized =
|
||||
normalize_raw_union(&Arc::clone(&union)).expect("a raw union normalizes");
|
||||
assert_eq!(
|
||||
series_frame_ordering(normalized.schema().as_ref()).unwrap(),
|
||||
SeriesOrdering::Interleaved,
|
||||
"the fused edge sees the weakest member"
|
||||
);
|
||||
}
|
||||
|
||||
let union = union(&[SeriesOrdering::Contiguous, SeriesOrdering::Contiguous]);
|
||||
let normalized = normalize_raw_union(&(Arc::clone(&union) as Arc<dyn ExecutionPlan>))
|
||||
.expect("a raw union normalizes");
|
||||
assert_eq!(
|
||||
series_frame_ordering(normalized.schema().as_ref()).unwrap(),
|
||||
SeriesOrdering::Contiguous,
|
||||
"nothing is lowered when every member is complete"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,9 +192,9 @@ impl DatafusionQueryEngine {
|
||||
// A region read is a remote body that streams until drained, so a query reading several
|
||||
// sources would otherwise run one body per source and partition. Bound the reads of the
|
||||
// plan shape that can hold the budget: the native raw PromQL topology, whose only
|
||||
// multi-input node polls every input at once. A plan that can wait for one input while
|
||||
// another holds a permit (any join, or a union drained input by input) is left unbounded
|
||||
// rather than risk a body budget deadlocking it.
|
||||
// multi-input node polls every input at once. A plan with any other multi-input node (a
|
||||
// join, or the union a discovered selector builds) keeps its per-scan bounds only rather
|
||||
// than take a query-wide budget its topology has not been checked against.
|
||||
if crate::promql::planner::native::native_raw_plan_bounds_region_reads(&physical_plan) {
|
||||
let target_partitions = ctx.state().config().target_partitions();
|
||||
ctx.config_mut()
|
||||
|
||||
@@ -138,10 +138,10 @@ fn plans_over_remote_regions(query_engine_state: &QueryEngineState) -> bool {
|
||||
/// region reads one query-wide body budget cannot deadlock.
|
||||
///
|
||||
/// That topology is a single [`FusedSeriesExec`]: it polls every input at once, so a region body
|
||||
/// holding a permit is always still being drained, whether it reads one source or several. Any
|
||||
/// other node with several inputs -- a join, or a union drained input by input -- can wait for one
|
||||
/// input while another holds a permit, which no permit count resolves, so such plans keep reading
|
||||
/// unbounded.
|
||||
/// holding a permit is always still being drained, whether it reads one source or several.
|
||||
/// Admission stops there: a plan with any other multi-input node (a join, or the union a
|
||||
/// discovered selector builds) keeps its per-scan bounds only and is not counted against the
|
||||
/// query-wide target until its own topology is checked against the budget.
|
||||
pub(crate) fn native_raw_plan_bounds_region_reads(plan: &Arc<dyn ExecutionPlan>) -> bool {
|
||||
fn walk(node: &dyn ExecutionPlan, fused: &mut usize) -> bool {
|
||||
let is_fused = node.is::<FusedSeriesExec>();
|
||||
|
||||
@@ -1945,6 +1945,57 @@ async fn collect_error(output: Output) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`native_result_rows`], with both label columns of the discovery fixture.
|
||||
async fn native_site_rows(output: Output) -> Vec<(i64, String, String, f64)> {
|
||||
let batches = match output.data {
|
||||
OutputData::Stream(stream) => collect_batches(stream).await.unwrap(),
|
||||
OutputData::RecordBatches(batches) => batches,
|
||||
_ => unreachable!("TQL EVAL returns record batches"),
|
||||
};
|
||||
let mut rows = batches
|
||||
.iter()
|
||||
.flat_map(|batch| {
|
||||
let timestamps = batch
|
||||
.column_by_name("ts")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<TimestampMillisecondArray>()
|
||||
.unwrap();
|
||||
let host = cast(
|
||||
batch.column_by_name("host").unwrap().as_ref(),
|
||||
&DataType::Utf8,
|
||||
)
|
||||
.unwrap();
|
||||
let host = host.as_any().downcast_ref::<StringArray>().unwrap();
|
||||
let site = cast(
|
||||
batch.column_by_name("site").unwrap().as_ref(),
|
||||
&DataType::Utf8,
|
||||
)
|
||||
.unwrap();
|
||||
let site = site.as_any().downcast_ref::<StringArray>().unwrap();
|
||||
let values = batch
|
||||
.columns()
|
||||
.iter()
|
||||
.filter(|column| column.data_type() == &DataType::Float64)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(values.len(), 1, "expected one Float64 value column");
|
||||
let values = values[0].as_any().downcast_ref::<Float64Array>().unwrap();
|
||||
(0..batch.num_rows())
|
||||
.map(|row| {
|
||||
(
|
||||
timestamps.value(row),
|
||||
host.value(row).to_string(),
|
||||
site.value(row).to_string(),
|
||||
values.value(row),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
rows.sort_by(|left, right| left.partial_cmp(right).unwrap());
|
||||
rows
|
||||
}
|
||||
|
||||
async fn native_result_rows(output: Output) -> Vec<(i64, String, f64)> {
|
||||
let batches = match output.data {
|
||||
OutputData::Stream(stream) => collect_batches(stream).await.unwrap(),
|
||||
@@ -3074,6 +3125,126 @@ async fn distributed_native_promql_disjoint_regions_do_not_repartition() {
|
||||
assert_eq!(control_rows, rows, "{expression}");
|
||||
}
|
||||
|
||||
/// A nameless selector discovers every metric table it matches and reads them as one `Union`.
|
||||
/// `UnionExec` reports the frame metadata of its last child, so a time-partitioned metric named
|
||||
/// before a host-partitioned one must still be reconciled: otherwise the union claims contiguous
|
||||
/// order and `increase` folds each region fragment as its own series.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn distributed_native_promql_metric_discovery_reconciles_mixed_ordering() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let cluster = GreptimeDbClusterBuilder::new("distributed_native_promql_discovery")
|
||||
.await
|
||||
.with_datanodes(2)
|
||||
.with_real_datanode_grpc_addr(true)
|
||||
.with_frontend_real_datanode_grpc(true)
|
||||
.with_query_options(QueryOptions {
|
||||
experimental_native_promql: true,
|
||||
..Default::default()
|
||||
})
|
||||
.build(false)
|
||||
.await;
|
||||
let instance = cluster.fe_instance().clone();
|
||||
// The names sort so the contiguous (host-partitioned) metric is the union's last child, which
|
||||
// is exactly the ordering a union would otherwise claim for the whole input.
|
||||
execute_all(
|
||||
&instance,
|
||||
"CREATE TABLE dist_native_disc_a_frag_phy (host STRING, site STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host, site)) PARTITION ON COLUMNS (ts) (ts < '1970-01-01 00:02:00', ts >= '1970-01-01 00:02:00' AND ts < '1970-01-01 00:04:00', ts >= '1970-01-01 00:04:00') ENGINE=metric WITH ('physical_metric_table'='true')",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
execute_all(
|
||||
&instance,
|
||||
"CREATE TABLE dist_native_disc_z_wide_phy (host STRING, site STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host, site)) PARTITION ON COLUMNS (host) (host < 'm', host >= 'm') ENGINE=metric WITH ('physical_metric_table'='true')",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
// Both metrics carry the same samples under their own `site`, so each contributes the same
|
||||
// increase and the two rows stay distinct after the metric name is folded away.
|
||||
for (table, physical, site) in [
|
||||
(
|
||||
"dist_native_disc_a_frag",
|
||||
"dist_native_disc_a_frag_phy",
|
||||
"left",
|
||||
),
|
||||
(
|
||||
"dist_native_disc_z_wide",
|
||||
"dist_native_disc_z_wide_phy",
|
||||
"right",
|
||||
),
|
||||
] {
|
||||
execute_all(
|
||||
&instance,
|
||||
&format!(
|
||||
"CREATE TABLE {table} (host STRING, site STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host, site)) ENGINE=metric WITH ('on_physical_table'='{physical}')"
|
||||
),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
execute_all(
|
||||
&instance,
|
||||
&format!(
|
||||
"INSERT INTO {table} (host, site, val, ts) VALUES ('a', '{site}', 2, 60000), ('a', '{site}', 4, 120000), ('a', '{site}', 6, 180000), ('a', '{site}', 8, 240000)"
|
||||
),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let query = PromQuery {
|
||||
query: r#"sum by (host, site) (increase({host="a"}[5m]))"#.to_string(),
|
||||
start: "180".to_string(),
|
||||
end: "240".to_string(),
|
||||
step: "60s".to_string(),
|
||||
..PromQuery::default()
|
||||
};
|
||||
cluster.reset_network_do_get_peak();
|
||||
let output = instance
|
||||
.do_promql_query(&query, native_query_context(true, 2))
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap();
|
||||
let plan = output.meta.plan.as_ref().expect("frontend physical plan");
|
||||
let shape = native_plan_shape(plan);
|
||||
assert_eq!(shape.fused, 1, "discovery stays native: {plan:?}");
|
||||
assert_eq!(
|
||||
shape.routers_below_fused, 1,
|
||||
"the fused node reconciles the lowered union exactly once: {plan:?}"
|
||||
);
|
||||
assert!(
|
||||
shape
|
||||
.scan_orderings
|
||||
.iter()
|
||||
.any(|ordering| ordering.as_deref() == Some("interleaved")),
|
||||
"the time-partitioned scan declares fragments: {:?}: {plan:?}",
|
||||
shape.scan_orderings
|
||||
);
|
||||
assert!(
|
||||
shape
|
||||
.scan_orderings
|
||||
.iter()
|
||||
.any(|ordering| ordering.as_deref() == Some("contiguous")),
|
||||
"the host-partitioned scan declares complete series: {:?}: {plan:?}",
|
||||
shape.scan_orderings
|
||||
);
|
||||
let rows = native_site_rows(output).await;
|
||||
// `increase` extrapolates the 2,4,6 window to the 5m boundary, as the cross-region fixture
|
||||
// also expects: each metric contributes 5 at 180s and 7 at 240s, under its own `site`.
|
||||
let expected = vec![
|
||||
(180_000, "a".to_string(), "left".to_string(), 5.0),
|
||||
(180_000, "a".to_string(), "right".to_string(), 5.0),
|
||||
(240_000, "a".to_string(), "left".to_string(), 7.0),
|
||||
(240_000, "a".to_string(), "right".to_string(), 7.0),
|
||||
];
|
||||
assert_eq!(expected, rows);
|
||||
assert_eq!(cluster.network_do_get_active(), 0, "every body is drained");
|
||||
// The discovered union feeds one reader per member partition: two from the time-partitioned
|
||||
// metric and one from the host-partitioned metric. That is the per-scan bound summed: the
|
||||
// query-wide budget is installed only for the single-fused plan, and a plan with a union is
|
||||
// not counted against it.
|
||||
let peak = cluster.network_do_get_peak_active();
|
||||
assert!((1..=3).contains(&peak), "region reads stay bounded: {peak}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn native_promql_label_rewrites_reach_the_native_route_and_keep_prometheus_answers() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
|
||||
Reference in New Issue
Block a user