diff --git a/config/config.md b/config/config.md
index cda48c547d8..27d8ee0f15b 100644
--- a/config/config.md
+++ b/config/config.md
@@ -145,6 +145,7 @@
| `procedure.max_running_procedures` | Integer | `128` | Max running procedures.
The maximum number of procedures that can be running at the same time.
If the number of running procedures exceeds this limit, the procedure will be rejected. |
| `query` | -- | -- | The query engine options. |
| `query.experimental_native_promql` | Bool | `false` | Enable experimental native PromQL execution for compatible queries.
This is the engine-wide default: a session
SET query.experimental_native_promql = true or a per-request
query.experimental_native_promql option overrides it, in that order.
Default: false |
+| `query.experimental_enable_factorized_join_agg` | Bool | `false` | Experimental opt-in for shape-based AVG/SUM join aggregation; default false. |
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.
Default to 0, which means the number of CPU cores. |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join,
and internal series merges during table scans).
Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
Projected Parquet row groups and streamed scan batches use scan_memory_limit separately. |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy:
- "greedy" (default): first-come-first-served allocation; preserves current behavior.
- "fair": divides available memory among spillable operators and may spill earlier.
Only effective when `memory_pool_size` is bounded (>0). |
@@ -397,6 +398,7 @@
| `meta_client.metadata_cache_tti` | String | `5m` | -- |
| `query` | -- | -- | The query engine options. |
| `query.experimental_native_promql` | Bool | `false` | Enable experimental native PromQL execution for compatible standalone queries.
Requires in-process region transport. This is the engine-wide default: a
session SET query.experimental_native_promql = true or a per-request
query.experimental_native_promql option overrides it, in that order.
Default: false |
+| `query.experimental_enable_factorized_join_agg` | Bool | `false` | Experimental opt-in for shape-based AVG/SUM join aggregation; default false. |
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.
Default to 0, which means the number of CPU cores. |
| `query.allow_query_fallback` | Bool | `false` | Whether to allow query fallback when push down optimize fails.
Default to false, meaning when push down optimize failed, return error msg |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join).
Supports absolute size (e.g., "4GB", "8GB") or percentage of system memory (e.g., "30%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
This pool applies to operators on this frontend. Datanodes use their own query
pools for local operators and internal series merges during table scans. |
@@ -631,6 +633,7 @@
| `wal.on_corrupted_segment` | String | `skip` | What a read does with a segment that still does not decode after a second fetch, because its checksum does not match or its content disagrees with its footer entry.
- `skip`: the segment is skipped and recorded as a WAL hole of its region, a metric is incremented and a warning is logged; the other regions of the object are unaffected (the default).
- `fail`: the read fails, so the region does not open.
**It's only used when the provider is `experimental_object_store`**. |
| `wal.accept_missing_history` | Bool | `false` | Whether a region opens although the WAL objects under the prefix do not hold its history.
An existing region fails to open when the prefix held no object when the WAL opened, or when the flushed entry id of the region names an object above every object of the prefix that holds entries. Both happen after `storage_provider`, or the bucket or root of the provider it names, changed without the WAL objects being copied, or after the objects were deleted.
To move the WAL, stop the instance, copy every object under the prefix to the new location and then change the configuration; the regions open with all their writes.
When the old WAL is lost, set this to `true` for one start: the regions open without their writes that were not flushed, which are lost, a warning names each region, and `greptime_logstore_object_store_wal_missing_history_accepted_total` counts them. Turn it off again once the instance has written to the WAL after that start; until then a later start refuses a region whose flushed entry id names an object above every object of the prefix that holds entries.
**It's only used when the provider is `experimental_object_store`**. |
| `query` | -- | -- | The query engine options. |
+| `query.experimental_enable_factorized_join_agg` | Bool | `false` | Experimental opt-in for shape-based AVG/SUM join aggregation; default false. |
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.
Default to 0, which means the number of CPU cores. |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join,
and internal series merges during table scans).
Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
Projected Parquet row groups and streamed scan batches use scan_memory_limit separately. |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy:
- "greedy" (default): first-come-first-served allocation; preserves current behavior.
- "fair": divides available memory among spillable operators and may spill earlier.
Only effective when `memory_pool_size` is bounded (>0). |
@@ -822,6 +825,7 @@
| `tracing` | -- | -- | The tracing options. Only effect when compiled with `tokio-console` feature. |
| `tracing.tokio_console_addr` | String | Unset | The tokio console address. |
| `query` | -- | -- | -- |
+| `query.experimental_enable_factorized_join_agg` | Bool | `false` | Experimental opt-in for shape-based AVG/SUM join aggregation; default false. |
| `query.parallelism` | Integer | `1` | Parallelism of the query engine for query sent by flownode.
Default to 1, so it won't use too much cpu or memory |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join).
Supports absolute size (e.g., "1GB", "2GB") or percentage of system memory (e.g., "20%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
NOTE: This does NOT limit memory used by table scans. |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy:
- "greedy" (default): first-come-first-served allocation; preserves current behavior.
- "fair": divides available memory among spillable operators and may spill earlier.
Only effective when `memory_pool_size` is bounded (>0). |
diff --git a/config/datanode.example.toml b/config/datanode.example.toml
index 28275c40f4a..1b30b8fca14 100644
--- a/config/datanode.example.toml
+++ b/config/datanode.example.toml
@@ -335,6 +335,8 @@ overwrite_entry_start_id = false
## The query engine options.
[query]
+## Experimental opt-in for shape-based AVG/SUM join aggregation; default false.
+experimental_enable_factorized_join_agg = false
## Parallelism of the query engine.
## Default to 0, which means the number of CPU cores.
diff --git a/config/flownode.example.toml b/config/flownode.example.toml
index 837e1b51d9e..63a84c69672 100644
--- a/config/flownode.example.toml
+++ b/config/flownode.example.toml
@@ -153,6 +153,8 @@ default_ratio = 1.0
#+ tokio_console_addr = "127.0.0.1"
[query]
+## Experimental opt-in for shape-based AVG/SUM join aggregation; default false.
+experimental_enable_factorized_join_agg = false
## Parallelism of the query engine for query sent by flownode.
## Default to 1, so it won't use too much cpu or memory
diff --git a/config/frontend.example.toml b/config/frontend.example.toml
index 72da7dd199b..e1b0cf64eb4 100644
--- a/config/frontend.example.toml
+++ b/config/frontend.example.toml
@@ -377,6 +377,9 @@ metadata_cache_tti = "5m"
## query.experimental_native_promql option overrides it, in that order.
## Default: false
#+ experimental_native_promql = false
+## Experimental opt-in for shape-based AVG/SUM join aggregation; default false.
+experimental_enable_factorized_join_agg = false
+
## Parallelism of the query engine.
## Default to 0, which means the number of CPU cores.
parallelism = 0
diff --git a/config/standalone.example.toml b/config/standalone.example.toml
index 01729fa0d6e..9cc3bb9af18 100644
--- a/config/standalone.example.toml
+++ b/config/standalone.example.toml
@@ -570,6 +570,9 @@ max_running_procedures = 128
## query.experimental_native_promql option overrides it, in that order.
## Default: false
#+ experimental_native_promql = false
+## Experimental opt-in for shape-based AVG/SUM join aggregation; default false.
+experimental_enable_factorized_join_agg = false
+
## Parallelism of the query engine.
## Default to 0, which means the number of CPU cores.
parallelism = 0
diff --git a/docs/how-to/query-options.md b/docs/how-to/query-options.md
index 3fdaa55979d..219160937c8 100644
--- a/docs/how-to/query-options.md
+++ b/docs/how-to/query-options.md
@@ -6,6 +6,7 @@ Query options adjust selected behavior for a connection or request; they are not
| --- | --- | --- |
| `query.parallelism` | `query_parallelism`, `query.parallelism` | Integer `1`–`1024`; server default `0` means automatic CPU-based parallelism. This is not a resource-pool limit. |
| `query.allow_query_fallback` | `query_fallback`, `allow_query_fallback`, `query.allow_query_fallback` (legacy `ALLOW_QUERY_FALLBACK` syntax / `query_fallback` hint also work) | `true` or `false` |
+| `query.experimental_enable_factorized_join_agg` | `experimental_enable_factorized_join_agg`, `query.experimental_enable_factorized_join_agg` | `true` or `false`; experimental opt-in for shape-based AVG/SUM join aggregation. Server default `false`; unset inherits it. |
| `query.enable_remote_dynamic_filter_pushdown` | canonical name | `true` or `false` |
| `datafusion.optimizer.*` | canonical name | Keys, types, defaults, and validation come from the linked DataFusion version (for example, numeric `max_passes` and Boolean `filter_null_join_keys`). |
diff --git a/src/query/src/datafusion.rs b/src/query/src/datafusion.rs
index 25d4fc585ef..0428c18a778 100644
--- a/src/query/src/datafusion.rs
+++ b/src/query/src/datafusion.rs
@@ -163,6 +163,16 @@ impl DatafusionQueryEngine {
Self { state, plugins }
}
+ /// Crate-visible view of the per-query engine context, for tests that
+ /// assert configuration propagation through the real query path.
+ #[cfg(test)]
+ pub(crate) fn engine_context_for_tests(
+ &self,
+ query_ctx: QueryContextRef,
+ ) -> QueryEngineContext {
+ self.engine_context(query_ctx).unwrap()
+ }
+
#[tracing::instrument(skip_all)]
async fn exec_query_plan(
&self,
diff --git a/src/query/src/optimizer.rs b/src/query/src/optimizer.rs
index 8864ab22617..34be248d2e7 100644
--- a/src/query/src/optimizer.rs
+++ b/src/query/src/optimizer.rs
@@ -18,6 +18,7 @@ pub mod count_nest_aggr;
pub mod count_wildcard;
pub mod enforce_sorting;
pub(crate) mod expr_depth;
+pub(crate) mod factorized_join_agg;
pub mod global_limit;
pub mod global_topk;
pub(crate) mod infer_aggregate_input_bounds;
diff --git a/src/query/src/optimizer/factorized_join_agg.rs b/src/query/src/optimizer/factorized_join_agg.rs
new file mode 100644
index 00000000000..38a726732cd
--- /dev/null
+++ b/src/query/src/optimizer/factorized_join_agg.rs
@@ -0,0 +1,561 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Shape-based `AVG(value * weight)` and `SUM(value * weight)`
+//! join-aggregation rewrites.
+//!
+//! Every rewrite turns `... JOIN ... GROUP BY host, area` with a single
+//! aggregate into a join of two partial aggregates computed on one side of the
+//! join each, with a projection above the join reconstructing the aggregate.
+//! Admission is decided by the plan shape alone: the rule never inspects the
+//! data its inputs will read.
+//!
+//! `AVG(value * weight)` / `SUM(value * weight)`: the aggregate over the
+//! pairwise products is replaced by `SUM(value) * SUM(weight)` divided by
+//! `COUNT(value) * COUNT(weight)` (`AVG`) or used as it is (`SUM`). The counts
+//! are checked individually for zero; for `AVG` they are cast to `Float64`
+//! before multiplication to avoid overflowing their `Int64` representation.
+//!
+//! # Approximation contract
+//!
+//! The payload rewrite is opt-in rule state and **shape-based**: it does not
+//! inspect the payloads, so it cannot know how well they factorize.
+//!
+//! - Floating-point reassociation means the factorized result can differ from
+//! the pairwise baseline; on inputs with heavy cancellation, intermediate
+//! overflow, or subnormal/extreme magnitudes, it can differ arbitrarily, in
+//! magnitude and in sign.
+//!
+//! That difference is accepted in this opt-in experiment mode: the opt-in
+//! switch and this documentation are the guard, not an admission classifier.
+//! Queries whose payloads may be ill-conditioned should keep the switch off.
+//!
+//! One difference is removed for free: a zero numerator is normalized to `+0.0`
+//! (a `CASE` in the reconstruction), so a cancellation the baseline evaluates to
+//! `+0.0` cannot surface here as `-0.0`.
+//!
+//! The rule is intentionally narrow: it matches only the join and group shapes
+//! described by `matching_payload_shape`. It is registered in the optimizer but
+//! remains inert unless enabled by config/session extension state.
+
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use crate::dist_plan::MergeScanLogicalPlan;
+use arrow_schema::DataType;
+use datafusion::functions_aggregate::average::Avg;
+use datafusion::functions_aggregate::count::count_udaf;
+use datafusion::functions_aggregate::sum::{Sum, sum_udaf};
+use datafusion_common::tree_node::Transformed;
+use datafusion_common::{Column, DFSchema, NullEquality, Result, ScalarValue};
+use datafusion_expr::expr::{AggregateFunction, BinaryExpr, Case, Cast};
+use datafusion_expr::logical_plan::{Aggregate, Join, JoinConstraint, JoinType, Projection};
+use datafusion_expr::{AggregateUDF, Expr, LogicalPlan, Operator};
+use datafusion_optimizer::optimizer::ApplyOrder;
+use datafusion_optimizer::{OptimizerConfig, OptimizerRule};
+
+/// Rewrites supported AVG/SUM payload products into partial aggregates.
+#[derive(Debug, Default)]
+pub(crate) struct FactorizedJoinAggRule;
+
+impl OptimizerRule for FactorizedJoinAggRule {
+ fn name(&self) -> &str {
+ "factorized_join_agg_rewrite"
+ }
+
+ fn apply_order(&self) -> Option {
+ Some(ApplyOrder::BottomUp)
+ }
+
+ fn rewrite(
+ &self,
+ plan: LogicalPlan,
+ config: &dyn OptimizerConfig,
+ ) -> Result> {
+ if !config
+ .options()
+ .extensions
+ .get::()
+ .is_some_and(|options| options.enabled)
+ {
+ return Ok(Transformed::no(plan));
+ }
+ let LogicalPlan::Aggregate(agg) = &plan else {
+ return Ok(Transformed::no(plan));
+ };
+ // The payload rewrites are shape-based: they need neither the pair bound
+ // nor any data certificate, only the matched join/group shape, and they
+ // never materialize the pair count. A single aggregate can match at most
+ // one of the two functions.
+ for function in [PayloadFunction::Avg, PayloadFunction::Sum] {
+ if let Some(matched) = matching_payload_shape(agg, function) {
+ return rewrite_payload(agg, &matched, function, config);
+ }
+ }
+ Ok(Transformed::no(plan))
+ }
+}
+
+/// Rewrites the matched `AVG(value * weight)` or `SUM(value * weight)`
+/// aggregate into a join of two partial aggregates whose projection
+/// reconstructs the payload function from them.
+///
+/// The projection computes, from the branch `nv`/`sv` (fact) and `nw`/`sw`
+/// (dim) outputs:
+///
+/// ```text
+/// no_products = (nv = 0) OR (nw = 0)
+/// total = CASE WHEN sv * sw = 0.0 THEN 0.0 ELSE sv * sw END
+/// AVG = CASE WHEN no_products THEN NULL ELSE total / (CAST(nv AS Float64) * CAST(nw AS Float64)) END
+/// SUM = CASE WHEN no_products THEN NULL ELSE total END
+/// ```
+///
+/// Both reconstructions return `NULL` for a group without a single non-null
+/// product, which is exactly when either payload count is zero. `AVG` over an
+/// empty pair set is `NULL` and so is `SUM`. Counts are never multiplied as
+/// `Int64`: `AVG` casts each count before multiplication, and `SUM` does not
+/// compute a count product.
+///
+/// `total` normalizes a zero numerator to `+0.0` because the pairwise numerator
+/// it must match can only cancel to `+0.0`: for facts `[1, -1]` with weight
+/// `[-1]`, the baseline sums the products `-1` and `+1` into `+0.0`, while
+/// `SUM(value)` is `+0.0`, `SUM(weight)` is `-1.0` and their naive product is
+/// `-0.0`, which would divide into `-0.0` instead of the baseline's `+0.0`. The
+/// normalization is free and shape-level: it removes that mismatch without
+/// looking at any data. Every other difference between the factorized and the
+/// pairwise result is the approximation the module documentation accepts.
+fn rewrite_payload(
+ agg: &Aggregate,
+ matched: &PayloadMatch<'_>,
+ function: PayloadFunction,
+ config: &dyn OptimizerConfig,
+) -> Result> {
+ let PayloadMatch {
+ join,
+ left_key,
+ right_key,
+ right_group,
+ fact_payload,
+ dim_payload,
+ } = matched;
+
+ let (fact_payloads_name, fact_sum_name, dim_payloads_name, dim_sum_name) =
+ partial_aliases(agg, join, config);
+
+ let left = Aggregate::try_new(
+ Arc::clone(&join.left),
+ vec![Expr::Column(left_key.clone())],
+ vec![
+ partial_aggregate(
+ count_udaf(),
+ vec![Expr::Column(fact_payload.clone())],
+ &fact_payloads_name,
+ ),
+ partial_aggregate(
+ sum_udaf(),
+ vec![Expr::Column(fact_payload.clone())],
+ &fact_sum_name,
+ ),
+ ],
+ )?;
+ let right = Aggregate::try_new(
+ Arc::clone(&join.right),
+ vec![
+ Expr::Column(right_key.clone()),
+ Expr::Column(right_group.clone()),
+ ],
+ vec![
+ partial_aggregate(
+ count_udaf(),
+ vec![Expr::Column(dim_payload.clone())],
+ &dim_payloads_name,
+ ),
+ partial_aggregate(
+ sum_udaf(),
+ vec![Expr::Column(dim_payload.clone())],
+ &dim_sum_name,
+ ),
+ ],
+ )?;
+
+ let left = Arc::new(LogicalPlan::Aggregate(left));
+ let right = Arc::new(LogicalPlan::Aggregate(right));
+ let right_area = left.schema().fields().len() + 1;
+ let join_keys = (column_at(left.schema(), 0), column_at(right.schema(), 0));
+ let rewritten_join = Join::try_new(
+ left,
+ right,
+ vec![(Expr::Column(join_keys.0), Expr::Column(join_keys.1))],
+ None,
+ JoinType::Inner,
+ JoinConstraint::On,
+ NullEquality::NullEqualsNothing,
+ false,
+ )?;
+
+ let partial = |name: &str| Expr::Column(Column::new_unqualified(name));
+ let fact_count = partial(&fact_payloads_name);
+ let dim_count = partial(&dim_payloads_name);
+ let no_products = Expr::BinaryExpr(BinaryExpr::new(
+ Box::new(is_zero(fact_count.clone(), int_literal(0))),
+ Operator::Or,
+ Box::new(is_zero(dim_count.clone(), int_literal(0))),
+ ));
+ let product = partial(&fact_sum_name) * partial(&dim_sum_name);
+ // `total`: the signed-zero normalization described on this function.
+ let total = Expr::Case(Case::new(
+ None,
+ vec![(
+ Box::new(is_zero(product.clone(), float_literal(0.0))),
+ Box::new(float_literal(0.0)),
+ )],
+ Some(Box::new(product)),
+ ));
+ let numerator = Expr::Case(Case::new(
+ None,
+ vec![(
+ Box::new(no_products),
+ Box::new(Expr::Literal(ScalarValue::Float64(None), None)),
+ )],
+ Some(Box::new(match function {
+ PayloadFunction::Avg => Expr::BinaryExpr(BinaryExpr::new(
+ Box::new(total),
+ Operator::Divide,
+ Box::new(
+ Expr::Cast(Cast::new(Box::new(fact_count), DataType::Float64))
+ * Expr::Cast(Cast::new(Box::new(dim_count), DataType::Float64)),
+ ),
+ )),
+ PayloadFunction::Sum => total,
+ })),
+ ));
+ let output = vec![
+ Expr::Column(column_at(&rewritten_join.schema, 0)),
+ Expr::Column(column_at(&rewritten_join.schema, right_area)),
+ numerator.alias(agg.schema.field(2).name()),
+ ];
+ let projection = Projection::try_new(output, Arc::new(LogicalPlan::Join(rewritten_join)))?;
+ Ok(Transformed::yes(LogicalPlan::Projection(projection)))
+}
+
+/// The four partial-aggregate output names, made collision-free against every
+/// field name the rewritten aggregates can still see.
+///
+/// `OptimizerConfig::alias_generator` only keeps generated aliases apart from
+/// each other, not from the input fields. A column literally named like a
+/// generated alias (say `partial_nv_1`) would then land next to the qualified
+/// grouping key of the same name in a partial aggregate's output schema, and
+/// `DFSchema` rejects that plan as ambiguous: `Schema contains qualified field
+/// name m.partial_nv_1 and unqualified field name partial_nv_1 which would be
+/// ambiguous`. Prepending underscores until the name is unused keeps the names
+/// deterministic and mutually distinct; the visible column set is finite, so
+/// the loop terminates.
+fn partial_aliases(
+ agg: &Aggregate,
+ join: &Join,
+ config: &dyn OptimizerConfig,
+) -> (String, String, String, String) {
+ // `agg.input` is the optional projection above the join, so it already
+ // covers both join inputs; the join schemas are collected as well so the
+ // used set does not depend on whether that projection is present.
+ let mut used: HashSet = HashSet::new();
+ for schema in [join.left.schema(), join.right.schema(), agg.input.schema()] {
+ used.extend(schema.fields().iter().map(|field| field.name().clone()));
+ }
+ let mut unique = |prefix: &str| {
+ let mut name = config.alias_generator().next(prefix);
+ while !used.insert(name.clone()) {
+ name = format!("_{name}");
+ }
+ name
+ };
+ (
+ unique("partial_nv"),
+ unique("partial_sv"),
+ unique("partial_nw"),
+ unique("partial_sw"),
+ )
+}
+
+fn partial_aggregate(udaf: Arc, args: Vec, alias: &str) -> Expr {
+ Expr::AggregateFunction(AggregateFunction::new_udf(
+ udaf,
+ args,
+ false,
+ None,
+ vec![],
+ None,
+ ))
+ .alias(alias)
+}
+
+fn int_literal(value: i64) -> Expr {
+ Expr::Literal(ScalarValue::Int64(Some(value)), None)
+}
+
+fn float_literal(value: f64) -> Expr {
+ Expr::Literal(ScalarValue::Float64(Some(value)), None)
+}
+
+/// ` = `, used to detect the zero and NULL cases of the `AVG`
+/// reconstruction.
+fn is_zero(lhs: Expr, rhs: Expr) -> Expr {
+ Expr::BinaryExpr(BinaryExpr::new(Box::new(lhs), Operator::Eq, Box::new(rhs)))
+}
+
+fn column_at(schema: &DFSchema, index: usize) -> Column {
+ let (qualifier, field) = schema.qualified_field(index);
+ Column::new(qualifier.cloned(), field.name())
+}
+
+/// The payload aggregate a rewrite reconstructs from the branch statistics.
+///
+/// Both functions share the same shape, the same two payload columns and the
+/// same branch statistics; they differ only in what the projection computes from
+/// the payload sum product: `AVG` divides it by the payload count product, `SUM`
+/// is the product itself.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum PayloadFunction {
+ /// `AVG( * )`.
+ Avg,
+ /// `SUM( * )`.
+ Sum,
+}
+
+/// The pieces of the `AVG`/`SUM( * )` shape the
+/// rewrite needs.
+struct PayloadMatch<'a> {
+ join: &'a Join,
+ left_key: Column,
+ right_key: Column,
+ right_group: Column,
+ fact_payload: Column,
+ dim_payload: Column,
+}
+
+/// Matches the narrow supported `AVG(payload * payload)` or
+/// `SUM(payload * payload)` shape and returns the join plus everything the
+/// rewrite needs from it.
+///
+/// Required shape: an inner `ON` equi-join whose group and payload columns map directly
+/// to the respective join sides,
+/// grouped by the left `host` and the right `area`, aggregated by a single
+/// `AVG` — or, for [`PayloadFunction::Sum`], `SUM` — of the product of those two
+/// columns, with no `DISTINCT`, `FILTER`, `ORDER BY`, null treatment or extra
+/// argument. The product operands may be given in either order and may reach the
+/// aggregate through a projection that repeats them.
+fn matching_payload_shape(agg: &Aggregate, function: PayloadFunction) -> Option> {
+ if agg.group_expr.len() != 2 || agg.aggr_expr.len() != 1 {
+ return None;
+ }
+ let (join, projection) = match agg.input.as_ref() {
+ LogicalPlan::Join(join) => (join, None),
+ LogicalPlan::Projection(projection) => match projection.input.as_ref() {
+ LogicalPlan::Join(join) => (join, Some(projection)),
+ _ => return None,
+ },
+ _ => return None,
+ };
+ // Distributed planning wraps each scan in a MergeScan extension and then
+ // restores the original scan schema with a projection. Keep the wrapper in
+ // the rewritten branches, but validate its hidden remote input is a scan.
+ if !is_scan_input(&join.left) || !is_scan_input(&join.right) {
+ return None;
+ }
+ if join.join_type != JoinType::Inner
+ || join.join_constraint != JoinConstraint::On
+ || join.null_equality != NullEquality::NullEqualsNothing
+ {
+ return None;
+ }
+ let (left_key, right_key) = equality_keys(join)?;
+
+ let aggregate = match &agg.aggr_expr[0] {
+ Expr::AggregateFunction(aggregate) => aggregate,
+ Expr::Alias(alias) => match alias.expr.as_ref() {
+ Expr::AggregateFunction(aggregate) => aggregate,
+ _ => return None,
+ },
+ _ => return None,
+ };
+ let params = &aggregate.params;
+ let inner = aggregate.func.inner();
+ let matches_function = match function {
+ PayloadFunction::Avg => inner.downcast_ref::().is_some(),
+ PayloadFunction::Sum => inner.downcast_ref::().is_some(),
+ };
+ if !matches_function
+ || params.distinct
+ || params.filter.is_some()
+ || !params.order_by.is_empty()
+ || params.null_treatment.is_some()
+ || params.args.len() != 1
+ {
+ return None;
+ }
+ let (Expr::Column(left_group), Expr::Column(right_group)) =
+ (&agg.group_expr[0], &agg.group_expr[1])
+ else {
+ return None;
+ };
+ let left_group = resolve_through_projection(left_group, projection)?;
+ let right_group = resolve_through_projection(right_group, projection)?;
+ let left_key = resolve_through_projection(left_key, None)?;
+ let right_key = resolve_through_projection(right_key, None)?;
+ if left_group != left_key
+ || right_group == right_key
+ || !join.left.schema().has_column(&left_group)
+ || !join.right.schema().has_column(&right_group)
+ {
+ return None;
+ }
+ let (first, second, operands_from_projection_expr) =
+ product_operands(¶ms.args[0], projection)?;
+ let (first, second) = match operands_from_projection_expr {
+ true => (column_expr(first)?, column_expr(second)?),
+ false => (
+ resolve_expr_through_projection(first, projection)?,
+ resolve_expr_through_projection(second, projection)?,
+ ),
+ };
+ let (fact_payload, dim_payload) =
+ if join.left.schema().has_column(&first) && join.right.schema().has_column(&second) {
+ (first, second)
+ } else if join.left.schema().has_column(&second) && join.right.schema().has_column(&first) {
+ (second, first)
+ } else {
+ return None;
+ };
+ if field_type(join.left.schema(), &fact_payload)? != &DataType::Float64
+ || field_type(join.right.schema(), &dim_payload)? != &DataType::Float64
+ {
+ return None;
+ }
+ Some(PayloadMatch {
+ join,
+ left_key,
+ right_key,
+ right_group,
+ fact_payload,
+ dim_payload,
+ })
+}
+
+/// The two operands of a payload aggregate's argument, which must be a
+/// multiplication of two columns of the joined inputs, in either order.
+///
+/// The projection that may sit between the aggregate and the join either passes
+/// the product's operands through under their original names (the argument is
+/// then the multiplication itself) or computes the product on its own, in which
+/// case the argument is a column of the projection and the multiplication is
+/// looked up there.
+fn product_operands<'a>(
+ argument: &'a Expr,
+ projection: Option<&'a Projection>,
+) -> Option<(&'a Expr, &'a Expr, bool)> {
+ let (entry, operands_from_projection_expr) = match argument {
+ Expr::BinaryExpr(binary) => (binary, false),
+ Expr::Column(column) => {
+ let projection = projection?;
+ let index = projection.schema.maybe_index_of_column(column)?;
+ let entry = projection.expr.get(index)?;
+ let binary = match entry {
+ Expr::BinaryExpr(binary) => binary,
+ Expr::Alias(alias) => match alias.expr.as_ref() {
+ Expr::BinaryExpr(binary) => binary,
+ _ => return None,
+ },
+ _ => return None,
+ };
+ (binary, true)
+ }
+ _ => return None,
+ };
+ if entry.op != Operator::Multiply {
+ return None;
+ }
+ Some((
+ entry.left.as_ref(),
+ entry.right.as_ref(),
+ operands_from_projection_expr,
+ ))
+}
+
+fn is_scan_input(plan: &LogicalPlan) -> bool {
+ match plan {
+ LogicalPlan::SubqueryAlias(alias) => is_scan_input(&alias.input),
+ // The distributed planner wraps each scan in a MergeScan extension and
+ // restores the original schema with a projection; a plain column
+ // selection may additionally sit between that wrapper and the join.
+ LogicalPlan::Projection(projection) => is_scan_input(&projection.input),
+ LogicalPlan::Extension(ext) => ext
+ .node
+ .as_any()
+ .downcast_ref::()
+ // The merge scan's input can itself carry the wrapped stages (a
+ // projection or filter over the original scan), so recurse.
+ .is_some_and(|scan| is_scan_input(scan.input())),
+ LogicalPlan::TableScan(_) => true,
+ LogicalPlan::Filter(filter) => is_scan_input(&filter.input),
+ _ => false,
+ }
+}
+
+/// Resolve columns through projections only when they are exact pass-throughs.
+fn column_expr(expr: &Expr) -> Option {
+ let Expr::Column(column) = expr else {
+ return None;
+ };
+ Some(column.clone())
+}
+
+fn resolve_expr_through_projection(expr: &Expr, projection: Option<&Projection>) -> Option {
+ let Expr::Column(column) = expr else {
+ return None;
+ };
+ resolve_through_projection(column, projection)
+}
+fn resolve_through_projection(column: &Column, projection: Option<&Projection>) -> Option {
+ if let Some(projection) = projection {
+ let idx = projection.schema.maybe_index_of_column(column)?;
+ let expr = projection.expr.get(idx)?;
+ let Expr::Column(c) = expr else {
+ return None;
+ };
+ return Some(c.clone());
+ }
+ Some(column.clone())
+}
+fn field_type<'a>(schema: &'a DFSchema, column: &Column) -> Option<&'a DataType> {
+ schema
+ .iter()
+ .find(|(q, f)| {
+ f.name().as_str() == column.name.as_str()
+ && column
+ .relation
+ .as_ref()
+ .is_none_or(|relation| *q == Some(relation))
+ })
+ .map(|(_, f)| f.data_type())
+}
+
+fn equality_keys(join: &Join) -> Option<(&Column, &Column)> {
+ if join.on.len() != 1 || join.filter.is_some() {
+ return None;
+ }
+ let (Expr::Column(left), Expr::Column(right)) = (&join.on[0].0, &join.on[0].1) else {
+ return None;
+ };
+ Some((left, right))
+}
diff --git a/src/query/src/options.rs b/src/query/src/options.rs
index fb058d56bda..a420ebe5d12 100644
--- a/src/query/src/options.rs
+++ b/src/query/src/options.rs
@@ -76,7 +76,40 @@ pub enum QueryMemoryPoolPolicy {
Fair,
}
-/// Query engine config
+#[derive(Debug, Clone, Default)]
+pub struct FactorizedJoinAggOptions {
+ pub enabled: bool,
+}
+
+impl ConfigExtension for FactorizedJoinAggOptions {
+ const PREFIX: &'static str = "factorized_join_agg";
+}
+
+impl ExtensionOptions for FactorizedJoinAggOptions {
+ fn as_any(&self) -> &dyn std::any::Any {
+ self
+ }
+ fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
+ self
+ }
+ fn cloned(&self) -> Box {
+ Box::new(self.clone())
+ }
+ fn set(&mut self, key: &str, value: &str) -> datafusion::error::Result<()> {
+ Err(datafusion::common::DataFusionError::NotImplemented(
+ format!("FactorizedJoinAggOptions does not support set key: {key} with value: {value}"),
+ ))
+ }
+ fn entries(&self) -> Vec {
+ vec![ConfigEntry {
+ key: "enabled".to_string(),
+ value: Some(self.enabled.to_string()),
+ description: "Enable experimental factorized join aggregation",
+ }]
+ }
+}
+
+/// Query engine configuration options.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct QueryOptions {
@@ -84,6 +117,8 @@ pub struct QueryOptions {
pub parallelism: usize,
/// Whether to allow query fallback when push down fails.
pub allow_query_fallback: bool,
+ /// Experimental: enable shape-based factorized AVG/SUM join aggregation. Default false.
+ pub experimental_enable_factorized_join_agg: bool,
/// Memory pool size for query execution. Setting it to 0 disables the limit (unbounded).
/// Supports absolute size (e.g., "2GB") or percentage (e.g., "50%").
/// When this limit is reached, queries will fail with ResourceExhausted error.
@@ -126,6 +161,7 @@ impl Default for QueryOptions {
Self {
parallelism: 0,
allow_query_fallback: false,
+ experimental_enable_factorized_join_agg: false,
memory_pool_size: MemoryLimit::default(),
enable_per_region_metrics: false,
experimental_spill_mode: QuerySpillMode::Default,
diff --git a/src/query/src/query_engine/state.rs b/src/query/src/query_engine/state.rs
index fbba7ae9098..fa3a8afe9eb 100644
--- a/src/query/src/query_engine/state.rs
+++ b/src/query/src/query_engine/state.rs
@@ -69,6 +69,7 @@ use crate::optimizer::count_nest_aggr::CountNestAggrRule;
use crate::optimizer::count_wildcard::CountWildcardToTimeIndexRule;
use crate::optimizer::enforce_sorting::EnforceSorting;
use crate::optimizer::expr_depth;
+use crate::optimizer::factorized_join_agg::FactorizedJoinAggRule;
use crate::optimizer::global_limit::EnsureGlobalLimitForFetch;
use crate::optimizer::global_topk::GlobalTopKOverFilteredScan;
use crate::optimizer::infer_aggregate_input_bounds::InferAggregateInputBoundsRule;
@@ -89,7 +90,8 @@ use crate::optimizer::transcribe_atat::TranscribeAtatRule;
use crate::optimizer::type_conversion::TypeConversionRule;
use crate::optimizer::windowed_sort::WindowedSortPhysicalRule;
use crate::options::{
- NativePromqlExtension, QueryMemoryPoolPolicy, QueryOptions as QueryOptionsNew,
+ FactorizedJoinAggOptions, NativePromqlExtension, QueryMemoryPoolPolicy,
+ QueryOptions as QueryOptionsNew,
};
use crate::promql::planner::NATIVE_PROMQL_EXTENSION_KEY;
use crate::promql::planner::native::native_promql_requested;
@@ -172,6 +174,12 @@ impl QueryEngineState {
if options.parallelism > 0 {
session_config = session_config.with_target_partitions(options.parallelism);
}
+ if options.experimental_enable_factorized_join_agg {
+ session_config
+ .options_mut()
+ .extensions
+ .insert(FactorizedJoinAggOptions { enabled: true });
+ }
if options.allow_query_fallback {
session_config
.options_mut()
@@ -264,6 +272,7 @@ impl QueryEngineState {
}
optimizer.rules.push(Arc::new(ScanHintRule));
optimizer.rules.push(Arc::new(JsonTypeConcretizeRule));
+ optimizer.rules.push(Arc::new(FactorizedJoinAggRule));
// add physical optimizer
let mut physical_optimizer = PhysicalOptimizer::new();
@@ -420,6 +429,15 @@ impl QueryEngineState {
.insert(NativePromqlExtension {
requested: native_promql,
});
+ if let Some(enabled) = options.get("query.experimental_enable_factorized_join_agg") {
+ state
+ .config_mut()
+ .options_mut()
+ .extensions
+ .insert(FactorizedJoinAggOptions {
+ enabled: enabled == "true",
+ });
+ }
Ok(query_ctx)
}
@@ -824,6 +842,7 @@ impl MemoryPool for MetricsMemoryPool {
#[cfg(test)]
mod tests {
+ mod factorized_join_agg_tests;
use std::sync::atomic::{AtomicBool, Ordering};
use common_base::Plugins;
diff --git a/src/query/src/query_engine/state/tests/factorized_join_agg_tests.rs b/src/query/src/query_engine/state/tests/factorized_join_agg_tests.rs
new file mode 100644
index 00000000000..cf54bb88ea6
--- /dev/null
+++ b/src/query/src/query_engine/state/tests/factorized_join_agg_tests.rs
@@ -0,0 +1,815 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, Float64Array, Int64Array, StringArray};
+use arrow::record_batch::RecordBatch as ArrowRecordBatch;
+use catalog::RegisterTableRequest;
+use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
+use common_recordbatch::RecordBatch;
+use datafusion_common::ScalarValue;
+use datafusion_expr::execution_props::ExecutionProps;
+use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
+use datafusion_physical_expr::create_physical_expr;
+use datatypes::prelude::*;
+use datatypes::schema::{ColumnSchema, Schema};
+use datatypes::vectors::{Float64Vector, StringVector, TimestampMillisecondVector};
+use session::context::QueryContext;
+use table::test_util::MemTable;
+
+use crate::options::QueryOptions;
+use crate::parser::QueryLanguageParser;
+use crate::query_engine::QueryEngineFactory;
+
+fn engine(enabled: bool, with_dist_planner: bool) -> crate::query_engine::QueryEngineRef {
+ let catalog = catalog::memory::new_memory_catalog_manager().unwrap();
+ let fact = RecordBatch::new(
+ Arc::new(Schema::new(vec![
+ ColumnSchema::new(
+ "ts",
+ ConcreteDataType::timestamp_millisecond_datatype(),
+ false,
+ )
+ .with_time_index(true),
+ ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
+ ])),
+ vec![
+ Arc::new(TimestampMillisecondVector::from_slice(vec![0])) as _,
+ Arc::new(StringVector::from(vec![Some("a")])) as _,
+ Arc::new(Float64Vector::from(vec![Some(2.0)])) as _,
+ ],
+ )
+ .unwrap();
+ let dim = RecordBatch::new(
+ Arc::new(Schema::new(vec![
+ ColumnSchema::new(
+ "ts",
+ ConcreteDataType::timestamp_millisecond_datatype(),
+ false,
+ )
+ .with_time_index(true),
+ ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("area", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("weight", ConcreteDataType::float64_datatype(), true),
+ ])),
+ vec![
+ Arc::new(TimestampMillisecondVector::from_slice(vec![0])) as _,
+ Arc::new(StringVector::from(vec![Some("a")])) as _,
+ Arc::new(StringVector::from(vec![Some("west")])) as _,
+ Arc::new(Float64Vector::from(vec![Some(3.0)])) as _,
+ ],
+ )
+ .unwrap();
+ for (name, table_id, batch) in [("fact", 101, fact), ("dim", 102, dim)] {
+ let table = MemTable::new_with_catalog(
+ name,
+ batch,
+ table_id,
+ DEFAULT_CATALOG_NAME.to_string(),
+ DEFAULT_SCHEMA_NAME.to_string(),
+ );
+ catalog
+ .register_table_sync(RegisterTableRequest {
+ catalog: DEFAULT_CATALOG_NAME.to_string(),
+ schema: DEFAULT_SCHEMA_NAME.to_string(),
+ table_name: name.to_string(),
+ table_id,
+ table,
+ })
+ .unwrap();
+ }
+ QueryEngineFactory::new(
+ catalog,
+ None,
+ None,
+ None,
+ None,
+ with_dist_planner,
+ QueryOptions {
+ experimental_enable_factorized_join_agg: enabled,
+ ..Default::default()
+ },
+ )
+ .query_engine()
+}
+
+async fn optimized_plan_for(engine: &crate::query_engine::QueryEngineRef, sql: &str) -> String {
+ let context = QueryContext::arc();
+ let statement = QueryLanguageParser::parse_sql(sql, &context).unwrap();
+ let plan = engine.planner().plan(&statement, context).await.unwrap();
+ let plan = engine.engine_state().optimize_logical_plan(plan).unwrap();
+ plan.display_indent().to_string()
+}
+
+async fn optimized_plan_schema_for(
+ engine: &crate::query_engine::QueryEngineRef,
+ sql: &str,
+) -> Vec<(String, arrow_schema::DataType)> {
+ let context = QueryContext::arc();
+ let statement = QueryLanguageParser::parse_sql(sql, &context).unwrap();
+ let plan = engine.planner().plan(&statement, context).await.unwrap();
+ let plan = engine.engine_state().optimize_logical_plan(plan).unwrap();
+ plan.schema()
+ .fields()
+ .iter()
+ .map(|field| (field.name().clone(), field.data_type().clone()))
+ .collect()
+}
+
+async fn optimized_plan(engine: &crate::query_engine::QueryEngineRef) -> String {
+ optimized_plan_for(
+ engine,
+ "SELECT f.host, d.area, AVG(f.value * d.weight) AS score FROM fact f JOIN dim d ON f.host = d.host GROUP BY f.host, d.area",
+ )
+ .await
+}
+
+#[tokio::test]
+async fn factorized_join_agg_matches_with_dist_planner() {
+ let baseline = optimized_plan(&engine(false, true)).await;
+ let rewritten = optimized_plan(&engine(true, true)).await;
+ assert_ne!(baseline, rewritten, "{rewritten}");
+ assert!(rewritten.contains("partial_nv"), "{rewritten}");
+}
+
+#[tokio::test]
+async fn duplicate_right_group_key_keeps_baseline() {
+ let query_engine = engine(true, false);
+ for aggregate in ["AVG", "SUM"] {
+ let sql = format!(
+ "SELECT f.host AS left_host, d.host AS right_host, {aggregate}(f.value * d.weight) AS score FROM fact f JOIN dim d ON f.host = d.host GROUP BY f.host, d.host"
+ );
+ let plan = optimized_plan_for(&query_engine, &sql).await;
+ let baseline = optimized_plan_for(&engine(false, false), &sql).await;
+ assert!(!plan.contains("partial_nv"), "{plan}");
+ assert_eq!(plan, baseline);
+ assert_eq!(
+ optimized_plan_schema_for(&query_engine, &sql).await,
+ vec![
+ ("left_host".to_string(), arrow_schema::DataType::Utf8),
+ ("right_host".to_string(), arrow_schema::DataType::Utf8),
+ ("score".to_string(), arrow_schema::DataType::Float64),
+ ]
+ );
+ let rows = query_output(&query_engine, &sql).await;
+ assert_eq!(
+ rows,
+ vec![vec!["a".to_string(), "a".to_string(), "6".to_string()]]
+ );
+ }
+}
+
+#[tokio::test]
+async fn reconstruction_uses_float_counts_and_nulls_empty_products() {
+ use datafusion_common::tree_node::TreeNode;
+ use datafusion_expr::{Expr, LogicalPlan};
+ use datafusion_optimizer::OptimizerRule;
+
+ let engine = engine(true, false);
+ for aggregate in ["AVG", "SUM"] {
+ let sql = format!(
+ "SELECT f.host, d.area, {aggregate}(f.value * d.weight) AS score FROM fact f JOIN dim d ON f.host = d.host GROUP BY f.host, d.area"
+ );
+ let context = QueryContext::arc();
+ let statement = QueryLanguageParser::parse_sql(&sql, &context).unwrap();
+ let logical = engine
+ .planner()
+ .plan(&statement, context.clone())
+ .await
+ .unwrap();
+ let mut optimizer_options = datafusion::config::ConfigOptions::default();
+ optimizer_options
+ .extensions
+ .insert(crate::options::FactorizedJoinAggOptions { enabled: true });
+ let optimizer_config = datafusion_optimizer::OptimizerContext::new_with_config_options(
+ Arc::new(optimizer_options),
+ );
+ let logical = logical
+ .transform_up(|plan| {
+ datafusion_optimizer::extract_equijoin_predicate::ExtractEquijoinPredicate::new()
+ .rewrite(plan, &optimizer_config)
+ })
+ .unwrap()
+ .data;
+ let LogicalPlan::Projection(planner_projection) = logical else {
+ panic!("expected planner projection after equijoin extraction");
+ };
+ let LogicalPlan::Aggregate(agg) = planner_projection.input.as_ref() else {
+ panic!("expected aggregate below planner projection");
+ };
+ let agg = agg.clone();
+ let transformed = crate::optimizer::factorized_join_agg::FactorizedJoinAggRule
+ .rewrite(LogicalPlan::Aggregate(agg), &optimizer_config)
+ .unwrap();
+ assert!(
+ transformed.transformed,
+ "factorized rule did not rewrite {sql}"
+ );
+ let rewritten = transformed.data;
+ let LogicalPlan::Projection(projection) = &rewritten else {
+ panic!("expected reconstruction projection: {rewritten:?}");
+ };
+ let expression = match projection.expr.last().unwrap() {
+ Expr::Alias(alias) => alias.expr.as_ref(),
+ expr => expr,
+ };
+ let input_schema = projection.input.schema();
+ let physical = create_physical_expr(
+ expression,
+ input_schema,
+ &ExecutionProps::new(),
+ &PhysicalPlanningContext::default(),
+ )
+ .unwrap();
+
+ let cases = [
+ (1_i64 << 32, 1_i64 << 32, false),
+ (1_i64 << 32, 1_i64 << 31, false),
+ (0, 1_i64 << 32, true),
+ (1_i64 << 32, 0, true),
+ ];
+ for (left_count, right_count, empty) in cases {
+ let schema = Arc::new(input_schema.as_arrow().clone());
+ let columns: Vec = input_schema
+ .fields()
+ .iter()
+ .map(|field| match field.name() {
+ name if name.contains("partial_nv") => {
+ Arc::new(Int64Array::from(vec![left_count])) as ArrayRef
+ }
+ name if name.contains("partial_nw") => {
+ Arc::new(Int64Array::from(vec![right_count])) as ArrayRef
+ }
+ name if name.contains("partial_sv") => {
+ Arc::new(Float64Array::from(vec![if left_count == 0 {
+ None
+ } else {
+ Some(left_count as f64 * 2.0)
+ }])) as ArrayRef
+ }
+ name if name.contains("partial_sw") => {
+ Arc::new(Float64Array::from(vec![if right_count == 0 {
+ None
+ } else {
+ Some(right_count as f64 * 3.0)
+ }])) as ArrayRef
+ }
+ _ if field.data_type() == &arrow_schema::DataType::Utf8 => {
+ Arc::new(StringArray::from(vec![Some("a")])) as ArrayRef
+ }
+ _ => panic!("unexpected reconstruction input field: {field:?}"),
+ })
+ .collect();
+ let batch = ArrowRecordBatch::try_new(schema, columns).unwrap();
+ let result = physical.evaluate(&batch).unwrap().into_array(1).unwrap();
+ let value = ScalarValue::try_from_array(result.as_ref(), 0).unwrap();
+ if empty {
+ assert_eq!(value, ScalarValue::Float64(None), "{aggregate}");
+ } else {
+ let ScalarValue::Float64(Some(value)) = value else {
+ panic!("expected Float64 result, got {value:?}");
+ };
+ assert!(value >= 0.0, "{aggregate}: {value}");
+ let expected = if aggregate == "AVG" {
+ 6.0
+ } else {
+ 6.0 * left_count as f64 * right_count as f64
+ };
+ assert_eq!(value, expected, "{aggregate}");
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn factorized_join_agg_is_opt_in() {
+ let disabled_plan = optimized_plan(&engine(false, false)).await;
+ let enabled_plan = optimized_plan(&engine(true, false)).await;
+ assert!(disabled_plan.contains("Aggregate"), "{disabled_plan}");
+ assert!(enabled_plan.contains("Aggregate"), "{enabled_plan}");
+ assert_ne!(disabled_plan, enabled_plan);
+}
+
+// ---------- Fixtures for the review-fix test matrix ----------
+
+/// Two tables NOT named fact/dim, with NULLs, duplicates, and a valid=0 group:
+/// metrics(host mhost, mval) x nodes(host nhost, zone, wgt).
+/// hosts: m1{1.0, NULL, 2.0}, m2{NULL, 4.0}; zones: m1:{west(2.0), east(NULL)},
+/// m2:{west(0.5)}. The (m2, west) group has 1 valid value; (m1, east) has
+/// valid=0 -> NULL AVG/SUM expected.
+fn metrics_and_nodes() -> (RecordBatch, RecordBatch) {
+ let metrics = RecordBatch::new(
+ Arc::new(Schema::new(vec![
+ ColumnSchema::new(
+ "ts",
+ ConcreteDataType::timestamp_millisecond_datatype(),
+ false,
+ )
+ .with_time_index(true),
+ ColumnSchema::new("mhost", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("mval", ConcreteDataType::float64_datatype(), true),
+ ])),
+ vec![
+ Arc::new(TimestampMillisecondVector::from_slice(vec![0; 5])) as _,
+ Arc::new(StringVector::from(vec![
+ Some("m1"),
+ Some("m1"),
+ Some("m1"),
+ Some("m2"),
+ Some("m2"),
+ ])) as _,
+ Arc::new(Float64Vector::from(vec![
+ Some(1.0),
+ None,
+ Some(2.0),
+ None,
+ Some(4.0),
+ ])) as _,
+ ],
+ )
+ .unwrap();
+ let nodes = RecordBatch::new(
+ Arc::new(Schema::new(vec![
+ ColumnSchema::new(
+ "ts",
+ ConcreteDataType::timestamp_millisecond_datatype(),
+ false,
+ )
+ .with_time_index(true),
+ ColumnSchema::new("nhost", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("zone", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("wgt", ConcreteDataType::float64_datatype(), true),
+ ])),
+ vec![
+ Arc::new(TimestampMillisecondVector::from_slice(vec![0; 3])) as _,
+ Arc::new(StringVector::from(vec![Some("m1"), Some("m1"), Some("m2")])) as _,
+ Arc::new(StringVector::from(vec![
+ Some("west"),
+ Some("east"),
+ Some("west"),
+ ])) as _,
+ Arc::new(Float64Vector::from(vec![Some(2.0), None, Some(0.5)])) as _,
+ ],
+ )
+ .unwrap();
+ (metrics, nodes)
+}
+
+/// Builds an engine over custom tables with the given option, registering
+/// `metrics`/`nodes` in place of fact/dim.
+fn engine_over(
+ metrics: RecordBatch,
+ nodes: RecordBatch,
+ enabled: bool,
+) -> crate::query_engine::QueryEngineRef {
+ let catalog = catalog::memory::new_memory_catalog_manager().unwrap();
+ for (name, table_id, batch) in [("metrics", 201, metrics), ("nodes", 202, nodes)] {
+ let table = MemTable::new_with_catalog(
+ name,
+ batch,
+ table_id,
+ DEFAULT_CATALOG_NAME.to_string(),
+ DEFAULT_SCHEMA_NAME.to_string(),
+ );
+ catalog
+ .register_table_sync(RegisterTableRequest {
+ catalog: DEFAULT_CATALOG_NAME.to_string(),
+ schema: DEFAULT_SCHEMA_NAME.to_string(),
+ table_name: name.to_string(),
+ table_id,
+ table,
+ })
+ .unwrap();
+ }
+ QueryEngineFactory::new(
+ catalog,
+ None,
+ None,
+ None,
+ None,
+ false,
+ QueryOptions {
+ experimental_enable_factorized_join_agg: enabled,
+ ..Default::default()
+ },
+ )
+ .query_engine()
+}
+
+async fn query_plan(engine: &crate::query_engine::QueryEngineRef, sql: &str) -> String {
+ let context = QueryContext::arc();
+ let statement = QueryLanguageParser::parse_sql(sql, &context).unwrap();
+ let plan = engine.planner().plan(&statement, context).await.unwrap();
+ let plan = engine.engine_state().optimize_logical_plan(plan).unwrap();
+ plan.display_indent().to_string()
+}
+
+async fn query_output(engine: &crate::query_engine::QueryEngineRef, sql: &str) -> Vec> {
+ let context = QueryContext::arc();
+ let statement = QueryLanguageParser::parse_sql(sql, &context).unwrap();
+ let plan = engine
+ .planner()
+ .plan(&statement, context.clone())
+ .await
+ .unwrap();
+ let output = engine.execute(plan, context).await.unwrap();
+ let data = output.data;
+ let batches = match data {
+ common_query::OutputData::RecordBatches(batches) => batches,
+ common_query::OutputData::Stream(stream) => {
+ common_recordbatch::util::collect_batches(stream)
+ .await
+ .unwrap()
+ }
+ other => panic!("unexpected output: {other:?}"),
+ };
+ let mut rows = Vec::new();
+ for batch in batches.iter() {
+ let vectors: Vec<_> = (0..batch.num_columns())
+ .map(|c| datatypes::vectors::Helper::try_into_vector(batch.column(c)).unwrap())
+ .collect();
+ for i in 0..batch.num_rows() {
+ let row: Vec = vectors
+ .iter()
+ .map(|v| {
+ let value = datatypes::value::Value::from(v.get_ref(i));
+ value.to_string()
+ })
+ .collect();
+ rows.push(row);
+ }
+ }
+ rows.sort();
+ rows
+}
+
+/// A NULL score displays as the type name ("Null"); a real one parses as f64.
+fn parse_score(cell: &str) -> Option {
+ if cell.contains("Null") {
+ None
+ } else {
+ Some(cell.parse().expect("score cell parses as f64"))
+ }
+}
+
+const METRIC_AVG_SQL: &str = "SELECT m.mhost, n.zone, AVG(m.mval * n.wgt) AS score FROM metrics m JOIN nodes n ON m.mhost = n.nhost GROUP BY m.mhost, n.zone";
+
+#[tokio::test]
+async fn renamed_tables_and_columns_are_rewritten() {
+ let (metrics, nodes) = metrics_and_nodes();
+ let baseline = query_plan(
+ &engine_over(metrics.clone(), nodes.clone(), false),
+ METRIC_AVG_SQL,
+ )
+ .await;
+ let rewritten = query_plan(&engine_over(metrics, nodes, true), METRIC_AVG_SQL).await;
+ assert_ne!(baseline, rewritten, "{rewritten}");
+ assert!(rewritten.contains("partial_nv"), "{rewritten}");
+}
+
+#[tokio::test]
+async fn rewritten_results_match_baseline_within_tolerance() {
+ let (metrics, nodes) = metrics_and_nodes();
+ let baseline_rows = query_output(
+ &engine_over(metrics.clone(), nodes.clone(), false),
+ METRIC_AVG_SQL,
+ )
+ .await;
+ let rewritten_rows = query_output(&engine_over(metrics, nodes, true), METRIC_AVG_SQL).await;
+ assert_eq!(baseline_rows.len(), rewritten_rows.len());
+ for (b, r) in baseline_rows.iter().zip(&rewritten_rows) {
+ assert_eq!(b[0], r[0], "host mismatch");
+ assert_eq!(b[1], r[1], "zone mismatch");
+ match (parse_score(&b[2]), parse_score(&r[2])) {
+ (Some(bv), Some(rv)) => assert!(
+ (bv - rv).abs() <= 1e-9 * bv.abs().max(1.0),
+ "score mismatch: baseline {bv} vs rewritten {rv}"
+ ),
+ (None, None) => {} // both NULL
+ (b, r) => panic!("nullness mismatch: baseline {b:?} vs rewritten {r:?}"),
+ }
+ }
+ // valid=0 group (m1, east) must be NULL in both arms.
+ let null_row = baseline_rows
+ .iter()
+ .find(|r| r[1] == "east")
+ .expect("east group present");
+ assert_eq!(
+ parse_score(&null_row[2]),
+ None,
+ "valid=0 group must be NULL"
+ );
+}
+
+#[tokio::test]
+async fn computed_alias_projection_keeps_the_baseline_plan() {
+ let (metrics, nodes) = metrics_and_nodes();
+ let sql = "SELECT host, zone, AVG(mval * wgt) AS score FROM (SELECT m.mhost AS host, n.zone, m.mval + 1 AS mval, n.wgt FROM metrics m JOIN nodes n ON m.mhost = n.nhost) GROUP BY host, zone";
+ let baseline_rows =
+ query_output(&engine_over(metrics.clone(), nodes.clone(), false), sql).await;
+ let enabled = engine_over(metrics, nodes, true);
+ let plan = query_plan(&enabled, sql).await;
+ assert!(
+ !plan.contains("partial_nv"),
+ "computed-alias projection must not rewrite:\n{plan}"
+ );
+ let rows = query_output(&enabled, sql).await;
+ assert_eq!(baseline_rows, rows);
+
+ let unchanged_groups_sql = "SELECT m.mhost, n.zone, AVG(mval * wgt) AS score FROM (SELECT m.mhost, n.zone, m.mval + 1 AS mval, n.wgt FROM metrics m JOIN nodes n ON m.mhost = n.nhost) GROUP BY m.mhost, n.zone";
+ let plan = query_plan(&enabled, unchanged_groups_sql).await;
+ assert!(
+ !plan.contains("partial_nv"),
+ "computed payload must not rewrite even when grouping columns pass through unchanged:\n{plan}"
+ );
+}
+
+#[tokio::test]
+async fn projected_product_rewrites_and_matches_baseline() {
+ let (metrics, nodes) = metrics_and_nodes();
+ let sql = "SELECT mhost, zone, AVG(p) AS score FROM (SELECT m.mhost, n.zone, m.mval * n.wgt AS p, n.wgt AS mval, m.mval AS wgt FROM metrics m JOIN nodes n ON m.mhost = n.nhost) GROUP BY mhost, zone";
+ let baseline = engine_over(metrics.clone(), nodes.clone(), false);
+ let rewritten = engine_over(metrics, nodes, true);
+ let plan = query_plan(&rewritten, sql).await;
+ assert!(
+ plan.contains("partial_nv"),
+ "projected product should rewrite:\n{plan}"
+ );
+ let plan_lower = plan.to_lowercase();
+ assert!(
+ plan_lower.contains("m.mval"),
+ "fact payload source missing:\n{plan}"
+ );
+ assert!(
+ plan_lower.contains("n.wgt"),
+ "dim payload source missing:\n{plan}"
+ );
+ assert_eq!(
+ query_output(&baseline, sql).await,
+ query_output(&rewritten, sql).await
+ );
+}
+
+#[tokio::test]
+async fn sum_and_reversed_product_rewrites_match_baseline() {
+ let (metrics, nodes) = metrics_and_nodes();
+ let cases = [
+ "SELECT m.mhost, n.zone, SUM(m.mval * n.wgt) AS score FROM metrics m JOIN nodes n ON m.mhost = n.nhost GROUP BY m.mhost, n.zone",
+ "SELECT m.mhost, n.zone, AVG(n.wgt * m.mval) AS score FROM metrics m JOIN nodes n ON m.mhost = n.nhost GROUP BY m.mhost, n.zone",
+ ];
+ for sql in cases {
+ let baseline = engine_over(metrics.clone(), nodes.clone(), false);
+ let rewritten = engine_over(metrics.clone(), nodes.clone(), true);
+ let plan = query_plan(&rewritten, sql).await;
+ assert!(plan.contains("partial_nv"), "should rewrite {sql}:\n{plan}");
+ assert_eq!(
+ query_output(&baseline, sql).await,
+ query_output(&rewritten, sql).await
+ );
+ }
+}
+
+#[tokio::test]
+async fn non_float64_payload_keeps_the_baseline_plan() {
+ let metrics = RecordBatch::new(
+ Arc::new(Schema::new(vec![
+ ColumnSchema::new(
+ "ts",
+ ConcreteDataType::timestamp_millisecond_datatype(),
+ false,
+ )
+ .with_time_index(true),
+ ColumnSchema::new("mhost", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("mval", ConcreteDataType::int64_datatype(), true),
+ ])),
+ vec![
+ Arc::new(TimestampMillisecondVector::from_slice(vec![0; 2])) as _,
+ Arc::new(StringVector::from(vec![Some("m1"), Some("m1")])) as _,
+ Arc::new(datatypes::vectors::Int64Vector::from(vec![
+ Some(1),
+ Some(2),
+ ])) as _,
+ ],
+ )
+ .unwrap();
+ let (_, nodes) = metrics_and_nodes();
+ let enabled = engine_over(metrics, nodes, true);
+ let plan = query_plan(&enabled, METRIC_AVG_SQL).await;
+ assert!(
+ !plan.contains("partial_nv"),
+ "Int64 payload must not rewrite:\n{plan}"
+ );
+}
+
+#[tokio::test]
+async fn near_miss_shapes_stay_on_the_baseline() {
+ let (metrics, nodes) = metrics_and_nodes();
+ let enabled = engine_over(metrics, nodes, true);
+ for sql in [
+ "SELECT m.mhost, n.zone, AVG(m.mval) AS score FROM metrics m JOIN nodes n ON m.mhost = n.nhost GROUP BY m.mhost, n.zone",
+ "SELECT m.mhost, n.zone, AVG(DISTINCT m.mval * n.wgt) AS score FROM metrics m JOIN nodes n ON m.mhost = n.nhost GROUP BY m.mhost, n.zone",
+ "SELECT m.mhost, n.zone, AVG(m.mval * n.wgt) FILTER (WHERE m.mval > 0) AS score FROM metrics m JOIN nodes n ON m.mhost = n.nhost GROUP BY m.mhost, n.zone",
+ "SELECT m.mhost, n.zone, AVG(m.mval * n.wgt) AS score, COUNT(*) AS c FROM metrics m JOIN nodes n ON m.mhost = n.nhost GROUP BY m.mhost, n.zone",
+ "SELECT m.mhost, n.zone, SUM(m.mval + n.wgt) AS score FROM metrics m JOIN nodes n ON m.mhost = n.nhost GROUP BY m.mhost, n.zone",
+ ] {
+ let plan = query_plan(&enabled, sql).await;
+ assert!(
+ !plan.contains("partial_nv"),
+ "must not rewrite {sql}:\n{plan}"
+ );
+ }
+}
+
+/// Optimize through the per-query state so session SET overrides exercise the
+/// actual optimizer extension, not just the option value.
+#[tokio::test]
+async fn session_set_false_overrides_server_true() {
+ use crate::options::FactorizedJoinAggOptions;
+ let (metrics, nodes) = metrics_and_nodes();
+ let engine = engine_over(metrics, nodes, true);
+ let df_engine = engine
+ .as_any()
+ .downcast_ref::()
+ .expect("datafusion engine");
+
+ // Session never SET: the server-level ON default reaches the query state.
+ let ctx = QueryContext::arc();
+ let engine_ctx = df_engine.engine_context_for_tests(ctx.clone());
+ let inherited = engine_ctx.state();
+ let inherited_on = inherited
+ .config()
+ .options()
+ .extensions
+ .get::()
+ .expect("server default present")
+ .enabled;
+ assert!(inherited_on);
+ let statement = QueryLanguageParser::parse_sql(METRIC_AVG_SQL, &ctx).unwrap();
+ let logical = engine
+ .planner()
+ .plan(&statement, ctx.clone())
+ .await
+ .unwrap();
+ let inherited_plan = inherited.optimize(&logical).unwrap();
+ assert!(
+ inherited_plan
+ .display_indent()
+ .to_string()
+ .contains("partial_nv"),
+ "server true must rewrite"
+ );
+
+ // Session SET false: the same state now reports disabled.
+ ctx.configuration_parameter()
+ .set_query_option("experimental_enable_factorized_join_agg", "false")
+ .unwrap();
+ let engine_ctx2 = df_engine.engine_context_for_tests(ctx.clone());
+ let overridden = engine_ctx2.state();
+ let now = overridden
+ .config()
+ .options()
+ .extensions
+ .get::()
+ .expect("extension present after SET")
+ .enabled;
+ assert!(!now, "session SET false must override server true");
+ let overridden_plan = overridden.optimize(&logical).unwrap();
+ assert!(
+ !overridden_plan
+ .display_indent()
+ .to_string()
+ .contains("partial_nv"),
+ "session false must keep baseline plan"
+ );
+
+ // Session SET true on a server-OFF engine: enabled.
+ let (metrics2, nodes2) = metrics_and_nodes();
+ let engine_off = engine_over(metrics2, nodes2, false);
+ let df_engine_off = engine_off
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ let ctx2 = QueryContext::arc();
+ ctx2.configuration_parameter()
+ .set_query_option("experimental_enable_factorized_join_agg", "true")
+ .unwrap();
+ let enabled = df_engine_off
+ .engine_context_for_tests(ctx2.clone())
+ .state()
+ .config()
+ .options()
+ .extensions
+ .get::()
+ .expect("extension present after SET true")
+ .enabled;
+ assert!(enabled);
+ let statement2 = QueryLanguageParser::parse_sql(METRIC_AVG_SQL, &ctx2).unwrap();
+ let logical2 = engine_off
+ .planner()
+ .plan(&statement2, ctx2.clone())
+ .await
+ .unwrap();
+ let enabled_ctx = df_engine_off.engine_context_for_tests(ctx2);
+ let enabled_state = enabled_ctx.state();
+ let enabled_plan = enabled_state.optimize(&logical2).unwrap();
+ assert!(
+ enabled_plan
+ .display_indent()
+ .to_string()
+ .contains("partial_nv"),
+ "session true must rewrite"
+ );
+}
+
+/// Two tables whose group/join keys are literally named like the aliases the
+/// rewrite generates: `partial_nv_1` is the left grouping/join key and
+/// `partial_nw_3` the right group column, so both land next to a qualified
+/// group field of the same bare name in a partial aggregate's output schema.
+/// `partial_sv_2`/`partial_sw_4` are plain payload-side columns named like the
+/// remaining two aliases. hosts: a{2.0}, b{4.0};
+/// areas: a:west(3.0), b:east(0.5).
+fn alias_like_column_names() -> (RecordBatch, RecordBatch) {
+ let metrics = RecordBatch::new(
+ Arc::new(Schema::new(vec![
+ ColumnSchema::new(
+ "ts",
+ ConcreteDataType::timestamp_millisecond_datatype(),
+ false,
+ )
+ .with_time_index(true),
+ ColumnSchema::new("partial_nv_1", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
+ ColumnSchema::new("partial_sv_2", ConcreteDataType::string_datatype(), true),
+ ])),
+ vec![
+ Arc::new(TimestampMillisecondVector::from_slice(vec![0, 1])) as _,
+ Arc::new(StringVector::from(vec![Some("a"), Some("b")])) as _,
+ Arc::new(Float64Vector::from(vec![Some(2.0), Some(4.0)])) as _,
+ Arc::new(StringVector::from(vec![Some("x"), Some("y")])) as _,
+ ],
+ )
+ .unwrap();
+ let nodes = RecordBatch::new(
+ Arc::new(Schema::new(vec![
+ ColumnSchema::new(
+ "ts",
+ ConcreteDataType::timestamp_millisecond_datatype(),
+ false,
+ )
+ .with_time_index(true),
+ ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("partial_nw_3", ConcreteDataType::string_datatype(), true),
+ ColumnSchema::new("weight", ConcreteDataType::float64_datatype(), true),
+ ColumnSchema::new("partial_sw_4", ConcreteDataType::string_datatype(), true),
+ ])),
+ vec![
+ Arc::new(TimestampMillisecondVector::from_slice(vec![0, 1])) as _,
+ Arc::new(StringVector::from(vec![Some("a"), Some("b")])) as _,
+ Arc::new(StringVector::from(vec![Some("west"), Some("east")])) as _,
+ Arc::new(Float64Vector::from(vec![Some(3.0), Some(0.5)])) as _,
+ Arc::new(StringVector::from(vec![Some("p"), Some("q")])) as _,
+ ],
+ )
+ .unwrap();
+ (metrics, nodes)
+}
+
+/// A column named like a generated alias must not make the partial aggregates'
+/// schemas ambiguous: the aliases are renamed instead, and the results still
+/// match the baseline exactly.
+#[tokio::test]
+async fn aliases_do_not_collide_with_column_names() {
+ let (metrics, nodes) = alias_like_column_names();
+ let sql = "SELECT m.partial_nv_1, n.partial_nw_3, AVG(m.value * n.weight) AS score \
+ FROM metrics m JOIN nodes n ON m.partial_nv_1 = n.host \
+ GROUP BY m.partial_nv_1, n.partial_nw_3";
+ let baseline = engine_over(metrics.clone(), nodes.clone(), false);
+ let rewritten = engine_over(metrics, nodes, true);
+ let baseline_plan = query_plan(&baseline, sql).await;
+ let rewritten_plan = query_plan(&rewritten, sql).await;
+ assert!(
+ rewritten_plan.contains("_partial_nv_1") && rewritten_plan.contains("_partial_nw_3"),
+ "colliding column names must be renamed in the rewrite:\n{rewritten_plan}"
+ );
+ assert!(
+ !baseline_plan.contains("_partial_"),
+ "switch off must keep the baseline plan:\n{baseline_plan}"
+ );
+ assert_eq!(
+ query_output(&baseline, sql).await,
+ query_output(&rewritten, sql).await
+ );
+}
diff --git a/src/query/src/sql.rs b/src/query/src/sql.rs
index a9dc822fe8a..aebb0cb6850 100644
--- a/src/query/src/sql.rs
+++ b/src/query/src/sql.rs
@@ -879,6 +879,14 @@ pub fn show_query_option(
.map(|options| options.allow_query_fallback)
.unwrap_or(false)
.to_string(),
+ "query.experimental_enable_factorized_join_agg" => context
+ .state()
+ .config_options()
+ .extensions
+ .get::()
+ .map(|options| options.enabled)
+ .unwrap_or(false)
+ .to_string(),
"query.enable_remote_dynamic_filter_pushdown" => {
crate::options::remote_dyn_filter_pushdown_enabled_from_extensions(
&context.query_ctx().extensions(),
diff --git a/src/session/src/query_options.rs b/src/session/src/query_options.rs
index d52d3dbb686..2bf4392e85c 100644
--- a/src/session/src/query_options.rs
+++ b/src/session/src/query_options.rs
@@ -22,6 +22,10 @@ pub fn canonical_query_option_name(key: &str) -> Option {
"query_fallback" | "allow_query_fallback" | "query.allow_query_fallback" => {
Some("query.allow_query_fallback".to_string())
}
+ "experimental_enable_factorized_join_agg"
+ | "query.experimental_enable_factorized_join_agg" => {
+ Some("query.experimental_enable_factorized_join_agg".to_string())
+ }
"query.enable_remote_dynamic_filter_pushdown" => {
Some("query.enable_remote_dynamic_filter_pushdown".to_string())
}
diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs
index 28d09a4802b..10630451618 100644
--- a/tests-integration/tests/http.rs
+++ b/tests-integration/tests/http.rs
@@ -4963,6 +4963,7 @@ ttl = "2months 29days 2h 52m 48s"
[query]
parallelism = 0
allow_query_fallback = false
+experimental_enable_factorized_join_agg = false
experimental_spill_mode = "default"
experimental_spill_max_temp_directory_size = "1GiB"
experimental_spill_compression = "uncompressed"
diff --git a/tests/cases/standalone/common/factorized_join_agg/factorized_join_agg.result b/tests/cases/standalone/common/factorized_join_agg/factorized_join_agg.result
new file mode 100644
index 00000000000..7df2bd1236d
--- /dev/null
+++ b/tests/cases/standalone/common/factorized_join_agg/factorized_join_agg.result
@@ -0,0 +1,221 @@
+-- Factorized join aggregation behind the experimental opt-in switch.
+-- Covers: rewrite off by default, SET enabling it, result parity, SET false
+-- overriding, and EXPLAIN showing the partial-aggregate shape.
+-- SQLNESS PROTOCOL MYSQL
+CREATE TABLE ffx_metrics (
+ ts TIMESTAMP TIME INDEX,
+ mhost STRING,
+ mval DOUBLE
+);
+
+affected_rows: 0
+
+-- SQLNESS PROTOCOL MYSQL
+CREATE TABLE ffx_nodes (
+ ts TIMESTAMP TIME INDEX,
+ nhost STRING,
+ area STRING,
+ wgt DOUBLE
+);
+
+affected_rows: 0
+
+-- SQLNESS PROTOCOL MYSQL
+INSERT INTO ffx_metrics VALUES
+ ('2024-01-01 00:00:00', 'm1', 1.0),
+ ('2024-01-01 00:00:01', 'm1', 2.0),
+ ('2024-01-01 00:00:02', 'm1', NULL),
+ ('2024-01-01 00:00:03', 'm2', 4.0);
+
+affected_rows: 4
+
+-- SQLNESS PROTOCOL MYSQL
+INSERT INTO ffx_nodes VALUES
+ ('2024-01-01 00:00:00', 'm1', 'west', 2.0),
+ ('2024-01-01 00:00:01', 'm1', 'east', NULL),
+ ('2024-01-01 00:00:02', 'm2', 'west', 0.5);
+
+affected_rows: 3
+
+-- Default (switch off): plain aggregate over the join.
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
++-------+------+-------+
+| mhost | area | score |
++-------+------+-------+
+| m1 | east | |
+| m1 | west | 3 |
+| m2 | west | 2 |
++-------+------+-------+
+
+-- Enable the experimental rewrite for this session.
+-- SQLNESS PROTOCOL MYSQL
+SET experimental_enable_factorized_join_agg = true;
+
+affected_rows: 0
+
+-- Rewritten path: identical results (NULL group preserved).
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
++-------+------+-------+
+| mhost | area | score |
++-------+------+-------+
+| m1 | east | |
+| m1 | west | 3 |
+| m2 | west | 2 |
++-------+------+-------+
+
+-- SUM variant also rewrites.
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, SUM(m.mval * n.wgt) AS total
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
++-------+------+-------+
+| mhost | area | total |
++-------+------+-------+
+| m1 | east | |
+| m1 | west | 6 |
+| m2 | west | 2 |
++-------+------+-------+
+
+-- Grouping by the right-side join key keeps the matching key pair intact.
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost AS left_host, n.nhost AS right_host, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.nhost ORDER BY m.mhost, n.nhost;
+
++-----------+------------+-------+
+| left_host | right_host | score |
++-----------+------------+-------+
+| m1 | m1 | 3 |
+| m2 | m2 | 2 |
++-----------+------------+-------+
+
+-- The rewrite appears in the plan as partial count/sum aggregates joined.
+-- SQLNESS PROTOCOL MYSQL
+-- SQLNESS REPLACE (peers.*) REDACTED
+EXPLAIN SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area;
+
++---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| plan_type | plan |
++---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| logical_plan | Projection: m.mhost, n.area, CASE WHEN partial_nv_1 = Int64(0) OR partial_nw_3 = Int64(0) THEN Float64(NULL) ELSE CASE WHEN partial_sv_2 * partial_sw_4 = Float64(0) THEN Float64(0) ELSE partial_sv_2 * partial_sw_4 END / CAST(partial_nv_1 AS Float64) * CAST(partial_nw_3 AS Float64) END AS score |
+| | Inner Join: m.mhost = n.nhost |
+| | Aggregate: groupBy=[[m.mhost]], aggr=[[count(m.mval) AS partial_nv_1, sum(m.mval) AS partial_sv_2]] |
+| | MergeScan [is_placeholder=false, remote_input=[ |
+| | Projection: m.mhost, m.mval |
+| | SubqueryAlias: m |
+| | Filter: ffx_metrics.mhost IS NOT NULL |
+| | TableScan: ffx_metrics, partial_filters=[ffx_metrics.mhost IS NOT NULL] |
+| | ]] |
+| | Aggregate: groupBy=[[n.nhost, n.area]], aggr=[[count(n.wgt) AS partial_nw_3, sum(n.wgt) AS partial_sw_4]] |
+| | MergeScan [is_placeholder=false, remote_input=[ |
+| | Projection: n.nhost, n.area, n.wgt |
+| | SubqueryAlias: n |
+| | Filter: ffx_nodes.nhost IS NOT NULL |
+| | TableScan: ffx_nodes, partial_filters=[ffx_nodes.nhost IS NOT NULL] |
+| | ]] |
+| physical_plan | ProjectionExec: expr=[mhost@0 as mhost, area@1 as area, CASE WHEN partial_nv_1@2 = 0 OR partial_nw_3@3 = 0 THEN NULL ELSE CASE WHEN partial_sv_2@4 * partial_sw_4@5 = 0 THEN 0 ELSE partial_sv_2@4 * partial_sw_4@5 END / CAST(partial_nv_1@2 AS Float64) * CAST(partial_nw_3@3 AS Float64) END as score] |
+| | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(mhost@0, nhost@0)], projection=[mhost@0, area@4, partial_nv_1@1, partial_nw_3@5, partial_sv_2@2, partial_sw_4@6] |
+| | AggregateExec: mode=FinalPartitioned, gby=[mhost@0 as mhost], aggr=[count(m.mval) as partial_nv_1, sum(m.mval) as partial_sv_2] |
+| | RepartitionExec: partitioning=Hash([mhost@0], 4), input_partitions=4 |
+| | AggregateExec: mode=Partial, gby=[mhost@0 as mhost], aggr=[count(m.mval) as partial_nv_1, sum(m.mval) as partial_sv_2] |
+| | RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 |
+| | MergeScanExec: REDACTED
+| | RepartitionExec: partitioning=Hash([nhost@0], 4), input_partitions=4 |
+| | AggregateExec: mode=FinalPartitioned, gby=[nhost@0 as nhost, area@1 as area], aggr=[count(n.wgt) as partial_nw_3, sum(n.wgt) as partial_sw_4] |
+| | RepartitionExec: partitioning=Hash([nhost@0, area@1], 4), input_partitions=4 |
+| | AggregateExec: mode=Partial, gby=[nhost@0 as nhost, area@1 as area], aggr=[count(n.wgt) as partial_nw_3, sum(n.wgt) as partial_sw_4] |
+| | RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 |
+| | MergeScanExec: REDACTED
+| | |
++---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+
+-- A shape that must NOT rewrite: single-column AVG.
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, AVG(m.mval) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
++-------+------+-------+
+| mhost | area | score |
++-------+------+-------+
+| m1 | east | 1.5 |
+| m1 | west | 1.5 |
+| m2 | west | 4 |
++-------+------+-------+
+
+-- Session SET false turns the rewrite back off.
+-- SQLNESS PROTOCOL MYSQL
+SET experimental_enable_factorized_join_agg = false;
+
+affected_rows: 0
+
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
++-------+------+-------+
+| mhost | area | score |
++-------+------+-------+
+| m1 | east | |
+| m1 | west | 3 |
+| m2 | west | 2 |
++-------+------+-------+
+
+-- SET false restores the plain aggregate plan without partial aliases.
+-- SQLNESS PROTOCOL MYSQL
+-- SQLNESS REPLACE (peers.*) REDACTED
+EXPLAIN SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area;
+
++---------------+---------------------------------------------------------------------------------------------------------------------------+
+| plan_type | plan |
++---------------+---------------------------------------------------------------------------------------------------------------------------+
+| logical_plan | Projection: m.mhost, n.area, avg(m.mval * n.wgt) AS score |
+| | Aggregate: groupBy=[[m.mhost, n.area]], aggr=[[avg(m.mval * n.wgt)]] |
+| | Projection: m.mhost, m.mval, n.area, n.wgt |
+| | Inner Join: m.mhost = n.nhost |
+| | MergeScan [is_placeholder=false, remote_input=[ |
+| | Projection: m.mhost, m.mval |
+| | SubqueryAlias: m |
+| | Filter: ffx_metrics.mhost IS NOT NULL |
+| | TableScan: ffx_metrics, partial_filters=[ffx_metrics.mhost IS NOT NULL] |
+| | ]] |
+| | MergeScan [is_placeholder=false, remote_input=[ |
+| | Projection: n.nhost, n.area, n.wgt |
+| | SubqueryAlias: n |
+| | Filter: ffx_nodes.nhost IS NOT NULL |
+| | TableScan: ffx_nodes, partial_filters=[ffx_nodes.nhost IS NOT NULL] |
+| | ]] |
+| physical_plan | ProjectionExec: expr=[mhost@0 as mhost, area@1 as area, avg(m.mval * n.wgt)@2 as score] |
+| | AggregateExec: mode=SinglePartitioned, gby=[mhost@0 as mhost, area@2 as area], aggr=[avg(m.mval * n.wgt)] |
+| | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(mhost@0, nhost@0)], projection=[mhost@0, mval@1, area@3, wgt@4] |
+| | RepartitionExec: partitioning=Hash([mhost@0], 4), input_partitions=1 |
+| | MergeScanExec: REDACTED
+| | RepartitionExec: partitioning=Hash([nhost@0], 4), input_partitions=1 |
+| | MergeScanExec: REDACTED
+| | |
++---------------+---------------------------------------------------------------------------------------------------------------------------+
+
+-- SQLNESS PROTOCOL MYSQL
+DROP TABLE ffx_metrics;
+
+affected_rows: 0
+
+-- SQLNESS PROTOCOL MYSQL
+DROP TABLE ffx_nodes;
+
+affected_rows: 0
+
diff --git a/tests/cases/standalone/common/factorized_join_agg/factorized_join_agg.sql b/tests/cases/standalone/common/factorized_join_agg/factorized_join_agg.sql
new file mode 100644
index 00000000000..2699368c994
--- /dev/null
+++ b/tests/cases/standalone/common/factorized_join_agg/factorized_join_agg.sql
@@ -0,0 +1,94 @@
+-- Factorized join aggregation behind the experimental opt-in switch.
+-- Covers: rewrite off by default, SET enabling it, result parity, SET false
+-- overriding, and EXPLAIN showing the partial-aggregate shape.
+
+-- SQLNESS PROTOCOL MYSQL
+CREATE TABLE ffx_metrics (
+ ts TIMESTAMP TIME INDEX,
+ mhost STRING,
+ mval DOUBLE
+);
+
+-- SQLNESS PROTOCOL MYSQL
+CREATE TABLE ffx_nodes (
+ ts TIMESTAMP TIME INDEX,
+ nhost STRING,
+ area STRING,
+ wgt DOUBLE
+);
+
+-- SQLNESS PROTOCOL MYSQL
+INSERT INTO ffx_metrics VALUES
+ ('2024-01-01 00:00:00', 'm1', 1.0),
+ ('2024-01-01 00:00:01', 'm1', 2.0),
+ ('2024-01-01 00:00:02', 'm1', NULL),
+ ('2024-01-01 00:00:03', 'm2', 4.0);
+
+-- SQLNESS PROTOCOL MYSQL
+INSERT INTO ffx_nodes VALUES
+ ('2024-01-01 00:00:00', 'm1', 'west', 2.0),
+ ('2024-01-01 00:00:01', 'm1', 'east', NULL),
+ ('2024-01-01 00:00:02', 'm2', 'west', 0.5);
+
+-- Default (switch off): plain aggregate over the join.
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
+-- Enable the experimental rewrite for this session.
+-- SQLNESS PROTOCOL MYSQL
+SET experimental_enable_factorized_join_agg = true;
+
+-- Rewritten path: identical results (NULL group preserved).
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
+-- SUM variant also rewrites.
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, SUM(m.mval * n.wgt) AS total
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
+-- Grouping by the right-side join key keeps the matching key pair intact.
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost AS left_host, n.nhost AS right_host, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.nhost ORDER BY m.mhost, n.nhost;
+
+-- The rewrite appears in the plan as partial count/sum aggregates joined.
+-- SQLNESS PROTOCOL MYSQL
+-- SQLNESS REPLACE (peers.*) REDACTED
+EXPLAIN SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area;
+
+-- A shape that must NOT rewrite: single-column AVG.
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, AVG(m.mval) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
+-- Session SET false turns the rewrite back off.
+-- SQLNESS PROTOCOL MYSQL
+SET experimental_enable_factorized_join_agg = false;
+
+-- SQLNESS PROTOCOL MYSQL
+SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area ORDER BY m.mhost, n.area;
+
+-- SET false restores the plain aggregate plan without partial aliases.
+-- SQLNESS PROTOCOL MYSQL
+-- SQLNESS REPLACE (peers.*) REDACTED
+EXPLAIN SELECT m.mhost, n.area, AVG(m.mval * n.wgt) AS score
+FROM ffx_metrics m JOIN ffx_nodes n ON m.mhost = n.nhost
+GROUP BY m.mhost, n.area;
+
+-- SQLNESS PROTOCOL MYSQL
+DROP TABLE ffx_metrics;
+
+-- SQLNESS PROTOCOL MYSQL
+DROP TABLE ffx_nodes;
diff --git a/tests/cases/standalone/common/tql-explain-analyze/explain.result b/tests/cases/standalone/common/tql-explain-analyze/explain.result
index 16930d8ccef..761c7f3f255 100644
--- a/tests/cases/standalone/common/tql-explain-analyze/explain.result
+++ b/tests/cases/standalone/common/tql-explain-analyze/explain.result
@@ -141,6 +141,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test;
| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_|
| logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_|
| logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_|
+| logical_plan after factorized_join_agg_rewrite_| SAME TEXT AS ABOVE_|
| logical_plan after rewrite_set_comparison_| SAME TEXT AS ABOVE_|
| logical_plan after optimize_unions_| SAME TEXT AS ABOVE_|
| logical_plan after unions_to_filter_| SAME TEXT AS ABOVE_|
@@ -170,6 +171,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test;
| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_|
| logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_|
| logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_|
+| logical_plan after factorized_join_agg_rewrite_| SAME TEXT AS ABOVE_|
| logical_plan_| MergeScan [is_placeholder=false, remote_input=[_|
|_| PromInstantManipulate: range=[0..10000], lookback=[300000], interval=[5000], time index=[j]_|
|_|_PromSeriesDivide: tags=["k"]_|
@@ -305,6 +307,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test AS series;
| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_|
| logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_|
| logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_|
+| logical_plan after factorized_join_agg_rewrite_| SAME TEXT AS ABOVE_|
| logical_plan after rewrite_set_comparison_| SAME TEXT AS ABOVE_|
| logical_plan after optimize_unions_| SAME TEXT AS ABOVE_|
| logical_plan after unions_to_filter_| SAME TEXT AS ABOVE_|
@@ -334,6 +337,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test AS series;
| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_|
| logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_|
| logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_|
+| logical_plan after factorized_join_agg_rewrite_| SAME TEXT AS ABOVE_|
| logical_plan_| MergeScan [is_placeholder=false, remote_input=[_|
|_| Projection: test.i AS series, test.k, test.j_|
|_|_PromInstantManipulate: range=[0..10000], lookback=[300000], interval=[5000], time index=[j]_|
@@ -500,6 +504,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test_nano;
| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_|
| logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_|
| logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_|
+| logical_plan after factorized_join_agg_rewrite_| SAME TEXT AS ABOVE_|
| logical_plan after rewrite_set_comparison_| SAME TEXT AS ABOVE_|
| logical_plan after optimize_unions_| SAME TEXT AS ABOVE_|
| logical_plan after unions_to_filter_| SAME TEXT AS ABOVE_|
@@ -529,6 +534,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test_nano;
| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_|
| logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_|
| logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_|
+| logical_plan after factorized_join_agg_rewrite_| SAME TEXT AS ABOVE_|
| logical_plan_| MergeScan [is_placeholder=false, remote_input=[_|
|_| PromInstantManipulate: range=[0..10000], lookback=[300000], interval=[5000], time index=[j]_|
|_|_PromSeriesDivide: tags=["k"]_|