mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-26 12:44:10 +00:00
feat(query): opt-in experimental factorized join aggregation rewrite (WIP) (#9546)
* feat(query): opt-in experimental factorized join aggregation rewrite Add an experimental shape-based rewrite for AVG(value * weight) and SUM(value * weight) over an inner equi-join grouped by (host, area), turning it into per-side preaggregates joined and combined in a projection. Opt-in via the new query option experimental_enable_factorized_join_agg (default false), settable per session with SET. The rule is registered always and gates at rewrite time. Approximation contract documented: well-conditioned inputs match baseline to ~1e-9; heavy cancellation/overflow may diverge and is accepted in this opt-in mode. WIP: config/config.md regeneration pending (make config-docs, needs Docker). Draft. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(query): finish switch wiring, config docs, engine-level opt-in test Declare the count_join module without the test gate, register the rule unconditionally, and read FactorizedJoinAggOptions at rewrite time (default off -> Transformed::no). Replace the ported fixture suite with an engine-level test comparing plans with the switch off and on. Regenerate config/config.md (make config-docs). Verified: cargo nextest -p query 815 passed / 2 skipped; -p cmd 94 passed; fmt and clippy clean on touched crates. The SQL SET path is not yet covered by a test. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(query): address review findings on factorized join aggregation Address the blind review of PR 9546: - Admission no longer keys on table/column names: the matcher accepts any inner equi-join of two single-table inputs grouped by (left key, right group column) with one AVG/SUM over a product of two Float64 payload columns, either operand order. Renamed tables rewrite; qualified names work. - Operand/group/key columns resolve through intermediate projections and must be exact pass-throughs; a projection that computes or renames them keeps the baseline plan (previously the rewrite read the raw column and silently dropped the computation). - The rule now fires behind the distributed planner: scan detection recurses through the recovering projection, MergeScan extension, filters, and subquery aliases. Verified by an engine-level test built with the dist planner enabled. - Payload columns must be Float64; Int64/Decimal inputs keep the baseline plan instead of producing mixed-type expressions. - Session SET experimental_enable_factorized_join_agg = false now overrides a server-level true; an unset session inherits the server default (tracked via an explicit set flag). - Renamed rule/module to factorized_join_agg, dropped unused COUNT partial aggregates and stale docs, restored the QueryOptions doc. - Tests: 8 engine-level cases covering renamed tables, result parity within 1e-9 with NULL/valid=0 semantics, computed-alias rejection, Int64 rejection, near-miss shapes, opt-in default, dist-planner firing, and SET override propagation. Verified: cargo nextest -p query 822 passed / 2 skipped; -p cmd 94 passed; fmt clean; clippy clean on touched code. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(query): projection operand scope and atomic session setting Address the post-fix review of PR 9546: - Product operands extracted from a projection expression reference the projection INPUT, so they are no longer re-resolved through the projection's output schema; only aggregate-argument columns resolve through it, and the unqualified name-only fallback is removed — a missing qualified column never silently matches an unrelated same-named column. Regression: a projected product with same-named columns on opposite sides rewrites with the correct payload columns; the projected-product positive shape is now admitted. - The session setting is one ArcSwap<Option<bool>> (None = unset, inherit server default; Some(v) = explicit override). Clone loads a single atomic snapshot; the previous value/flag pair could clone a state that never existed under a concurrent first SET. Clone preservation tests cover unset, explicit false, explicit true. - Tests: computed-payload rejection keeps the grouping columns unchanged so payload validation is the decisive condition; added SUM rewrite parity and reversed-operand AVG parity. Verified: cargo nextest -p query 824 passed / 2 skipped; -p session 17 passed; fmt clean; clippy clean on touched code. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): sqlness case for the factorized join aggregation switch Add a standalone sqlness case exercising the experimental rewrite end to end through the MySQL protocol on one connection: default off, SET experimental_enable_factorized_join_agg = true enabling it (EXPLAIN shows the partial count/sum aggregates joined with the CASE reconstruction), AVG/SUM result parity including the NULL (valid=0) group, a non-matching shape left alone, and SET false turning the rewrite back off. The case must run entirely on the MySQL protocol: session-level SET only propagates within the same connection, and sqlness sends unannotated statements over gRPC with a fresh query context. Verified with cargo sqlness bare -t factorized_join_agg (passes twice in a row on a rebuilt greptime binary); query 824 passed / 2 skipped; session 17 passed. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(query): preserve factorized aggregate schema and count semantics Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): refresh factorized join agg sqlness expectation for MergeScan pushdown Upstream #10221 pushes the column projection through MergeScan, so both the baseline and the rewritten plans now show the projection inside the remote input instead of above it. Regenerated with `cargo sqlness bare -t factorized_join_agg`. All 52 changed lines are Projection/ProjectionExec/MergeScan reordering; result rows, group counts, and the partial aggregate shape are unchanged, and both the standalone and distributed environments pass. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(query): make partial aliases collision-free and refresh CI expectations Address the post-ready review of PR 9546: - The four partial-aggregate aliases are now collision-free against every field name visible to the rewritten aggregates: `join.left.schema()`, `join.right.schema()` and `agg.input.schema()` (the last one includes the optional projection above the join). A real column literally named `partial_nv_1` used to land next to the qualified grouping key of the same bare name in a partial aggregate's output schema, which DFSchema rejects as ambiguous. `aliases_do_not_collide_with_column_names` reproduces that shape (left join/group key `partial_nv_1`, right group column `partial_nw_3`) and asserts both switches plan and produce identical output. - Both EXPLAIN statements in the new sqlness case now carry `-- SQLNESS REPLACE (peers.*) REDACTED`, so the expected output no longer embeds allocation-dependent node IDs; the case passed standalone but failed in the full suite because of them. - Regenerated `common/tql-explain-analyze/explain.result`: registering the rule adds one `logical_plan after factorized_join_agg_rewrite` row per EXPLAIN statement (all `SAME TEXT AS ABOVE`, since the rule leaves those plans unchanged). - `tests-integration/tests/http.rs`: the expected config-API TOML now includes `experimental_enable_factorized_join_agg = false` right after `allow_query_fallback`, matching the field order in `QueryOptions`. Verified on this head: `cargo nextest -p query factorized_join_agg` 13 passed; sqlness `factorized_join_agg` and `tql-explain-analyze` pass in standalone and distributed; `integration_http_file_test::test_config_api` passes; `cargo fmt` clean; clippy `-p query -p tests-integration --all-targets -- -D warnings` clean. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
@@ -145,6 +145,7 @@
|
||||
| `procedure.max_running_procedures` | Integer | `128` | Max running procedures.<br/>The maximum number of procedures that can be running at the same time.<br/>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.<br/>This is the engine-wide default: a session<br/>SET query.experimental_native_promql = true or a per-request<br/>query.experimental_native_promql option overrides it, in that order.<br/>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.<br/>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,<br/>and internal series merges during table scans).<br/>Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>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:<br/>- "greedy" (default): first-come-first-served allocation; preserves current behavior.<br/>- "fair": divides available memory among spillable operators and may spill earlier.<br/>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.<br/>Requires in-process region transport. This is the engine-wide default: a<br/>session SET query.experimental_native_promql = true or a per-request<br/>query.experimental_native_promql option overrides it, in that order.<br/>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.<br/>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.<br/>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).<br/>Supports absolute size (e.g., "4GB", "8GB") or percentage of system memory (e.g., "30%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>This pool applies to operators on this frontend. Datanodes use their own query<br/>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.<br/>- `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).<br/>- `fail`: the read fails, so the region does not open.<br/>**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.<br/>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.<br/>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.<br/>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.<br/>**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.<br/>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,<br/>and internal series merges during table scans).<br/>Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>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:<br/>- "greedy" (default): first-come-first-served allocation; preserves current behavior.<br/>- "fair": divides available memory among spillable operators and may spill earlier.<br/>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.<br/>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).<br/>Supports absolute size (e.g., "1GB", "2GB") or percentage of system memory (e.g., "20%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>NOTE: This does NOT limit memory used by table scans. |
|
||||
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy:<br/>- "greedy" (default): first-come-first-served allocation; preserves current behavior.<br/>- "fair": divides available memory among spillable operators and may spill earlier.<br/>Only effective when `memory_pool_size` is bounded (>0). |
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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`). |
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<ApplyOrder> {
|
||||
Some(ApplyOrder::BottomUp)
|
||||
}
|
||||
|
||||
fn rewrite(
|
||||
&self,
|
||||
plan: LogicalPlan,
|
||||
config: &dyn OptimizerConfig,
|
||||
) -> Result<Transformed<LogicalPlan>> {
|
||||
if !config
|
||||
.options()
|
||||
.extensions
|
||||
.get::<crate::options::FactorizedJoinAggOptions>()
|
||||
.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<Transformed<LogicalPlan>> {
|
||||
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<String> = 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<AggregateUDF>, args: Vec<Expr>, 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)
|
||||
}
|
||||
|
||||
/// `<lhs> = <rhs>`, 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(<fact payload> * <dim payload>)`.
|
||||
Avg,
|
||||
/// `SUM(<fact payload> * <dim payload>)`.
|
||||
Sum,
|
||||
}
|
||||
|
||||
/// The pieces of the `AVG`/`SUM(<fact payload> * <dim payload>)` 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<PayloadMatch<'_>> {
|
||||
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::<Avg>().is_some(),
|
||||
PayloadFunction::Sum => inner.downcast_ref::<Sum>().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::<MergeScanLogicalPlan>()
|
||||
// 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<Column> {
|
||||
let Expr::Column(column) = expr else {
|
||||
return None;
|
||||
};
|
||||
Some(column.clone())
|
||||
}
|
||||
|
||||
fn resolve_expr_through_projection(expr: &Expr, projection: Option<&Projection>) -> Option<Column> {
|
||||
let Expr::Column(column) = expr else {
|
||||
return None;
|
||||
};
|
||||
resolve_through_projection(column, projection)
|
||||
}
|
||||
fn resolve_through_projection(column: &Column, projection: Option<&Projection>) -> Option<Column> {
|
||||
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))
|
||||
}
|
||||
@@ -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<dyn ExtensionOptions> {
|
||||
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<ConfigEntry> {
|
||||
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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<ArrayRef> = 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<Vec<String>> {
|
||||
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<String> = 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<f64> {
|
||||
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::<crate::datafusion::DatafusionQueryEngine>()
|
||||
.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::<FactorizedJoinAggOptions>()
|
||||
.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::<FactorizedJoinAggOptions>()
|
||||
.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::<crate::datafusion::DatafusionQueryEngine>()
|
||||
.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::<FactorizedJoinAggOptions>()
|
||||
.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
|
||||
);
|
||||
}
|
||||
@@ -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::<crate::options::FactorizedJoinAggOptions>()
|
||||
.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(),
|
||||
|
||||
@@ -22,6 +22,10 @@ pub fn canonical_query_option_name(key: &str) -> Option<String> {
|
||||
"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())
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
@@ -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"]_|
|
||||
|
||||
Reference in New Issue
Block a user