fn rewrite_payload(
agg: &Aggregate,
matched: &PayloadMatch<'_>,
function: PayloadFunction,
config: &dyn OptimizerConfig,
) -> Result<Transformed<LogicalPlan>>Expand description
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:
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 ENDBoth 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.