Skip to main content

query/optimizer/
factorized_join_agg.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Shape-based `AVG(value * weight)` and `SUM(value * weight)`
16//! join-aggregation rewrites.
17//!
18//! Every rewrite turns `... JOIN ... GROUP BY host, area` with a single
19//! aggregate into a join of two partial aggregates computed on one side of the
20//! join each, with a projection above the join reconstructing the aggregate.
21//! Admission is decided by the plan shape alone: the rule never inspects the
22//! data its inputs will read.
23//!
24//! `AVG(value * weight)` / `SUM(value * weight)`: the aggregate over the
25//! pairwise products is replaced by `SUM(value) * SUM(weight)` divided by
26//! `COUNT(value) * COUNT(weight)` (`AVG`) or used as it is (`SUM`). The counts
27//! are checked individually for zero; for `AVG` they are cast to `Float64`
28//! before multiplication to avoid overflowing their `Int64` representation.
29//!
30//! # Approximation contract
31//!
32//! The payload rewrite is opt-in rule state and **shape-based**: it does not
33//! inspect the payloads, so it cannot know how well they factorize.
34//!
35//! - Floating-point reassociation means the factorized result can differ from
36//!   the pairwise baseline; on inputs with heavy cancellation, intermediate
37//!   overflow, or subnormal/extreme magnitudes, it can differ arbitrarily, in
38//!   magnitude and in sign.
39//!
40//! That difference is accepted in this opt-in experiment mode: the opt-in
41//! switch and this documentation are the guard, not an admission classifier.
42//! Queries whose payloads may be ill-conditioned should keep the switch off.
43//!
44//! One difference is removed for free: a zero numerator is normalized to `+0.0`
45//! (a `CASE` in the reconstruction), so a cancellation the baseline evaluates to
46//! `+0.0` cannot surface here as `-0.0`.
47//!
48//! The rule is intentionally narrow: it matches only the join and group shapes
49//! described by `matching_payload_shape`. It is registered in the optimizer but
50//! remains inert unless enabled by config/session extension state.
51
52use std::collections::HashSet;
53use std::sync::Arc;
54
55use crate::dist_plan::MergeScanLogicalPlan;
56use arrow_schema::DataType;
57use datafusion::functions_aggregate::average::Avg;
58use datafusion::functions_aggregate::count::count_udaf;
59use datafusion::functions_aggregate::sum::{Sum, sum_udaf};
60use datafusion_common::tree_node::Transformed;
61use datafusion_common::{Column, DFSchema, NullEquality, Result, ScalarValue};
62use datafusion_expr::expr::{AggregateFunction, BinaryExpr, Case, Cast};
63use datafusion_expr::logical_plan::{Aggregate, Join, JoinConstraint, JoinType, Projection};
64use datafusion_expr::{AggregateUDF, Expr, LogicalPlan, Operator};
65use datafusion_optimizer::optimizer::ApplyOrder;
66use datafusion_optimizer::{OptimizerConfig, OptimizerRule};
67
68/// Rewrites supported AVG/SUM payload products into partial aggregates.
69#[derive(Debug, Default)]
70pub(crate) struct FactorizedJoinAggRule;
71
72impl OptimizerRule for FactorizedJoinAggRule {
73    fn name(&self) -> &str {
74        "factorized_join_agg_rewrite"
75    }
76
77    fn apply_order(&self) -> Option<ApplyOrder> {
78        Some(ApplyOrder::BottomUp)
79    }
80
81    fn rewrite(
82        &self,
83        plan: LogicalPlan,
84        config: &dyn OptimizerConfig,
85    ) -> Result<Transformed<LogicalPlan>> {
86        if !config
87            .options()
88            .extensions
89            .get::<crate::options::FactorizedJoinAggOptions>()
90            .is_some_and(|options| options.enabled)
91        {
92            return Ok(Transformed::no(plan));
93        }
94        let LogicalPlan::Aggregate(agg) = &plan else {
95            return Ok(Transformed::no(plan));
96        };
97        // The payload rewrites are shape-based: they need neither the pair bound
98        // nor any data certificate, only the matched join/group shape, and they
99        // never materialize the pair count. A single aggregate can match at most
100        // one of the two functions.
101        for function in [PayloadFunction::Avg, PayloadFunction::Sum] {
102            if let Some(matched) = matching_payload_shape(agg, function) {
103                return rewrite_payload(agg, &matched, function, config);
104            }
105        }
106        Ok(Transformed::no(plan))
107    }
108}
109
110/// Rewrites the matched `AVG(value * weight)` or `SUM(value * weight)`
111/// aggregate into a join of two partial aggregates whose projection
112/// reconstructs the payload function from them.
113///
114/// The projection computes, from the branch `nv`/`sv` (fact) and `nw`/`sw`
115/// (dim) outputs:
116///
117/// ```text
118/// no_products = (nv = 0) OR (nw = 0)
119/// total       = CASE WHEN sv * sw = 0.0 THEN 0.0 ELSE sv * sw END
120/// AVG         = CASE WHEN no_products THEN NULL ELSE total / (CAST(nv AS Float64) * CAST(nw AS Float64)) END
121/// SUM         = CASE WHEN no_products THEN NULL ELSE total END
122/// ```
123///
124/// Both reconstructions return `NULL` for a group without a single non-null
125/// product, which is exactly when either payload count is zero. `AVG` over an
126/// empty pair set is `NULL` and so is `SUM`. Counts are never multiplied as
127/// `Int64`: `AVG` casts each count before multiplication, and `SUM` does not
128/// compute a count product.
129///
130/// `total` normalizes a zero numerator to `+0.0` because the pairwise numerator
131/// it must match can only cancel to `+0.0`: for facts `[1, -1]` with weight
132/// `[-1]`, the baseline sums the products `-1` and `+1` into `+0.0`, while
133/// `SUM(value)` is `+0.0`, `SUM(weight)` is `-1.0` and their naive product is
134/// `-0.0`, which would divide into `-0.0` instead of the baseline's `+0.0`. The
135/// normalization is free and shape-level: it removes that mismatch without
136/// looking at any data. Every other difference between the factorized and the
137/// pairwise result is the approximation the module documentation accepts.
138fn rewrite_payload(
139    agg: &Aggregate,
140    matched: &PayloadMatch<'_>,
141    function: PayloadFunction,
142    config: &dyn OptimizerConfig,
143) -> Result<Transformed<LogicalPlan>> {
144    let PayloadMatch {
145        join,
146        left_key,
147        right_key,
148        right_group,
149        fact_payload,
150        dim_payload,
151    } = matched;
152
153    let (fact_payloads_name, fact_sum_name, dim_payloads_name, dim_sum_name) =
154        partial_aliases(agg, join, config);
155
156    let left = Aggregate::try_new(
157        Arc::clone(&join.left),
158        vec![Expr::Column(left_key.clone())],
159        vec![
160            partial_aggregate(
161                count_udaf(),
162                vec![Expr::Column(fact_payload.clone())],
163                &fact_payloads_name,
164            ),
165            partial_aggregate(
166                sum_udaf(),
167                vec![Expr::Column(fact_payload.clone())],
168                &fact_sum_name,
169            ),
170        ],
171    )?;
172    let right = Aggregate::try_new(
173        Arc::clone(&join.right),
174        vec![
175            Expr::Column(right_key.clone()),
176            Expr::Column(right_group.clone()),
177        ],
178        vec![
179            partial_aggregate(
180                count_udaf(),
181                vec![Expr::Column(dim_payload.clone())],
182                &dim_payloads_name,
183            ),
184            partial_aggregate(
185                sum_udaf(),
186                vec![Expr::Column(dim_payload.clone())],
187                &dim_sum_name,
188            ),
189        ],
190    )?;
191
192    let left = Arc::new(LogicalPlan::Aggregate(left));
193    let right = Arc::new(LogicalPlan::Aggregate(right));
194    let right_area = left.schema().fields().len() + 1;
195    let join_keys = (column_at(left.schema(), 0), column_at(right.schema(), 0));
196    let rewritten_join = Join::try_new(
197        left,
198        right,
199        vec![(Expr::Column(join_keys.0), Expr::Column(join_keys.1))],
200        None,
201        JoinType::Inner,
202        JoinConstraint::On,
203        NullEquality::NullEqualsNothing,
204        false,
205    )?;
206
207    let partial = |name: &str| Expr::Column(Column::new_unqualified(name));
208    let fact_count = partial(&fact_payloads_name);
209    let dim_count = partial(&dim_payloads_name);
210    let no_products = Expr::BinaryExpr(BinaryExpr::new(
211        Box::new(is_zero(fact_count.clone(), int_literal(0))),
212        Operator::Or,
213        Box::new(is_zero(dim_count.clone(), int_literal(0))),
214    ));
215    let product = partial(&fact_sum_name) * partial(&dim_sum_name);
216    // `total`: the signed-zero normalization described on this function.
217    let total = Expr::Case(Case::new(
218        None,
219        vec![(
220            Box::new(is_zero(product.clone(), float_literal(0.0))),
221            Box::new(float_literal(0.0)),
222        )],
223        Some(Box::new(product)),
224    ));
225    let numerator = Expr::Case(Case::new(
226        None,
227        vec![(
228            Box::new(no_products),
229            Box::new(Expr::Literal(ScalarValue::Float64(None), None)),
230        )],
231        Some(Box::new(match function {
232            PayloadFunction::Avg => Expr::BinaryExpr(BinaryExpr::new(
233                Box::new(total),
234                Operator::Divide,
235                Box::new(
236                    Expr::Cast(Cast::new(Box::new(fact_count), DataType::Float64))
237                        * Expr::Cast(Cast::new(Box::new(dim_count), DataType::Float64)),
238                ),
239            )),
240            PayloadFunction::Sum => total,
241        })),
242    ));
243    let output = vec![
244        Expr::Column(column_at(&rewritten_join.schema, 0)),
245        Expr::Column(column_at(&rewritten_join.schema, right_area)),
246        numerator.alias(agg.schema.field(2).name()),
247    ];
248    let projection = Projection::try_new(output, Arc::new(LogicalPlan::Join(rewritten_join)))?;
249    Ok(Transformed::yes(LogicalPlan::Projection(projection)))
250}
251
252/// The four partial-aggregate output names, made collision-free against every
253/// field name the rewritten aggregates can still see.
254///
255/// `OptimizerConfig::alias_generator` only keeps generated aliases apart from
256/// each other, not from the input fields. A column literally named like a
257/// generated alias (say `partial_nv_1`) would then land next to the qualified
258/// grouping key of the same name in a partial aggregate's output schema, and
259/// `DFSchema` rejects that plan as ambiguous: `Schema contains qualified field
260/// name m.partial_nv_1 and unqualified field name partial_nv_1 which would be
261/// ambiguous`. Prepending underscores until the name is unused keeps the names
262/// deterministic and mutually distinct; the visible column set is finite, so
263/// the loop terminates.
264fn partial_aliases(
265    agg: &Aggregate,
266    join: &Join,
267    config: &dyn OptimizerConfig,
268) -> (String, String, String, String) {
269    // `agg.input` is the optional projection above the join, so it already
270    // covers both join inputs; the join schemas are collected as well so the
271    // used set does not depend on whether that projection is present.
272    let mut used: HashSet<String> = HashSet::new();
273    for schema in [join.left.schema(), join.right.schema(), agg.input.schema()] {
274        used.extend(schema.fields().iter().map(|field| field.name().clone()));
275    }
276    let mut unique = |prefix: &str| {
277        let mut name = config.alias_generator().next(prefix);
278        while !used.insert(name.clone()) {
279            name = format!("_{name}");
280        }
281        name
282    };
283    (
284        unique("partial_nv"),
285        unique("partial_sv"),
286        unique("partial_nw"),
287        unique("partial_sw"),
288    )
289}
290
291fn partial_aggregate(udaf: Arc<AggregateUDF>, args: Vec<Expr>, alias: &str) -> Expr {
292    Expr::AggregateFunction(AggregateFunction::new_udf(
293        udaf,
294        args,
295        false,
296        None,
297        vec![],
298        None,
299    ))
300    .alias(alias)
301}
302
303fn int_literal(value: i64) -> Expr {
304    Expr::Literal(ScalarValue::Int64(Some(value)), None)
305}
306
307fn float_literal(value: f64) -> Expr {
308    Expr::Literal(ScalarValue::Float64(Some(value)), None)
309}
310
311/// `<lhs> = <rhs>`, used to detect the zero and NULL cases of the `AVG`
312/// reconstruction.
313fn is_zero(lhs: Expr, rhs: Expr) -> Expr {
314    Expr::BinaryExpr(BinaryExpr::new(Box::new(lhs), Operator::Eq, Box::new(rhs)))
315}
316
317fn column_at(schema: &DFSchema, index: usize) -> Column {
318    let (qualifier, field) = schema.qualified_field(index);
319    Column::new(qualifier.cloned(), field.name())
320}
321
322/// The payload aggregate a rewrite reconstructs from the branch statistics.
323///
324/// Both functions share the same shape, the same two payload columns and the
325/// same branch statistics; they differ only in what the projection computes from
326/// the payload sum product: `AVG` divides it by the payload count product, `SUM`
327/// is the product itself.
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
329pub(crate) enum PayloadFunction {
330    /// `AVG(<fact payload> * <dim payload>)`.
331    Avg,
332    /// `SUM(<fact payload> * <dim payload>)`.
333    Sum,
334}
335
336/// The pieces of the `AVG`/`SUM(<fact payload> * <dim payload>)` shape the
337/// rewrite needs.
338struct PayloadMatch<'a> {
339    join: &'a Join,
340    left_key: Column,
341    right_key: Column,
342    right_group: Column,
343    fact_payload: Column,
344    dim_payload: Column,
345}
346
347/// Matches the narrow supported `AVG(payload * payload)` or
348/// `SUM(payload * payload)` shape and returns the join plus everything the
349/// rewrite needs from it.
350///
351/// Required shape: an inner `ON` equi-join whose group and payload columns map directly
352/// to the respective join sides,
353/// grouped by the left `host` and the right `area`, aggregated by a single
354/// `AVG` — or, for [`PayloadFunction::Sum`], `SUM` — of the product of those two
355/// columns, with no `DISTINCT`, `FILTER`, `ORDER BY`, null treatment or extra
356/// argument. The product operands may be given in either order and may reach the
357/// aggregate through a projection that repeats them.
358fn matching_payload_shape(agg: &Aggregate, function: PayloadFunction) -> Option<PayloadMatch<'_>> {
359    if agg.group_expr.len() != 2 || agg.aggr_expr.len() != 1 {
360        return None;
361    }
362    let (join, projection) = match agg.input.as_ref() {
363        LogicalPlan::Join(join) => (join, None),
364        LogicalPlan::Projection(projection) => match projection.input.as_ref() {
365            LogicalPlan::Join(join) => (join, Some(projection)),
366            _ => return None,
367        },
368        _ => return None,
369    };
370    // Distributed planning wraps each scan in a MergeScan extension and then
371    // restores the original scan schema with a projection. Keep the wrapper in
372    // the rewritten branches, but validate its hidden remote input is a scan.
373    if !is_scan_input(&join.left) || !is_scan_input(&join.right) {
374        return None;
375    }
376    if join.join_type != JoinType::Inner
377        || join.join_constraint != JoinConstraint::On
378        || join.null_equality != NullEquality::NullEqualsNothing
379    {
380        return None;
381    }
382    let (left_key, right_key) = equality_keys(join)?;
383
384    let aggregate = match &agg.aggr_expr[0] {
385        Expr::AggregateFunction(aggregate) => aggregate,
386        Expr::Alias(alias) => match alias.expr.as_ref() {
387            Expr::AggregateFunction(aggregate) => aggregate,
388            _ => return None,
389        },
390        _ => return None,
391    };
392    let params = &aggregate.params;
393    let inner = aggregate.func.inner();
394    let matches_function = match function {
395        PayloadFunction::Avg => inner.downcast_ref::<Avg>().is_some(),
396        PayloadFunction::Sum => inner.downcast_ref::<Sum>().is_some(),
397    };
398    if !matches_function
399        || params.distinct
400        || params.filter.is_some()
401        || !params.order_by.is_empty()
402        || params.null_treatment.is_some()
403        || params.args.len() != 1
404    {
405        return None;
406    }
407    let (Expr::Column(left_group), Expr::Column(right_group)) =
408        (&agg.group_expr[0], &agg.group_expr[1])
409    else {
410        return None;
411    };
412    let left_group = resolve_through_projection(left_group, projection)?;
413    let right_group = resolve_through_projection(right_group, projection)?;
414    let left_key = resolve_through_projection(left_key, None)?;
415    let right_key = resolve_through_projection(right_key, None)?;
416    if left_group != left_key
417        || right_group == right_key
418        || !join.left.schema().has_column(&left_group)
419        || !join.right.schema().has_column(&right_group)
420    {
421        return None;
422    }
423    let (first, second, operands_from_projection_expr) =
424        product_operands(&params.args[0], projection)?;
425    let (first, second) = match operands_from_projection_expr {
426        true => (column_expr(first)?, column_expr(second)?),
427        false => (
428            resolve_expr_through_projection(first, projection)?,
429            resolve_expr_through_projection(second, projection)?,
430        ),
431    };
432    let (fact_payload, dim_payload) =
433        if join.left.schema().has_column(&first) && join.right.schema().has_column(&second) {
434            (first, second)
435        } else if join.left.schema().has_column(&second) && join.right.schema().has_column(&first) {
436            (second, first)
437        } else {
438            return None;
439        };
440    if field_type(join.left.schema(), &fact_payload)? != &DataType::Float64
441        || field_type(join.right.schema(), &dim_payload)? != &DataType::Float64
442    {
443        return None;
444    }
445    Some(PayloadMatch {
446        join,
447        left_key,
448        right_key,
449        right_group,
450        fact_payload,
451        dim_payload,
452    })
453}
454
455/// The two operands of a payload aggregate's argument, which must be a
456/// multiplication of two columns of the joined inputs, in either order.
457///
458/// The projection that may sit between the aggregate and the join either passes
459/// the product's operands through under their original names (the argument is
460/// then the multiplication itself) or computes the product on its own, in which
461/// case the argument is a column of the projection and the multiplication is
462/// looked up there.
463fn product_operands<'a>(
464    argument: &'a Expr,
465    projection: Option<&'a Projection>,
466) -> Option<(&'a Expr, &'a Expr, bool)> {
467    let (entry, operands_from_projection_expr) = match argument {
468        Expr::BinaryExpr(binary) => (binary, false),
469        Expr::Column(column) => {
470            let projection = projection?;
471            let index = projection.schema.maybe_index_of_column(column)?;
472            let entry = projection.expr.get(index)?;
473            let binary = match entry {
474                Expr::BinaryExpr(binary) => binary,
475                Expr::Alias(alias) => match alias.expr.as_ref() {
476                    Expr::BinaryExpr(binary) => binary,
477                    _ => return None,
478                },
479                _ => return None,
480            };
481            (binary, true)
482        }
483        _ => return None,
484    };
485    if entry.op != Operator::Multiply {
486        return None;
487    }
488    Some((
489        entry.left.as_ref(),
490        entry.right.as_ref(),
491        operands_from_projection_expr,
492    ))
493}
494
495fn is_scan_input(plan: &LogicalPlan) -> bool {
496    match plan {
497        LogicalPlan::SubqueryAlias(alias) => is_scan_input(&alias.input),
498        // The distributed planner wraps each scan in a MergeScan extension and
499        // restores the original schema with a projection; a plain column
500        // selection may additionally sit between that wrapper and the join.
501        LogicalPlan::Projection(projection) => is_scan_input(&projection.input),
502        LogicalPlan::Extension(ext) => ext
503            .node
504            .as_any()
505            .downcast_ref::<MergeScanLogicalPlan>()
506            // The merge scan's input can itself carry the wrapped stages (a
507            // projection or filter over the original scan), so recurse.
508            .is_some_and(|scan| is_scan_input(scan.input())),
509        LogicalPlan::TableScan(_) => true,
510        LogicalPlan::Filter(filter) => is_scan_input(&filter.input),
511        _ => false,
512    }
513}
514
515/// Resolve columns through projections only when they are exact pass-throughs.
516fn column_expr(expr: &Expr) -> Option<Column> {
517    let Expr::Column(column) = expr else {
518        return None;
519    };
520    Some(column.clone())
521}
522
523fn resolve_expr_through_projection(expr: &Expr, projection: Option<&Projection>) -> Option<Column> {
524    let Expr::Column(column) = expr else {
525        return None;
526    };
527    resolve_through_projection(column, projection)
528}
529fn resolve_through_projection(column: &Column, projection: Option<&Projection>) -> Option<Column> {
530    if let Some(projection) = projection {
531        let idx = projection.schema.maybe_index_of_column(column)?;
532        let expr = projection.expr.get(idx)?;
533        let Expr::Column(c) = expr else {
534            return None;
535        };
536        return Some(c.clone());
537    }
538    Some(column.clone())
539}
540fn field_type<'a>(schema: &'a DFSchema, column: &Column) -> Option<&'a DataType> {
541    schema
542        .iter()
543        .find(|(q, f)| {
544            f.name().as_str() == column.name.as_str()
545                && column
546                    .relation
547                    .as_ref()
548                    .is_none_or(|relation| *q == Some(relation))
549        })
550        .map(|(_, f)| f.data_type())
551}
552
553fn equality_keys(join: &Join) -> Option<(&Column, &Column)> {
554    if join.on.len() != 1 || join.filter.is_some() {
555        return None;
556    }
557    let (Expr::Column(left), Expr::Column(right)) = (&join.on[0].0, &join.on[0].1) else {
558        return None;
559    };
560    Some((left, right))
561}