[VL] Lazy aggregate expand: aggregate at the finest grain below Expand for grouping analytics#12554
Draft
malinjawi wants to merge 1 commit into
Draft
[VL] Lazy aggregate expand: aggregate at the finest grain below Expand for grouping analytics#12554malinjawi wants to merge 1 commit into
malinjawi wants to merge 1 commit into
Conversation
…ng sets) For aggregation over grouping sets, Spark expands every input row once per grouping set before the partial aggregation, so the partial aggregate consumes and hashes (input rows * number of grouping sets) rows. TPC-DS q67 is a 9x amplification on an 8-key rollup. When the number of distinct full-grouping-key combinations is much smaller than the input row count, it is cheaper to aggregate at the finest grain once, expand only the intermediate aggregation buffers, and merge the expanded states before shuffle: partial aggregate <- expand <- child becomes flushable partial-merge agg <- expand(over agg buffers) <- flushable partial agg <- child The pre-shuffle partial-merge stage collapses duplicated coarse-grained groups locally so shuffle volume does not increase. Both new aggregates are flushable, so on high-cardinality grouping keys Velox's abandon-partial-aggregation bounds the worst case (the regression class seen with the ClickHouse backend's lazy expand, GLUTEN-7986) -- the protection comes from existing Velox machinery. Gated by spark.gluten.sql.columnar.backend.velox.lazyAggregateExpand.enabled, default false. Eligibility (v1): sum/count/min/max/avg; no DISTINCT, no FILTER, no try_sum/try_avg; grouping and shuffle keys are attributes/literals with at least one attribute-backed atomic grouping key; float sum/avg follow the floatingPointMode policy. New nodes are natively validated; on any failure the rule leaves the plan untouched. Includes the regenerated velox-configuration.md.
malinjawi
force-pushed
the
vl-lazy-aggregate-expand
branch
from
July 22, 2026 11:32
837759c to
4e4f2f3
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changes were proposed in this pull request?
Adds
LazyAggregateExpandRuleto the Velox backend: a post-transform rule that, for grouping analytics (ROLLUP / CUBE / GROUPING SETS), moves the partial aggregation below the Expand operator so the input is aggregated once at the finest grain, then expands only the intermediate aggregation buffers and merges them before shuffle.Before:
After:
Gated by
spark.gluten.sql.columnar.backend.velox.lazyAggregateExpand.enabled(default false). No native changes; the rewrite reuses existing companion-function, extract-struct/row-construct, and flush/abandon machinery.Why are the changes needed?
Expand multiplies every input row by the number of grouping sets (TPC-DS q67: 9x on an 8-key rollup), and the partial aggregate pays hashing and shuffle for every copy. When the finest grain reduces the row count, aggregating first is substantially cheaper, and the coarser grouping sets collapse from already-aggregated states.
Safety on high-cardinality keys (where the finest grain does not reduce): both inserted aggregates are flushable, so Velox's abandon-partial-aggregation turns the bottom aggregate into a streaming to-intermediate conversion and the merge stage into an identity pass-through - the worst case degrades to roughly the original plan plus one cheap pass. This is the failure mode that regressed q67 for the CH backend's lazy expand (#7986, fixed there by a native re-aggregation step in #7995); here the protection comes from existing Velox machinery.
Prior art: the CH backend has this optimization since #7649 (GLUTEN-7647, default-on there). #12052 already explored the same three-stage shape for the Velox backend (including the pre-shuffle PartialMerge); this PR differs in making the finest-grain aggregate flushable so both stages inherit Velox's abandon adaptivity (the worst-case protection on high-cardinality keys), binding aggregation buffers by exprId against a verified ordering contract, the eligibility guards above, and a dedicated test suite.
Eligibility (v1, conservative)
sum/count/min/max/avg; no DISTINCT, no FILTER, notry_sum, nobloom_filter_aggGROUPING SETS ((),())empty-input case)RewriteDistinctAggregatesExpand); deterministic pre-projections and filters onlysum/avgfollow the samefloatingPointModepolicy as flushable aggregationBenchmarks
SQL-level simulation of the rewrite on vanilla Spark 4.0.1 (local[10], 12-core machine; result sets checksum-verified identical in every case). The simulation pays one extra shuffle the actual rule avoids, so it understates the rule — but it measures the same underlying algorithm.
Real TPC-DS q67, SF10, end to end (real dsdgen data, full query incl. joins and the rank() window):
Run-to-run spread was large (baseline 147-194s, rewrite 120-208s), so this is best read as "no measurable end-to-end win", not as a precise 5% regression.
Why, measured on the same data:
q67's finest grain is very nearly unique, so aggregating below the Expand has almost nothing to collapse. This optimization's premise is that the finest grain reduces the row count materially; on q67 it does not.
Synthetic sweeps, showing where the premise does and does not hold (stage-level, no window/joins):
An earlier revision of this description presented the middle row as "q67-shaped". That was wrong: at 3.14 rows/group it has roughly 3x more finest-grain reduction than real q67 (1.11), which is the variable that decides the outcome. The table above is corrected.
Reading of the evidence. The rewrite is a large win when the finest grain reduces (many rollup/cube workloads), a no-op when it does not (q67), and a regression when it does not AND the adaptive valve is absent — which is what the flushable-aggregate requirement in this PR exists to prevent. q67 specifically needs the amplification removed without depending on fine-grain reduction, i.e. a fused rollup operator (see #12052 discussion); that is complementary to this PR, not served by it.
Gluten A/B numbers with the flag on/off at scale will follow - keeping this as a draft until then.
How was this patch tested?
New
LazyAggregateExpandSuite(20 cases): plan-shape assertions (flushable aggregates on both sides of the Expand) plus result comparison against vanilla Spark, covering rollup/cube with sum/count/min/max/avg, genuine-NULL keys vs rolled-up NULL withgrouping_id, decimal sum buffers, the pre-projected q67 shape, aggregates over grouping keys, empty input, degenerate grouping sets, duplicate grouping sets, single and multi count-distinct, FILTER / strict-float / non-whitelisted-function / non-atomic-key rejections, early-abandon interplay, AQE on/off, and flushable-disabled behavior.