mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-26 12:44:10 +00:00
perf(promql): return a fixed plan-metrics set instead of cloning the live one (#10525)
Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -109,7 +109,7 @@ use crate::extension_plan::{RawSeriesSourceExec, SeriesRouting};
|
||||
use crate::grid_series::METADATA_LABELS;
|
||||
use crate::histogram_eval::HISTOGRAM_ROUTING_EXCLUDED_LABELS;
|
||||
use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor};
|
||||
use crate::native::metrics::{NodeMetricsSnapshot, is_node_metric};
|
||||
use crate::native::metrics::NodeMetricsSnapshot;
|
||||
use crate::native::plan::{
|
||||
AggregateStage, AggregateStateSchema, BoundInput, BoundMap, Grouping, InstantValue, MapOp,
|
||||
NativeExpr, NativeNode, NativeTree, NativeType, reads_across_series,
|
||||
@@ -2149,6 +2149,11 @@ pub struct FusedSeriesExec {
|
||||
/// Shared with the tree's own registration, which reads these figures when a reader asks for
|
||||
/// the tree: that reader outlives this borrow, and must never keep the set alive.
|
||||
metric: Arc<ExecutionPlanMetricsSet>,
|
||||
/// The fixed membership returned by `metrics()`: at construction only the `native.tree` Custom
|
||||
/// is registered; later per-partition `native.<path>.*` figures were always filtered out.
|
||||
/// If a physical operator metric is registered during execution, it must also be included here
|
||||
/// or this cache must gain invalidation; otherwise the membership regression test will fail.
|
||||
own_metrics: MetricsSet,
|
||||
format: FusedOutputFormat,
|
||||
matching_parallelism: Option<usize>,
|
||||
/// Whether this node is a partition-local canonical producer.
|
||||
@@ -2793,6 +2798,7 @@ impl FusedSeriesExec {
|
||||
));
|
||||
let metric = Arc::new(ExecutionPlanMetricsSet::new());
|
||||
register_tree_metric(&tree, &metric);
|
||||
let own_metrics = metric.clone_inner();
|
||||
Ok(Self {
|
||||
promql,
|
||||
tree,
|
||||
@@ -2808,6 +2814,7 @@ impl FusedSeriesExec {
|
||||
claimed: Vec::new(),
|
||||
}),
|
||||
metric,
|
||||
own_metrics,
|
||||
properties,
|
||||
format,
|
||||
matching_parallelism,
|
||||
@@ -2881,16 +2888,7 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
/// registers as [`NativeTreeMetric`] - so they are left out here and this node reports only what
|
||||
/// an operator of its own would add.
|
||||
fn metrics(&self) -> Option<MetricsSet> {
|
||||
let mut own = MetricsSet::new();
|
||||
for metric in self.metric.clone_inner().iter() {
|
||||
// The tree is not a figure of this node: it is what the node runs, reported on its own
|
||||
// (see `NativeTreeMetric`), so it stays here rather than being flattened into a number.
|
||||
let tree = matches!(metric.value(), MetricValue::Custom { .. });
|
||||
if tree || !is_node_metric(metric.value().name()) {
|
||||
own.push(Arc::clone(metric));
|
||||
}
|
||||
}
|
||||
Some(own)
|
||||
Some(self.own_metrics.clone())
|
||||
}
|
||||
|
||||
fn properties(&self) -> &Arc<PlanProperties> {
|
||||
|
||||
@@ -42,7 +42,9 @@ use common_query::native_histogram::NativeHistogram;
|
||||
use common_query::series_frame::{
|
||||
frame_schema_with, pack_evaluated_series, unpack_evaluated_series, unpack_raw_series,
|
||||
};
|
||||
use common_recordbatch::adapter::{NATIVE_TREE_METRIC, format_metric};
|
||||
use common_recordbatch::adapter::{
|
||||
NATIVE_TREE_METRIC, NativeTreeMetric, NativeTreeMetrics, format_metric,
|
||||
};
|
||||
use common_recordbatch::{
|
||||
EmptyRecordBatchStream, SendableRecordBatchStream as CommonSendableRecordBatchStream,
|
||||
};
|
||||
@@ -114,7 +116,7 @@ use crate::histogram_eval::HistogramFunction;
|
||||
use crate::info::InfoSelector;
|
||||
use crate::map_label::LabelRewrite;
|
||||
use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor};
|
||||
use crate::native::metrics::{NodeMetric, NodeMetricsSnapshot};
|
||||
use crate::native::metrics::{NodeMetric, NodeMetricsSnapshot, is_node_metric};
|
||||
use crate::native::plan::{
|
||||
AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, BoundInput, BoundInstant,
|
||||
BoundMap, BoundScalar, BoundVectorOp, BoundWindow, Grouping, InstantValue, MapOp, NativeExpr,
|
||||
@@ -3635,6 +3637,26 @@ impl Display for Explain<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The live tree registered in a physical operator's own metrics.
|
||||
fn native_tree(metrics: &MetricsSet) -> &NativeTreeMetric {
|
||||
metrics
|
||||
.iter()
|
||||
.find_map(|metric| match metric.value() {
|
||||
MetricValue::Custom { name, value } if name.as_ref() == NATIVE_TREE_METRIC => {
|
||||
value.as_any().downcast_ref::<NativeTreeMetric>()
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("the operator reports its native tree")
|
||||
}
|
||||
|
||||
fn tree_output_values(tree: &NativeTreeMetrics) -> usize {
|
||||
tree.metrics
|
||||
.iter()
|
||||
.find_map(|(name, value)| (name == "output_values").then_some(*value))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The logical node prints the compiled tree without metrics.
|
||||
#[test]
|
||||
fn fmt_for_explain_prints_the_native_tree() {
|
||||
@@ -3775,6 +3797,133 @@ async fn metrics_reports_no_figure_of_the_tree_it_runs() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Caching membership preserves the old filtering rule and the live tree's changing values.
|
||||
#[tokio::test]
|
||||
async fn metrics_membership_is_fixed_while_native_tree_values_change() {
|
||||
let exec = plan(rate_tree(), memory_exec(two_series_frames())).unwrap();
|
||||
let before = exec.metrics().unwrap();
|
||||
let names = |metrics: &MetricsSet| {
|
||||
metrics
|
||||
.iter()
|
||||
.map(|metric| metric.value().name().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(vec![NATIVE_TREE_METRIC.to_string()], names(&before));
|
||||
assert_eq!(0, tree_output_values(&native_tree(&before).report()));
|
||||
|
||||
let batches = collect(Arc::clone(&exec), SessionContext::default().task_ctx())
|
||||
.await
|
||||
.unwrap();
|
||||
let output_values = batches.iter().map(RecordBatch::num_rows).sum::<usize>();
|
||||
assert!(output_values > 0);
|
||||
|
||||
let after = exec.metrics().unwrap();
|
||||
assert_eq!(before.iter().count(), after.iter().count());
|
||||
assert_eq!(names(&before), names(&after));
|
||||
for (initial, current) in before.iter().zip(after.iter()) {
|
||||
assert!(Arc::ptr_eq(initial, current));
|
||||
}
|
||||
// The handle captured before execution must observe values registered afterwards, too.
|
||||
assert_eq!(
|
||||
output_values,
|
||||
tree_output_values(&native_tree(&before).report())
|
||||
);
|
||||
assert_eq!(
|
||||
output_values,
|
||||
tree_output_values(&native_tree(&after).report())
|
||||
);
|
||||
|
||||
// Compare the cached membership against the complete set using the pre-cache filtering rule.
|
||||
// This also catches a future operator metric registered during execute but omitted by the cache.
|
||||
let registered = node_metric_set(&exec);
|
||||
let formerly_reported = registered
|
||||
.iter()
|
||||
.filter(|metric| {
|
||||
matches!(metric.value(), MetricValue::Custom { .. })
|
||||
|| !is_node_metric(metric.value().name())
|
||||
})
|
||||
.map(|metric| metric.value().name().to_string())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(formerly_reported, names(&after));
|
||||
}
|
||||
|
||||
/// The complete registration and the ANALYZE tree retain figures from every execution partition.
|
||||
#[tokio::test]
|
||||
async fn native_tree_metrics_preserve_all_partitions() {
|
||||
let partitions = [1.0, 2.0, 3.0]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(partition, scale)| {
|
||||
vec![frame(&series_chunk(
|
||||
&format!("web-{partition}"),
|
||||
&series_samples(scale),
|
||||
true,
|
||||
))]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let exec = plan(rate_tree(), memory_exec_partitioned(partitions)).unwrap();
|
||||
let own = exec.metrics().unwrap();
|
||||
assert_eq!(0, tree_output_values(&native_tree(&own).report()));
|
||||
let context = SessionContext::default().task_ctx();
|
||||
|
||||
// Read the same cached handle after each partition; it must see later registrations as well.
|
||||
for partition in 0..3 {
|
||||
let batches = exec
|
||||
.execute(partition, Arc::clone(&context))
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
GRID_LEN as usize,
|
||||
batches.iter().map(RecordBatch::num_rows).sum::<usize>()
|
||||
);
|
||||
|
||||
let registered = node_metric_set(&exec);
|
||||
for completed in 0..=partition {
|
||||
let metric = registered
|
||||
.iter()
|
||||
.find(|metric| {
|
||||
metric.value().name() == "native.root.output_values"
|
||||
&& metric.partition() == Some(completed)
|
||||
})
|
||||
.expect("the complete set retains each partition's output counter");
|
||||
assert_eq!(GRID_LEN as usize, metric.value().as_usize());
|
||||
assert!(registered.iter().any(|metric| {
|
||||
metric.value().name() == "native.root.input.input_batches"
|
||||
&& metric.partition() == Some(completed)
|
||||
&& metric.value().as_usize() > 0
|
||||
}));
|
||||
assert!(registered.iter().any(|metric| {
|
||||
metric.value().name() == format!("native.p{completed}.root.peak_reserved_bytes")
|
||||
&& metric.partition() == Some(completed)
|
||||
}));
|
||||
}
|
||||
let output_values = (partition + 1) * GRID_LEN as usize;
|
||||
assert_eq!(
|
||||
output_values,
|
||||
count(®istered, "native.root.output_values")
|
||||
);
|
||||
let report = native_tree(&own).report();
|
||||
assert_eq!(output_values, tree_output_values(&report));
|
||||
// ANALYZE first aggregates operator metrics by name before reading the Custom tree.
|
||||
let analyzed = native_tree(&own.aggregate_by_name()).report();
|
||||
assert_eq!(output_values, tree_output_values(&analyzed));
|
||||
assert!(
|
||||
report.children[0]
|
||||
.metrics
|
||||
.iter()
|
||||
.any(|(name, value)| { name == "input_batches" && *value == partition + 1 })
|
||||
);
|
||||
|
||||
let text = displayable(exec.as_ref()).indent(false).to_string();
|
||||
assert!(
|
||||
tree_line(&text, "Window: rate").contains(&format!("output_values: {output_values}")),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` is one of the figures a node of a tree registered, `native.<path>.<metric>`.
|
||||
///
|
||||
/// The tree an operator runs is registered under [`NATIVE_TREE_METRIC`], which shares the prefix
|
||||
|
||||
Reference in New Issue
Block a user