fix(query): keep ordinary plans on the encoding path

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-10-24 21:30:49 +08:00
parent 3957e0d401
commit ed99673c7f
6 changed files with 113 additions and 66 deletions
+21 -20
View File
@@ -37,7 +37,7 @@ use datafusion_optimizer::push_down_filter::PushDownFilter;
use datafusion_optimizer::rewrite_set_comparison::RewriteSetComparison;
use datafusion_optimizer::scalar_subquery_to_join::ScalarSubqueryToJoin;
use datafusion_optimizer::simplify_expressions::SimplifyExpressions;
use promql::extension_plan::SeriesDivide;
use promql::extension_plan::{FusedSeries, SeriesDivide};
use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
use table::metadata::TableType;
use table::table::adapter::DfTableProviderAdapter;
@@ -113,9 +113,9 @@ pub struct DistPlannerAnalyzer {
/// Whether every region a rewritten plan reads is reached in process.
///
/// A region input normally has to be encoded to Substrait before it can leave the frontend, and
/// [`PlanRewriter::should_expand`] cuts the plan at the first node that does not encode. When
/// regions are reached in process, that input travels as a `LogicalPlan` instead, so nothing is
/// encoded and no node has to be cut for encoding's sake.
/// [`PlanRewriter::should_expand`] cuts the plan at the first node that does not encode. In
/// process, a root `FusedSeries` plan travels as a `LogicalPlan` instead and skips that gate;
/// other plans retain the ordinary encoding checks.
///
/// Whoever builds the query engine sets this, once, from the transport it wired. It is neither a
/// query-time decision nor a property of a region.
@@ -445,12 +445,11 @@ struct PlanRewriter {
/// Whether the whole plan this rewriter walks can be encoded to Substrait.
/// Used by [`PlanRewriter::should_expand`] to skip the per-node encoding check.
///
/// Only read when that gate applies, i.e. when `in_process_region_transport` is false. With
/// in-process regions the question has no answer worth computing and the field stays `false`.
/// Used for the ordinary standalone fast path when the root plan is encodable. It is not
/// needed when the root itself is the in-process `FusedSeries` exception.
whole_plan_encodable: bool,
/// Whether the regions this plan reads are reached in process, so an input crosses to a region
/// as a `LogicalPlan` rather than as Substrait bytes. See [`DistPlannerAnalyzer`].
in_process_region_transport: bool,
/// In-process transport skips the encodability gate only when the rewritten root itself is FusedSeries.
skip_encodability_gate: bool,
/// Current level in the tree
level: usize,
/// Simulated stack for the `rewrite` recursion
@@ -506,19 +505,23 @@ struct PlanRewriter {
new_child_plan: Option<LogicalPlan>,
}
fn is_fused_series_plan(plan: &LogicalPlan) -> bool {
matches!(plan, LogicalPlan::Extension(extension) if extension.node.as_any().is::<FusedSeries>())
}
impl PlanRewriter {
/// `plan` must be the root of the tree that is about to be rewritten, otherwise
/// [`PlanRewriter::should_expand`] may skip a check it has to perform.
fn new(plan: &LogicalPlan, in_process_region_transport: bool) -> Self {
let skip_encodability_gate = in_process_region_transport && is_fused_series_plan(plan);
Self {
// Only a plan that crosses to a region as Substrait bytes has to encode at all, and
// encoding is the expensive part of a pass. With in-process regions the answer is never
// read, so it is not computed.
whole_plan_encodable: !in_process_region_transport
// Preserve the ordinary whole-plan fast path unless this is the in-process root
// exception: no node in that tree needs an encoding check.
skip_encodability_gate,
whole_plan_encodable: !skip_encodability_gate
&& DFLogicalSubstraitConvertor
.encode(plan, DefaultSerializer)
.is_ok(),
in_process_region_transport,
..Default::default()
}
}
@@ -551,15 +554,13 @@ impl PlanRewriter {
// When the root does not encode, the plan holds at least one node that has to stay
// on the frontend and only the per-node check locates it.
//
// This question only exists for a plan that has to cross to a region as Substrait bytes.
// With in-process regions the same `LogicalPlan` is handed to `RegionServer::handle_read`
// never having been encoded, so encodability says nothing about where a node may run, and
// asking it would cut the plan at the first node with no serializer branch (`FusedSeries`)
// before `check_plan` could decide. Skipping it only removes a reason to expand: every
// For the in-process root `FusedSeries` exception, encodability says nothing about where
// a node may run, and asking it would cut the plan at the first node with no serializer
// branch before `check_plan` could decide. Skipping it only removes a reason to expand: every
// check below still runs, and a node they call `NonCommutative`/`Unimplemented`/
// `Unsupported` still expands, so a node no serializer lists only rides to a region when
// the categorizer places it there.
if !self.in_process_region_transport
if !self.skip_encodability_gate
&& !self.whole_plan_encodable
&& let Err(e) = DFLogicalSubstraitConvertor.encode(plan, DefaultSerializer)
{
+2 -1
View File
@@ -345,7 +345,8 @@ impl DfLogicalPlanner {
stmt,
&self.engine_state,
promql_annotations,
crate::promql::planner::native::native_promql_requested(&query_ctx),
self.engine_state.experimental_native_promql()
&& crate::promql::planner::native::native_promql_requested(&query_ctx),
)
.await
.map_err(BoxedError::new)
+2 -3
View File
@@ -300,9 +300,8 @@ pub struct PromPlanner {
/// `false` when the query says nothing: with it off, planning takes the existing path unchanged
/// and nothing below is reached.
///
/// The engine-wide `QueryOptions::experimental_native_promql` is not the source. It is consumed
/// while `QueryEngineState` is built and not kept, so the planner cannot read it; the extension
/// is what a client sets for one request.
/// The engine-wide `QueryOptions::experimental_native_promql` is applied while `QueryEngineState`
/// is built; this planner reads the per-query request extension instead.
native_fused: bool,
}
+44 -42
View File
@@ -32,7 +32,6 @@ use std::time::{Duration, UNIX_EPOCH};
use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit as ArrowTimeUnit};
use datafusion::common::{DFSchema, DFSchemaRef};
use datafusion::datasource::DefaultTableSource;
use datafusion::error::DataFusionError;
use datafusion::logical_expr::{Extension, LogicalPlan};
use datatypes::series::SeriesOrdering;
@@ -44,9 +43,7 @@ use promql_parser::parser::{
};
use session::context::QueryContextRef;
use snafu::ResultExt;
use store_api::storage::TimeSeriesDistribution;
use crate::dummy_catalog::DummyTableProvider;
use crate::promql::error::{DataFusionPlanningSnafu, Result};
use crate::promql::native_compile::{compile, statement_grid};
use crate::promql::planner::PromPlanner;
@@ -57,8 +54,8 @@ use crate::promql::planner::PromPlanner;
/// and read exactly the way the other per-query override in this crate is read
/// ([`remote_dyn_filter_pushdown_enabled_from_extensions`]): a query-context extension, which a
/// client can set per request over the HTTP hints header or as a gRPC context key. The engine-wide
/// option is a query-engine setting that `QueryEngineState` consumes while it is built and does not
/// keep, so it is not readable from the planner's call site; see [`native_promql_requested`].
/// option is applied while building query-engine state; this planner reads the per-query request
/// extension at the call site; see [`native_promql_requested`].
///
/// [`QueryOptions::experimental_native_promql`]: crate::options::QueryOptions::experimental_native_promql
/// [`remote_dyn_filter_pushdown_enabled_from_extensions`]:
@@ -160,7 +157,7 @@ impl PromPlanner {
// physical planner turns it into the region scan the node reads, and building a scan here
// instead would let the two paths disagree about the columns they read.
let table_ref = self.table_ref()?;
let input = self.create_table_scan_plan(table_ref.clone()).await?;
let mut input = self.create_table_scan_plan(table_ref.clone()).await?;
// The node reads the region scan itself, so the plan below it has to *be* that scan: a
// filter, a projection or a `__tsid` rewrite in between produces a different physical
// child, and the physical layer cannot reach through it. Declining here, while the logical
@@ -168,17 +165,39 @@ impl PromPlanner {
let LogicalPlan::TableScan(_) = &input else {
return Ok(None);
};
let offset = selector
.offset
.as_ref()
.map(|offset| match offset {
promql_parser::parser::Offset::Pos(duration) => duration.as_millis() as i64,
promql_parser::parser::Offset::Neg(duration) => -(duration.as_millis() as i64),
})
.unwrap_or_default();
let (saved_start, saved_end, saved_range) = (self.ctx.start, self.ctx.end, self.ctx.range);
self.ctx.range = selector_range_millis(prom_expr);
// Keep the fused scan's bounds identical to the legacy selector scan, including @ and offset.
let time_filter = (|| {
let anchored = self.at_modifier_offset(&selector.at, &selector.offset)?;
if anchored.is_some() {
self.ctx.end = saved_start;
}
self.build_time_index_filter(anchored.unwrap_or(offset), &input.schema())
})();
self.ctx.start = saved_start;
self.ctx.end = saved_end;
self.ctx.range = saved_range;
let time_filter = time_filter?;
if let Some(filter) = time_filter {
let LogicalPlan::TableScan(scan) = &mut input else {
unreachable!();
};
scan.filters.push(filter);
}
// A window over a native histogram yields a histogram, which the output schema below
// cannot declare; the existing path evaluates those with its own kernels.
if Self::field_columns_contain_native_histogram(input.schema(), &fields) {
return Ok(None);
}
// A raw series frame is produced by the region's series scan, which a region scan only
// prepares when the request asks for the per-series distribution. Without the hint the
// region scans by row and has no raw frame to hand over, so the node would be planned with
// an input that cannot feed it.
let input = with_per_series_distribution(input);
let Some(stmt) = self.native_statement(prom_expr) else {
return Ok(None);
};
@@ -293,42 +312,25 @@ fn fused_output_schema(
))
}
/// The selector's own scan, asking the region for the per-series distribution.
///
/// The distribution is a hint on the *table scan*, which the region server reads when it builds
/// the region scan: `PerSeries` is what makes a region prepare its series scan, whose raw-series
/// entrypoint is the only one that packs a series' chunks into the frame this node reads. The
/// existing planner asks for the same hint indirectly, through a sort on `(series key, time)` that
/// [`ScanHintRule`](crate::optimizer::scan_hint::ScanHintRule) turns into this distribution; the
/// native node has no such sort below it, because it reads raw samples rather than sorted rows, so
/// the hint is attached here.
///
/// The provider is cloned for this use-site first, exactly as that rule does: a catalog provider can
/// be shared by several scans, and a hint attached to the shared one would change their requests
/// too. A table whose provider is not the region-server provider - a test fixture, or an engine
/// this route cannot read - is left untouched, and the physical route declines it there.
fn with_per_series_distribution(plan: LogicalPlan) -> LogicalPlan {
let LogicalPlan::TableScan(mut scan) = plan else {
return plan;
};
let Some(source) = scan.source.downcast_ref::<DefaultTableSource>() else {
return LogicalPlan::TableScan(scan);
};
let Some(provider) = source.table_provider.downcast_ref::<DummyTableProvider>() else {
return LogicalPlan::TableScan(scan);
};
let adapter = provider.clone_for_scan();
adapter.with_distribution(TimeSeriesDistribution::PerSeries);
scan.source = Arc::new(DefaultTableSource::new(Arc::new(adapter)));
LogicalPlan::TableScan(scan)
}
/// The one selector `expr` folds, if it names exactly one.
///
/// The walk follows the grammar the native compiler accepts — a call, a range selector, a selector
/// and parentheses — and stops at every other shape, because a shape the compiler cannot compile
/// needs no selector resolved. Two distinct selectors are not one input, and a tree built over the
/// wrong one of them would evaluate a window the query did not write.
fn selector_range_millis(expr: &PromExpr) -> Option<i64> {
match expr {
PromExpr::MatrixSelector(matrix) => Some(matrix.range.as_millis() as i64),
PromExpr::Paren(paren) => selector_range_millis(&paren.expr),
PromExpr::Call(call) => call
.args
.args
.iter()
.find_map(|arg| selector_range_millis(arg)),
_ => None,
}
}
fn single_selector(expr: &PromExpr) -> Option<&VectorSelector> {
let mut selectors = Vec::new();
collect_selectors(expr, &mut selectors);
+38
View File
@@ -1693,6 +1693,44 @@ async fn native_fused_flag_off_keeps_the_existing_plan() {
assert!(display.contains("PromRangeManipulate"), "{display}");
}
/// The native selector scan is bounded to the range selector window, not the table retention.
#[tokio::test]
async fn native_fused_rate_scan_has_bounded_time_filter() {
let plan = build_native_fused_plan("rate(some_metric[5m])", true).await;
let display = plan.display_indent().to_string();
assert!(
display.contains("timestamp >= TimestampMillisecond(-299999, None)")
&& display.contains("timestamp <= TimestampMillisecond(100000000, None)"),
"native scan should include the bounded five-minute statement window: {display}"
);
}
/// An anchored native range scan uses the anchor, while preserving the outer statement window.
#[tokio::test]
async fn native_fused_offset_rate_scan_uses_offset_window_bounds() {
let plan = build_native_fused_plan("rate(some_metric[5m] offset 10s)", true).await;
let display = plan.display_indent().to_string();
assert!(
display.contains("timestamp >= TimestampMillisecond(-309999, None)")
&& display.contains("timestamp <= TimestampMillisecond(99990000, None)"),
"native scan should account for the selector offset: {display}"
);
}
#[tokio::test]
async fn native_fused_anchored_rate_scan_uses_anchor_bounds() {
let plan = build_native_fused_plan("rate(some_metric[5m] @ 300)", true).await;
let display = plan.display_indent().to_string();
assert!(
display.contains("timestamp >= TimestampMillisecond(1, None)")
&& display.contains("timestamp <= TimestampMillisecond(300000, None)"),
"native scan should cover the five-minute window ending at the anchor: {display}"
);
}
#[tokio::test]
async fn single_abs() {
do_single_instant_function_call("abs", "abs").await;
+6
View File
@@ -99,6 +99,7 @@ pub struct QueryEngineState {
table_functions: Arc<RwLock<HashMap<String, Arc<TableFunction>>>>,
extension_rules: Vec<Arc<dyn ExtensionAnalyzerRule + Send + Sync>>,
plugins: Plugins,
experimental_native_promql: bool,
}
impl fmt::Debug for QueryEngineState {
@@ -332,6 +333,7 @@ impl QueryEngineState {
table_functions: Arc::new(RwLock::new(HashMap::new())),
extension_rules,
plugins,
experimental_native_promql: options.experimental_native_promql,
scalar_functions: Arc::new(RwLock::new(HashMap::new())),
})
}
@@ -480,6 +482,10 @@ impl QueryEngineState {
self.df_context.register_udwf(func);
}
pub(crate) fn experimental_native_promql(&self) -> bool {
self.experimental_native_promql
}
pub fn catalog_manager(&self) -> &CatalogManagerRef {
&self.catalog_manager
}