fix(query): match the whole operand instead of copying matchers

A native binary must report what Prometheus reports: when one side holds two
series under one matching label set, the query fails with "found duplicate
series for the match group ... on the right hand-side". The legacy route
answers a value instead, because `matching_filters::propagate` copies the
matcher into the other operand's scan and the groups without a partner are
dropped before the join - its own documentation says that hides the duplicate.
This branch had started applying that rewrite to native operands as well, and
had refused multi-selector trees over partitioned tables in process to force
the hybrid topology back. Both kept a legacy behaviour the native route does
not need: a native binary reads independent raw sources and checks the whole
one-side groups itself.

Drop the rewrite for native operands, and keep the refusal only for several
scans of one partitioned table, whose node cannot run inside a region. The
partitioned acceptance case now asserts the duplicate error and that the pair
really runs as one native binary; the legacy value stays in the test as the
contrast that documents the difference.

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-11-06 11:06:02 +08:00
parent 58a67a47c3
commit 5f42ad975f
4 changed files with 75 additions and 161 deletions
+26 -83
View File
@@ -22,8 +22,6 @@ pub use native::{NATIVE_PROMQL_EXTENSION_KEY, discovers_metric_name};
mod set_operator;
use std::collections::{BTreeSet, HashSet, VecDeque};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use arrow::datatypes::IntervalDayTime;
@@ -310,11 +308,6 @@ pub struct PromPlanner {
type BinaryFieldPair<'a> = (&'a String, &'a String);
/// [`PromPlanner::try_plan_native_operand`]'s future, boxed; see
/// [`PromPlanner::native_operand_future`] for why it is not kept inline.
type NativeOperandFuture<'a> =
Pin<Box<dyn Future<Output = Result<Option<(LogicalPlan, PromPlannerContext)>>> + Send + 'a>>;
impl PromPlanner {
pub async fn stmt_to_plan(
table_provider: DfTableSourceProvider,
@@ -1177,63 +1170,6 @@ impl PromPlanner {
})
}
/// Boxes [`Self::try_plan_native_operand`]'s future.
///
/// The planner re-enters [`Self::prom_expr_to_plan_inner`] and
/// [`Self::prom_binary_expr_to_plan`] once per nesting level of the statement, and both frames
/// are large in a debug build. The native route's future is large as well, so a caller that
/// also plans the same expression with the existing path would carry a copy of it on the stack
/// at every level. Built here, the future moves into the box before that recursion starts, and
/// only the attempt itself pays for it.
fn native_operand_future<'a>(
&'a mut self,
expr: &'a PromExpr,
query_engine_state: &'a QueryEngineState,
) -> NativeOperandFuture<'a> {
Box::pin(self.try_plan_native_operand(expr, query_engine_state))
}
/// Re-plans one operand that [`matching_filters::propagate`] rewrote, publishing the plan and
/// its context through `context`.
///
/// A copied matcher belongs to the scan, not to the operand's identity: `absent()` turns
/// `selector_matcher` into the labels it reports, so the re-planned context keeps the matchers
/// the operand was written with.
///
/// A natively planned operand is re-planned natively: the matcher has to reach the fused node's
/// own scan, or the join keeps the non-joining rows that node reported. The route decides per
/// expression, so a decline falls back to the existing plan exactly as it would have on its own.
async fn replan_rewritten_operand(
&mut self,
rewritten: &PromExpr,
used_native: bool,
query_engine_state: &QueryEngineState,
context: &mut PromPlannerContext,
) -> Result<LogicalPlan> {
let selectors = std::mem::take(&mut context.selector_matcher);
let native = if used_native {
self.native_operand_future(rewritten, query_engine_state)
.await?
} else {
None
};
let plan = match native {
Some((plan, replanned)) => {
*context = replanned;
plan
}
None => {
let plan = self
.prom_expr_to_plan(rewritten, query_engine_state)
.await?;
*context = self.ctx.clone();
plan
}
};
context.selector_matcher = selectors;
Ok(plan)
}
async fn prom_binary_expr_to_plan(
&mut self,
query_engine_state: &QueryEngineState,
@@ -1483,32 +1419,39 @@ impl PromPlanner {
// Both operands are planned first because only the planned contexts tell a tag
// from a value field. The rewrite merely adds matchers to a selector, so the
// table reference, time index and field columns captured above stay valid.
if let Some(rewritten) = matching_filters::propagate(
binary_expr,
&left_context.tag_columns,
&right_context.tag_columns,
&left_context.aggregation_field_labels,
&right_context.aggregation_field_labels,
) {
// Matcher propagation belongs to the legacy route: copying a matcher into the
// other operand's scan drops the groups that have no partner, which is exactly
// what lets the legacy join answer where Prometheus would report a duplicated
// match group. A native operand must not be rewritten this way - the native
// matcher checks the complete one-side groups itself, and filtering them first
// would hide that error. So the rewrite only runs when neither operand is native.
if !used_native
&& let Some(rewritten) = matching_filters::propagate(
binary_expr,
&left_context.tag_columns,
&right_context.tag_columns,
&left_context.aggregation_field_labels,
&right_context.aggregation_field_labels,
)
{
// A copied matcher belongs to the scan, not to the operand's identity:
// `absent()` turns `selector_matcher` into the labels it reports, so the
// re-planned context keeps the matchers the operand was written with.
if rewritten.lhs.as_ref() != lhs.as_ref() {
let selectors = std::mem::take(&mut left_context.selector_matcher);
left_input = self
.replan_rewritten_operand(
&rewritten.lhs,
used_native,
query_engine_state,
&mut left_context,
)
.prom_expr_to_plan(&rewritten.lhs, query_engine_state)
.await?;
left_context = self.ctx.clone();
left_context.selector_matcher = selectors;
}
if rewritten.rhs.as_ref() != rhs.as_ref() {
let selectors = std::mem::take(&mut right_context.selector_matcher);
right_input = self
.replan_rewritten_operand(
&rewritten.rhs,
used_native,
query_engine_state,
&mut right_context,
)
.prom_expr_to_plan(&rewritten.rhs, query_engine_state)
.await?;
right_context = self.ctx.clone();
right_context.selector_matcher = selectors;
}
// The code below reads `self.ctx` as the right operand's context.
self.ctx = right_context.clone();
+11 -9
View File
@@ -869,15 +869,17 @@ impl PromPlanner {
.map(|(scan, ..)| scan)
.filter(|scan| !is_empty_discovered_input(scan)),
) || logical_ids_differ;
// A multi-selector tree over a partitioned table has no in-process placement whose matching
// and uniqueness semantics equal the frontend route. One node over several scans of one
// partitioned table reads neither the other scans nor the fragments another region holds,
// and one node over several tables' sources matches every series those sources delivered,
// where the frontend route copies the operands' matchers into their scans first and checks
// uniqueness above the join. Keep the existing plan in process; the hybrid route lifts such
// a tree one operand at a time. Over the wire every occurrence is already its own raw source
// reconciled above the regions, so the route keeps those trees.
if selectors.len() > 1 && !self_contained && prepared.iter().any(|input| input.5) {
// A node over several scans of one partitioned table cannot run inside a region: it would
// read neither the other scans nor the fragments another region holds, and a segment reads
// one bare scan. A cross-table tree already has a frontend placement over its independent
// raw sources, so it is not refused here. Over the wire every occurrence is its own raw
// source with its own bounds and identity, reconciled above the regions, so the refusal
// only holds the in-process same-table bare-scan route.
if selectors.len() > 1
&& !cross_table
&& !self_contained
&& 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.
+8 -39
View File
@@ -3757,37 +3757,19 @@ async fn native_fused_same_table_nested_match_keeps_prior_admission() {
);
}
/// On the wire, partitioned cross-table operands are independently transported by raw sources:
/// the pair is one fused node whose two inputs each name the metric they read. In process the same
/// pair keeps the frontend hybrid route instead, because only that route copies the matcher's
/// labels into each operand's scan and checks uniqueness above the join. Repeated scans of one
/// partitioned table retain the region-local multi-scan refusal on both routes.
/// Partitioned cross-table operands are independently transported by raw sources: the pair is one
/// native binary whose two inputs each name the metric they read. Repeated scans of one partitioned
/// table retain the region-local multi-scan refusal, since that node would read neither the other
/// scans nor the fragments another region holds.
#[tokio::test]
async fn native_fused_partitioned_pair_requires_per_selector_raw_sources() {
let state = QueryEngineState::try_new_with_region_transport(
new_memory_catalog_manager().unwrap(),
None,
None,
None,
None,
None,
let plan = build_native_fused_plan_with_provider(
"some_metric / other_metric",
true,
false,
Plugins::default(),
QueryOptions::default(),
)
.unwrap();
let eval_stmt = build_eval_stmt("some_metric / other_metric");
let plan = PromPlanner::stmt_to_plan_with_annotations(
native_two_table_provider(vec![0]).await,
&eval_stmt,
&state,
None,
true,
)
.await
.unwrap();
let fused = find_fused_series(&plan).expect("cross-table pair is native on the wire");
.await;
let fused = find_fused_series(&plan).expect("cross-table pair is native");
assert_eq!(fused.inputs().len(), 2, "{plan}");
for input in fused.inputs() {
assert!(
@@ -3796,19 +3778,6 @@ async fn native_fused_partitioned_pair_requires_per_selector_raw_sources() {
"{plan}"
);
}
// The same pair in process must not become one two-input node: the frontend hybrid route is
// what the matcher propagation and the uniqueness check live in, and that is the plan the
// partitioned-RHS hybrid cases assert.
let in_process = build_native_fused_plan_with_provider(
"some_metric / other_metric",
true,
native_two_table_provider(vec![0]).await,
)
.await;
assert!(
!has_pair_node(&in_process),
"an in-process partitioned pair keeps the hybrid route: {in_process}"
);
let repeated = build_native_fused_plan_with_provider(
"some_metric / some_metric",
true,
@@ -567,38 +567,38 @@ async fn native_hybrid_binary_05_06_08() {
.map(|row| row.value.unwrap())
.collect::<Vec<_>>()
);
// The native route matches the whole right operand and checks the one-side groups itself, so
// it reports the duplicated `other` group that Prometheus reports. The legacy value above is
// the one that differs: copying the left matcher into the right scan drops every group without
// a partner, and a dropped group cannot be reported as duplicated. A partition column on the
// right table does not change that - the pair reads independent raw sources either way.
let mark = observer.mark();
let (hybrid, capture) = run_query(&instance, &propagated, true, &observer).await;
assert_eq!(
vec![5.0],
hybrid
.rows
.iter()
.map(|row| row.value.unwrap())
.collect::<Vec<_>>()
);
assert_eq!(
2,
capture.fused.len(),
"both binary operands use native execution"
);
let plans = observer.since(mark);
let frontend = plans
.iter()
.find(|plan| find_binary_join(plan).is_some())
.expect("frontend Join plan");
let join = find_binary_join(frontend).unwrap();
let uniqueness = join
.children()
.iter()
.map(|branch| uniqueness_operators_above_merge(branch))
.fold((false, false), |(window, filter), found| {
(window || found.0, filter || found.1)
});
let mut query_ctx = QueryContext::with_db_name(None);
query_ctx.set_extension(QUERY_PARALLELISM_HINT, SCAN_PARTITIONS.to_string());
query_ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true".to_string());
let output = instance
.do_query(&tql_eval(&propagated), Arc::new(query_ctx))
.await
.remove(0)
.expect("the query plans");
let error = match output.data {
OutputData::Stream(stream) => collect_batches(stream)
.await
.expect_err("a duplicate match group fails"),
other => panic!("`{propagated}` was expected to stream: {other:?}"),
};
assert!(
uniqueness.0 && uniqueness.1,
"on(job) FE uniqueness operators: {}",
displayable(frontend.as_ref()).indent(false)
error.to_string().contains(
"found duplicate series for the match group {job=\"other\"} on the right hand-side"
),
"{propagated}: {error}"
);
// The statement is admitted natively: a fallback to the legacy plan would have answered the
// value instead of reporting the duplicate.
let capture = NativeCapture::from_plans(&observer.since(mark));
assert!(
capture.fused.iter().any(|node| node.children().len() == 2),
"the partitioned pair runs as one native binary"
);
// The left selector is a nonempty single `api` series, while the unpartitioned RHS also