mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 13:44:03 +00:00
feat(query): execute native raw promql over real datanodes
Plan a whole native statement as one fused node over raw series sources when the frontend reaches regions over the wire, including single-selector statements, while keeping the in-process split and segment shapes unchanged. Validate the whole tree with the runtime constructor before committing to that plan, so unsupported shapes still fall back to the legacy route. Bound the region reads of that topology with a query-wide permit budget of target_partitions, held until each region body is drained; other plan shapes keep unbounded reads rather than risk a body budget they could deadlock. Acceptance on a real two-datanode cluster with TCP frontend clients: time-partitioned series are reconciled before the fused node and match the unpartitioned control, with the DoGet peak at the target bound; series that no region shares keep contiguous per-series order and reach the fused node without a reconciling router. Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -8047,127 +8047,6 @@ async fn histogram_state_router_dispatches_each_row_of_a_packed_batch() {
|
||||
},
|
||||
true,
|
||||
))
|
||||
assert_eq!(&[1, 2], &chunk.time.as_buffer()[..]);
|
||||
assert!(chunk.is_last);
|
||||
assert!(
|
||||
futures::future::poll_fn(|cx| Pin::new(&mut stream).poll_next(cx))
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
drop(stream);
|
||||
wait_until("raw owner releases memory", || pool.reserved() == 0).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_interleaved_deduplicates_identical_overlaps_and_rejects_conflicts() {
|
||||
for (later, expect_error) in [(1.0, false), (9.0, true)] {
|
||||
let child = RawScripted::plan_with_ordering(
|
||||
vec![RawPartition {
|
||||
chunks: vec![
|
||||
raw_chunk("a", Some(raw_metric("a")), &[1], vec![Some(1.0)], true),
|
||||
raw_chunk("b", Some(raw_metric("b")), &[1], vec![Some(2.0)], true),
|
||||
raw_chunk("a", Some(raw_metric("a")), &[1], vec![Some(later)], true),
|
||||
],
|
||||
gate: None,
|
||||
gate_chunks: false,
|
||||
}],
|
||||
SeriesOrdering::Interleaved,
|
||||
);
|
||||
let plan = raw_node(child, 1);
|
||||
let pool = Arc::new(GreedyMemoryPool::new(8 << 20));
|
||||
let context = task_context(&pool);
|
||||
let (chunks, error) = drain_raw(&plan, &context).await;
|
||||
if expect_error {
|
||||
assert!(chunks.is_empty(), "a conflicting identity is not published");
|
||||
assert!(
|
||||
error
|
||||
.expect("conflicting values are rejected")
|
||||
.to_string()
|
||||
.contains("duplicate raw timestamp has conflicting samples")
|
||||
);
|
||||
} else {
|
||||
assert!(error.is_none());
|
||||
let a: Vec<_> = chunks
|
||||
.iter()
|
||||
.filter(|chunk| chunk.primary_key.as_slice() == b"a")
|
||||
.collect();
|
||||
let times: Vec<_> = a
|
||||
.iter()
|
||||
.flat_map(|chunk| chunk.time.as_buffer().iter().copied())
|
||||
.collect();
|
||||
assert_eq!(times, [1]);
|
||||
assert!(matches!(
|
||||
a[0].fields.get(0).unwrap().sample(0),
|
||||
datatypes::series::samples::SampleRef::Float(value) if value == 1.0
|
||||
));
|
||||
assert_eq!(1, a.iter().filter(|chunk| chunk.is_last).count());
|
||||
assert!(
|
||||
chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk.primary_key.as_slice() == b"b")
|
||||
);
|
||||
}
|
||||
wait_until("raw merge releases memory", || pool.reserved() == 0).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_interleaved_complete_disjoint_is_rejected() {
|
||||
let child = RawScripted::plan_with_ordering(
|
||||
vec![RawPartition {
|
||||
chunks: vec![],
|
||||
gate: None,
|
||||
gate_chunks: false,
|
||||
}],
|
||||
SeriesOrdering::Interleaved,
|
||||
);
|
||||
let error = SeriesRepartitionExec::try_new_complete_disjoint(child, 1)
|
||||
.expect_err("interleaved raw identities cannot be disjoint chains");
|
||||
assert!(error.to_string().contains("CompleteDisjoint"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_interleaved_late_error_and_cancellation_release_retained_groups() {
|
||||
for cancel in [false, true] {
|
||||
let gate = Arc::new(Switch::default());
|
||||
let child = RawScripted::plan_with_ordering_and_failure(
|
||||
vec![RawPartition {
|
||||
chunks: vec![
|
||||
raw_chunk("a", Some(raw_metric("a")), &[1], vec![Some(1.0)], true),
|
||||
raw_chunk("b", Some(raw_metric("b")), &[1], vec![Some(2.0)], true),
|
||||
raw_chunk("a", Some(raw_metric("a")), &[2], vec![Some(3.0)], true),
|
||||
],
|
||||
gate: Some(Arc::clone(&gate)),
|
||||
gate_chunks: false,
|
||||
}],
|
||||
SeriesOrdering::Interleaved,
|
||||
true,
|
||||
);
|
||||
let plan = raw_node(child, 1);
|
||||
let pool = Arc::new(GreedyMemoryPool::new(8 << 20));
|
||||
let context = task_context(&pool);
|
||||
let mut stream = plan.execute(0, context).unwrap();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(200), stream.next())
|
||||
.await
|
||||
.is_err(),
|
||||
"no identity may precede the late error or cancellation"
|
||||
);
|
||||
assert!(pool.reserved() > 0, "the pending groups remain charged");
|
||||
if cancel {
|
||||
drop(stream);
|
||||
} else {
|
||||
gate.open();
|
||||
let error = match stream.next().await {
|
||||
Some(Err(error)) => error,
|
||||
_ => panic!("late error must precede every output"),
|
||||
};
|
||||
assert!(error.to_string().contains("late raw scripted failure"));
|
||||
assert!(stream.next().await.is_none());
|
||||
drop(stream);
|
||||
}
|
||||
wait_until("interleaved raw input releases memory", || {
|
||||
pool.reserved() == 0
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut packed = common_query::series_frame::pack_aggregate_state(
|
||||
|
||||
@@ -75,6 +75,7 @@ use crate::options::ScheduledTimeExtension;
|
||||
use crate::physical_wrapper::PhysicalPlanWrapperRef;
|
||||
use crate::planner::{DfLogicalPlanner, LogicalPlanner};
|
||||
use crate::query_engine::{DescribeResult, QueryEngineContext, QueryEngineState};
|
||||
use crate::region_query::RegionReadLimiter;
|
||||
use crate::{QueryEngine, metrics};
|
||||
|
||||
/// Query parallelism hint key.
|
||||
@@ -188,6 +189,18 @@ impl DatafusionQueryEngine {
|
||||
physical_plan
|
||||
};
|
||||
|
||||
// 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.
|
||||
if crate::promql::planner::native::native_raw_plan_bounds_region_reads(&physical_plan) {
|
||||
let target_partitions = ctx.state().config().target_partitions();
|
||||
ctx.config_mut()
|
||||
.set_extension(Arc::new(RegionReadLimiter::new(target_partitions)));
|
||||
}
|
||||
|
||||
let stream = self.execute_stream(&ctx, &physical_plan)?;
|
||||
|
||||
Ok(Output::new(
|
||||
|
||||
@@ -77,7 +77,7 @@ use crate::dist_plan::{
|
||||
use crate::metrics::{MERGE_SCAN_ERRORS_TOTAL, MERGE_SCAN_POLL_ELAPSED, MERGE_SCAN_REGIONS};
|
||||
use crate::options::{FlowQueryExtensions, remote_dyn_filter_pushdown_enabled_from_extensions};
|
||||
use crate::query_engine::QueryEngineState;
|
||||
use crate::region_query::RegionQueryHandlerRef;
|
||||
use crate::region_query::{RegionQueryHandlerRef, RegionReadLimiter};
|
||||
|
||||
fn query_engine_state_from_task_context(context: &TaskContext) -> Option<Arc<QueryEngineState>> {
|
||||
context.session_config().get_extension()
|
||||
@@ -670,6 +670,10 @@ impl MergeScanExec {
|
||||
&query_ctx,
|
||||
&captured_remote_dyn_filters,
|
||||
);
|
||||
// The query's own bound on region reads in flight; see [`RegionReadLimiter`].
|
||||
let region_read_limiter = context
|
||||
.session_config()
|
||||
.get_extension::<RegionReadLimiter>();
|
||||
|
||||
let stream = Box::pin(stream!({
|
||||
let remote_dyn_filter_registry_lease = remote_dyn_filter_registry_lease;
|
||||
@@ -757,6 +761,12 @@ impl MergeScanExec {
|
||||
);
|
||||
}
|
||||
|
||||
// Hold the permit until this region's body is drained or dropped: the bound
|
||||
// counts reads in flight, whichever scan or partition started them.
|
||||
let _region_read_permit = match region_read_limiter.as_ref() {
|
||||
Some(limiter) => Some(limiter.acquire().await),
|
||||
None => None,
|
||||
};
|
||||
let do_get_start = Instant::now();
|
||||
let do_get_result = region_query_handler
|
||||
.do_get(&target, request)
|
||||
|
||||
@@ -49,6 +49,7 @@ use datafusion::logical_expr::UserDefinedLogicalNode;
|
||||
use datafusion::logical_expr::{
|
||||
EmptyRelation, Extension, LogicalPlan, LogicalPlanBuilder, TableScanBuilder, Union,
|
||||
};
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datafusion::prelude::Expr as DfExpr;
|
||||
use datafusion_expr::Expr;
|
||||
use datatypes::data_type::DataType as _;
|
||||
@@ -56,8 +57,8 @@ use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use datatypes::series::time::EvalGrid;
|
||||
use promql::extension_plan::{
|
||||
FieldKind, FusedOutputFormat, FusedSeries, FusedSeriesBinding, InputLocality, RawSeriesSource,
|
||||
input_locality, matching_operands_drop_key, tree_source_fields,
|
||||
FieldKind, FusedOutputFormat, FusedSeries, FusedSeriesBinding, FusedSeriesExec, InputLocality,
|
||||
RawSeriesSource, input_locality, matching_operands_drop_key, tree_source_fields,
|
||||
};
|
||||
use promql::native::execute::NativeExecutionState;
|
||||
use promql::native::plan::{
|
||||
@@ -108,6 +109,57 @@ pub(crate) fn native_promql_requested(query_ctx: &QueryContextRef) -> bool {
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("true"))
|
||||
}
|
||||
|
||||
/// The analyzer rule an engine that plans distributed statements installs on its session; see
|
||||
/// [`DistPlannerAnalyzer`](crate::dist_plan::analyzer::DistPlannerAnalyzer).
|
||||
const DIST_PLANNER_RULE: &str = "DistPlannerAnalyzer";
|
||||
|
||||
/// Whether a plan built here is split into a frontend plan over regions reached over the wire.
|
||||
///
|
||||
/// This is the one condition under which every scan this route prepares has to be a
|
||||
/// [`RawSeriesSource`]. The remote transport carries a region's half as Substrait bytes, which can
|
||||
/// only encode that source, so over the wire the single fused node over raw sources is the only
|
||||
/// shape admitted; in process a region accepts a `LogicalPlan` and the split and segmented shapes
|
||||
/// keep running region-locally, so those stay and this returns `false`.
|
||||
///
|
||||
/// An engine that plans no distributed statement plans no region at all, and its plans are the
|
||||
/// standalone ones: it installs the distributed planner as an analyzer rule exactly when it was
|
||||
/// built to split statements, so the rule says whether this engine has a region to satisfy.
|
||||
fn plans_over_remote_regions(query_engine_state: &QueryEngineState) -> bool {
|
||||
!query_engine_state.in_process_region_transport()
|
||||
&& query_engine_state
|
||||
.session_state()
|
||||
.analyzer()
|
||||
.rules
|
||||
.iter()
|
||||
.any(|rule| rule.name() == DIST_PLANNER_RULE)
|
||||
}
|
||||
|
||||
/// Whether this executable plan is the native raw PromQL topology, the one plan shape whose
|
||||
/// 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.
|
||||
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>();
|
||||
if is_fused {
|
||||
*fused += 1;
|
||||
}
|
||||
if node.children().len() > 1 && !is_fused {
|
||||
return false;
|
||||
}
|
||||
node.children()
|
||||
.iter()
|
||||
.all(|child| walk(child.as_ref(), fused))
|
||||
}
|
||||
|
||||
let mut fused = 0;
|
||||
walk(plan.as_ref(), &mut fused) && fused == 1
|
||||
}
|
||||
|
||||
/// The ordering this route compiles its trees against.
|
||||
///
|
||||
/// Which ordering a raw-series scan declares is decided when the region scanner is prepared, during
|
||||
@@ -176,9 +228,13 @@ impl PromPlanner {
|
||||
pub(super) async fn try_plan_native_operand(
|
||||
&mut self,
|
||||
expr: &PromExpr,
|
||||
query_engine_state: &QueryEngineState,
|
||||
) -> Result<Option<(LogicalPlan, super::PromPlannerContext)>> {
|
||||
let saved = self.ctx.clone();
|
||||
let (plan, operand_ctx) = match self.try_plan_native_fused_with_context(expr).await? {
|
||||
let (plan, operand_ctx) = match self
|
||||
.try_plan_native_fused_with_context(expr, query_engine_state)
|
||||
.await?
|
||||
{
|
||||
Some((plan, Some(operand_ctx))) => (plan, operand_ctx),
|
||||
_ => {
|
||||
self.ctx = saved;
|
||||
@@ -213,6 +269,7 @@ impl PromPlanner {
|
||||
|
||||
/// Builds the scan of the one logical table the current context is bound to. The caller has
|
||||
/// already preprocessed this selector's matchers and set the context to its table.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn prepare_one_scan(
|
||||
&mut self,
|
||||
matchers: Matchers,
|
||||
@@ -221,7 +278,7 @@ impl PromPlanner {
|
||||
logical_scan_id: &mut Option<u32>,
|
||||
logical_ids_differ: &mut bool,
|
||||
statement_kind: &mut Option<FieldKind>,
|
||||
any_partitioned: &mut bool,
|
||||
self_contained: bool,
|
||||
) -> Result<Option<PreparedInput>> {
|
||||
let (Some(metric), Some(time)) = (
|
||||
self.ctx.table_name.clone(),
|
||||
@@ -344,19 +401,19 @@ impl PromPlanner {
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
// Preserve the existing single-selector guard that its partition keys are tags.
|
||||
// Preserve the existing single-selector guard that its partition keys are tags. A partition
|
||||
// column that is not a tag is the time index, so one series spans several regions; a bare
|
||||
// scan cannot reconcile the fragments, which is why this route kept the existing plan for
|
||||
// it. The raw source can, so the guard only holds the shapes that read a bare scan - the
|
||||
// ones a region can run in process.
|
||||
if selector_count == 1
|
||||
&& !self_contained
|
||||
&& !table_meta
|
||||
.partition_column_names()
|
||||
.all(|column| tags.iter().any(|tag| tag == column))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
// Whether this input's table is split into regions along a partition column. The
|
||||
// canonical boundary below is the only part of this route that claims a whole-query
|
||||
// label-set answer, and a region-local producer cannot see the pieces another region
|
||||
// holds, so this fact decides whether that boundary may be claimed at all.
|
||||
*any_partitioned |= table_meta.partition_column_names().next().is_some();
|
||||
// This route declares one output column per field, so every field it binds carries
|
||||
// one kind: `Float64`, or the canonical native histogram struct. A field of any
|
||||
// other type - an integer, a `Float32`, a decimal, a string - keeps the existing
|
||||
@@ -410,9 +467,10 @@ impl PromPlanner {
|
||||
pub(super) async fn try_plan_native_fused(
|
||||
&mut self,
|
||||
prom_expr: &PromExpr,
|
||||
query_engine_state: &QueryEngineState,
|
||||
) -> Result<Option<LogicalPlan>> {
|
||||
Ok(self
|
||||
.try_plan_native_fused_with_context(prom_expr)
|
||||
.try_plan_native_fused_with_context(prom_expr, query_engine_state)
|
||||
.await?
|
||||
.map(|(plan, _)| plan))
|
||||
}
|
||||
@@ -436,10 +494,16 @@ impl PromPlanner {
|
||||
async fn try_plan_native_fused_with_context(
|
||||
&mut self,
|
||||
prom_expr: &PromExpr,
|
||||
query_engine_state: &QueryEngineState,
|
||||
) -> Result<Option<(LogicalPlan, Option<super::PromPlannerContext>)>> {
|
||||
if !self.native_fused {
|
||||
return Ok(None);
|
||||
}
|
||||
// Over the wire the region half of a plan is Substrait bytes, and the only fused shape that
|
||||
// encodes is one node over raw sources: a bare scan below it, or the split and segmented
|
||||
// shapes, cannot be carried. So this route plans the whole statement as that one node when
|
||||
// the transport is remote, and keeps the shapes that run region-locally when it is not.
|
||||
let self_contained = plans_over_remote_regions(query_engine_state);
|
||||
// Only the statement root is offered: the tree is compiled against the statement's grid,
|
||||
// and a subquery's expression is evaluated on its own, smaller one. A range-vector root is
|
||||
// the instant query's raw sample result, which the existing path reports as a matrix rather
|
||||
@@ -527,7 +591,6 @@ impl PromPlanner {
|
||||
// The kind every bound field carries. A statement declares one column per field, so
|
||||
// selectors that disagree have no column to declare and keep the existing plan.
|
||||
let mut statement_kind: Option<FieldKind> = None;
|
||||
let mut any_partitioned = false;
|
||||
for selector in &selectors {
|
||||
self.ctx = original_context.clone();
|
||||
// These matchers are alternatives the one scan below the node cannot represent, so the
|
||||
@@ -669,7 +732,7 @@ impl PromPlanner {
|
||||
&mut logical_scan_id,
|
||||
&mut logical_ids_differ,
|
||||
&mut statement_kind,
|
||||
&mut any_partitioned,
|
||||
self_contained,
|
||||
)
|
||||
.await?
|
||||
else {
|
||||
@@ -767,7 +830,7 @@ impl PromPlanner {
|
||||
&mut logical_scan_id,
|
||||
&mut logical_ids_differ,
|
||||
&mut statement_kind,
|
||||
&mut any_partitioned,
|
||||
self_contained,
|
||||
)
|
||||
.await?
|
||||
else {
|
||||
@@ -780,18 +843,11 @@ impl PromPlanner {
|
||||
single_input_context,
|
||||
logical_ids_differ,
|
||||
statement_kind,
|
||||
any_partitioned,
|
||||
)))
|
||||
}
|
||||
.await;
|
||||
self.ctx = original_context;
|
||||
let Some((
|
||||
mut prepared,
|
||||
single_input_context,
|
||||
logical_ids_differ,
|
||||
statement_kind,
|
||||
any_partitioned,
|
||||
)) =
|
||||
let Some((mut prepared, single_input_context, logical_ids_differ, statement_kind)) =
|
||||
preparation?
|
||||
else {
|
||||
return Ok(None);
|
||||
@@ -813,7 +869,7 @@ impl PromPlanner {
|
||||
) || logical_ids_differ;
|
||||
// Only cross-table selectors are converted into independent raw sources below.
|
||||
// A same-table multi-scan cannot be placed in one of several regions safely.
|
||||
if selectors.len() > 1 && !cross_table && any_partitioned {
|
||||
if selectors.len() > 1 && !cross_table && prepared.iter().any(|input| input.5) {
|
||||
return Ok(None);
|
||||
}
|
||||
// The first input names the output's time index and, on one table, binds every scan.
|
||||
@@ -1019,7 +1075,11 @@ impl PromPlanner {
|
||||
LogicalPlan::Extension(extension)
|
||||
if extension.node.as_any().is::<RawSeriesSource>()
|
||||
);
|
||||
if !cross_table || already_sourced {
|
||||
// A scan stays bare only where a region runs the node over it in process. Over the
|
||||
// wire every input is a raw source, whichever table it reads: the source is what the
|
||||
// transport carries, and it is also what reconciles the fragments of a series that
|
||||
// several regions hold.
|
||||
if (!cross_table && !self_contained) || already_sourced {
|
||||
return Ok(scan);
|
||||
}
|
||||
let Some(metric) = metric else {
|
||||
@@ -1141,8 +1201,9 @@ impl PromPlanner {
|
||||
// Catch construction-time refusals before choosing native execution: errors raised during
|
||||
// physical planning cannot fall back. This includes unsupported aggregates and `topk`,
|
||||
// `limitk` or CountValues groupings; it does not cover data-dependent errors raised while
|
||||
// executing the tree.
|
||||
if multi_input
|
||||
// executing the tree. A tree planned over the wire commits to the fused node without the
|
||||
// split or a segment above it, so it validates itself the same way before that choice.
|
||||
if (multi_input || self_contained)
|
||||
&& NativeExecutionState::try_new(&tree, Arc::new(UnboundedMemoryPool::default()), None)
|
||||
.is_err()
|
||||
{
|
||||
@@ -1184,8 +1245,10 @@ impl PromPlanner {
|
||||
// would. The general segmentation below is the fallback for the trees it declines,
|
||||
// which are the ones its per-series prefix cannot express. The split is decided before
|
||||
// anything consumes a child, so a tree it declines keeps the plan it would have built
|
||||
// without this route.
|
||||
let split = if !multi_input && selectors.len() == 1 {
|
||||
// without this route. It is a plan over one bare scan, though, which the remote
|
||||
// transport cannot carry, so over the wire the whole tree is planned as the one
|
||||
// raw-source node instead.
|
||||
let split = if !multi_input && !self_contained && selectors.len() == 1 {
|
||||
FusedSeries::split_aggregate(&tree, &time).context(DataFusionPlanningSnafu)?
|
||||
} else {
|
||||
None
|
||||
@@ -1231,7 +1294,11 @@ impl PromPlanner {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
if required_placement || matches!(locality, InputLocality::SinglePartition) {
|
||||
// A tree planned over the wire cannot be segmented: a segment reads a bare scan, and only
|
||||
// the raw source crosses the transport. Such a tree is planned as the one node below.
|
||||
if !self_contained
|
||||
&& (required_placement || matches!(locality, InputLocality::SinglePartition))
|
||||
{
|
||||
let segment_metric = if cross_table { None } else { metric.clone() };
|
||||
let plan = Box::pin(segment_tree(
|
||||
prom_expr,
|
||||
@@ -1292,8 +1359,9 @@ impl PromPlanner {
|
||||
// already carry their own labels, so it binds neither tags nor one metric name of its own -
|
||||
// each child names the metric it reads. A multi-input plan whose children stay direct
|
||||
// scans reads one table through the one metric and tag set they share, and keeps this
|
||||
// binding, which is the same identity those scans carry.
|
||||
let (tags, metric) = if cross_table {
|
||||
// binding, which is the same identity those scans carry. The same holds over the wire,
|
||||
// where every input is a raw source.
|
||||
let (tags, metric) = if cross_table || self_contained {
|
||||
(Vec::new(), None)
|
||||
} else {
|
||||
(tags, metric)
|
||||
@@ -3212,6 +3280,7 @@ mod tests {
|
||||
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use promql::native::plan::{NativeExpr, NativeNode, NativeTree};
|
||||
@@ -3220,9 +3289,33 @@ mod tests {
|
||||
use super::{
|
||||
ArrowDataType, ArrowTimeUnit, FieldKind, METRIC_NAME, NATIVE_PROMQL_EXTENSION_KEY,
|
||||
NativeType, collect_selectors, cut_segments, fused_output_schema, hybrid_binary_admitted,
|
||||
independent_scan_pair, native_output_tags, native_promql_requested, scan_time_filter,
|
||||
independent_scan_pair, native_output_tags, native_promql_requested,
|
||||
native_raw_plan_bounds_region_reads, scan_time_filter,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn native_raw_region_read_budget_needs_the_native_topology() {
|
||||
let schema = Arc::new(datafusion::arrow::datatypes::Schema::new(vec![
|
||||
datafusion::arrow::datatypes::Field::new(
|
||||
"ts",
|
||||
datafusion::arrow::datatypes::DataType::Int64,
|
||||
false,
|
||||
),
|
||||
]));
|
||||
let scan = || {
|
||||
Arc::new(datafusion::physical_plan::empty::EmptyExec::new(
|
||||
schema.clone(),
|
||||
)) as Arc<dyn ExecutionPlan>
|
||||
};
|
||||
|
||||
// No `FusedSeriesExec`: nothing here reads regions the way the budget assumes.
|
||||
assert!(!native_raw_plan_bounds_region_reads(&scan()));
|
||||
// A union drains its inputs one after another, so a body budget could stall it.
|
||||
let union = datafusion::physical_plan::union::UnionExec::try_new(vec![scan(), scan()])
|
||||
.expect("two inputs");
|
||||
assert!(!native_raw_plan_bounds_region_reads(&union));
|
||||
}
|
||||
|
||||
fn compiled_test_tree(query: &str) -> NativeTree {
|
||||
compiled_test_tree_with_fields(query, &["v0"])
|
||||
}
|
||||
|
||||
@@ -42,6 +42,13 @@ impl QueryEngineContext {
|
||||
self.query_ctx.clone()
|
||||
}
|
||||
|
||||
/// The session configuration the execution task context is built from, so that a plan may
|
||||
/// extend it before execution.
|
||||
#[inline]
|
||||
pub fn config_mut(&mut self) -> &mut datafusion::execution::config::SessionConfig {
|
||||
self.state.config_mut()
|
||||
}
|
||||
|
||||
pub fn build_task_ctx(&self) -> Arc<TaskContext> {
|
||||
let dbname = self.query_ctx.get_db_string();
|
||||
let state = &self.state;
|
||||
|
||||
@@ -22,9 +22,36 @@ use common_query::request::QueryRequest;
|
||||
use common_recordbatch::SendableRecordBatchStream;
|
||||
use partition::manager::PartitionRuleManagerRef;
|
||||
use session::ReadPreference;
|
||||
use tokio::sync::{Semaphore, SemaphorePermit};
|
||||
|
||||
use crate::error::Result;
|
||||
|
||||
/// Caps the region reads one query keeps in flight.
|
||||
///
|
||||
/// A region read is a `DoGet` whose body streams until that region is drained, so a query
|
||||
/// reading several sources would otherwise run one body per source and partition at once.
|
||||
/// The bound belongs to the query, not to one scan: its permit count is the query's target
|
||||
/// partitions, so two scans of three regions no longer read four bodies at once.
|
||||
pub(crate) struct RegionReadLimiter {
|
||||
permits: Semaphore,
|
||||
}
|
||||
|
||||
impl RegionReadLimiter {
|
||||
pub(crate) fn new(permits: usize) -> Self {
|
||||
Self {
|
||||
permits: Semaphore::new(permits.max(1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for one region read to be allowed; the read stays counted until the permit drops.
|
||||
pub(crate) async fn acquire(&self) -> SemaphorePermit<'_> {
|
||||
self.permits
|
||||
.acquire()
|
||||
.await
|
||||
.expect("the region read limiter is never closed")
|
||||
}
|
||||
}
|
||||
|
||||
/// The peer selected to serve a region query.
|
||||
///
|
||||
/// The target is frozen when the query is dispatched. Follow-up controls must
|
||||
|
||||
@@ -14,10 +14,12 @@
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::env;
|
||||
use std::future::Future;
|
||||
use std::net::TcpListener;
|
||||
use std::ops::RangeInclusive;
|
||||
use std::sync::Arc;
|
||||
use std::ops::{Deref, DerefMut, RangeInclusive};
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -88,21 +90,61 @@ use crate::test_util::{
|
||||
create_tmp_dir_and_datanode_opts,
|
||||
};
|
||||
|
||||
/// Flight `DoGet` requests another node sent to a datanode over its network address (see
|
||||
/// [`GreptimeDbClusterBuilder::with_real_datanode_grpc_addr`]).
|
||||
///
|
||||
/// The frontend and datanodes inside the test process use in-process clients, so counted requests
|
||||
/// come from remote nodes querying regions owned by this datanode.
|
||||
/// Flight `DoGet` requests sent to a datanode over its network address (see
|
||||
/// [`GreptimeDbClusterBuilder::with_real_datanode_grpc_addr`]). In-process duplex requests are not
|
||||
/// counted. Request totals are per datanode; active and peak counts are shared by all datanode
|
||||
/// listeners in the cluster. By default, the frontend uses duplex, but it can opt into TCP with
|
||||
/// [`GreptimeDbClusterBuilder::with_frontend_real_datanode_grpc`].
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DatanodeRpcStats {
|
||||
do_get_requests: AtomicUsize,
|
||||
active: Arc<Mutex<ActiveDoGet>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ActiveDoGet {
|
||||
current: usize,
|
||||
peak: usize,
|
||||
}
|
||||
|
||||
impl DatanodeRpcStats {
|
||||
/// The number of Flight `DoGet` requests another node sent to the datanode.
|
||||
/// The total number of Flight `DoGet` requests received over TCP.
|
||||
pub fn requests(&self) -> usize {
|
||||
self.do_get_requests.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The cluster-wide number of TCP `DoGet` calls with a pending response or live response body.
|
||||
pub fn active(&self) -> usize {
|
||||
self.active.lock().unwrap().current
|
||||
}
|
||||
|
||||
/// The cluster-wide peak number of concurrently active TCP `DoGet` calls since the last reset.
|
||||
pub fn peak_active(&self) -> usize {
|
||||
self.active.lock().unwrap().peak
|
||||
}
|
||||
|
||||
/// Reset the peak to the number of currently active calls.
|
||||
pub fn reset_peak_active(&self) {
|
||||
let mut active = self.active.lock().unwrap();
|
||||
active.peak = active.current;
|
||||
}
|
||||
|
||||
fn start(self: &Arc<Self>) -> DoGetGuard {
|
||||
self.do_get_requests.fetch_add(1, Ordering::Relaxed);
|
||||
let mut active = self.active.lock().unwrap();
|
||||
active.current += 1;
|
||||
active.peak = active.peak.max(active.current);
|
||||
DoGetGuard(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a `DoGet` active until its response body is dropped, including cancellation and errors.
|
||||
struct DoGetGuard(Arc<DatanodeRpcStats>);
|
||||
|
||||
impl Drop for DoGetGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.active.lock().unwrap().current -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GreptimeDbCluster {
|
||||
@@ -113,6 +155,7 @@ pub struct GreptimeDbCluster {
|
||||
/// The stats of the network address of every datanode, empty unless the cluster serves the
|
||||
/// datanodes at their own addresses.
|
||||
pub datanode_rpc_stats: HashMap<DatanodeId, Arc<DatanodeRpcStats>>,
|
||||
network_do_get: Arc<Mutex<ActiveDoGet>>,
|
||||
pub kv_backend: KvBackendRef,
|
||||
pub metasrv: Arc<Metasrv>,
|
||||
pub frontend: Arc<Frontend>,
|
||||
@@ -130,6 +173,22 @@ impl GreptimeDbCluster {
|
||||
self.datanode_rpc_stats.get(&datanode_id)
|
||||
}
|
||||
|
||||
/// Number of active TCP `DoGet` calls across all datanodes in this cluster.
|
||||
pub fn network_do_get_active(&self) -> usize {
|
||||
self.network_do_get.lock().unwrap().current
|
||||
}
|
||||
|
||||
/// Peak active TCP `DoGet` calls across all datanodes since the last reset.
|
||||
pub fn network_do_get_peak_active(&self) -> usize {
|
||||
self.network_do_get.lock().unwrap().peak
|
||||
}
|
||||
|
||||
/// Reset the cluster-wide peak to the number of currently active calls.
|
||||
pub fn reset_network_do_get_peak(&self) {
|
||||
let mut active = self.network_do_get.lock().unwrap();
|
||||
active.peak = active.current;
|
||||
}
|
||||
|
||||
/// List all SST files from all datanodes.
|
||||
pub async fn list_sst_files_from_all_datanodes(&self) -> BTreeSet<String> {
|
||||
let mut sst_files = BTreeSet::new();
|
||||
@@ -209,6 +268,8 @@ pub struct GreptimeDbClusterBuilder {
|
||||
local_file_access: LocalFileAccess,
|
||||
event_recorder_options: EventRecorderOptions,
|
||||
real_datanode_grpc_addr: bool,
|
||||
frontend_real_datanode_grpc: bool,
|
||||
query_options: query::options::QueryOptions,
|
||||
}
|
||||
|
||||
impl GreptimeDbClusterBuilder {
|
||||
@@ -247,6 +308,8 @@ impl GreptimeDbClusterBuilder {
|
||||
local_file_access: LocalFileAccess::default(),
|
||||
event_recorder_options: EventRecorderOptions::default(),
|
||||
real_datanode_grpc_addr: false,
|
||||
frontend_real_datanode_grpc: false,
|
||||
query_options: query::options::QueryOptions::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,6 +410,21 @@ impl GreptimeDbClusterBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Routes frontend-to-datanode RPCs through real TCP clients instead of duplex clients.
|
||||
/// This only has an effect when `with_real_datanode_grpc_addr(true)` is also set.
|
||||
#[must_use]
|
||||
pub fn with_frontend_real_datanode_grpc(mut self, enabled: bool) -> Self {
|
||||
self.frontend_real_datanode_grpc = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Overrides query options for this test cluster's frontend.
|
||||
#[must_use]
|
||||
pub fn with_query_options(mut self, options: query::options::QueryOptions) -> Self {
|
||||
self.query_options = options;
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn build_with(
|
||||
&self,
|
||||
datanode_options: Vec<DatanodeOptions>,
|
||||
@@ -356,7 +434,7 @@ impl GreptimeDbClusterBuilder {
|
||||
let datanodes = datanode_options.len();
|
||||
|
||||
let channel_config = ChannelConfig::new().timeout(Some(Duration::from_secs(20)));
|
||||
let datanode_clients = Arc::new(NodeClients::new(channel_config));
|
||||
let datanode_clients = Arc::new(NodeClients::new(channel_config.clone()));
|
||||
|
||||
let opt = MetasrvOptions {
|
||||
procedure: ProcedureConfig {
|
||||
@@ -394,10 +472,19 @@ impl GreptimeDbClusterBuilder {
|
||||
.build_datanodes_with_options(&metasrv, &datanode_options)
|
||||
.await;
|
||||
|
||||
let network_do_get = Arc::new(Mutex::new(ActiveDoGet::default()));
|
||||
let datanode_rpc_stats = if self.real_datanode_grpc_addr {
|
||||
datanode_options
|
||||
.iter()
|
||||
.map(|opts| (opts.node_id.unwrap(), Arc::new(DatanodeRpcStats::default())))
|
||||
.map(|opts| {
|
||||
(
|
||||
opts.node_id.unwrap(),
|
||||
Arc::new(DatanodeRpcStats {
|
||||
active: network_do_get.clone(),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<_, _>>()
|
||||
} else {
|
||||
HashMap::new()
|
||||
@@ -414,12 +501,15 @@ impl GreptimeDbClusterBuilder {
|
||||
self.wait_datanodes_alive(metasrv.metasrv.meta_peer_client(), datanodes)
|
||||
.await;
|
||||
|
||||
// Metasrv keeps its duplex clients; the frontend gets an empty cache so its misses
|
||||
// construct TCP clients using the addresses registered by the datanodes.
|
||||
let frontend_clients = if self.real_datanode_grpc_addr && self.frontend_real_datanode_grpc {
|
||||
Arc::new(NodeClients::new(channel_config))
|
||||
} else {
|
||||
datanode_clients.clone()
|
||||
};
|
||||
let mut frontend = self
|
||||
.build_frontend(
|
||||
metasrv.clone(),
|
||||
datanode_clients.clone(),
|
||||
start_frontend_servers,
|
||||
)
|
||||
.build_frontend(metasrv.clone(), frontend_clients, start_frontend_servers)
|
||||
.await;
|
||||
|
||||
frontend.start().await.unwrap();
|
||||
@@ -429,6 +519,7 @@ impl GreptimeDbClusterBuilder {
|
||||
guards,
|
||||
datanode_instances,
|
||||
datanode_rpc_stats,
|
||||
network_do_get,
|
||||
kv_backend: self.kv_backend.clone(),
|
||||
metasrv: metasrv.metasrv,
|
||||
frontend: Arc::new(frontend),
|
||||
@@ -653,6 +744,7 @@ impl GreptimeDbClusterBuilder {
|
||||
let mut fe_opts = FrontendOptions {
|
||||
auto_create_table: self.frontend_auto_create_table,
|
||||
event_recorder: self.event_recorder_options.clone(),
|
||||
query: self.query_options.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -771,14 +863,12 @@ fn serve_datanode_region_server<I, IO>(
|
||||
|
||||
/// Serves the region server of `datanode` and returns the address and the client of the address.
|
||||
///
|
||||
/// The returned client is always an in-process client: the frontend and the datanodes of the test
|
||||
/// process reach the region server through a duplex stream, no matter which address they use. This
|
||||
/// keeps the in-process traffic out of `rpc_stats`.
|
||||
/// The returned client is always an in-process duplex client, keeping its traffic out of
|
||||
/// `rpc_stats`. The frontend can instead use separate TCP clients when opted in.
|
||||
///
|
||||
/// [`test_util::PEER_PLACEHOLDER_ADDR`] is not a real address, so it cannot be served over the
|
||||
/// network at all. Any other address is a real one: the region server is additionally served on
|
||||
/// its local TCP port (`rpc_stats` counts the requests of the remote nodes that reach it, e.g. the
|
||||
/// region query that a datanode sends for the regions of another datanode).
|
||||
/// its local TCP port, and `rpc_stats` counts requests reaching that port.
|
||||
async fn create_datanode_client(
|
||||
datanode: &Datanode,
|
||||
addr: &str,
|
||||
@@ -831,24 +921,61 @@ struct CountRequests<S> {
|
||||
|
||||
impl<S, ReqBody> Service<http::Request<ReqBody>> for CountRequests<S>
|
||||
where
|
||||
S: Service<http::Request<ReqBody>>,
|
||||
S: Service<http::Request<ReqBody>, Response = http::Response<tonic::body::Body>>,
|
||||
S::Future: Send + 'static,
|
||||
S::Error: Send + 'static,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Response = http::Response<tonic::body::Body>;
|
||||
type Error = S::Error;
|
||||
type Future = S::Future;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
self.inner.poll_ready(cx)
|
||||
}
|
||||
|
||||
fn call(&mut self, request: http::Request<ReqBody>) -> Self::Future {
|
||||
if request.uri().path() == "/arrow.flight.protocol.FlightService/DoGet"
|
||||
&& let Some(rpc_stats) = &self.rpc_stats
|
||||
{
|
||||
rpc_stats.do_get_requests.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
let guard = if request.uri().path() == "/arrow.flight.protocol.FlightService/DoGet" {
|
||||
self.rpc_stats.as_ref().map(DatanodeRpcStats::start)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let future = self.inner.call(request);
|
||||
|
||||
self.inner.call(request)
|
||||
Box::pin(async move {
|
||||
let response = future.await?;
|
||||
Ok(response.map(|body| match guard {
|
||||
Some(guard) => {
|
||||
// The pinned body delegates HTTP frames (including gRPC trailers) while the
|
||||
// pointer owns the guard until the body is dropped.
|
||||
tonic::body::Body::new(Pin::new(GuardedBody {
|
||||
body: Box::new(body),
|
||||
_guard: guard,
|
||||
}))
|
||||
}
|
||||
None => body,
|
||||
}))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Dereferencing to the inner body lets tonic wrap it while keeping the guard alive until the
|
||||
// streaming body is completed and dropped, or the caller cancels the response.
|
||||
struct GuardedBody {
|
||||
body: Box<tonic::body::Body>,
|
||||
_guard: DoGetGuard,
|
||||
}
|
||||
|
||||
impl Deref for GuardedBody {
|
||||
type Target = tonic::body::Body;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.body
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for GuardedBody {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.body
|
||||
}
|
||||
}
|
||||
|
||||
@@ -893,6 +1020,104 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_do_get_stats_follow_response_body_lifetime() {
|
||||
let stats = Arc::new(DatanodeRpcStats::default());
|
||||
let mut service = CountRequests {
|
||||
inner: service_fn(|_: http::Request<()>| async {
|
||||
let stream = futures::stream::once(async {
|
||||
Ok::<_, std::io::Error>(axum::body::Bytes::from_static(b"data"))
|
||||
});
|
||||
let body = tonic::body::Body::new(axum::body::Body::from_stream(stream));
|
||||
Ok::<_, std::convert::Infallible>(http::Response::new(body))
|
||||
}),
|
||||
rpc_stats: Some(stats.clone()),
|
||||
};
|
||||
let request = || {
|
||||
http::Request::builder()
|
||||
.uri("/arrow.flight.protocol.FlightService/DoGet")
|
||||
.body(())
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let first = service.call(request()).await.unwrap();
|
||||
let other_stats = Arc::new(DatanodeRpcStats {
|
||||
active: stats.active.clone(),
|
||||
..Default::default()
|
||||
});
|
||||
service.rpc_stats = Some(other_stats.clone());
|
||||
let second = service.call(request()).await.unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
stats.requests(),
|
||||
other_stats.requests(),
|
||||
stats.active(),
|
||||
stats.peak_active()
|
||||
),
|
||||
(1, 1, 2, 2)
|
||||
);
|
||||
assert_eq!((other_stats.active(), other_stats.peak_active()), (2, 2));
|
||||
stats.reset_peak_active();
|
||||
assert_eq!(stats.peak_active(), 2);
|
||||
|
||||
// Completing one body and dropping another both release their guards.
|
||||
let body = axum::body::Body::new(first.into_body());
|
||||
assert_eq!(
|
||||
axum::body::to_bytes(body, usize::MAX).await.unwrap(),
|
||||
"data"
|
||||
);
|
||||
assert_eq!(stats.active(), 1);
|
||||
stats.reset_peak_active();
|
||||
assert_eq!(stats.peak_active(), 1);
|
||||
drop(second);
|
||||
assert_eq!(stats.active(), 0);
|
||||
stats.reset_peak_active();
|
||||
assert_eq!(stats.peak_active(), 0);
|
||||
|
||||
let other = http::Request::builder().uri("/other").body(()).unwrap();
|
||||
let other = service.call(other).await.unwrap();
|
||||
assert_eq!(
|
||||
(stats.requests(), other_stats.requests(), stats.active()),
|
||||
(1, 1, 0)
|
||||
);
|
||||
drop(other);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_do_get_stats_release_on_future_cancel_or_error() {
|
||||
let stats = Arc::new(DatanodeRpcStats::default());
|
||||
let request = || {
|
||||
http::Request::builder()
|
||||
.uri("/arrow.flight.protocol.FlightService/DoGet")
|
||||
.body(())
|
||||
.unwrap()
|
||||
};
|
||||
let mut pending = CountRequests {
|
||||
inner: service_fn(|_: http::Request<()>| {
|
||||
std::future::pending::<
|
||||
Result<http::Response<tonic::body::Body>, std::convert::Infallible>,
|
||||
>()
|
||||
}),
|
||||
rpc_stats: Some(stats.clone()),
|
||||
};
|
||||
let future = pending.call(request());
|
||||
assert_eq!(stats.active(), 1);
|
||||
drop(future);
|
||||
assert_eq!(stats.active(), 0);
|
||||
|
||||
let mut failing = CountRequests {
|
||||
inner: service_fn(|_: http::Request<()>| async {
|
||||
Err::<http::Response<tonic::body::Body>, _>(std::io::Error::other("failed"))
|
||||
}),
|
||||
rpc_stats: Some(stats.clone()),
|
||||
};
|
||||
assert!(failing.call(request()).await.is_err());
|
||||
assert_eq!(
|
||||
(stats.requests(), stats.active(), stats.peak_active()),
|
||||
(2, 0, 1)
|
||||
);
|
||||
}
|
||||
|
||||
const HEALTH_REFRESH_INTERVAL: Duration = Duration::from_millis(10);
|
||||
const HEALTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ use table::table::scan::SeriesScanExec;
|
||||
use super::test_util::{
|
||||
both_instances_cases, check_unordered_output_stream, distributed, standalone,
|
||||
};
|
||||
use crate::cluster::GreptimeDbClusterBuilder;
|
||||
use crate::standalone::GreptimeDbStandaloneBuilder;
|
||||
use crate::tests::test_util::MockInstance;
|
||||
|
||||
@@ -2400,6 +2401,679 @@ async fn native_test_instance_with_options(
|
||||
(standalone, observer)
|
||||
}
|
||||
|
||||
async fn native_scalar_rows(output: Output) -> Vec<(i64, f64)> {
|
||||
let batches = match output.data {
|
||||
OutputData::Stream(stream) => collect_batches(stream).await.unwrap(),
|
||||
OutputData::RecordBatches(batches) => batches,
|
||||
_ => unreachable!("PromQL query returns record batches"),
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
for batch in batches {
|
||||
let timestamps = batch
|
||||
.column_by_name("ts")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<TimestampMillisecondArray>()
|
||||
.unwrap();
|
||||
let values = batch
|
||||
.columns()
|
||||
.iter()
|
||||
.filter(|column| column.data_type() == &DataType::Float64)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(values.len(), 1, "one result value column");
|
||||
assert_eq!(batch.num_columns(), 2, "scalar output has no labels");
|
||||
let values = values[0].as_any().downcast_ref::<Float64Array>().unwrap();
|
||||
for row in 0..batch.num_rows() {
|
||||
rows.push((timestamps.value(row), values.value(row)));
|
||||
}
|
||||
}
|
||||
rows.sort_by_key(|row| row.0);
|
||||
rows
|
||||
}
|
||||
|
||||
/// The shape a native distributed plan is asserted on: its fused producer, the region set every
|
||||
/// merge scan selects, the routers that reconcile series several regions hold, and the per-series
|
||||
/// order every merge scan declares.
|
||||
struct NativePlanShape {
|
||||
fused: usize,
|
||||
regions_per_scan: Vec<usize>,
|
||||
routers: usize,
|
||||
/// `SeriesRepartitionExec` nodes inside the subtree of the single `FusedSeriesExec`, i.e. the
|
||||
/// routers that have to reconcile fragments of one series before the fused node reads them.
|
||||
/// A router above the fused node (the coalescer of its output) is not one of them; `routers`
|
||||
/// counts those too.
|
||||
routers_below_fused: usize,
|
||||
/// The `greptime.series.ordering` every merge scan declares, in traversal order. `contiguous`
|
||||
/// means one region holds each series whole; `interleaved` means a series may be split.
|
||||
scan_orderings: Vec<Option<String>>,
|
||||
}
|
||||
|
||||
/// Every node of the tree rooted at `root`, the root included.
|
||||
fn native_plan_nodes(root: &Arc<dyn ExecutionPlan>) -> Vec<Arc<dyn ExecutionPlan>> {
|
||||
let mut nodes = Vec::new();
|
||||
let mut stack = vec![Arc::clone(root)];
|
||||
while let Some(node) = stack.pop() {
|
||||
stack.extend(node.children().into_iter().map(Arc::clone));
|
||||
nodes.push(node);
|
||||
}
|
||||
nodes
|
||||
}
|
||||
|
||||
fn native_plan_shape(plan: &Arc<dyn ExecutionPlan>) -> NativePlanShape {
|
||||
let nodes = native_plan_nodes(plan);
|
||||
let mut shape = NativePlanShape {
|
||||
fused: 0,
|
||||
regions_per_scan: Vec::new(),
|
||||
routers: 0,
|
||||
routers_below_fused: 0,
|
||||
scan_orderings: Vec::new(),
|
||||
};
|
||||
for node in &nodes {
|
||||
shape.fused += usize::from(node.name() == "FusedSeriesExec");
|
||||
shape.routers += usize::from(node.name() == "SeriesRepartitionExec");
|
||||
if let Some(scan) = node.downcast_ref::<MergeScanExec>() {
|
||||
shape.regions_per_scan.push(
|
||||
scan.regions()
|
||||
.iter()
|
||||
.copied()
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len(),
|
||||
);
|
||||
shape.scan_orderings.push(
|
||||
scan.schema()
|
||||
.metadata()
|
||||
.get("greptime.series.ordering")
|
||||
.cloned(),
|
||||
);
|
||||
}
|
||||
}
|
||||
for fused in nodes.iter().filter(|node| node.name() == "FusedSeriesExec") {
|
||||
for node in native_plan_nodes(fused).into_iter().skip(1) {
|
||||
shape.routers_below_fused += usize::from(node.name() == "SeriesRepartitionExec");
|
||||
}
|
||||
}
|
||||
shape
|
||||
}
|
||||
|
||||
fn assert_native_merge_scans(
|
||||
plan: &Arc<dyn ExecutionPlan>,
|
||||
expected_scans: usize,
|
||||
expected_regions: usize,
|
||||
) {
|
||||
let shape = native_plan_shape(plan);
|
||||
assert_eq!(shape.fused, 1, "one fused FE plan: {plan:?}");
|
||||
assert_eq!(
|
||||
shape.regions_per_scan.len(),
|
||||
expected_scans,
|
||||
"merge scans: {plan:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
shape.regions_per_scan,
|
||||
vec![expected_regions; expected_scans],
|
||||
"all time partitions must be selected: {plan:?}"
|
||||
);
|
||||
assert!(
|
||||
shape.routers > 0,
|
||||
"fragmented raw inputs need reconciliation: {plan:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The shape every disjoint plan has: one fused producer over one merge scan per selector, and every
|
||||
/// scan selecting one region per partition value. Whether a node above the scans has to move frames
|
||||
/// is what the two disjoint cases differ in - a global fold gathers, a per-series match does not -
|
||||
/// so that stays with the caller.
|
||||
fn assert_native_disjoint_shape(
|
||||
plan: &Arc<dyn ExecutionPlan>,
|
||||
expected_scans: usize,
|
||||
expected_regions: usize,
|
||||
) -> NativePlanShape {
|
||||
let shape = native_plan_shape(plan);
|
||||
assert_eq!(shape.fused, 1, "one fused FE plan: {plan:?}");
|
||||
assert_eq!(
|
||||
shape.regions_per_scan.len(),
|
||||
expected_scans,
|
||||
"merge scans: {plan:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
shape.regions_per_scan,
|
||||
vec![expected_regions; expected_scans],
|
||||
"every disjoint region must be selected: {plan:?}"
|
||||
);
|
||||
shape
|
||||
}
|
||||
|
||||
/// The rows of the cross-region fixture, inserted into the logical tables `{prefix}_a`,
|
||||
/// `{prefix}_b` and `{prefix}_reset`. The partitioned fixture and its control hold the same rows,
|
||||
/// so the two differ only in how the engine has to reach them.
|
||||
fn cross_region_fixture_inserts(prefix: &str) -> String {
|
||||
format!(
|
||||
"INSERT INTO {prefix}_a (host, val, ts) VALUES ('x', 2, 60000), ('x', 4, 120000), ('x', 6, 180000), ('x', 8, 240000), ('y', 4, 60000), ('y', 6, 120000), ('y', 8, 180000), ('y', 10, 240000); INSERT INTO {prefix}_b (host, val, ts) VALUES ('x', 1, 60000), ('x', 2, 120000), ('x', 3, 180000), ('x', 4, 240000), ('y', 2, 60000), ('y', 3, 120000), ('y', 4, 180000), ('y', 5, 240000); INSERT INTO {prefix}_reset (host, val, ts) VALUES ('x', 0, 0), ('x', 5, 60000), ('x', 10, 120000), ('x', 1, 180000), ('x', 3, 240000), ('x', 5, 300000), ('y', 0, 0), ('y', 1, 60000), ('y', 2, 120000), ('y', 3, 180000), ('y', 4, 240000), ('y', 5, 300000)"
|
||||
)
|
||||
}
|
||||
|
||||
/// Real two-datanode TCP acceptance for raw series fragmented by time. Ratios alone can hide
|
||||
/// history dropped on both sides, so an absolute increase is checked separately as well.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn distributed_native_promql_cross_region_targets_match_expected_values() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let cluster = GreptimeDbClusterBuilder::new("distributed_native_promql_cross_region")
|
||||
.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();
|
||||
execute_all(
|
||||
&instance,
|
||||
"CREATE TABLE dist_native_phy (host STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host)) 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;
|
||||
for table in ["dist_native_a", "dist_native_b", "dist_native_reset"] {
|
||||
execute_all(
|
||||
&instance,
|
||||
&format!(
|
||||
"CREATE TABLE {table} (host STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host)) ENGINE=metric WITH ('on_physical_table'='dist_native_phy')"
|
||||
),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
execute_all(
|
||||
&instance,
|
||||
&cross_region_fixture_inserts("dist_native"),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// The semantic reference: the same rows in one unpartitioned physical table. The distributed
|
||||
// legacy path evaluates every region fragment on its own, so on the partitioned fixture it is
|
||||
// not an oracle for these expressions and is deliberately not compared here. The engine over
|
||||
// the complete series is the oracle, and the native distributed plan must agree with it.
|
||||
execute_all(
|
||||
&instance,
|
||||
"CREATE TABLE dist_native_ctl_phy (host STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host)) ENGINE=metric WITH ('physical_metric_table'='true')",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
for table in [
|
||||
"dist_native_ctl_a",
|
||||
"dist_native_ctl_b",
|
||||
"dist_native_ctl_reset",
|
||||
] {
|
||||
execute_all(
|
||||
&instance,
|
||||
&format!(
|
||||
"CREATE TABLE {table} (host STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host)) ENGINE=metric WITH ('on_physical_table'='dist_native_ctl_phy')"
|
||||
),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
execute_all(
|
||||
&instance,
|
||||
&cross_region_fixture_inserts("dist_native_ctl"),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
|
||||
for (expression, expected) in [
|
||||
(
|
||||
"sum(increase(dist_native_a[5m])) / sum(increase(dist_native_b[5m]))",
|
||||
vec![(180_000, 2.0), (240_000, 2.0)],
|
||||
),
|
||||
(
|
||||
"sum(max(dist_native_a)) / sum(dist_native_b)",
|
||||
vec![(180_000, 8.0 / 7.0), (240_000, 10.0 / 9.0)],
|
||||
),
|
||||
(
|
||||
"sum(increase(dist_native_b[5m]))",
|
||||
vec![(180_000, 5.0), (240_000, 7.0)],
|
||||
),
|
||||
(
|
||||
"sum(increase(dist_native_reset[5m]))",
|
||||
vec![(180_000, 14.0), (240_000, 17.0)],
|
||||
),
|
||||
] {
|
||||
let query = PromQuery {
|
||||
query: expression.to_string(),
|
||||
start: "180".to_string(),
|
||||
end: "240".to_string(),
|
||||
step: "60s".to_string(),
|
||||
..PromQuery::default()
|
||||
};
|
||||
// The control tables hold the complete series, so the engine's own evaluation over them
|
||||
// defines the expected values; the native distributed plan has to reproduce them.
|
||||
let control = expression.replace("dist_native_", "dist_native_ctl_");
|
||||
let control_rows = native_scalar_rows(
|
||||
instance
|
||||
.do_promql_query(
|
||||
&PromQuery {
|
||||
query: control.clone(),
|
||||
..query.clone()
|
||||
},
|
||||
native_query_context(false, 2),
|
||||
)
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
control_rows.len(),
|
||||
expected.len(),
|
||||
"the control defines every row: {control}"
|
||||
);
|
||||
for (actual, expected) in control_rows.iter().zip(expected.iter()) {
|
||||
assert_eq!(actual.0, expected.0, "control row timestamp: {control}");
|
||||
assert!(
|
||||
(actual.1 - expected.1).abs() < 1e-9,
|
||||
"control row value: {control}: {control_rows:?}"
|
||||
);
|
||||
}
|
||||
|
||||
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");
|
||||
assert_native_merge_scans(plan, usize::from(expression.contains(" / ")) + 1, 3);
|
||||
let rows = native_scalar_rows(output).await;
|
||||
assert_eq!(
|
||||
cluster.network_do_get_active(),
|
||||
0,
|
||||
"every response body is finished: {expression}"
|
||||
);
|
||||
assert_eq!(
|
||||
cluster.network_do_get_peak_active(),
|
||||
2,
|
||||
"three region streams must use exactly the target-partition bound: {expression}"
|
||||
);
|
||||
assert_eq!(rows.len(), expected.len(), "all rows: {expression}");
|
||||
for (actual, expected) in rows.iter().zip(expected) {
|
||||
assert_eq!(actual.0, expected.0, "{expression}");
|
||||
assert!(
|
||||
(actual.1 - expected.1).abs() < 1e-9,
|
||||
"{expression}: {rows:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A per-series operation on the fragmented fixture: every series is split across the three
|
||||
// time partitions, so no region holds a series whole and none can answer for a host alone.
|
||||
// What comes back is per-series rows - two hosts at two timestamps - which a scalar helper
|
||||
// cannot read, so this case compares labels as well as values.
|
||||
let expression = "increase(dist_native_b[5m])";
|
||||
let query = PromQuery {
|
||||
query: expression.to_string(),
|
||||
start: "180".to_string(),
|
||||
end: "240".to_string(),
|
||||
step: "60s".to_string(),
|
||||
..PromQuery::default()
|
||||
};
|
||||
let control = expression.replace("dist_native_", "dist_native_ctl_");
|
||||
let control_rows = native_result_rows(
|
||||
instance
|
||||
.do_promql_query(
|
||||
&PromQuery {
|
||||
query: control.clone(),
|
||||
..query.clone()
|
||||
},
|
||||
native_query_context(false, 2),
|
||||
)
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
control_rows.len(),
|
||||
4,
|
||||
"the control over the complete series defines every row: {control}"
|
||||
);
|
||||
|
||||
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, "one fused FE plan: {plan:?}");
|
||||
assert_eq!(
|
||||
shape.regions_per_scan,
|
||||
vec![3],
|
||||
"the selector reads all three time partitions: {plan:?}"
|
||||
);
|
||||
assert!(
|
||||
shape.routers_below_fused >= 1,
|
||||
"time partitioning splits every series across regions, so the region fragments must be \
|
||||
reconciled before the fused node reads them: {plan:?}"
|
||||
);
|
||||
assert!(
|
||||
shape
|
||||
.scan_orderings
|
||||
.iter()
|
||||
.all(|ordering| ordering.as_deref() == Some("interleaved")),
|
||||
"the frontend cannot prove a series stays in one time partition, so the scans must not \
|
||||
claim contiguous per-series order: {:?}: {plan:?}",
|
||||
shape.scan_orderings
|
||||
);
|
||||
let rows = native_result_rows(output).await;
|
||||
assert_eq!(
|
||||
cluster.network_do_get_active(),
|
||||
0,
|
||||
"every response body is finished: {expression}"
|
||||
);
|
||||
let peak = cluster.network_do_get_peak_active();
|
||||
assert!(
|
||||
(1..=2).contains(&peak),
|
||||
"fragmented region streams stay within the target-partition bound: {expression}: {peak}"
|
||||
);
|
||||
assert_eq!(control_rows, rows, "{expression}");
|
||||
}
|
||||
|
||||
/// The rows of the disjoint fixture, inserted into the logical tables `{prefix}_a` and
|
||||
/// `{prefix}_b`. Both hosts carry the same shape and land in different partitions.
|
||||
fn disjoint_fixture_inserts(prefix: &str) -> String {
|
||||
format!(
|
||||
"INSERT INTO {prefix}_a (host, val, ts) VALUES ('a', 2, 60000), ('a', 4, 120000), ('a', 6, 180000), ('a', 8, 240000), ('z', 4, 60000), ('z', 6, 120000), ('z', 8, 180000), ('z', 10, 240000); INSERT INTO {prefix}_b (host, val, ts) VALUES ('a', 1, 60000), ('a', 2, 120000), ('a', 3, 180000), ('a', 4, 240000), ('z', 2, 60000), ('z', 3, 120000), ('z', 4, 180000), ('z', 5, 240000)"
|
||||
)
|
||||
}
|
||||
|
||||
/// Real two-datanode TCP acceptance for raw series that no region shares: partitioning on the raw
|
||||
/// primary key puts every series in exactly one region, so the native plan must read all of them
|
||||
/// and reconcile none of them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn distributed_native_promql_disjoint_regions_do_not_repartition() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let cluster = GreptimeDbClusterBuilder::new("distributed_native_promql_disjoint")
|
||||
.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();
|
||||
execute_all(
|
||||
&instance,
|
||||
"CREATE TABLE dist_native_disjoint_phy (host STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host)) PARTITION ON COLUMNS (host) (host < 'm', host >= 'm') ENGINE=metric WITH ('physical_metric_table'='true')",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
for table in ["dist_native_disjoint_a", "dist_native_disjoint_b"] {
|
||||
execute_all(
|
||||
&instance,
|
||||
&format!(
|
||||
"CREATE TABLE {table} (host STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host)) ENGINE=metric WITH ('on_physical_table'='dist_native_disjoint_phy')"
|
||||
),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
execute_all(
|
||||
&instance,
|
||||
&disjoint_fixture_inserts("dist_native_disjoint"),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// The semantic reference over the complete series, as in the fragmented case: the engine's own
|
||||
// evaluation of the unpartitioned fixture defines the expected values.
|
||||
execute_all(
|
||||
&instance,
|
||||
"CREATE TABLE dist_native_disjoint_ctl_phy (host STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host)) ENGINE=metric WITH ('physical_metric_table'='true')",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
for table in ["dist_native_disjoint_ctl_a", "dist_native_disjoint_ctl_b"] {
|
||||
execute_all(
|
||||
&instance,
|
||||
&format!(
|
||||
"CREATE TABLE {table} (host STRING, val DOUBLE, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host)) ENGINE=metric WITH ('on_physical_table'='dist_native_disjoint_ctl_phy')"
|
||||
),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
execute_all(
|
||||
&instance,
|
||||
&disjoint_fixture_inserts("dist_native_disjoint_ctl"),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
|
||||
for (expression, expected, expected_scans) in [
|
||||
(
|
||||
"sum(increase(dist_native_disjoint_a[5m])) / sum(increase(dist_native_disjoint_b[5m]))",
|
||||
vec![(180_000, 2.0), (240_000, 2.0)],
|
||||
2,
|
||||
),
|
||||
(
|
||||
"sum(increase(dist_native_disjoint_a[5m]))",
|
||||
vec![(180_000, 10.0), (240_000, 14.0)],
|
||||
1,
|
||||
),
|
||||
] {
|
||||
let query = PromQuery {
|
||||
query: expression.to_string(),
|
||||
start: "180".to_string(),
|
||||
end: "240".to_string(),
|
||||
step: "60s".to_string(),
|
||||
..PromQuery::default()
|
||||
};
|
||||
let control = expression.replace("dist_native_disjoint_", "dist_native_disjoint_ctl_");
|
||||
let control_rows = native_scalar_rows(
|
||||
instance
|
||||
.do_promql_query(
|
||||
&PromQuery {
|
||||
query: control.clone(),
|
||||
..query.clone()
|
||||
},
|
||||
native_query_context(false, 2),
|
||||
)
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
control_rows.len(),
|
||||
expected.len(),
|
||||
"the control defines every row: {control}"
|
||||
);
|
||||
for (actual, expected) in control_rows.iter().zip(expected.iter()) {
|
||||
assert_eq!(actual.0, expected.0, "control row timestamp: {control}");
|
||||
assert!(
|
||||
(actual.1 - expected.1).abs() < 1e-9,
|
||||
"control row value: {control}: {control_rows:?}"
|
||||
);
|
||||
}
|
||||
|
||||
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");
|
||||
// A global fold normalizes every input to one partition, so the gather it needs is the
|
||||
// frames of complete series moving, not fragments of one series being put back together.
|
||||
assert_native_disjoint_shape(plan, expected_scans, 2);
|
||||
let rows = native_scalar_rows(output).await;
|
||||
assert_eq!(
|
||||
cluster.network_do_get_active(),
|
||||
0,
|
||||
"every response body is finished: {expression}"
|
||||
);
|
||||
let peak = cluster.network_do_get_peak_active();
|
||||
assert!(
|
||||
(1..=2).contains(&peak),
|
||||
"disjoint region streams stay within the target-partition bound: {expression}: {peak}"
|
||||
);
|
||||
assert_eq!(rows.len(), expected.len(), "all rows: {expression}");
|
||||
for (actual, expected) in rows.iter().zip(expected) {
|
||||
assert_eq!(actual.0, expected.0, "{expression}");
|
||||
assert!(
|
||||
(actual.1 - expected.1).abs() < 1e-9,
|
||||
"{expression}: {rows:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A per-series operation reads the two tables host by host: no series crosses a region, so
|
||||
// nothing in the native plan has to put one back together. A global fold above would gather
|
||||
// complete series instead, which is why this case is the one that states the disjoint claim.
|
||||
let expression = "increase(dist_native_disjoint_a[5m]) / increase(dist_native_disjoint_b[5m])";
|
||||
let query = PromQuery {
|
||||
query: expression.to_string(),
|
||||
start: "180".to_string(),
|
||||
end: "240".to_string(),
|
||||
step: "60s".to_string(),
|
||||
..PromQuery::default()
|
||||
};
|
||||
let expected = vec![
|
||||
(180_000, "a".to_string(), 2.0),
|
||||
(180_000, "z".to_string(), 2.0),
|
||||
(240_000, "a".to_string(), 2.0),
|
||||
(240_000, "z".to_string(), 2.0),
|
||||
];
|
||||
let control = expression.replace("dist_native_disjoint_", "dist_native_disjoint_ctl_");
|
||||
let control_rows = native_result_rows(
|
||||
instance
|
||||
.do_promql_query(
|
||||
&PromQuery {
|
||||
query: control.clone(),
|
||||
..query.clone()
|
||||
},
|
||||
native_query_context(false, 2),
|
||||
)
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
expected, control_rows,
|
||||
"the control over the complete series defines every row: {control}"
|
||||
);
|
||||
|
||||
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 = assert_native_disjoint_shape(plan, 2, 2);
|
||||
assert!(
|
||||
shape
|
||||
.scan_orderings
|
||||
.iter()
|
||||
.all(|ordering| ordering.as_deref() == Some("contiguous")),
|
||||
"the frontend proved each series lives in one region, so every merge scan keeps its \
|
||||
declared contiguous per-series order: {:?}: {plan:?}",
|
||||
shape.scan_orderings
|
||||
);
|
||||
// The fused node emits one partition, so each side of the match is gathered to it. That moves
|
||||
// complete series, not fragments of one: no series crosses a region here.
|
||||
assert_eq!(
|
||||
shape.routers_below_fused, 2,
|
||||
"one gather per side of the match below the fused node: {plan:?}"
|
||||
);
|
||||
let rows = native_result_rows(output).await;
|
||||
assert_eq!(
|
||||
cluster.network_do_get_active(),
|
||||
0,
|
||||
"every response body is finished: {expression}"
|
||||
);
|
||||
let peak = cluster.network_do_get_peak_active();
|
||||
assert!(
|
||||
(1..=2).contains(&peak),
|
||||
"disjoint region streams stay within the target-partition bound: {expression}: {peak}"
|
||||
);
|
||||
assert_eq!(expected, rows, "{expression}");
|
||||
|
||||
// The same claim for a per-series operation with nothing to match: each series is complete in
|
||||
// the region that holds it, so the fused node reads the merge scans directly and no router sits
|
||||
// between them.
|
||||
let expression = "increase(dist_native_disjoint_a[5m])";
|
||||
let query = PromQuery {
|
||||
query: expression.to_string(),
|
||||
start: "180".to_string(),
|
||||
end: "240".to_string(),
|
||||
step: "60s".to_string(),
|
||||
..PromQuery::default()
|
||||
};
|
||||
let control = expression.replace("dist_native_disjoint_", "dist_native_disjoint_ctl_");
|
||||
let control_rows = native_result_rows(
|
||||
instance
|
||||
.do_promql_query(
|
||||
&PromQuery {
|
||||
query: control.clone(),
|
||||
..query.clone()
|
||||
},
|
||||
native_query_context(false, 2),
|
||||
)
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
control_rows.len(),
|
||||
4,
|
||||
"the control over the complete series defines every row: {control}"
|
||||
);
|
||||
|
||||
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 = assert_native_disjoint_shape(plan, 1, 2);
|
||||
assert!(
|
||||
shape
|
||||
.scan_orderings
|
||||
.iter()
|
||||
.all(|ordering| ordering.as_deref() == Some("contiguous")),
|
||||
"the frontend proved each series lives in one region, so the merge scan keeps its declared \
|
||||
contiguous per-series order: {:?}: {plan:?}",
|
||||
shape.scan_orderings
|
||||
);
|
||||
assert_eq!(
|
||||
shape.routers_below_fused, 0,
|
||||
"each series is complete in one region, so the fused node reads the merge scans directly \
|
||||
and nothing has to reconcile fragments of one: {plan:?}"
|
||||
);
|
||||
let rows = native_result_rows(output).await;
|
||||
assert_eq!(
|
||||
cluster.network_do_get_active(),
|
||||
0,
|
||||
"every response body is finished: {expression}"
|
||||
);
|
||||
let peak = cluster.network_do_get_peak_active();
|
||||
assert!(
|
||||
(1..=2).contains(&peak),
|
||||
"disjoint region streams stay within the target-partition bound: {expression}: {peak}"
|
||||
);
|
||||
assert_eq!(control_rows, rows, "{expression}");
|
||||
}
|
||||
|
||||
#[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