You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ul...@apache.org on 2026/08/17 09:10:34 UTC
(spark) branch master updated: [SPARK-58511][SQL] Bypass ineffective pre-shuffle partial aggregation at runtime
This is an automated email from the ASF dual-hosted git repository.
ulysses-you pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 5bcd5f59b9f0 [SPARK-58511][SQL] Bypass ineffective pre-shuffle partial aggregation at runtime
5bcd5f59b9f0 is described below
commit 5bcd5f59b9f059c9c29eee55a28586a74680f354
Author: Xiduo You <ul...@gmail.com>
AuthorDate: Mon Aug 17 17:10:18 2026 +0800
[SPARK-58511][SQL] Bypass ineffective pre-shuffle partial aggregation at runtime
### What changes were proposed in this pull request?
This PR makes hash aggregation detect at runtime that a pre-shuffle partial aggregation is not reducing rows, and bypass it: the remaining input rows are passed through as single-row partial buffers that the downstream `Final` aggregation merges, so the output contract is unchanged.
The decision is driven by the **compaction ratio** - processed rows divided by the number of keys the operator holds. A ratio of 10 means the partial aggregation collapses ten rows into one; a ratio near 1 means it is doing bookkeeping for nothing. The partial aggregation is bypassed for the rest of the input when the ratio falls below `minCompaction`, checked at two points:
- **periodically**, every `minRows` processed rows, so a decision is never made on too few rows.
- **on spill**, when the map cannot allocate for a new key and would otherwise spill. Spilling is when an ineffective partial aggregation starts paying disk I/O, so it is worth re-checking off-cycle.
Both checks share the same predicate and the same threshold. The row and key counts are measured at the operator level, over all processed rows and across both maps (`fastMap.getNumKeys() + regularMap.getNumKeys()`), which is what makes a single threshold meaningful on both the two-level and single-map paths.
The counters restart after each spill, so a new in-memory map epoch is judged on its own rows rather than on a ratio diluted by everything already spilled. Pass-through can therefore begin after earlier spills have happened.
Only a pre-shuffle `Partial` hash aggregation with grouping keys is eligible. Streaming partial aggregates are excluded (`!isStreaming`): they keep state across batches. A batch `session_window` grouping is likewise kept out, because its partial aggregate feeds a `MergingSessionsExec` that merges overlapping sessions. `requiredChildDistributionExpressions.isEmpty` identifies that phase and, importantly, keeps a group-by-only aggregate's `Final` phase out - its `aggregateExpressions` i [...]
Once pass-through is active the maps are frozen and the remaining input rows stream through as single-row partial buffers. Until the maps have fully drained, each streamed row is held in a small queue behind them: queuing a row advances the map output by one row, and the queue flushes only once the maps are drained, so every frozen-map buffer is emitted before any streamed row that could collide with it. A downstream `Final` merges in emit order, so a group that straddles the freeze s [...]
`DISTINCT` aggregates are eligible: in the multi-phase distinct plan the intermediate `PartialMerge` phase is not `Partial` mode (and requires a distribution), so it always aggregates and de-duplicates, and the rows reaching the distinct `Partial` phase therefore carry exactly one distinct value each.
New configs, all under `spark.sql.execution.aggregate.adaptivePartialAggregation.*`:
| config | default | meaning |
| --- | --- | --- |
| `enabled` | `false` | the feature switch (opt-in) |
| `minRows` | `100000` | rows between two compaction-ratio evaluations |
| `minCompaction` | `1.05` | the ratio below which the partial aggregation is bypassed |
A `numBypassingRows` SQL metric reports how many rows bypassed, on the eligible operators.
The comparison is strict: a ratio exactly equal to `minCompaction` does not bypass. `minCompaction` is validated to be at least 1.0, because a ratio below 1.0 is impossible for a non-empty map (each key is held by at least one processed row); at exactly 1.0 the strict comparison still never bypasses, so the effective range is above 1.0.
### Why are the changes needed?
For high-cardinality grouping keys the pre-shuffle partial aggregation reduces little or nothing, but still pays for maintaining - and often spilling - an aggregation map as large as the input. Bypassing it at runtime removes that cost while keeping the two-phase plan intact, so the decision needs no planner-side statistics and adapts per task.
This is related to, but independent of, the static `spark.sql.execution.bypassPartialAggregation` (SPARK-57688), which drops the partial aggregation at planning time. The runtime version keeps the partial aggregation when it does reduce rows and only bypasses when the observed ratio says it does not; the two can be used together.
### Does this PR introduce _any_ user-facing change?
Order-sensitive aggregates such as `first`/`last` are unaffected: once pass-through is active the frozen map's output always precedes the passed-through rows, so a group that straddles the freeze merges its map buffer before its pass-through buffers, matching a run that never bypasses. The feature is disabled by default (opt-in) and, when enabled, otherwise changes only how the pre-shuffle partial aggregation is executed, plus the new `numBypassingRows` metric in the SQL UI. The pass- [...]
### How was this patch tested?
New `AdaptivePartialAggregationSuite` (51 tests), in two halves:
- **Correctness**: output identical to the feature-off reference across the full matrix of codegen on/off, two-level map on/off, and spill/no-spill, over a range of aggregate shapes (multi-slot buffers, imperative buffers, `FILTER (WHERE ...)`), key types (string, decimal, date, nullable), group-by-only aggregates with duplicate keys, empty input, and `Expand`-bearing plans (ROLLUP / CUBE / GROUPING SETS / multi-distinct).
- **Triggering**: the `numBypassingRows` metric proves the bypass fires when (and only when) it should - high cardinality bypasses, low cardinality does not, the feature switch and eligibility rules are honored, and both check points work. There are tests for the exact ratio boundary, and for a new in-memory map epoch bypassing after an earlier spill. These tests also compare against the feature-off reference so a bypassing run can never pass on metrics alone. For `count(DISTINCT v) G [...]
Three tests use an order-sensitive `first`/`last` aggregate to pin the merge order under a fan-out child, where the trigger row's whole fan-out batch is queued at once and the map drains inside it. Each compares every enabled cell against the feature-off reference across the split and unsplit plan shapes, whole-stage on/off, two-level map on/off, and spill/no-spill: one splits the aggregates with an `Exchange` so the held batch cannot overtake the map, one widens the fan-out batch to [...]
`AdaptivePartialAggregationBenchmark` covers the {high, low}-cardinality x {no-spill, on-spill} grid, each across codegen on/off and the adaptive switch.
<details>
<summary>Generated code for `select c2, count(*) from t3 group by c2` (partial aggregation stage, two-level map enabled)</summary>
```java
/* 001 */ public Object generate(Object[] references) {
/* 002 */ return new GeneratedIteratorForCodegenStage1(references);
/* 003 */ }
/* 004 */
/* 005 */ // codegenStageId=1
/* 006 */ final class GeneratedIteratorForCodegenStage1 extends org.apache.spark.sql.execution.BufferedRowIterator {
/* 007 */ private Object[] references;
/* 008 */ private scala.collection.Iterator[] inputs;
/* 009 */ private boolean hashAgg_initAgg_0;
/* 010 */ private boolean hashAgg_adaptivePassThrough_0;
/* 011 */ private long hashAgg_processedRows_0;
/* 012 */ private long hashAgg_adaptiveNextCheckRow_0;
/* 013 */ private boolean hashAgg_adaptiveChildrenConsumed_0;
/* 014 */ private boolean hashAgg_adaptiveMapOutputDone_0;
/* 015 */ private boolean hashAgg_adaptiveMapSetupDone_0;
/* 016 */ private int hashAgg_adaptiveFastKeysAtSpill_0;
/* 017 */ private java.util.LinkedList<UnsafeRow[]> hashAgg_adaptivePendingRows_0;
/* 018 */ private boolean hashAgg_bufIsNull_0;
/* 019 */ private long hashAgg_bufValue_0;
/* 020 */ private hashAgg_FastHashMap_0 hashAgg_fastHashMap_0;
/* 021 */ private org.apache.spark.unsafe.KVIterator<UnsafeRow, UnsafeRow> hashAgg_fastHashMapIter_0;
/* 022 */ private org.apache.spark.unsafe.KVIterator hashAgg_mapIter_0;
/* 023 */ private org.apache.spark.sql.execution.UnsafeFixedWidthAggregationMap hashAgg_hashMap_0;
/* 024 */ private org.apache.spark.sql.execution.UnsafeKVExternalSorter hashAgg_sorter_0;
/* 025 */ private int columnartorow_batchIdx_0;
/* 026 */ private org.apache.spark.sql.vectorized.ColumnarBatch[] columnartorow_mutableStateArray_1 = new org.apache.spark.sql.vectorized.ColumnarBatch[1];
/* 027 */ private org.apache.spark.sql.execution.vectorized.OnHeapColumnVector[] columnartorow_mutableStateArray_2 = new org.apache.spark.sql.execution.vectorized.OnHeapColumnVector[1];
/* 028 */ private scala.collection.Iterator[] columnartorow_mutableStateArray_0 = new scala.collection.Iterator[1];
/* 029 */ private org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter[] hashAgg_mutableStateArray_0 = new org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter[5];
/* 030 */
/* 031 */ public GeneratedIteratorForCodegenStage1(Object[] references) {
/* 032 */ this.references = references;
/* 033 */ }
/* 034 */
/* 035 */ public void init(int index, scala.collection.Iterator[] inputs) {
/* 036 */ partitionIndex = index;
/* 037 */ this.inputs = inputs;
/* 038 */
/* 039 */ hashAgg_adaptiveNextCheckRow_0 = 100000L;
/* 040 */ hashAgg_adaptivePendingRows_0 = new java.util.LinkedList<UnsafeRow[]>();
/* 041 */ hashAgg_mutableStateArray_0[0] = new org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter(2, 0);
/* 042 */ columnartorow_mutableStateArray_0[0] = inputs[0];
/* 043 */ hashAgg_mutableStateArray_0[1] = new org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter(1, 0);
/* 044 */ hashAgg_mutableStateArray_0[2] = new org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter(1, 0);
/* 045 */ hashAgg_mutableStateArray_0[3] = new org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter(1, 0);
/* 046 */ hashAgg_mutableStateArray_0[4] = new org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter(1, 0);
/* 047 */
/* 048 */ }
/* 049 */
/* 050 */ public class hashAgg_FastHashMap_0
/* 051 */ extends org.apache.spark.sql.execution.aggregate.RowBasedAggregateHashMap {
/* 052 */ public hashAgg_FastHashMap_0(
/* 053 */ org.apache.spark.memory.TaskMemoryManager taskMemoryManager,
/* 054 */ InternalRow emptyAggregationBuffer) {
/* 055 */ super(((org.apache.spark.sql.types.StructType) references[1] /* keySchemaTerm */), ((org.apache.spark.sql.types.StructType) references[2] /* valueSchemaTerm */), taskMemoryManager, emptyAggregationBuffer,
/* 056 */ 1 << 16, 1, 0);
/* 057 */ }
/* 058 */
/* 059 */ public org.apache.spark.sql.catalyst.expressions.UnsafeRow findOrInsert(long hashAgg_key_0) {
/* 060 */ long h = hash(hashAgg_key_0);
/* 061 */ int step = 0;
/* 062 */ int idx = (int) h & (numBuckets - 1);
/* 063 */ while (step < maxSteps) {
/* 064 */ // Return bucket index if it's either an empty slot or already contains the key
/* 065 */ if (buckets[idx] == -1) {
/* 066 */ if (numRows < capacity && !isBatchFull) {
/* 067 */ rowWriter.reset();
/* 068 */ rowWriter.zeroOutNullBytes();
/* 069 */ rowWriter.write(0, hashAgg_key_0);
/* 070 */ return appendCurrentKey(idx);
/* 071 */ } else {
/* 072 */ // No more space
/* 073 */ return null;
/* 074 */ }
/* 075 */ } else if (equals(idx, hashAgg_key_0)) {
/* 076 */ return batch.getValueRow(buckets[idx]);
/* 077 */ }
/* 078 */ idx = (idx + 1) & (numBuckets - 1);
/* 079 */ step++;
/* 080 */ }
/* 081 */ // Didn't find it
/* 082 */ return null;
/* 083 */ }
/* 084 */
/* 085 */ private boolean equals(int idx, long hashAgg_key_0) {
/* 086 */ UnsafeRow row = batch.getKeyRow(buckets[idx]);
/* 087 */ return (row.getLong(0) == hashAgg_key_0);
/* 088 */ }
/* 089 */
/* 090 */ private long hash(long hashAgg_key_0) {
/* 091 */ long hashAgg_hash_0 = 0;
/* 092 */
/* 093 */ long hashAgg_result_0 = hashAgg_key_0;
/* 094 */ hashAgg_hash_0 = (hashAgg_hash_0 ^ (0x9e3779b9)) + hashAgg_result_0 + (hashAgg_hash_0 << 6) + (hashAgg_hash_0 >>> 2);
/* 095 */
/* 096 */ return hashAgg_hash_0;
/* 097 */ }
/* 098 */
/* 099 */ }
/* 100 */
/* 101 */ private void hashAgg_doAggregateWithKeysOutput_0(UnsafeRow hashAgg_keyTerm_0, UnsafeRow hashAgg_bufferTerm_0)
/* 102 */ throws java.io.IOException {
/* 103 */ ((org.apache.spark.sql.execution.metric.SQLMetric) references[7] /* numOutputRows */).add(1);
/* 104 */
/* 105 */ boolean hashAgg_isNull_1 = hashAgg_keyTerm_0.isNullAt(0);
/* 106 */ long hashAgg_value_2 = hashAgg_isNull_1 ?
/* 107 */ -1L : (hashAgg_keyTerm_0.getLong(0));
/* 108 */ long hashAgg_value_3 = hashAgg_bufferTerm_0.getLong(0);
/* 109 */
/* 110 */ hashAgg_mutableStateArray_0[0].reset();
/* 111 */
/* 112 */ hashAgg_mutableStateArray_0[0].zeroOutNullBytes();
/* 113 */
/* 114 */ hashAgg_mutableStateArray_0[0].writeNullable(0, hashAgg_value_2, hashAgg_isNull_1);
/* 115 */
/* 116 */ hashAgg_mutableStateArray_0[0].write(1, hashAgg_value_3);
/* 117 */ append((hashAgg_mutableStateArray_0[0].getRow()));
/* 118 */
/* 119 */ }
/* 120 */
/* 121 */ private void hashAgg_doAggregateWithKeys_0(int partitionIndex) throws java.io.IOException {
/* 122 */ if (columnartorow_mutableStateArray_1[0] == null) {
/* 123 */ columnartorow_nextBatch_0();
/* 124 */ }
/* 125 */ while ( columnartorow_mutableStateArray_1[0] != null) {
/* 126 */ int columnartorow_numRows_0 = columnartorow_mutableStateArray_1[0].numRows();
/* 127 */ int columnartorow_localEnd_0 = columnartorow_numRows_0 - columnartorow_batchIdx_0;
/* 128 */ for (int columnartorow_localIdx_0 = 0; columnartorow_localIdx_0 < columnartorow_localEnd_0; columnartorow_localIdx_0++) {
/* 129 */ int columnartorow_rowIdx_0 = columnartorow_batchIdx_0 + columnartorow_localIdx_0;
/* 130 */ boolean columnartorow_isNull_0 = columnartorow_mutableStateArray_2[0].isNullAt(columnartorow_rowIdx_0);
/* 131 */ long columnartorow_value_0 = columnartorow_isNull_0 ? -1L : (columnartorow_mutableStateArray_2[0].getLong(columnartorow_rowIdx_0));
/* 132 */
/* 133 */ hashAgg_doConsume_0(columnartorow_value_0, columnartorow_isNull_0);
/* 134 */ if (shouldStop()) { columnartorow_batchIdx_0 = columnartorow_rowIdx_0 + 1; return; }
/* 135 */ }
/* 136 */ columnartorow_batchIdx_0 = columnartorow_numRows_0;
/* 137 */ columnartorow_nextBatch_0();
/* 138 */ }
/* 139 */ // clean up resources
/* 140 */ if (columnartorow_mutableStateArray_1[0] != null) {
/* 141 */ columnartorow_mutableStateArray_1[0].close();
/* 142 */ }
/* 143 */
/* 144 */ if (!shouldStop()) { hashAgg_adaptiveChildrenConsumed_0 = true; }
/* 145 */ }
/* 146 */
/* 147 */ private void wholestagecodegen_outputMapAndFlush_0() throws java.io.IOException {
/* 148 */ if (!hashAgg_adaptiveMapSetupDone_0) {
/* 149 */ hashAgg_fastHashMapIter_0 = hashAgg_fastHashMap_0.rowIterator();
/* 150 */ hashAgg_mapIter_0 = ((org.apache.spark.sql.execution.aggregate.HashAggregateExec) references[0] /* plan */).finishAggregate(hashAgg_hashMap_0, hashAgg_sorter_0, ((org.apache.spark.sql.execution.metric.SQLMetric) references[3] /* peakMemory */), ((org.apache.spark.sql.execution.metric.SQLMetric) references[4] /* spillSize */), ((org.apache.spark.sql.execution.metric.SQLMetric) references[5] /* avgHashProbe */), ((org.apache.spark.sql.execution.metric.SQLMetric) referenc [...]
/* 151 */
/* 152 */ hashAgg_adaptiveMapSetupDone_0 = true;
/* 153 */ }
/* 154 */
/* 155 */ while ( hashAgg_fastHashMapIter_0.next()) {
/* 156 */ UnsafeRow hashAgg_aggKey_0 = (UnsafeRow) hashAgg_fastHashMapIter_0.getKey();
/* 157 */ UnsafeRow hashAgg_aggBuffer_0 = (UnsafeRow) hashAgg_fastHashMapIter_0.getValue();
/* 158 */ hashAgg_doAggregateWithKeysOutput_0(hashAgg_aggKey_0, hashAgg_aggBuffer_0);
/* 159 */
/* 160 */ if (shouldStop()) return;
/* 161 */ }
/* 162 */ hashAgg_fastHashMap_0.close();
/* 163 */
/* 164 */ while ( hashAgg_mapIter_0.next()) {
/* 165 */ UnsafeRow hashAgg_aggKey_0 = (UnsafeRow) hashAgg_mapIter_0.getKey();
/* 166 */ UnsafeRow hashAgg_aggBuffer_0 = (UnsafeRow) hashAgg_mapIter_0.getValue();
/* 167 */ hashAgg_doAggregateWithKeysOutput_0(hashAgg_aggKey_0, hashAgg_aggBuffer_0);
/* 168 */ if (shouldStop()) return;
/* 169 */ }
/* 170 */ hashAgg_mapIter_0.close();
/* 171 */ if (hashAgg_sorter_0 == null) {
/* 172 */ hashAgg_hashMap_0.free();
/* 173 */ }
/* 174 */
/* 175 */ hashAgg_adaptiveMapOutputDone_0 = true;
/* 176 */ while (!hashAgg_adaptivePendingRows_0.isEmpty()) {
/* 177 */ UnsafeRow[] wholestagecodegen_pendingRow_0 = (UnsafeRow[]) hashAgg_adaptivePendingRows_0.poll();
/* 178 */ hashAgg_doAggregateWithKeysOutput_0(wholestagecodegen_pendingRow_0[0], wholestagecodegen_pendingRow_0[1]);
/* 179 */ }
/* 180 */ }
/* 181 */
/* 182 */ private void hashAgg_doConsume_0(long hashAgg_expr_0_0, boolean hashAgg_exprIsNull_0_0) throws java.io.IOException {
/* 183 */ UnsafeRow hashAgg_unsafeRowAggBuffer_0 = null;
/* 184 */ UnsafeRow hashAgg_fastAggBuffer_0 = null;
/* 185 */
/* 186 */ boolean hashAgg_adaptiveRowBypassed_0 = false;
/* 187 */
/* 188 */ if (!hashAgg_adaptivePassThrough_0) {
/* 189 */ if (!hashAgg_exprIsNull_0_0) {
/* 190 */ hashAgg_fastAggBuffer_0 = hashAgg_fastHashMap_0.findOrInsert(
/* 191 */ hashAgg_expr_0_0);
/* 192 */ }
/* 193 */
/* 194 */ }
/* 195 */
/* 196 */ // Cannot find the key in fast hash map, try regular hash map.
/* 197 */ if (hashAgg_fastAggBuffer_0 == null) {
/* 198 */ // generate grouping key
/* 199 */ hashAgg_mutableStateArray_0[3].reset();
/* 200 */
/* 201 */ hashAgg_mutableStateArray_0[3].zeroOutNullBytes();
/* 202 */
/* 203 */ hashAgg_mutableStateArray_0[3].writeNullable(0, hashAgg_expr_0_0, hashAgg_exprIsNull_0_0);
/* 204 */ if (!hashAgg_adaptivePassThrough_0) {
/* 205 */ int hashAgg_unsafeRowKeyHash_0 = (hashAgg_mutableStateArray_0[3].getRow()).hashCode();
/* 206 */ if (true) {
/* 207 */ // try to get the buffer from hash map
/* 208 */ hashAgg_unsafeRowAggBuffer_0 =
/* 209 */ hashAgg_hashMap_0.getAggregationBufferFromUnsafeRow((hashAgg_mutableStateArray_0[3].getRow()), hashAgg_unsafeRowKeyHash_0);
/* 210 */ }
/* 211 */
/* 212 */ if (hashAgg_unsafeRowAggBuffer_0 == null) {
/* 213 */ if (hashAgg_processedRows_0 > 0 && hashAgg_processedRows_0 < (double) (hashAgg_fastHashMap_0.getNumKeys() - hashAgg_adaptiveFastKeysAtSpill_0 + hashAgg_hashMap_0.getNumKeys()) * 1.05D) {
/* 214 */ hashAgg_adaptivePassThrough_0 = true;
/* 215 */ } else {
/* 216 */ if (hashAgg_sorter_0 == null) {
/* 217 */ hashAgg_sorter_0 = hashAgg_hashMap_0.destructAndCreateExternalSorter();
/* 218 */ } else {
/* 219 */ hashAgg_sorter_0.merge(hashAgg_hashMap_0.destructAndCreateExternalSorter());
/* 220 */ }
/* 221 */
/* 222 */ // the hash map had been spilled, so it should have enough memory now,
/* 223 */ // try to allocate buffer again.
/* 224 */ hashAgg_unsafeRowAggBuffer_0 = hashAgg_hashMap_0.getAggregationBufferFromUnsafeRow(
/* 225 */ (hashAgg_mutableStateArray_0[3].getRow()), hashAgg_unsafeRowKeyHash_0);
/* 226 */ if (hashAgg_unsafeRowAggBuffer_0 == null) {
/* 227 */ // failed to allocate the first page
/* 228 */ throw QueryExecutionErrors.aggregateOutOfMemoryError();
/* 229 */ }
/* 230 */
/* 231 */ hashAgg_processedRows_0 = 0L;
/* 232 */ hashAgg_adaptiveNextCheckRow_0 = 100000L;
/* 233 */ hashAgg_adaptiveFastKeysAtSpill_0 = hashAgg_fastHashMap_0.getNumKeys();
/* 234 */
/* 235 */ }
/* 236 */ }
/* 237 */ }
/* 238 */
/* 239 */ }
/* 240 */
/* 241 */ if ((hashAgg_fastAggBuffer_0 != null || hashAgg_unsafeRowAggBuffer_0 != null)) {
/* 242 */ if (!hashAgg_adaptivePassThrough_0) {
/* 243 */ hashAgg_processedRows_0 += 1;
/* 244 */ if (hashAgg_processedRows_0 == hashAgg_adaptiveNextCheckRow_0) {
/* 245 */ if (hashAgg_processedRows_0 < (double) (hashAgg_fastHashMap_0.getNumKeys() - hashAgg_adaptiveFastKeysAtSpill_0 + hashAgg_hashMap_0.getNumKeys()) * 1.05D) {
/* 246 */ hashAgg_adaptivePassThrough_0 = true;
/* 247 */ } else {
/* 248 */ hashAgg_adaptiveNextCheckRow_0 += 100000L;
/* 249 */ }
/* 250 */ }
/* 251 */ }
/* 252 */ } else if (hashAgg_adaptivePassThrough_0) {
/* 253 */ hashAgg_adaptiveRowBypassed_0 = true;
/* 254 */ hashAgg_mutableStateArray_0[4].reset();
/* 255 */
/* 256 */ hashAgg_mutableStateArray_0[4].write(0, 0L);
/* 257 */ hashAgg_unsafeRowAggBuffer_0 = (hashAgg_mutableStateArray_0[4].getRow());
/* 258 */ }
/* 259 */
/* 260 */ // Updates the proper row buffer
/* 261 */ if (hashAgg_fastAggBuffer_0 != null) {
/* 262 */ hashAgg_unsafeRowAggBuffer_0 = hashAgg_fastAggBuffer_0;
/* 263 */ }
/* 264 */
/* 265 */ // common sub-expressions
/* 266 */
/* 267 */ // evaluate aggregate functions and update aggregation buffers
/* 268 */
/* 269 */ long hashAgg_value_13 = hashAgg_unsafeRowAggBuffer_0.getLong(0);
/* 270 */
/* 271 */ long hashAgg_value_12 = -1L;
/* 272 */
/* 273 */ hashAgg_value_12 = org.apache.spark.sql.catalyst.util.MathUtils.addExact(hashAgg_value_13, 1L, ((org.apache.spark.sql.catalyst.trees.SQLQueryContext) references[10] /* errCtx */));
/* 274 */
/* 275 */ hashAgg_unsafeRowAggBuffer_0.setLong(0, hashAgg_value_12);
/* 276 */
/* 277 */ if (hashAgg_adaptiveRowBypassed_0) {
/* 278 */ ((org.apache.spark.sql.execution.metric.SQLMetric) references[11] /* numBypassingRows */).add(1);
/* 279 */ if (hashAgg_adaptiveMapOutputDone_0) {
/* 280 */ hashAgg_doAggregateWithKeysOutput_0((hashAgg_mutableStateArray_0[3].getRow()), hashAgg_unsafeRowAggBuffer_0);
/* 281 */ } else {
/* 282 */ hashAgg_adaptivePendingRows_0.add(new UnsafeRow[] {
/* 283 */ (hashAgg_mutableStateArray_0[3].getRow()).copy(), hashAgg_unsafeRowAggBuffer_0.copy() });
/* 284 */ wholestagecodegen_outputMapAndFlush_0();
/* 285 */ }
/* 286 */ }
/* 287 */
/* 288 */ }
/* 289 */
/* 290 */ protected void processNext() throws java.io.IOException {
/* 291 */ if (!hashAgg_initAgg_0) {
/* 292 */ hashAgg_initAgg_0 = true;
/* 293 */ hashAgg_fastHashMap_0 = new hashAgg_FastHashMap_0(((org.apache.spark.sql.execution.aggregate.HashAggregateExec) references[0] /* plan */).getTaskContext().taskMemoryManager(), ((org.apache.spark.sql.execution.aggregate.HashAggregateExec) references[0] /* plan */).getEmptyAggregationBuffer());
/* 294 */
/* 295 */ ((org.apache.spark.sql.execution.aggregate.HashAggregateExec) references[0] /* plan */).addFastHashMapCloseHook(hashAgg_fastHashMap_0);
/* 296 */
/* 297 */ hashAgg_hashMap_0 = ((org.apache.spark.sql.execution.aggregate.HashAggregateExec) references[0] /* plan */).createHashMap();
/* 298 */ long hashAgg_beforeAgg_0 = System.nanoTime();
/* 299 */ hashAgg_doAggregateWithKeys_0(partitionIndex);
/* 300 */ ((org.apache.spark.sql.execution.metric.SQLMetric) references[12] /* aggTime */).add((System.nanoTime() - hashAgg_beforeAgg_0) / 1000000);
/* 301 */ if (shouldStop()) return;
/* 302 */ }
/* 303 */
/* 304 */ if (!hashAgg_adaptiveChildrenConsumed_0) {
/* 305 */ if (!hashAgg_adaptiveMapOutputDone_0) {
/* 306 */ wholestagecodegen_outputMapAndFlush_0();
/* 307 */ if (shouldStop()) return;
/* 308 */ }
/* 309 */
/* 310 */ long hashAgg_beforeResumedAgg_0 = System.nanoTime();
/* 311 */ hashAgg_doAggregateWithKeys_0(partitionIndex);
/* 312 */ ((org.apache.spark.sql.execution.metric.SQLMetric) references[12] /* aggTime */).add((System.nanoTime() - hashAgg_beforeResumedAgg_0) / 1000000);
/* 313 */ if (shouldStop()) return;
/* 314 */ }
/* 315 */
/* 316 */ if (!hashAgg_adaptiveMapOutputDone_0) {
/* 317 */ wholestagecodegen_outputMapAndFlush_0();
/* 318 */ if (shouldStop()) return;
/* 319 */ }
/* 320 */ }
/* 321 */
/* 322 */ private void columnartorow_nextBatch_0() throws java.io.IOException {
/* 323 */ columnartorow_mutableStateArray_1[0] = org.apache.spark.sql.execution.ColumnarToRowExec.advanceBatch(
/* 324 */ columnartorow_mutableStateArray_0[0], columnartorow_mutableStateArray_1[0], ((org.apache.spark.sql.execution.metric.SQLMetric) references[9] /* numInputBatches */), ((org.apache.spark.sql.execution.metric.SQLMetric) references[8] /* numOutputRows */));
/* 325 */ if (columnartorow_mutableStateArray_1[0] != null) {
/* 326 */ columnartorow_batchIdx_0 = 0;
/* 327 */ columnartorow_mutableStateArray_2[0] = (org.apache.spark.sql.execution.vectorized.OnHeapColumnVector) columnartorow_mutableStateArray_1[0].column(0);
/* 328 */
/* 329 */ }
/* 330 */ }
/* 331 */ }
```
</details>
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 4.5)
Closes #57742 from ulysses-you/worktree-adaptive-partial-agg.
Authored-by: Xiduo You <ul...@gmail.com>
Signed-off-by: Xiduo You <ul...@apache.org>
---
docs/sql-performance-tuning.md | 68 ++
.../org/apache/spark/sql/internal/SQLConf.scala | 50 +
...vePartialAggregationBenchmark-jdk21-results.txt | 56 +
...vePartialAggregationBenchmark-jdk25-results.txt | 56 +
...AdaptivePartialAggregationBenchmark-results.txt | 56 +
.../execution/UnsafeFixedWidthAggregationMap.java | 8 +
.../aggregate/RowBasedAggregateHashMap.java | 8 +
.../execution/aggregate/HashAggregateExec.scala | 561 ++++++++-
.../aggregate/TungstenAggregationIterator.scala | 173 ++-
.../aggregate/VectorizedHashMapGenerator.scala | 4 +
.../AdaptivePartialAggregationSuite.scala | 1256 ++++++++++++++++++++
.../AdaptivePartialAggregationBenchmark.scala | 142 +++
12 files changed, 2356 insertions(+), 82 deletions(-)
diff --git a/docs/sql-performance-tuning.md b/docs/sql-performance-tuning.md
index 36dfb2e47fc3..468d482b16ab 100644
--- a/docs/sql-performance-tuning.md
+++ b/docs/sql-performance-tuning.md
@@ -181,6 +181,74 @@ Missing or inaccurate statistics will hinder Spark's ability to select an optima
- **Query plan estimates**: You can inspect Spark's cost estimates in the optimized query plan via [`EXPLAIN COST`](sql-ref-syntax-qry-explain.html) or `DataFrame.explain(mode="cost")`.
- **Runtime statistics**: You can inspect these statistics in the [SQL UI](web-ui.html#sql-tab) under the "Details" section as a query is running. Look for `Statistics(..., isRuntime=true)` in the plan.
+## Optimizing the Aggregate
+
+### Adaptive Partial Aggregation
+
+A grouping aggregation normally runs in two phases: a partial aggregation before the shuffle and a
+final aggregation after it. The partial aggregation is only worthwhile when it actually reduces the
+number of rows; when the grouping keys are close to unique it maintains, and possibly spills, an
+aggregation map roughly as large as its input while emitting almost as many rows as it consumed.
+
+When adaptive partial aggregation is enabled, hash aggregation measures the compaction ratio (the
+number of processed rows divided by the number of keys held in its aggregation maps) at runtime
+and, if the partial aggregation is not collapsing enough rows to be worthwhile, stops populating
+the aggregation map and passes the remaining rows through as single-row partial aggregation buffers
+for the final aggregation to merge. Once pass-through is active the map is frozen and its output
+always comes before the passed-through rows: rows that collide with the frozen map are held in a
+queue behind it and flushed only after it drains, so a duplicate of a key already in the map still
+merges after that key's accumulated rows, keeping an order-sensitive aggregate such as
+`first`/`last` consistent with a run that never bypasses. The ratio is evaluated periodically, and
+again right before the aggregation map would spill, in which case the spill is skipped entirely.
+
+Both evaluations use the cumulative rows and keys of the current map epoch and, once triggered,
+pass-through is not reversed for the rest of the task, so a skewed prefix biases the outcome in
+either direction. A favorable prefix can mask a later distinct-heavy tail, keeping the aggregation
+on until a spill restarts the accounting; conversely, a distinct-heavy prefix can trip the
+pass-through early and keep it tripped even where the rest of the input would aggregate well. To
+catch the former without waiting for a spill, raise `minCompaction` so the cumulative ratio trips
+the threshold on a weaker late turn (a higher threshold also bypasses more readily on other inputs).
+To avoid committing the task to pass-through on the latter, raise `minRows` so the periodic
+evaluations start later.
+
+<table class="spark-config">
+ <thead><tr><th>Property Name</th><th>Default</th><th>Meaning</th><th>Since Version</th></tr></thead>
+ <tr>
+ <td><code>spark.sql.execution.aggregate.adaptivePartialAggregation.enabled</code></td>
+ <td>false</td>
+ <td>
+ When true, hash aggregation adaptively bypasses the pre-shuffle partial aggregation at runtime
+ when it observes that the partial aggregation is not reducing the number of rows enough to be
+ worthwhile. This applies only to hash aggregation with grouping keys.
+ </td>
+ <td>4.4.0</td>
+ </tr>
+ <tr>
+ <td><code>spark.sql.execution.aggregate.adaptivePartialAggregation.minRows</code></td>
+ <td>100000</td>
+ <td>
+ The number of rows between periodic compaction-ratio evaluations. Setting this to
+ <code>0</code> disables the periodic evaluation. The ratio may still be evaluated when the
+ aggregation map is about to spill. A larger value also delays the periodic evaluations, so
+ when one of them trips pass-through the frozen map tends to hold more rows; the frozen map
+ stays resident until its output is drained, so a larger value raises that transient memory
+ peak.
+ </td>
+ <td>4.4.0</td>
+ </tr>
+ <tr>
+ <td><code>spark.sql.execution.aggregate.adaptivePartialAggregation.minCompaction</code></td>
+ <td>1.05</td>
+ <td>
+ The minimum compaction ratio required to keep the partial aggregation. A ratio of 10 means the
+ partial aggregation collapses ten rows into one key; when an evaluation finds the ratio below
+ this value the partial aggregation is bypassed for the rest of the input. A larger value
+ bypasses more aggressively.
+ </td>
+ <td>4.4.0</td>
+ </tr>
+</table>
+
## Optimizing the Join Strategy
### Automatically Broadcasting Joins
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index ff7c005e4a26..b9abc03aeda2 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -4347,6 +4347,47 @@ object SQLConf {
.booleanConf
.createWithDefault(false)
+ val ADAPTIVE_PARTIAL_AGGREGATION_ENABLED =
+ buildConf("spark.sql.execution.aggregate.adaptivePartialAggregation.enabled")
+ .doc("When true, hash aggregation adaptively bypasses the pre-shuffle partial aggregation " +
+ "at runtime when it observes that the partial aggregation is not reducing the number of " +
+ "rows enough to be worthwhile. Once bypassed, the remaining input rows are passed " +
+ "through as single-row partial aggregation buffers for the final aggregation to merge, " +
+ "which avoids the cost of maintaining and spilling a large aggregation map with little " +
+ "reduction benefit. Disabled by default. This applies only to hash aggregation with " +
+ "grouping keys.")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+ .booleanConf
+ .createWithDefault(false)
+
+ val ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS =
+ buildConf("spark.sql.execution.aggregate.adaptivePartialAggregation.minRows")
+ .doc("The number of rows between periodic compaction-ratio evaluations by adaptive partial " +
+ s"aggregation (see '${ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key}'). Setting this to 0 " +
+ "disables the periodic evaluation. The ratio may still be evaluated when the aggregation " +
+ "map is about to spill.")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+ .longConf
+ .checkValue(_ >= 0, "The minimum row count must not be negative.")
+ .createWithDefault(100000)
+
+ val ADAPTIVE_PARTIAL_AGGREGATION_MIN_COMPACTION =
+ buildConf("spark.sql.execution.aggregate.adaptivePartialAggregation.minCompaction")
+ .doc("The minimum compaction ratio required to keep the pre-shuffle partial aggregation " +
+ s"(see '${ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key}'). The compaction ratio is the " +
+ "number of processed rows divided by the number of keys held in the aggregation maps, " +
+ "so a ratio of 10 means the partial aggregation collapses ten rows into one. When an " +
+ "evaluation finds the ratio below this value, the partial aggregation is bypassed for " +
+ "the rest of the input. A larger value bypasses more aggressively.")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+ .doubleConf
+ .checkValue(v => v >= 1.0 && v.isFinite,
+ "The minimum compaction ratio must be a finite value of at least 1.0.")
+ .createWithDefault(1.05)
+
val JSON_GENERATOR_IGNORE_NULL_FIELDS =
buildConf("spark.sql.jsonGenerator.ignoreNullFields")
.doc("Whether to ignore null fields when generating JSON objects in JSON data source and " +
@@ -9162,6 +9203,15 @@ class SQLConf extends Serializable with Logging with SqlApiConf {
def bypassPartialAggregation: Boolean = getConf(BYPASS_PARTIAL_AGGREGATION)
+ def adaptivePartialAggregationEnabled: Boolean =
+ getConf(ADAPTIVE_PARTIAL_AGGREGATION_ENABLED)
+
+ def adaptivePartialAggregationMinRows: Long =
+ getConf(ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS)
+
+ def adaptivePartialAggregationMinCompaction: Double =
+ getConf(ADAPTIVE_PARTIAL_AGGREGATION_MIN_COMPACTION)
+
def objectAggSortBasedFallbackThreshold: Int = getConf(OBJECT_AGG_SORT_BASED_FALLBACK_THRESHOLD)
def variableSubstituteEnabled: Boolean = getConf(VARIABLE_SUBSTITUTE_ENABLED)
diff --git a/sql/core/benchmarks/AdaptivePartialAggregationBenchmark-jdk21-results.txt b/sql/core/benchmarks/AdaptivePartialAggregationBenchmark-jdk21-results.txt
new file mode 100644
index 000000000000..dd08f21eca70
--- /dev/null
+++ b/sql/core/benchmarks/AdaptivePartialAggregationBenchmark-jdk21-results.txt
@@ -0,0 +1,56 @@
+================================================================================================
+high-cardinality input, pass-through at the periodic check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1020-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, high card, no spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+-------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 4069 4145 108 2.1 485.0 1.0X
+codegen = true, adaptive = T 2585 2632 67 3.2 308.1 1.6X
+codegen = false, adaptive = F 4818 4849 44 1.7 574.3 0.8X
+codegen = false, adaptive = T 2983 3150 236 2.8 355.6 1.4X
+
+
+================================================================================================
+low-cardinality input, pass-through at the periodic check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1020-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, low card, no spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 281 292 7 59.6 16.8 1.0X
+codegen = true, adaptive = T 291 323 52 57.7 17.3 1.0X
+codegen = false, adaptive = F 1289 1303 20 13.0 76.8 0.2X
+codegen = false, adaptive = T 1266 1270 7 13.3 75.4 0.2X
+
+
+================================================================================================
+high-cardinality input, pass-through at the spill check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1020-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, high card, spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 8120 8126 9 1.0 968.0 1.0X
+codegen = true, adaptive = T 4460 4476 22 1.9 531.7 1.8X
+codegen = false, adaptive = F 9331 9389 82 0.9 1112.3 0.9X
+codegen = false, adaptive = T 5369 5382 18 1.6 640.1 1.5X
+
+
+================================================================================================
+low-cardinality input, pass-through at the spill check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1020-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, low card, spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 768 782 12 21.8 45.8 1.0X
+codegen = true, adaptive = T 769 780 13 21.8 45.8 1.0X
+codegen = false, adaptive = F 1366 1369 4 12.3 81.4 0.6X
+codegen = false, adaptive = T 1358 1358 0 12.4 80.9 0.6X
+
+
diff --git a/sql/core/benchmarks/AdaptivePartialAggregationBenchmark-jdk25-results.txt b/sql/core/benchmarks/AdaptivePartialAggregationBenchmark-jdk25-results.txt
new file mode 100644
index 000000000000..f54c40877aaf
--- /dev/null
+++ b/sql/core/benchmarks/AdaptivePartialAggregationBenchmark-jdk25-results.txt
@@ -0,0 +1,56 @@
+================================================================================================
+high-cardinality input, pass-through at the periodic check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1021-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, high card, no spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+-------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 4338 4408 100 1.9 517.1 1.0X
+codegen = true, adaptive = T 2586 2608 30 3.2 308.3 1.7X
+codegen = false, adaptive = F 5146 5199 76 1.6 613.4 0.8X
+codegen = false, adaptive = T 3271 3287 22 2.6 390.0 1.3X
+
+
+================================================================================================
+low-cardinality input, pass-through at the periodic check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1021-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, low card, no spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 269 275 4 62.5 16.0 1.0X
+codegen = true, adaptive = T 284 294 6 59.1 16.9 0.9X
+codegen = false, adaptive = F 1317 1321 6 12.7 78.5 0.2X
+codegen = false, adaptive = T 1309 1382 104 12.8 78.0 0.2X
+
+
+================================================================================================
+high-cardinality input, pass-through at the spill check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1021-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, high card, spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 8332 8462 184 1.0 993.2 1.0X
+codegen = true, adaptive = T 4677 4683 9 1.8 557.5 1.8X
+codegen = false, adaptive = F 9932 9966 47 0.8 1184.0 0.8X
+codegen = false, adaptive = T 5412 5618 291 1.6 645.1 1.5X
+
+
+================================================================================================
+low-cardinality input, pass-through at the spill check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1021-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, low card, spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 773 786 17 21.7 46.1 1.0X
+codegen = true, adaptive = T 790 803 20 21.2 47.1 1.0X
+codegen = false, adaptive = F 1370 1377 10 12.2 81.6 0.6X
+codegen = false, adaptive = T 1366 1373 11 12.3 81.4 0.6X
+
+
diff --git a/sql/core/benchmarks/AdaptivePartialAggregationBenchmark-results.txt b/sql/core/benchmarks/AdaptivePartialAggregationBenchmark-results.txt
new file mode 100644
index 000000000000..5523166ca01f
--- /dev/null
+++ b/sql/core/benchmarks/AdaptivePartialAggregationBenchmark-results.txt
@@ -0,0 +1,56 @@
+================================================================================================
+high-cardinality input, pass-through at the periodic check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 17.0.20+8-LTS on Linux 6.17.0-1020-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, high card, no spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+-------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 4118 4125 11 2.0 490.9 1.0X
+codegen = true, adaptive = T 2411 2427 23 3.5 287.4 1.7X
+codegen = false, adaptive = F 4846 4861 21 1.7 577.7 0.8X
+codegen = false, adaptive = T 2991 3009 25 2.8 356.6 1.4X
+
+
+================================================================================================
+low-cardinality input, pass-through at the periodic check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 17.0.20+8-LTS on Linux 6.17.0-1020-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, low card, no spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 270 311 37 62.2 16.1 1.0X
+codegen = true, adaptive = T 293 318 22 57.3 17.5 0.9X
+codegen = false, adaptive = F 1305 1312 10 12.9 77.8 0.2X
+codegen = false, adaptive = T 1329 1435 150 12.6 79.2 0.2X
+
+
+================================================================================================
+high-cardinality input, pass-through at the spill check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 17.0.20+8-LTS on Linux 6.17.0-1020-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, high card, spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 8196 8247 73 1.0 977.0 1.0X
+codegen = true, adaptive = T 4433 4530 137 1.9 528.5 1.8X
+codegen = false, adaptive = F 9544 9555 15 0.9 1137.8 0.9X
+codegen = false, adaptive = T 5243 5395 215 1.6 625.0 1.6X
+
+
+================================================================================================
+low-cardinality input, pass-through at the spill check
+================================================================================================
+
+OpenJDK 64-Bit Server VM 17.0.20+8-LTS on Linux 6.17.0-1020-azure
+AMD EPYC 7763 64-Core Processor
+adaptive partial agg, low card, spill: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+codegen = true, adaptive = F 803 813 11 20.9 47.8 1.0X
+codegen = true, adaptive = T 829 839 9 20.2 49.4 1.0X
+codegen = false, adaptive = F 1362 1387 35 12.3 81.2 0.6X
+codegen = false, adaptive = T 1365 1376 15 12.3 81.4 0.6X
+
+
diff --git a/sql/core/src/main/java/org/apache/spark/sql/execution/UnsafeFixedWidthAggregationMap.java b/sql/core/src/main/java/org/apache/spark/sql/execution/UnsafeFixedWidthAggregationMap.java
index af8d5a4610f6..d850d0d18bef 100644
--- a/sql/core/src/main/java/org/apache/spark/sql/execution/UnsafeFixedWidthAggregationMap.java
+++ b/sql/core/src/main/java/org/apache/spark/sql/execution/UnsafeFixedWidthAggregationMap.java
@@ -227,6 +227,14 @@ public final class UnsafeFixedWidthAggregationMap {
return map.getAvgHashProbesPerKey();
}
+ /**
+ * Returns the number of distinct keys currently stored in the underlying `BytesToBytesMap`.
+ * Used by adaptive partial aggregation to estimate the pre-shuffle reduction ratio.
+ */
+ public int getNumKeys() {
+ return map.numKeys();
+ }
+
/**
* Sorts the map's records in place, spill them to disk, and returns an [[UnsafeKVExternalSorter]]
*
diff --git a/sql/core/src/main/java/org/apache/spark/sql/execution/aggregate/RowBasedAggregateHashMap.java b/sql/core/src/main/java/org/apache/spark/sql/execution/aggregate/RowBasedAggregateHashMap.java
index 3f67d050a8c8..859a2fdf60d9 100644
--- a/sql/core/src/main/java/org/apache/spark/sql/execution/aggregate/RowBasedAggregateHashMap.java
+++ b/sql/core/src/main/java/org/apache/spark/sql/execution/aggregate/RowBasedAggregateHashMap.java
@@ -110,6 +110,14 @@ public abstract class RowBasedAggregateHashMap implements AutoCloseable {
return batch.rowIterator();
}
+ /**
+ * Returns the number of distinct keys currently held by this map. Used by adaptive partial
+ * aggregation to measure the reduction ratio across both aggregation maps.
+ */
+ public final int getNumKeys() {
+ return numRows;
+ }
+
@Override
public final void close() {
batch.close();
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateExec.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateExec.scala
index 62c4f896f2ee..6c927dd859c3 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateExec.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateExec.scala
@@ -72,7 +72,16 @@ case class HashAggregateExec(
"aggTime" -> SQLMetrics.createTimingMetric(sparkContext, "time in aggregation build"),
"avgHashProbe" ->
SQLMetrics.createAverageMetric(sparkContext, "avg hash probes per key"),
- "numTasksFallBacked" -> SQLMetrics.createMetric(sparkContext, "number of sort fallback tasks"))
+ "numTasksFallBacked" -> SQLMetrics.createMetric(sparkContext, "number of sort fallback tasks")
+ ) ++ {
+ // Only the aggregates that can actually bypass report this, so the rest do not show a
+ // constant 0 in the SQL UI (see `UnionExec.metrics` for the same approach).
+ if (adaptivePartialAggEnabled) {
+ Map("numBypassingRows" -> SQLMetrics.createMetric(sparkContext, "number of bypassing rows"))
+ } else {
+ Map.empty[String, SQLMetric]
+ }
+ }
// This is for testing. We force TungstenAggregationIterator to fall back to the unsafe row hash
// map and/or the sort-based aggregation once it has processed a given number of input rows.
@@ -94,6 +103,8 @@ case class HashAggregateExec(
val avgHashProbe = longMetric("avgHashProbe")
val aggTime = longMetric("aggTime")
val numTasksFallBacked = longMetric("numTasksFallBacked")
+ // Registered only when the feature applies, and only read from the pass-through path.
+ val numBypassingRows = if (adaptivePartialAggEnabled) longMetric("numBypassingRows") else null
child.execute().mapPartitionsWithIndex { (partIndex, iter) =>
@@ -121,7 +132,12 @@ case class HashAggregateExec(
peakMemory,
spillSize,
avgHashProbe,
- numTasksFallBacked)
+ numTasksFallBacked,
+ numBypassingRows,
+ aggTime,
+ adaptivePartialAggEnabled,
+ adaptiveMinRows,
+ adaptiveMinCompaction)
if (!hasInput && groupingExpressions.isEmpty) {
numOutputRows += 1
Iterator.single[UnsafeRow](aggregationIterator.outputForEmptyGroupingKeyWithoutInput())
@@ -141,6 +157,49 @@ case class HashAggregateExec(
.map(_.asInstanceOf[DeclarativeAggregate])
private val bufferSchema = DataTypeUtils.fromAttributes(aggregateBufferAttributes)
+ /**
+ * Whether adaptive partial aggregation applies to this operator. When it does, the aggregation
+ * may bypass partial aggregation at runtime and pass the remaining input rows through as
+ * single-row partial buffers (see [[SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED]]). It only
+ * applies to a pre-shuffle partial aggregation with grouping keys:
+ * - `Partial` mode only: the downstream `Final` aggregation merges the passed-through
+ * single-row buffers. `Final`/`Complete` produce the result themselves and have no such
+ * downstream. `PartialMerge` does have one and could be
+ * supported by passing its incoming buffer through unchanged, but that is left for later.
+ * The mode check is also what excludes the intermediate phase of a DISTINCT plan, whose
+ * modes are `PartialMerge ++ Partial`.
+ * - grouping keys present: a global aggregation produces a single output row, so partial
+ * aggregation achieves the maximum reduction and must never be bypassed.
+ * - no required distribution: with no aggregate functions (a group-by-only aggregate) the
+ * mode check is vacuously true for both phases, so `requiredChildDistributionExpressions`
+ * tells them apart, the `Final` phase requiring a distribution and the pre-shuffle phase
+ * not. It is not a general pre-shuffle test, because `AggUtils.planAggregateWithOneDistinct`
+ * leaves it `None` on a post-shuffle aggregate. DISTINCT aggregate functions are allowed:
+ * the phase that de-duplicates on (keys ++ distinct columns) requires a distribution, so
+ * this check keeps it out, while the distinct `Partial` phase that groups on the keys
+ * alone is eligible even though it sits after a shuffle: another `Exchange` and a `Final`
+ * follow it, so its passed-through buffers are still merged.
+ * - batch only: a streaming partial aggregate keeps state across batches, and it is built
+ * with all-`Partial` modes and no required distribution, so it would otherwise qualify.
+ * A batch `session_window` grouping likewise qualifies, but its partial aggregate feeds a
+ * `MergingSessionsExec` that merges overlapping sessions, so it is kept out for now. The
+ * static sibling `spark.sql.execution.bypassPartialAggregation` likewise stays away from
+ * streaming and `session_window` groupings.
+ */
+ private val adaptivePartialAggEnabled: Boolean = {
+ conf.adaptivePartialAggregationEnabled &&
+ groupingExpressions.nonEmpty &&
+ !isStreaming &&
+ !groupingExpressions.exists(_.metadata.contains(SessionWindow.marker)) &&
+ aggregateExpressions.forall(a => a.mode == Partial) &&
+ requiredChildDistributionExpressions.isEmpty
+ }
+
+ // The number of rows between two compaction-ratio evaluations, and the ratio below which the
+ // partial aggregation is considered ineffective. Only read when the feature applies.
+ private val adaptiveMinRows: Long = conf.adaptivePartialAggregationMinRows
+ private val adaptiveMinCompaction: Double = conf.adaptivePartialAggregationMinCompaction
+
// The name for Fast HashMap
private var fastHashMapTerm: String = _
private var isFastHashMapEnabled: Boolean = false
@@ -154,6 +213,47 @@ case class HashAggregateExec(
private var hashMapTerm: String = _
private var sorterTerm: String = _
+ // Codegen state for adaptive partial aggregation. When the aggregation maps stop collapsing
+ // enough rows, the operator stops populating them and instead streams each remaining row through
+ // as a single-row partial buffer for the Final aggregate to merge. The compaction ratio is
+ // measured at the operator level: all processed rows against the keys held by both the fast and
+ // the regular map, so two-level-map routing does not change the decision.
+ private var adaptivePassThroughTerm: String = _
+ private var processedRowsTerm: String = _
+ private var adaptiveChildrenConsumedTerm: String = _
+ // Whether the map output has already been emitted (and the maps freed). Once pass-through is
+ // active the maps are frozen; draining them -- which also frees them -- releases their memory
+ // before the rest of the input is streamed. The drain starts as soon as the first passed-through
+ // row queues a copy behind the maps, advancing one map row per queued row (see
+ // `handlePassThroughRow`); this flag lets the later output skip the maps.
+ private var adaptiveMapOutputDoneTerm: String = _
+ // Whether the map iterators have been set up (`finishHashMap`). The map-output function may be
+ // re-entered when its loops return via `shouldStop()` to drain the buffer, and `finishAggregate`
+ // destructs the map, so the setup must run only once.
+ private var adaptiveMapSetupDoneTerm: String = _
+ // The processed-row count at which the compaction ratio is evaluated next. It advances by
+ // `minRows` after every check, and the count is reset after a spill so the new in-memory map
+ // epoch is judged on its own rows.
+ private var adaptiveNextCheckRowTerm: String = _
+ // The fast map's key count as of the last spill. The fast map never spills and is never cleared,
+ // so its keys outlive the epoch the processed-row count is reset for; subtracting this baseline
+ // keeps both sides of the ratio on the same epoch. Once the fast map fills it stops accepting
+ // keys, so the difference settles at zero and the ratio is the regular map's alone.
+ private var adaptiveFastKeysAtSpillTerm: String = _
+ // The name of the generated output function, promoted to a field so `doConsumeWithKeys` can emit
+ // pass-through rows directly from within the build loop.
+ private var outputFunc: String = _
+ // The name of the generated function that drains the frozen maps and, once they are fully
+ // drained, flushes the queue of passed-through rows held behind them. Promoted to a field so
+ // `doConsumeWithKeys` can advance the maps one row per passed-through row (see
+ // `handlePassThroughRow`).
+ private var adaptiveOutputMapAndFlushFuncName: String = _
+ // The queue of passed-through rows, held behind the frozen maps so the maps are emitted first.
+ // Each queued row advances the map output by one row, so the queue stays bounded by how many
+ // passed-through rows a child emits before it honours `shouldStop()` (see
+ // `handlePassThroughRow`).
+ private var adaptivePendingRowsTerm: String = _
+
/**
* This is called by generated Java class, should be public.
*/
@@ -436,6 +536,25 @@ case class HashAggregateExec(
protected override def doProduceWithKeys(ctx: CodegenContext): String = {
val initAgg = ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "initAgg")
+ if (adaptivePartialAggEnabled) {
+ adaptivePassThroughTerm =
+ ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "adaptivePassThrough")
+ processedRowsTerm = ctx.addMutableState(CodeGenerator.JAVA_LONG, "processedRows")
+ adaptiveNextCheckRowTerm =
+ ctx.addMutableState(CodeGenerator.JAVA_LONG, "adaptiveNextCheckRow",
+ v => s"$v = ${adaptiveMinRows}L;")
+ adaptiveChildrenConsumedTerm =
+ ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "adaptiveChildrenConsumed")
+ adaptiveMapOutputDoneTerm =
+ ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "adaptiveMapOutputDone")
+ adaptiveMapSetupDoneTerm =
+ ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "adaptiveMapSetupDone")
+ adaptiveFastKeysAtSpillTerm =
+ ctx.addMutableState(CodeGenerator.JAVA_INT, "adaptiveFastKeysAtSpill")
+ adaptivePendingRowsTerm = ctx.addMutableState(
+ "java.util.LinkedList<UnsafeRow[]>", "adaptivePendingRows",
+ v => s"$v = new java.util.LinkedList<UnsafeRow[]>();", forceInline = true)
+ }
if (conf.enableTwoLevelAggMap) {
enableTwoLevelHashMap()
} else if (conf.enableVectorizedHashMap) {
@@ -535,19 +654,31 @@ case class HashAggregateExec(
// `addNewFunction` spills this helper into a nested class (as can happen
// once the outer class passes the code-size threshold), the bare field
// reference fails with `IllegalAccessError`.
- val doAggFuncName = ctx.addNewFunction(doAgg,
- s"""
- |private void $doAgg(int partitionIndex) throws java.io.IOException {
- | ${child.asInstanceOf[CodegenSupport].produce(ctx, this)}
- | $finishHashMap
- |}
- """.stripMargin)
- // generate code for output
+ // Generate code for output. With adaptive partial aggregation enabled this must happen before
+ // the `doAgg` helper below, because `doConsumeWithKeys` (invoked from the child's produce
+ // inside `doAgg`) emits pass-through rows by calling this output function directly. Otherwise
+ // the output function is generated after `doAgg`, so the early `consume(...)` inside it cannot
+ // change the codegen layout for plans the feature never touches.
val keyTerm = ctx.freshName("aggKey")
val bufferTerm = ctx.freshName("aggBuffer")
- val outputFunc = generateResultFunction(ctx)
+ if (adaptivePartialAggEnabled) {
+ outputFunc = generateResultFunction(ctx)
+ }
+ // After the child input is consumed, finish the build: with adaptive partial aggregation mark
+ // that the child is fully consumed (to support re-entry; the map iterators are set up inside
+ // the map-output function), otherwise set up the map iterators for the output below.
+ // A child may leave its produce loop early rather than exhausting its input: `UnionExec` runs
+ // each child inside its own helper, so a streamed row that fills the output buffer returns
+ // only as far as here. Reaching the end of `produce` therefore does not by itself mean the
+ // input is consumed -- pending output says the child parked instead, and the build resumes on
+ // re-entry. Without this the rest of that partition is silently dropped.
+ val postChildProduce = if (adaptivePartialAggEnabled) {
+ s"if (!shouldStop()) { $adaptiveChildrenConsumedTerm = true; }"
+ } else {
+ finishHashMap
+ }
val limitNotReachedCondition = limitNotReachedCond
def outputFromFastHashMap: String = {
@@ -615,8 +746,109 @@ case class HashAggregateExec(
""".stripMargin
}
+ // With adaptive partial aggregation the maps are frozen once pass-through is active, so their
+ // output (which also frees them) can happen as soon as pass-through fires, releasing the memory
+ // before the remaining input is streamed. The output loops are wrapped in a function so the
+ // same code runs either early (once pass-through freezes the maps) or at the end of the build.
+ // The done flag is set inside, after the loops, so a mid-output drain (the loops return via
+ // `shouldStop()`) leaves it unset and the caller resumes the map iterator on re-entry; once it
+ // is set the maps have been fully output and freed and will not be touched again. The iterator
+ // setup (`finishHashMap`, which destructs the map) is guarded to run only once. The queue of
+ // passed-through rows held behind the maps is flushed here, right after the done flag is set:
+ // the maps must precede the held rows so the downstream Final merges a group's map buffer
+ // before its pass-through buffers (a group can straddle the freeze, since the maps only freeze
+ // once pass-through fires), and the copies were made when the row was queued, so emitting them
+ // here cannot corrupt the build's reusable rows.
+ adaptiveOutputMapAndFlushFuncName = if (adaptivePartialAggEnabled) {
+ val name = ctx.freshName("outputMapAndFlush")
+ val pair = ctx.freshName("pendingRow")
+ ctx.addNewFunction(name,
+ s"""
+ |private void $name() throws java.io.IOException {
+ | if (!$adaptiveMapSetupDoneTerm) {
+ | $finishHashMap
+ | $adaptiveMapSetupDoneTerm = true;
+ | }
+ | $outputFromFastHashMap
+ | $outputFromRegularHashMap
+ | $adaptiveMapOutputDoneTerm = true;
+ | while (!$adaptivePendingRowsTerm.isEmpty()) {
+ | UnsafeRow[] $pair = (UnsafeRow[]) $adaptivePendingRowsTerm.poll();
+ | $outputFunc($pair[0], $pair[1]);
+ | }
+ |}
+ """.stripMargin)
+ } else {
+ ""
+ }
+
+ val doAggFuncName = ctx.addNewFunction(doAgg,
+ s"""
+ |private void $doAgg(int partitionIndex) throws java.io.IOException {
+ | ${child.asInstanceOf[CodegenSupport].produce(ctx, this)}
+ | $postChildProduce
+ |}
+ """.stripMargin)
+ // For a non-adaptive plan, generate the output function only after `doAgg` so its
+ // `consume(...)` cannot reorder the codegen layout (see above). It must still land before
+ // `adaptiveFinalOutput` reads it below.
+ if (!adaptivePartialAggEnabled) {
+ outputFunc = generateResultFunction(ctx)
+ }
+
val aggTime = metricTerm(ctx, "aggTime")
val beforeAgg = ctx.freshName("beforeAgg")
+ // Split by an exchange, `doAgg` may start appending pass-through rows to the output buffer
+ // mid-build. In that case `shouldStop()` becomes true and we must return so the buffered rows
+ // are drained; on re-entry the frozen maps are output first (`adaptiveOutputMapAndFlush`) and
+ // then the build resumes (guarded by `childrenConsumed`) until the child input is exhausted.
+ // Fused with the Final, nothing is buffered, so `shouldStop()` never fires and the maps are
+ // drained inside the build (see `handlePassThroughRow`).
+ val adaptiveStopCheck = if (adaptivePartialAggEnabled) {
+ "if (shouldStop()) return;"
+ } else {
+ ""
+ }
+ // Once pass-through is active the maps are frozen, so output them (releasing their memory)
+ // ahead of the passed-through rows. The output starts the moment the first passed-through row
+ // queues behind the maps (`handlePassThroughRow` advances the maps by one row per queued row),
+ // and continues on re-entry here; `adaptiveFinalOutput` covers the case where pass-through
+ // never fired during the build, when the full maps are the result. The output loops return via
+ // `shouldStop()` when the buffer fills, so the done flag is set inside the output function and
+ // re-entry resumes the map iterator. Only once the maps are fully drained are the queued
+ // pass-through rows flushed, so every map buffer precedes the rows that collided with it.
+ val adaptiveOutputMapAndFlush = if (adaptivePartialAggEnabled) {
+ s"""
+ |if (!$adaptiveMapOutputDoneTerm) {
+ | $adaptiveOutputMapAndFlushFuncName();
+ | if (shouldStop()) return;
+ |}
+ """.stripMargin
+ } else {
+ ""
+ }
+ val adaptiveResumeBuild = if (adaptivePartialAggEnabled) {
+ val beforeResumedAgg = ctx.freshName("beforeResumedAgg")
+ s"""
+ |if (!$adaptiveChildrenConsumedTerm) {
+ | $adaptiveOutputMapAndFlush
+ | long $beforeResumedAgg = System.nanoTime();
+ | $doAggFuncName(partitionIndex);
+ | $aggTime.add((System.nanoTime() - $beforeResumedAgg) / $NANOS_PER_MILLIS);
+ | if (shouldStop()) return;
+ |}
+ """.stripMargin
+ } else {
+ ""
+ }
+ val adaptiveFinalOutput = if (adaptivePartialAggEnabled) {
+ adaptiveOutputMapAndFlush
+ } else {
+ s"""
+ |$outputFromFastHashMap
+ |$outputFromRegularHashMap
+ """.stripMargin
+ }
s"""
|if (!$initAgg) {
| $initAgg = true;
@@ -626,13 +858,39 @@ case class HashAggregateExec(
| long $beforeAgg = System.nanoTime();
| $doAggFuncName(partitionIndex);
| $aggTime.add((System.nanoTime() - $beforeAgg) / $NANOS_PER_MILLIS);
+ | $adaptiveStopCheck
|}
- |// output the result
- |$outputFromFastHashMap
- |$outputFromRegularHashMap
+ |$adaptiveResumeBuild
+ |$adaptiveFinalOutput
""".stripMargin
}
+ // Blocking operators normally suppress the child's `shouldStop()` check because they buffer all
+ // output. With adaptive partial aggregation, pass-through rows are appended to the output buffer
+ // while consuming child input, so the stop check is re-enabled to let the child yield between
+ // rows.
+ //
+ // This bounds the buffer only as far as the child honours it. Each passed-through row queues a
+ // copy and advances the frozen-map output by one row, and that one appended map row makes
+ // `shouldStop()` true, so a child that checks between rows never queues more than one row. A
+ // one-to-many child that does not check `shouldStop()` inside its fan-out (`GenerateExec` emits
+ // `for (index ...) { consume }` and `while (iterator.hasNext()) { consume }` with no check)
+ // appends every row produced from one input row before it can yield: the fan-out batch lands in
+ // `BufferedRowIterator.currentRows` (which is not spillable), and the map advances one row per
+ // queued row, so the buffer grows to roughly the batch width rather than `minRows`.
+ override def needStopCheck: Boolean = adaptivePartialAggEnabled
+
+ // Blocking operators normally do not copy their result because every output row is drained (via
+ // `shouldStop()`) before the next one is produced. Adaptive pass-through breaks that assumption:
+ // `outputFunc` writes every output row into the same reusable result `UnsafeRow`, and under a
+ // fan-out child several such rows are appended without an intervening drain - the frozen-map
+ // rows, emitted one per queued row inside the child's fan-out loop, and the held pass-through
+ // batch, flushed from `outputMapAndFlush` after the maps drain. Without a copy they would all
+ // alias the single result row. Such children report `needCopyResult` themselves, so propagate
+ // their requirement rather than copying for every adaptive aggregate.
+ override def needCopyResult: Boolean = adaptivePartialAggEnabled &&
+ child.asInstanceOf[CodegenSupport].needCopyResult
+
protected override def doConsumeWithKeys(ctx: CodegenContext, input: Seq[ExprCode]): String = {
// create grouping key
val unsafeRowKeyCode = GenerateUnsafeProjection.createCode(
@@ -644,6 +902,18 @@ case class HashAggregateExec(
val unsafeRowBuffer = ctx.freshName("unsafeRowAggBuffer")
val fastRowBuffer = ctx.freshName("fastAggBuffer")
+ // For adaptive partial aggregation pass-through, each bypassed row is emitted as a single-row
+ // partial buffer: start from the initial aggregation buffer, apply the update expressions once,
+ // and output `key ++ buffer` for the Final aggregate to merge. This projects the initial
+ // buffer.
+ val emptyAggBufferCode = if (adaptivePartialAggEnabled) {
+ GenerateUnsafeProjection.createCode(ctx, declFunctions.flatMap(f => f.initialValues))
+ } else {
+ null
+ }
+ // Per-row local flag marking that the current row is being streamed through (held by no map).
+ val adaptiveRowBypassedTerm = ctx.freshName("adaptiveRowBypassed")
+
// To individually generate code for each aggregate function, an element in `updateExprs` holds
// all the expressions for the buffer of an aggregation function.
val updateExprs = aggregateExpressions.map { e =>
@@ -663,46 +933,129 @@ case class HashAggregateExec(
case _ => ("true", "", "")
}
- val findOrInsertRegularHashMap: String =
- s"""
- |// generate grouping key
- |${unsafeRowKeyCode.code}
- |int $unsafeRowKeyHash = ${unsafeRowKeyCode.value}.hashCode();
- |if ($checkFallbackForBytesToBytesMap) {
- | // try to get the buffer from hash map
- | $unsafeRowBuffer =
- | $hashMapTerm.getAggregationBufferFromUnsafeRow($unsafeRowKeys, $unsafeRowKeyHash);
- |}
- |// Can't allocate buffer from the hash map. Spill the map and fallback to sort-based
- |// aggregation after processing all input rows.
- |if ($unsafeRowBuffer == null) {
- | if ($sorterTerm == null) {
- | $sorterTerm = $hashMapTerm.destructAndCreateExternalSorter();
- | } else {
- | $sorterTerm.merge($hashMapTerm.destructAndCreateExternalSorter());
- | }
- | $resetCounter
- | // the hash map had be spilled, it should have enough memory now,
- | // try to allocate buffer again.
- | $unsafeRowBuffer = $hashMapTerm.getAggregationBufferFromUnsafeRow(
- | $unsafeRowKeys, $unsafeRowKeyHash);
- | if ($unsafeRowBuffer == null) {
- | // failed to allocate the first page
- | throw QueryExecutionErrors.aggregateOutOfMemoryError();
- | }
- |}
- """.stripMargin
+ // The compaction ratio is measured at the operator level: all processed rows against the keys
+ // held by both maps, so two-level-map routing does not change the decision. The same predicate
+ // decides both check points -- periodically every `minRows` rows, and right before the map
+ // would spill (in which case the spill is skipped entirely). `minRows = 0` disables the
+ // periodic check: the row count is only ever compared after being incremented past 0, so it
+ // never matches and only the spill check remains.
+ val adaptiveIneffective = if (adaptivePartialAggEnabled) {
+ val totalKeys = if (isFastHashMapEnabled) {
+ s"($fastHashMapTerm.getNumKeys() - $adaptiveFastKeysAtSpillTerm + " +
+ s"$hashMapTerm.getNumKeys())"
+ } else {
+ s"$hashMapTerm.getNumKeys()"
+ }
+ s"$processedRowsTerm < (double) $totalKeys * ${adaptiveMinCompaction}D"
+ } else {
+ ""
+ }
+
+ val findOrInsertRegularHashMap: String = {
+ // Assumes the grouping key projection (`unsafeRowKeyCode.code`) has already run for this row,
+ // so `unsafeRowKeyCode.value` holds the current key. The projection is emitted exactly once
+ // per regular-map row (see below); emitting it in more than one runtime branch is unsafe
+ // because the projection's subexpression/writer state assigned in one branch would be read
+ // stale from another (e.g. the adaptive pass-through path would reuse the last probed key).
+ val probeRegularMap =
+ s"""
+ |int $unsafeRowKeyHash = ${unsafeRowKeyCode.value}.hashCode();
+ |if ($checkFallbackForBytesToBytesMap) {
+ | // try to get the buffer from hash map
+ | $unsafeRowBuffer =
+ | $hashMapTerm.getAggregationBufferFromUnsafeRow($unsafeRowKeys, $unsafeRowKeyHash);
+ |}
+ """.stripMargin
+
+ val spillMap =
+ s"""
+ |if ($sorterTerm == null) {
+ | $sorterTerm = $hashMapTerm.destructAndCreateExternalSorter();
+ |} else {
+ | $sorterTerm.merge($hashMapTerm.destructAndCreateExternalSorter());
+ |}
+ |$resetCounter
+ |// the hash map had been spilled, so it should have enough memory now,
+ |// try to allocate buffer again.
+ |$unsafeRowBuffer = $hashMapTerm.getAggregationBufferFromUnsafeRow(
+ | $unsafeRowKeys, $unsafeRowKeyHash);
+ |if ($unsafeRowBuffer == null) {
+ | // failed to allocate the first page
+ | throw QueryExecutionErrors.aggregateOutOfMemoryError();
+ |}
+ """.stripMargin
+
+ if (adaptivePartialAggEnabled) {
+ // Spilling starts a new in-memory epoch, so the counters restart and the ratio of that
+ // epoch alone decides the remaining rows. The fast map neither spills nor clears, so its
+ // keys outlive the epoch; snapshotting them here keeps both sides of the ratio on the
+ // same rows. Once the fast map fills it stops accepting keys and the difference settles
+ // at zero, leaving the regular map's keys alone.
+ val snapshotFastKeys = if (isFastHashMapEnabled) {
+ s"$adaptiveFastKeysAtSpillTerm = $fastHashMapTerm.getNumKeys();"
+ } else {
+ ""
+ }
+ val spillAndRestartEpoch =
+ s"""
+ |$spillMap
+ |$processedRowsTerm = 0L;
+ |$adaptiveNextCheckRowTerm = ${adaptiveMinRows}L;
+ |$snapshotFastKeys
+ """.stripMargin
+ s"""
+ |// generate grouping key
+ |${unsafeRowKeyCode.code}
+ |if (!$adaptivePassThroughTerm) {
+ | $probeRegularMap
+ | if ($unsafeRowBuffer == null) {
+ | if ($processedRowsTerm > 0 && $adaptiveIneffective) {
+ | $adaptivePassThroughTerm = true;
+ | } else {
+ | $spillAndRestartEpoch
+ | }
+ | }
+ |}
+ """.stripMargin
+ } else {
+ s"""
+ |// generate grouping key
+ |${unsafeRowKeyCode.code}
+ |$probeRegularMap
+ |// Can't allocate buffer from the hash map. Spill the map and fallback to sort-based
+ |// aggregation after processing all input rows.
+ |if ($unsafeRowBuffer == null) {
+ | $spillMap
+ |}
+ """.stripMargin
+ }
+ }
val findOrInsertHashMap: String = {
- if (isFastHashMapEnabled) {
+ val findCode = if (isFastHashMapEnabled) {
// If fast hash map is on, we first generate code to probe and update the fast hash map.
// If the probe is successful the corresponding fast row buffer will hold the mutable row.
+ // Once adaptive pass-through is active, skip the fast map entirely so the row is streamed
+ // through instead of being inserted anywhere.
+ val fastMapProbe =
+ s"""
+ |${fastRowKeys.map(_.code).mkString("\n")}
+ |if (${fastRowKeys.map("!" + _.isNull).mkString(" && ")}) {
+ | $fastRowBuffer = $fastHashMapTerm.findOrInsert(
+ | ${fastRowKeys.map(_.value).mkString(", ")});
+ |}
+ """.stripMargin
+ val guardedFastMapProbe = if (adaptivePartialAggEnabled) {
+ s"""
+ |if (!$adaptivePassThroughTerm) {
+ | $fastMapProbe
+ |}
+ """.stripMargin
+ } else {
+ fastMapProbe
+ }
s"""
- |${fastRowKeys.map(_.code).mkString("\n")}
- |if (${fastRowKeys.map("!" + _.isNull).mkString(" && ")}) {
- | $fastRowBuffer = $fastHashMapTerm.findOrInsert(
- | ${fastRowKeys.map(_.value).mkString(", ")});
- |}
+ |$guardedFastMapProbe
|// Cannot find the key in fast hash map, try regular hash map.
|if ($fastRowBuffer == null) {
| $findOrInsertRegularHashMap
@@ -711,6 +1064,54 @@ case class HashAggregateExec(
} else {
findOrInsertRegularHashMap
}
+
+ // Every row is either accepted by an aggregation map or streamed through -- the fast map
+ // serves a row without it ever reaching the regular map, so both buffers are consulted to
+ // tell the two apart.
+ //
+ // An accepted row counts toward the compaction ratio, so the numerator matches the
+ // operator-level denominator. Counting inside the regular-map branch alone would drop the
+ // rows the fast map absorbed from the ratio and bypass an aggregation that is in fact
+ // reducing. A row no map holds is streamed once pass-through is active: both probes are
+ // skipped (guarded above), so neither buffer is set, and `rowBypassed` marks exactly those
+ // rows. The row that fails to insert at the spill boundary lands here too, while the row
+ // that merely flipped pass-through at the check point is already aggregated in the map that
+ // took it and must not be re-emitted.
+ val countOrPassThroughRow = if (adaptivePartialAggEnabled) {
+ val heldByAMap = if (isFastHashMapEnabled) {
+ s"($fastRowBuffer != null || $unsafeRowBuffer != null)"
+ } else {
+ s"($unsafeRowBuffer != null)"
+ }
+ // The grouping key was already projected in `findOrInsertRegularHashMap`
+ // (`unsafeRowKeyCode.code`), so `unsafeRowKeyCode.value` holds this row's key. Only build
+ // the single-row partial buffer here.
+ s"""
+ |if ($heldByAMap) {
+ | if (!$adaptivePassThroughTerm) {
+ | $processedRowsTerm += 1;
+ | if ($processedRowsTerm == $adaptiveNextCheckRowTerm) {
+ | if ($adaptiveIneffective) {
+ | $adaptivePassThroughTerm = true;
+ | } else {
+ | $adaptiveNextCheckRowTerm += ${adaptiveMinRows}L;
+ | }
+ | }
+ | }
+ |} else if ($adaptivePassThroughTerm) {
+ | $adaptiveRowBypassedTerm = true;
+ | ${emptyAggBufferCode.code}
+ | $unsafeRowBuffer = ${emptyAggBufferCode.value};
+ |}
+ """.stripMargin
+ } else {
+ ""
+ }
+
+ s"""
+ |$findCode
+ |$countOrPassThroughRow
+ """.stripMargin
}
val inputAttrs = aggregateBufferAttributes ++ inputAttributes
@@ -845,29 +1246,75 @@ case class HashAggregateExec(
}
}
- val declareRowBuffer: String = if (isFastHashMapEnabled) {
- val fastRowType = if (isVectorizedHashMapEnabled) {
- classOf[MutableColumnarRow].getName
+ val declareRowBuffer: String = {
+ val declareBuffers = if (isFastHashMapEnabled) {
+ val fastRowType = if (isVectorizedHashMapEnabled) {
+ classOf[MutableColumnarRow].getName
+ } else {
+ "UnsafeRow"
+ }
+ s"""
+ |UnsafeRow $unsafeRowBuffer = null;
+ |$fastRowType $fastRowBuffer = null;
+ """.stripMargin
+ } else {
+ s"UnsafeRow $unsafeRowBuffer = null;"
+ }
+ val declareBypassed = if (adaptivePartialAggEnabled) {
+ s"boolean $adaptiveRowBypassedTerm = false;"
} else {
- "UnsafeRow"
+ ""
}
s"""
- |UnsafeRow $unsafeRowBuffer = null;
- |$fastRowType $fastRowBuffer = null;
+ |$declareBuffers
+ |$declareBypassed
""".stripMargin
- } else {
- s"UnsafeRow $unsafeRowBuffer = null;"
}
// We try to do hash map based in-memory aggregation first. If there is not enough memory (the
// hash map will return null for new key), we spill the hash map to disk to free memory, then
// continue to do in-memory aggregation and spilling until all the rows had been processed.
// Finally, sort the spilled aggregate buffers by key, and merge them together for same key.
+ //
+ // With adaptive partial aggregation, once pass-through is active `updateRowInHashMap` fills the
+ // single-row buffer built above; we then emit `key ++ buffer` straight to the parent so the row
+ // skips both the fast map and the regular map.
+ //
+ // The maps were frozen when pass-through fired, so a group can straddle the freeze and hold
+ // both a map buffer and pass-through buffers. The downstream Final merges in emit order, so
+ // every map buffer must precede the pass-through buffers of the same group. We hold each
+ // passed-through row in a queue behind the maps: the row is queued as a copy, and queuing it
+ // advances the map output by one row. That one appended map row is what makes `shouldStop()`
+ // true, so a child that honours the check yields at the end of its batch and never queues more
+ // than one row; a one-to-many child that cannot yield mid-fan-out queues its whole batch at
+ // once, bounding the queue by the batch width. The map drains one row per queued row (the same
+ // cadence the 1:1 shape already uses), and once the maps are fully drained the queue is
+ // flushed, so the maps always precede the held rows. Fused with the Final, nothing is
+ // buffered, `shouldStop()` never fires, and the single output call drains the whole map before
+ // the held row follows.
+ val handlePassThroughRow = if (adaptivePartialAggEnabled) {
+ val numBypassingRows = metricTerm(ctx, "numBypassingRows")
+ s"""
+ |if ($adaptiveRowBypassedTerm) {
+ | $numBypassingRows.add(1);
+ | if ($adaptiveMapOutputDoneTerm) {
+ | $outputFunc(${unsafeRowKeyCode.value}, $unsafeRowBuffer);
+ | } else {
+ | $adaptivePendingRowsTerm.add(new UnsafeRow[] {
+ | ${unsafeRowKeyCode.value}.copy(), $unsafeRowBuffer.copy() });
+ | $adaptiveOutputMapAndFlushFuncName();
+ | }
+ |}
+ """.stripMargin
+ } else {
+ ""
+ }
s"""
|$declareRowBuffer
|$findOrInsertHashMap
|$incCounter
|$updateRowInHashMap
+ |$handlePassThroughRow
""".stripMargin
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/TungstenAggregationIterator.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/TungstenAggregationIterator.scala
index 00d18a2f79a8..9521a68ae4b2 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/TungstenAggregationIterator.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/TungstenAggregationIterator.scala
@@ -17,6 +17,8 @@
package org.apache.spark.sql.execution.aggregate
+import java.util.concurrent.TimeUnit.NANOSECONDS
+
import org.apache.spark.{SparkException, TaskContext}
import org.apache.spark.internal.Logging
import org.apache.spark.sql.catalyst.InternalRow
@@ -57,9 +59,10 @@ import org.apache.spark.util.ArrayImplicits._
* - Part 3: Methods and fields used by hash-based aggregation.
* - Part 4: Methods and fields used when we switch to sort-based aggregation.
* - Part 5: Methods and fields used by sort-based aggregation.
- * - Part 6: Loads input and process input rows.
- * - Part 7: Public methods of this iterator.
- * - Part 8: A utility function used to generate a result when there is no
+ * - Part 6: Methods and fields used by adaptive partial aggregation pass-through.
+ * - Part 7: Loads input and processes input rows.
+ * - Part 8: Public methods of this iterator.
+ * - Part 9: A utility function used to generate a result when there is no
* input and there is no grouping expression.
*
* @param partIndex
@@ -95,7 +98,12 @@ class TungstenAggregationIterator(
peakMemory: SQLMetric,
spillSize: SQLMetric,
avgHashProbe: SQLMetric,
- numTasksFallBacked: SQLMetric)
+ numTasksFallBacked: SQLMetric,
+ numBypassingRows: SQLMetric,
+ aggTime: SQLMetric,
+ adaptivePartialAggEnabled: Boolean,
+ adaptiveMinRows: Long,
+ adaptiveMinCompaction: Double)
extends AggregationIterator(
partIndex,
groupingExpressions,
@@ -121,8 +129,9 @@ class TungstenAggregationIterator(
///////////////////////////////////////////////////////////////////////////
// Creates a new aggregation buffer and initializes buffer values.
- // This function should be only called at most two times (when we create the hash map,
- // and when we create the re-used buffer for sort-based aggregation).
+ // This function should be called at most three times: when we create the hash map, when we
+ // create the re-used buffer for sort-based aggregation, and when we create the buffer for
+ // pass-through rows.
private def createNewAggregationBuffer(): UnsafeRow = {
val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
val buffer: UnsafeRow = UnsafeProjection.create(bufferSchema.map(_.dataType))
@@ -179,6 +188,21 @@ class TungstenAggregationIterator(
// hashMap. If there is not enough memory, it will multiple hash-maps, spilling
// after each becomes full then using sort to merge these spills, finally do sort
// based aggregation.
+ //
+ // When adaptive partial aggregation is enabled (`adaptivePartialAggEnabled`), the processing may
+ // stop early and switch to pass-through mode: the remaining input rows are not added to the map
+ // but are instead emitted as single-row partial buffers by the output stage (see
+ // `nextPassThroughOutput`). One predicate decides both check points -- the aggregation is
+ // ineffective when `processedRows < distinctKeys * minCompaction`, i.e. it does not collapse
+ // `minCompaction` rows into one key:
+ // - periodically, every `minRows` processed rows;
+ // - when the map is about to spill, in which case the spill is skipped entirely and the row
+ // that could not be inserted becomes the first pass-through row.
+ // A spill starts a new in-memory map epoch: the row counters restart so that epoch is judged on
+ // its own rows, which lets an input whose cardinality only turns unfavorable later still be
+ // passed through. Pass-through may therefore coexist with earlier spills. The output order
+ // matches the generated path: the frozen map (or sort-based) output comes first, and the
+ // pass-through rows stream afterwards.
private def processInputs(fallbackStartsAt: (Int, Int)): Unit = {
if (groupingExpressions.isEmpty) {
// If there is no grouping expressions, we can just reuse the same buffer over and over again.
@@ -191,7 +215,19 @@ class TungstenAggregationIterator(
}
} else {
var i = 0
- while (inputIter.hasNext) {
+ var processedRows = 0L
+ val minRows = adaptiveMinRows
+ // The processed-row count at which the compaction ratio is evaluated next. It advances by
+ // `minRows` after every check, and restarts after a spill so the new in-memory map epoch is
+ // judged on its own rows. `minRows = 0` disables the periodic check: the count is only ever
+ // compared after being incremented past 0, so it never matches and only the spill check
+ // below remains.
+ var nextCheckRow = minRows
+ // The partial aggregation is ineffective when it does not collapse `minCompaction` rows into
+ // one key. There is no fast map on this path, so the map's keys are all the operator holds.
+ def ineffective(): Boolean =
+ processedRows < hashMap.getNumKeys().toDouble * adaptiveMinCompaction
+ while (inputIter.hasNext && !passThrough) {
val newInput = inputIter.next()
val groupingKey = groupingProjection.apply(newInput)
var buffer: UnsafeRow = null
@@ -199,21 +235,47 @@ class TungstenAggregationIterator(
buffer = hashMap.getAggregationBufferFromUnsafeRow(groupingKey)
}
if (buffer == null) {
- val sorter = hashMap.destructAndCreateExternalSorter()
- if (externalSorter == null) {
- externalSorter = sorter
+ // The map is full and would normally spill. Adaptive partial aggregation may instead
+ // bypass: keep the in-memory map as-is, pass this row and all remaining rows through,
+ // and skip the spill entirely.
+ if (adaptivePartialAggEnabled && processedRows > 0 && ineffective()) {
+ passThrough = true
+ // `newInput` could not be inserted; stash a copy as the first pass-through row so it
+ // is not lost when we drain the rest of `inputIter`.
+ pendingPassThroughRow = newInput.copy()
} else {
- externalSorter.merge(sorter)
+ val sorter = hashMap.destructAndCreateExternalSorter()
+ if (externalSorter == null) {
+ externalSorter = sorter
+ } else {
+ externalSorter.merge(sorter)
+ }
+ i = 0
+ // The map starts a new in-memory epoch, so the counters restart and the ratio of that
+ // epoch alone decides whether the remaining rows are passed through.
+ processedRows = 0L
+ nextCheckRow = minRows
+ buffer = hashMap.getAggregationBufferFromUnsafeRow(groupingKey)
+ if (buffer == null) {
+ // failed to allocate the first page
+ throw QueryExecutionErrors.aggregateOutOfMemoryError()
+ }
}
- i = 0
- buffer = hashMap.getAggregationBufferFromUnsafeRow(groupingKey)
- if (buffer == null) {
- // failed to allocate the first page
- throw QueryExecutionErrors.aggregateOutOfMemoryError()
+ }
+ if (!passThrough) {
+ processRow(buffer, newInput)
+ i += 1
+ processedRows += 1
+ // Periodic check: if the aggregation is not collapsing enough rows, bypass it for the
+ // rest of the input.
+ if (adaptivePartialAggEnabled && processedRows == nextCheckRow) {
+ if (ineffective()) {
+ passThrough = true
+ } else {
+ nextCheckRow += minRows
+ }
}
}
- processRow(buffer, newInput)
- i += 1
}
if (externalSorter != null) {
@@ -355,7 +417,55 @@ class TungstenAggregationIterator(
}
///////////////////////////////////////////////////////////////////////////
- // Part 6: Loads input rows and setup aggregationBufferMapIterator if we
+ // Part 6: Methods and fields used by adaptive partial aggregation pass-through.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // Indicates that partial aggregation has been bypassed and the remaining input rows should be
+ // passed through as single-row partial buffers. Set in `processInputs` by either check point.
+ // It may coexist with earlier spills. The output order matches the generated path: the frozen
+ // map (or sort-based) output comes first, and the pass-through rows stream afterwards.
+ private[this] var passThrough: Boolean = false
+
+ // The row that could not be inserted at the spill check. It is stashed here (as
+ // a copy) so it becomes the first pass-through row rather than being lost.
+ private[this] var pendingPassThroughRow: InternalRow = null
+
+ // A reused aggregation buffer for building single-row partial buffers during pass-through. It is
+ // re-initialized from `initialAggregationBuffer` for every passed-through row.
+ private[this] lazy val passThroughAggregationBuffer: UnsafeRow = createNewAggregationBuffer()
+
+ // Whether there are remaining pass-through rows to emit.
+ private def passThroughHasNext: Boolean =
+ passThrough && (pendingPassThroughRow != null || inputIter.hasNext)
+
+ // `aggTime` only covers the build, which runs to completion in the constructor before
+ // pass-through is known; the interpreted path consumes the rest of the input lazily through
+ // `next()`. The drain is therefore timed there, bracketed once per drain (not per row) so the
+ // timing call does not distort the per-row work, mirroring the generated path which times the
+ // drain around each resume of the build.
+ private var passThroughDrainStart: Long = -1L
+
+ // Emits the next input row as a single-row partial aggregation buffer, i.e. a group of size one.
+ // The output (grouping key ++ buffer) is a valid partial buffer that the downstream Final
+ // aggregation merges, so the result is identical to running partial aggregation on this row.
+ private def nextPassThroughOutput(): UnsafeRow = {
+ val row = if (pendingPassThroughRow != null) {
+ val stashed = pendingPassThroughRow
+ pendingPassThroughRow = null
+ stashed
+ } else {
+ inputIter.next()
+ }
+ val groupingKey = groupingProjection.apply(row)
+ // Reset the buffer to initial values, then update it with this single row.
+ passThroughAggregationBuffer.copyFrom(initialAggregationBuffer)
+ processRow(passThroughAggregationBuffer, row)
+ numBypassingRows += 1
+ generateOutput(groupingKey, passThroughAggregationBuffer)
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Part 7: Loads input rows and sets up aggregationBufferMapIterator if we
// have not switched to sort-based aggregation.
///////////////////////////////////////////////////////////////////////////
@@ -394,16 +504,17 @@ class TungstenAggregationIterator(
})
///////////////////////////////////////////////////////////////////////////
- // Part 7: Iterator's public methods.
+ // Part 8: Iterator's public methods.
///////////////////////////////////////////////////////////////////////////
override final def hasNext: Boolean = {
- (sortBased && sortedInputHasNewGroup) || (!sortBased && mapIteratorHasNext)
+ (sortBased && sortedInputHasNewGroup) || (!sortBased && mapIteratorHasNext) ||
+ passThroughHasNext
}
override final def next(): UnsafeRow = {
if (hasNext) {
- val res = if (sortBased) {
+ val res = if (sortBased && sortedInputHasNewGroup) {
// Process the current group.
processCurrentSortedGroup()
// Generate output row for the current group.
@@ -412,7 +523,7 @@ class TungstenAggregationIterator(
sortBasedAggregationBuffer.copyFrom(initialAggregationBuffer)
outputRow
- } else {
+ } else if (mapIteratorHasNext) {
// We did not fall back to sort-based aggregation.
val result =
generateOutput(
@@ -426,13 +537,25 @@ class TungstenAggregationIterator(
if (!mapIteratorHasNext) {
// If there is no input from aggregationBufferMapIterator, we copy current result.
val resultCopy = result.copy()
- // Then, we free the map.
+ // Then, we free the map. Pass-through (if any) does not use the map.
hashMap.free()
resultCopy
} else {
result
}
+ } else {
+ // Adaptive partial aggregation bypassed partial aggregation: emit the remaining input
+ // rows as single-row partial buffers, after the frozen map output above.
+ if (passThroughDrainStart == -1L) {
+ passThroughDrainStart = System.nanoTime()
+ }
+ val out = nextPassThroughOutput()
+ if (!passThroughHasNext) {
+ aggTime += NANOSECONDS.toMillis(System.nanoTime() - passThroughDrainStart)
+ passThroughDrainStart = -1L
+ }
+ out
}
numOutputRows += 1
@@ -444,7 +567,7 @@ class TungstenAggregationIterator(
}
///////////////////////////////////////////////////////////////////////////
- // Part 8: Utility functions
+ // Part 9: Utility functions
///////////////////////////////////////////////////////////////////////////
/**
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/VectorizedHashMapGenerator.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/VectorizedHashMapGenerator.scala
index f9c4ecc14e6c..e1f9682439a3 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/VectorizedHashMapGenerator.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/VectorizedHashMapGenerator.scala
@@ -83,6 +83,10 @@ class VectorizedHashMapGenerator(
| buckets = new int[numBuckets];
| java.util.Arrays.fill(buckets, -1);
| }
+ |
+ | public int getNumKeys() {
+ | return numRows;
+ | }
""".stripMargin
}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/aggregate/AdaptivePartialAggregationSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/aggregate/AdaptivePartialAggregationSuite.scala
new file mode 100644
index 000000000000..1727a3415a5b
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/aggregate/AdaptivePartialAggregationSuite.scala
@@ -0,0 +1,1256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.{DataFrame, QueryTest, Row}
+import org.apache.spark.sql.catalyst.expressions.aggregate.Partial
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+
+/**
+ * Tests for runtime adaptive partial aggregation
+ * (see [[SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED]]). When a partial aggregate is not reducing
+ * rows, the operator stops aggregating and streams the remaining rows through as single-row partial
+ * buffers for the Final aggregate to merge. Once pass-through is active the map is frozen, and its
+ * output always precedes the passed-through rows: a row that collides with a frozen key is held
+ * behind the map and flushed only after it drains, so every group merges its buffers in the same
+ * order as a run that never bypasses, including order-sensitive aggregates such as `first`/`last`.
+ *
+ * The suite has two halves:
+ * 1. Correctness: aggregate results are identical to the reference (feature-off) run across the
+ * full matrix of codegen on/off, two-level map on/off, and spill/no-spill, over a range of
+ * aggregate shapes, key types, and `Expand`-bearing plans (ROLLUP / CUBE / GROUPING SETS /
+ * multi-distinct). Order-sensitive aggregates are tested against the reference too, including
+ * under a fan-out child that queues its whole batch behind the frozen map.
+ * 2. Triggering: the `numBypassingRows` metric proves the bypass actually fires when (and only
+ * when) it should -- high-cardinality input bypasses, low-cardinality input keeps aggregating,
+ * the feature switch and eligibility rules are honored, and both check points work.
+ */
+class AdaptivePartialAggregationSuite extends QueryTest with SharedSparkSession
+ with AdaptiveSparkPlanHelper {
+
+ import testImplicits._
+
+ // A `testFallbackStartsAt` setting ("fastMapCounter, regularMapCounter") that makes the regular
+ // map fall back (spill) periodically, exercising the spill-check decision path in both the
+ // codegen and interpreted aggregation paths. Kept moderate so low-cardinality inputs (which are
+ // never bypassed and therefore really spill) do not open an unbounded number of spill readers.
+ private val forceSpillFallback = "4, 16"
+
+ // The upstream `CombineAdjacentAggregation` and `ReplaceHashWithSortAgg` rules would change the
+ // plan of these small single-partition queries away from a Partial+Final `HashAggregateExec`:
+ // the former merges the two adjacent phases (no shuffle in between) into a single `Complete`
+ // aggregate, and the latter converts a hash aggregate to a sort aggregate when the input is
+ // already sorted by the grouping key (a `Range` over an ascending `id` key). The adaptive
+ // feature lives in the partial hash aggregation, so both rules are disabled to keep that
+ // structure in the tests.
+ private val fixedPlanConfs = Seq(
+ SQLConf.COMBINE_ADJACENT_AGGREGATION_ENABLED.key -> "false",
+ SQLConf.REPLACE_HASH_WITH_SORT_AGG_ENABLED.key -> "false")
+
+ /**
+ * Runs `build` with adaptive partial aggregation disabled (the reference) and then across the
+ * full configuration matrix with it enabled, asserting every enabled run matches the reference.
+ *
+ * `build` takes the number of input partitions, which the matrix varies along with everything
+ * else, because the plan shape decides which parts of the feature run at all. When the two
+ * aggregates end up in one whole-stage -- no `Exchange` between them -- the partial aggregate's
+ * output feeds the Final's `doConsume` directly and never reaches
+ * `BufferedRowIterator.currentRows`, so `shouldStop()` stays false for the whole build and
+ * neither `needStopCheck` nor the resumed-build path is exercised. Splitting them puts the
+ * streamed rows through the output buffer and runs both.
+ *
+ * More than one input partition is necessary but not sufficient for that split: a `Range` keyed
+ * directly on `id` already reports an output partitioning that satisfies the Final aggregate's
+ * `ClusteredDistribution`, so `EnsureRequirements` inserts no `Exchange` however many partitions
+ * it has. Tests that want the split shape group on a derived key (a cast, say) so the input
+ * partitioning no longer satisfies the requirement.
+ *
+ * `expectBypass` ties the correctness guarantee to the triggering guarantee: beyond matching the
+ * reference, every cell must either actually stream rows through (when true) or keep
+ * aggregating (when false). Without it a test could silently stop exercising pass-through if the
+ * input stopped being bypassable, and only this assertion makes that fail loudly.
+ */
+ private def checkAdaptiveMatchesReference(
+ build: Int => DataFrame,
+ expectBypass: Boolean = true): Unit = {
+ for {
+ inputPartitions <- Seq(1, 2)
+ wholeStage <- Seq(true, false)
+ twoLevelMap <- Seq(true, false)
+ forceSpill <- Seq(true, false)
+ } {
+ // The reference is built with the same partitioning, so only the feature differs.
+ val reference = withSQLConf(
+ (SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "false") +: fixedPlanConfs: _*) {
+ build(inputPartitions).collect().toSeq
+ }
+ val spillConf = if (forceSpill) {
+ Seq("spark.sql.TungstenAggregate.testFallbackStartsAt" -> forceSpillFallback)
+ } else {
+ Nil
+ }
+ withSQLConf(
+ (Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> twoLevelMap.toString,
+ // Small `minRows` so the periodic check runs on modest inputs.
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS.key -> "8") ++
+ spillConf ++ fixedPlanConfs): _*) {
+ val msg = s"inputPartitions=$inputPartitions wholeStage=$wholeStage " +
+ s"twoLevelMap=$twoLevelMap forceSpill=$forceSpill"
+ withClue(msg) {
+ // Collect once so the metrics are populated, then check whether the bypass fired for
+ // this cell. The metric lives on the `Partial`-mode `HashAggregateExec`, so that is the
+ // operator the assertion reads.
+ val df = build(inputPartitions)
+ df.collect()
+ val skipped = collect(df.queryExecution.executedPlan) {
+ case agg: HashAggregateExec if agg.aggregateExpressions.forall(_.mode == Partial) =>
+ agg.metrics.get("numBypassingRows").map(_.value).getOrElse(0L)
+ }.sum
+ if (expectBypass) {
+ assert(skipped > 0,
+ s"expected rows to bypass partial aggregation, got $skipped bypassed rows")
+ } else {
+ assert(skipped == 0,
+ s"expected no rows to bypass partial aggregation, got $skipped bypassed rows")
+ }
+ checkAnswer(df, reference)
+ }
+ }
+ }
+ }
+
+ /**
+ * The observable per-run counters we assert on, all read from the partial `HashAggregateExec` in
+ * a single execution so the metrics are not double-counted:
+ * - `skipped`: our self-reported `numBypassingRows` metric.
+ * - `partialOutputRows`: the partial aggregate's own `numOutputRows`. An independent,
+ * pre-existing counter driven by the normal output path, so it is the ground truth for
+ * whether rows were streamed through -- it equals the distinct key count when aggregation is
+ * effective and climbs toward the input row count once the operator bypasses.
+ * - `spillBytes`: the partial aggregate's `spillSize`. Reliable only when no fallback is
+ * forced: on the interpreted path this is derived from the task-cumulative memory-spill
+ * counter, so a forced fallback (or downstream shuffle-write spill) can inflate it.
+ * Asserted only by the periodic check test, which forces no fallback; use
+ * `tasksFallBacked` otherwise.
+ * - `tasksFallBacked`: the partial aggregate's `numTasksFallBacked`, incremented only when the
+ * regular map actually falls back into sort-based aggregation. When the spill check bypasses
+ * at the spill boundary the sorter is never created, so this stays 0 -- direct, per-operator
+ * evidence the bypass replaced the sort fallback.
+ */
+ private case class AggCounters(
+ skipped: Long,
+ partialOutputRows: Long,
+ spillBytes: Long,
+ tasksFallBacked: Long)
+
+ // Verifies `df` (an already-collected bypassing run) produces the same results as the feature-off
+ // reference. `build` is re-run for the reference so it gets a genuinely non-adaptive plan rather
+ // than reusing the bypassing run's cached one.
+ private def checkAgainstReference(df: DataFrame, build: () => DataFrame): Unit = {
+ val reference = withSQLConf(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "false") {
+ build().collect().toSeq
+ }
+ checkAnswer(df, reference)
+ }
+
+ private def runAndReadCounters(build: () => DataFrame): AggCounters = {
+ // The triggering tests assert on metrics, so also verify the bypassing run produces the same
+ // results as the feature-off reference.
+ val df = build()
+ df.collect()
+ val partialAggs = collect(df.queryExecution.executedPlan) {
+ case agg: HashAggregateExec if agg.aggregateExpressions.forall(_.mode == Partial) => agg
+ }
+ // A partial aggregate is always present for the grouped queries these tests use.
+ assert(partialAggs.nonEmpty, "expected a partial HashAggregateExec in the plan")
+ val counters = AggCounters(
+ // The metric is only registered on aggregates the feature applies to; an aggregate without
+ // it bypassed nothing.
+ skipped = partialAggs.map(_.metrics.get("numBypassingRows").map(_.value).getOrElse(0L)).sum,
+ partialOutputRows = partialAggs.map(_.metrics("numOutputRows").value).sum,
+ spillBytes = partialAggs.map(_.metrics("spillSize").value).sum,
+ tasksFallBacked = partialAggs.map(_.metrics("numTasksFallBacked").value).sum)
+ checkAgainstReference(df, build)
+ counters
+ }
+
+ private def numBypassingRows(build: () => DataFrame): Long = runAndReadCounters(build).skipped
+
+ // Returns the bypassed-row count per Partial-mode `HashAggregateExec`, keyed by the number of
+ // grouping keys, and verifies the run matches the feature-off reference. A `count(DISTINCT ...)`
+ // group-by has two such Partial phases -- the de-duplication partial (grouping on key + distinct
+ // columns) and the distinct partial (grouping on the keys only) -- so their bypasses can be told
+ // apart by the grouping key count.
+ private def bypassRowsByGroupingKeyCount(build: () => DataFrame): Map[Int, Long] = {
+ val df = build()
+ df.collect()
+ val byKeyCount = collect(df.queryExecution.executedPlan) {
+ case agg: HashAggregateExec if agg.aggregateExpressions.forall(_.mode == Partial) =>
+ agg.groupingExpressions.length ->
+ agg.metrics.get("numBypassingRows").map(_.value).getOrElse(0L)
+ }.groupBy(_._1).map { case (n, pairs) => n -> pairs.map(_._2).sum }
+ checkAgainstReference(df, build)
+ byKeyCount
+ }
+
+ /**
+ * Runs `body` once per (wholeStage, twoLevelMap) combination with the feature enabled and a small
+ * `minRows`, threading a descriptive clue for failure messages.
+ *
+ * The fast (first-level) map is append-only and never spills, so only the regular (second-level)
+ * map can reach a spill boundary. With the default fast-map capacity (2^16) a small
+ * high-cardinality input would be fully absorbed by the fast map and never reach the regular map,
+ * so nothing could ever bypass. To make the triggering tests meaningful when the two-level map is
+ * on, we shrink the fast map via the first field of `testFallbackStartsAt` so rows fall through
+ * to the regular map. `regularFallback` optionally sets the second field to also force the
+ * regular map to spill (for the spill check); when 0 the regular map does not spill.
+ */
+ private def forEachCodegenAndMap(
+ minRows: Long = 8,
+ regularFallback: Int = 0,
+ minCompaction: Double = -1.0)(
+ body: String => Unit): Unit = {
+ for {
+ wholeStage <- Seq(true, false)
+ twoLevelMap <- Seq(true, false)
+ } {
+ // Shrink the fast map to 4 keys when it is on so rows reach the regular map. The second field
+ // controls regular-map spilling; 0 means "never" (a large sentinel).
+ val fallbackConf = if (twoLevelMap || regularFallback > 0) {
+ val fastCap = if (twoLevelMap) 4 else 1
+ val regular = if (regularFallback > 0) regularFallback else Int.MaxValue
+ Seq("spark.sql.TungstenAggregate.testFallbackStartsAt" -> s"$fastCap, $regular")
+ } else {
+ Nil
+ }
+ // A negative value means "leave the threshold at its default".
+ val thresholdConf = if (minCompaction >= 0.0) {
+ Seq(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_COMPACTION.key -> minCompaction.toString)
+ } else {
+ Nil
+ }
+ withSQLConf(
+ (Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> twoLevelMap.toString,
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS.key -> minRows.toString) ++
+ fallbackConf ++ thresholdConf ++ fixedPlanConfs): _*) {
+ body(s"wholeStage=$wholeStage twoLevelMap=$twoLevelMap")
+ }
+ }
+ }
+
+ /////////////////////////////////////////////////////////////////////////////
+ // Part 1: Correctness -- results identical to the feature-off reference.
+ /////////////////////////////////////////////////////////////////////////////
+
+ test("results unchanged for high-cardinality input that bypasses partial aggregation") {
+ // Every grouping key is distinct, so partial aggregation reduces nothing and should be
+ // bypassed by the periodic check.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 200, 1, parts)
+ .select($"id".cast("string") as "k", ($"id" * 2) as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s", count(lit(1)) as "c", max($"v") as "m")
+ }
+ }
+
+ test("results unchanged for low-cardinality input that keeps partial aggregation") {
+ // Few distinct keys, high reduction: partial aggregation is effective and should be kept, so
+ // the bypass metric must stay zero in every cell.
+ checkAdaptiveMatchesReference(
+ expectBypass = false,
+ build = { parts =>
+ spark.range(0, 600, 1, parts)
+ .select(($"id" % 5).cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s", count(lit(1)) as "c", min($"v") as "mn", max($"v") as "mx")
+ })
+ }
+
+ test("results unchanged for medium-cardinality input near the reduction threshold") {
+ // Roughly half the rows are distinct keys; exercises the boundary of the ratio checks. The
+ // overall compaction ratio (~2.0) is above the threshold, but the *first* periodic check still
+ // sees the leading distinct keys and fires, so the bypass must be observable too.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 1000, 1, parts)
+ .select(($"id" % 500).cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s", count(lit(1)) as "c")
+ }
+ }
+
+ test("results unchanged with multiple grouping keys and string keys") {
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 500, 1, parts)
+ .select(
+ concat(lit("g"), ($"id" % 300).cast("string")) as "k1",
+ ($"id" % 7) as "k2",
+ $"id" as "v")
+ .groupBy($"k1", $"k2")
+ .agg(sum($"v") as "s", count(lit(1)) as "c")
+ }
+ }
+
+ test("results unchanged with nullable grouping keys") {
+ // Nulls are sparse enough (1 in 40) that the keys stay close to unique and the input really
+ // does bypass; a denser null key would lift the compaction ratio above the threshold and the
+ // test would never engage the feature.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 400, 1, parts)
+ .select(
+ when($"id" % 40 === 0, lit(null)).otherwise($"id").cast("string") as "k",
+ $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s", count(lit(1)) as "c")
+ }
+ }
+
+ test("results unchanged with average (multi-slot buffer) aggregate") {
+ // avg has a two-slot partial buffer (sum, count); pass-through buffers must carry all slots.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 300, 1, parts)
+ .select($"id".cast("string") as "k", ($"id" + 1) as "v")
+ .groupBy($"k")
+ .agg(avg($"v") as "a", sum($"v") as "s")
+ }
+ }
+
+ test("results unchanged with a mix of many aggregate functions and buffer types") {
+ // Exercises a wide pass-through buffer spanning several aggregate buffer layouts at once:
+ // sum (decimal), avg (double), count, min/max, first/last, and stddev (declarative buffer).
+ // The imperative-buffer case is covered separately (see the `approx_count_distinct` test).
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 400, 1, parts)
+ .select(
+ $"id" as "k",
+ ($"id" % 97).cast("decimal(10,2)") as "d",
+ ($"id" % 13).cast("double") as "dbl")
+ .groupBy($"k")
+ .agg(
+ sum($"d") as "sd",
+ avg($"dbl") as "ad",
+ count(lit(1)) as "c",
+ min($"dbl") as "mn",
+ max($"dbl") as "mx",
+ first($"dbl") as "f",
+ last($"dbl") as "l",
+ stddev($"dbl") as "sd2")
+ }
+ }
+
+ test("results unchanged with an imperative-buffer aggregate") {
+ // `approx_count_distinct` uses `HyperLogLogPlusPlus`, an `ImperativeAggregate` whose buffer
+ // state is written by `initialize(buffer)` rather than by a projection, so a pass-through
+ // single-row buffer has to be re-initialized with `copyFrom(initialAggregationBuffer)` for
+ // every row. No declarative aggregate exercises that reset. It also reports
+ // `supportCodegen = false`, so the operator only ever runs on `TungstenAggregationIterator`;
+ // keep it in its own test rather than folding it into a codegen cell that would quietly
+ // become interpreted.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 300, 1, parts)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(approx_count_distinct($"v") as "c")
+ }
+ }
+
+ test("results unchanged with filtered aggregate functions") {
+ // A `FILTER (WHERE ...)` aggregate is compiled into a per-row guard around the buffer update
+ // rather than a separate filtering operator: `If(filter, update, buffer)` in the interpreted
+ // path and an `if (!cond) continue` guard in the generated code. Pass-through reuses those
+ // exact update expressions, so a bypassed row whose filter is false contributes nothing to its
+ // single-row buffer. The all-true and all-false filters pin the two extremes, and the fully
+ // distinct grouping keys ensure rows bypass (in the regular-map-only configurations) so the
+ // filter guard actually runs in the pass-through path.
+ withTempView("t") {
+ spark.range(0, 400, 1, 1)
+ .select($"id".cast("string") as "k", ($"id" % 100) as "v")
+ .createOrReplaceTempView("t")
+ checkAdaptiveMatchesReference { parts =>
+ spark.sql(
+ """SELECT k,
+ | sum(v) FILTER (WHERE v % 2 = 0) AS s_even,
+ | count(1) FILTER (WHERE v > 50) AS c_gt50,
+ | avg(v) FILTER (WHERE v > 25) AS a_gt25,
+ | sum(v) FILTER (WHERE true) AS s_all,
+ | sum(v) FILTER (WHERE false) AS s_none
+ |FROM t GROUP BY k""".stripMargin)
+ }
+ }
+ }
+
+ test("results unchanged with decimal and date grouping keys") {
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 300, 1, parts)
+ .select(
+ ($"id" % 280).cast("decimal(12,3)") as "k1",
+ date_add(lit(java.sql.Date.valueOf("2020-01-01")), ($"id" % 250).cast("int")) as "k2",
+ $"id" as "v")
+ .groupBy($"k1", $"k2")
+ .agg(sum($"v") as "s", count(lit(1)) as "c")
+ }
+ }
+
+ test("results unchanged for group-by-only (distinct) with no aggregate functions") {
+ // No aggregate functions: the pass-through buffer is a zero-column UnsafeRow, so the output is
+ // just the grouping key. High-cardinality keys should bypass, and the de-duplicated result must
+ // still match the reference.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 400, 1, parts)
+ .select(($"id" % 350) as "k1", ($"id" % 11) as "k2")
+ .distinct()
+ }
+ }
+
+ test("results unchanged for group-by-only with duplicate keys (Final phase must not bypass)") {
+ // A group-by-only aggregate has an empty `aggregateExpressions`, so checking the aggregate
+ // modes alone is vacuously true and could wrongly admit the `Final` phase of the two-phase
+ // plan. With duplicate keys, a bypassing `Final` would skip its de-duplication and return
+ // duplicate rows. The two-level map off variants route the rows to the regular map so the
+ // periodic check fires and the regression would show up.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 1000, 1, parts)
+ .select(($"id" % 10) as "c")
+ .distinct()
+ }
+ }
+
+ test("results unchanged when a large frozen map is output before pass-through streaming") {
+ // A larger `minRows` lets the map accumulate many keys before the periodic check bypasses,
+ // so the early map output (which also frees the map) spans several drain cycles and re-enters
+ // the map-output function; the results must still match the feature-off reference.
+ val query = () => spark.range(0, 400000, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withSQLConf(
+ (Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS.key -> "200000",
+ SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "false") ++ fixedPlanConfs): _*) {
+ val df = query()
+ df.collect()
+ val skipped = collect(df.queryExecution.executedPlan) {
+ case agg: HashAggregateExec if agg.aggregateExpressions.forall(_.mode == Partial) =>
+ agg.metrics.get("numBypassingRows").map(_.value).getOrElse(0L)
+ }.sum
+ assert(skipped > 0,
+ s"expected the large frozen map to eventually bypass, got $skipped bypassed rows")
+ val reference = withSQLConf(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "false") {
+ query().collect().toSeq
+ }
+ checkAnswer(df, reference)
+ }
+ }
+
+ test("distinct aggregation stays correct") {
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 300, 1, parts)
+ .select($"id".cast("string") as "k", ($"id" % 50) as "v")
+ .groupBy($"k")
+ .agg(countDistinct($"v") as "cd", sum($"v") as "s")
+ }
+ }
+
+ test("distinct aggregation bypasses on high-cardinality input") {
+ // The `PartialMerge` phase of the multi-phase distinct plan always aggregates (it is not
+ // `Partial` mode and requires a distribution), so the rows reaching the distinct `Partial`
+ // phase are de-duplicated and pass-through carries exactly one distinct value each.
+ forEachCodegenAndMap() { clue =>
+ val df = () => spark.range(0, 1000, 1, 1)
+ .select(($"id" % 100).cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(countDistinct($"v") as "cd")
+ withClue(clue) {
+ assert(numBypassingRows(df) > 0,
+ "expected a distinct partial aggregation to bypass for high-cardinality input")
+ }
+ }
+ }
+
+ test("count distinct: the de-duplication partial aggregate bypasses") {
+ // `count(DISTINCT v) GROUP BY k` plans two `Partial` phases: the de-duplication partial groups
+ // on (k, v) and the distinct partial groups on (k). Fully distinct (k, v) pairs make the
+ // de-duplication partial (2 grouping keys) reduce nothing, so it must bypass.
+ forEachCodegenAndMap() { clue =>
+ val df = () => spark.range(0, 400, 1, 1)
+ .select(($"id" % 4).cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(countDistinct($"v") as "cd")
+ withClue(clue) {
+ val byKeyCount = bypassRowsByGroupingKeyCount(df)
+ assert(byKeyCount.get(2).exists(_ > 0),
+ s"expected the (k, v) de-duplication partial to bypass, got $byKeyCount")
+ }
+ }
+ }
+
+ test("count distinct: the distinct partial aggregate bypasses") {
+ // Mirror of the test above for the other phase: with many distinct keys but few distinct
+ // values per key, the (k, v) de-duplication partial reduces well while the distinct partial
+ // (1 grouping key) sees a fresh key per row and must bypass.
+ forEachCodegenAndMap() { clue =>
+ val df = () => spark.range(0, 400, 1, 1)
+ .select($"id".cast("string") as "k", ($"id" % 2) as "v")
+ .groupBy($"k")
+ .agg(countDistinct($"v") as "cd")
+ withClue(clue) {
+ val byKeyCount = bypassRowsByGroupingKeyCount(df)
+ assert(byKeyCount.get(1).exists(_ > 0),
+ s"expected the distinct partial (grouping on k) to bypass, got $byKeyCount")
+ }
+ }
+ }
+
+ test("count distinct: both partial aggregates bypass and results stay correct") {
+ // Fully distinct keys and fully distinct values: neither partial phase reduces anything, so
+ // both bypass in the same execution. The de-duplication partial keeps the (k, v) pairs unique
+ // and the distinct partial counts them, so the result must still match the reference.
+ forEachCodegenAndMap() { clue =>
+ val df = () => spark.range(0, 400, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(countDistinct($"v") as "cd")
+ withClue(clue) {
+ val byKeyCount = bypassRowsByGroupingKeyCount(df)
+ assert(byKeyCount.get(2).exists(_ > 0),
+ s"expected the (k, v) de-duplication partial to bypass, got $byKeyCount")
+ assert(byKeyCount.get(1).exists(_ > 0),
+ s"expected the distinct partial (grouping on k) to bypass, got $byKeyCount")
+ }
+ }
+ }
+
+ test("global aggregation (no grouping keys) is never bypassed and stays correct") {
+ withSQLConf(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true") {
+ checkAnswer(
+ spark.range(0, 100, 1, 1).agg(sum($"id") as "s", count(lit(1)) as "c"),
+ Row(4950L, 100L))
+ }
+ }
+
+ test("results unchanged with an empty input") {
+ // No rows means the check points never fire; the metric must stay zero.
+ checkAdaptiveMatchesReference(
+ expectBypass = false,
+ build = { parts =>
+ spark.range(0, 0, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s", count(lit(1)) as "c")
+ })
+ }
+
+ // The following four tests cover plans where an `ExpandExec` sits below the partial aggregate
+ // (ROLLUP / CUBE / GROUPING SETS / multi-distinct). PR apache/spark#28804 statically disabled its
+ // skip-partial-aggregate optimization whenever an Expand was present, but that was a performance
+ // heuristic guarding its *static* row sampling, not a correctness requirement. Our decision is
+ // made at runtime from the observed compaction ratio, so we deliberately do not port that
+ // exclusion. These tests assert results stay correct with the exclusion absent.
+ //
+ // The ROLLUP and CUBE cases below use two grouping columns, where the grand-total set keeps the
+ // compaction ratio high enough that they decline to bypass -- they cover the eligible-but-
+ // declining side. (Widening the rollup lowers the ratio: with five distinct columns the same
+ // shape does bypass.) The GROUPING SETS and multi-distinct tests, and `pass-through fires for
+ // high-cardinality input below an Expand`, cover an Expand that bypasses.
+
+ test("results unchanged for ROLLUP (Expand below partial aggregate)") {
+ // The grand-total group repeats on every expanded row, so the compaction ratio stays above the
+ // threshold and the partial aggregate declines to bypass in every cell.
+ checkAdaptiveMatchesReference(
+ expectBypass = false,
+ build = { parts =>
+ spark.range(0, 400, 1, parts)
+ .select(($"id" % 200) as "k1", ($"id" % 7) as "k2", $"id" as "v")
+ .rollup($"k1", $"k2")
+ .agg(sum($"v") as "s", count(lit(1)) as "c")
+ })
+ }
+
+ test("results unchanged for CUBE (Expand below partial aggregate)") {
+ // Same as ROLLUP: the grand-total group keeps the ratio above the threshold, so nothing
+ // bypasses.
+ checkAdaptiveMatchesReference(
+ expectBypass = false,
+ build = { parts =>
+ spark.range(0, 400, 1, parts)
+ .select(($"id" % 150) as "k1", ($"id" % 5) as "k2", $"id" as "v")
+ .cube($"k1", $"k2")
+ .agg(sum($"v") as "s", count(lit(1)) as "c")
+ })
+ }
+
+ test("results unchanged for GROUPING SETS (Expand below partial aggregate)") {
+ // No `()` grouping set, and both keys distinct, so every expanded row is a fresh key and the
+ // input genuinely bypasses. A grand-total set would collapse all rows into one group and lift
+ // the compaction ratio above the threshold (see the ROLLUP and CUBE tests below).
+ withTempView("t") {
+ spark.range(0, 400, 1, 1)
+ .select($"id" as "k1", ($"id" + 1000) as "k2", $"id" as "v")
+ .createOrReplaceTempView("t")
+ checkAdaptiveMatchesReference { parts =>
+ spark.sql(
+ """SELECT k1, k2, sum(v) AS s, count(1) AS c
+ |FROM t
+ |GROUP BY k1, k2 GROUPING SETS ((k1, k2), (k1), (k2))""".stripMargin)
+ }
+ }
+ }
+
+ test("results unchanged for multi-distinct (Expand below partial aggregate)") {
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 400, 1, parts)
+ .select(($"id" % 100).cast("string") as "k", ($"id" % 30) as "a", ($"id" % 40) as "b")
+ .groupBy($"k")
+ .agg(countDistinct($"a") as "da", countDistinct($"b") as "db", sum($"a") as "s")
+ }
+ }
+
+ test("results unchanged under a fused Union (child yields from a nested helper)") {
+ // `UnionExec` wraps each child's produce in its own helper, so a streamed row that fills the
+ // output buffer returns only as far as the aggregate's build loop. Reaching the end of the
+ // child's produce therefore does not mean the input is exhausted, and treating it as such
+ // drops the rest of the partition.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 100, 1, parts + 1)
+ .union(spark.range(100, 200, 1, parts + 1))
+ .groupBy("id").count()
+ }
+ }
+
+ test("results unchanged when an Exchange separates the two aggregates") {
+ // Grouping on a derived key stops the `Range`'s output partitioning from satisfying the Final
+ // aggregate's `ClusteredDistribution`, so the plan keeps an `Exchange` and the two aggregates
+ // land in separate whole-stages. That is the shape where streamed rows actually pass through
+ // `BufferedRowIterator.currentRows` -- fused, they go straight into the Final's hash map and
+ // neither `needStopCheck` nor the resumed build is reached.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 200, 1, parts)
+ .select($"id".cast("string") as "k", ($"id" * 2) as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s", count(lit(1)) as "c", max($"v") as "m")
+ }
+ }
+
+ test("order-sensitive aggregates match a non-bypassed run") {
+ // Bypassing must merge a group's buffers in the same order as a run that never bypasses: a
+ // group can straddle the freeze and hold both a map buffer and pass-through buffers, and the
+ // `Final` merges in emit order. The queue holds each passed-through row behind the frozen map
+ // and flushes it only after the map drains, so the map buffer always precedes the colliding
+ // pass-through buffers on both execution paths -- exactly the merge order of a run that never
+ // bypasses, so every enabled cell must match the feature-off reference and
+ // `spark.sql.codegen.wholeStage` must not be observable.
+ //
+ // The flip fires at the first periodic check: with `minRows=8` it lands on the 8th aggregated
+ // row, when the map already holds 8 distinct keys (id 0 maps to -1, ids 1-7 to keys 1-7), so
+ // the compaction ratio 1.0 is below `minCompaction` (1.05) and every remaining row streams;
+ // id 8 is the first bypassed row. At `dupAt=8` the colliding row is that first bypassed row,
+ // queued behind the frozen map and flushed only after the map drains, so its buffer still
+ // reaches the `Final` after the frozen map's and `first`/`last` match the merge order; at
+ // `dupAt=9` the colliding row streams directly after the map and the group stays in input
+ // order. Both plan shapes are exercised separately: splitting the aggregates with an
+ // `Exchange` (or not) changes whether streamed rows pass through
+ // `BufferedRowIterator.currentRows` or feed the `Final`'s `doConsume` directly.
+ for {
+ splits <- Seq(1, 2)
+ derivedKey <- Seq(false, true)
+ dupAt <- Seq(8, 9)
+ wholeStage <- Seq(true, false)
+ twoLevelMap <- Seq(true, false)
+ forceSpill <- Seq(true, false)
+ } {
+ val query = () => {
+ val base = when($"id" === 0 || $"id" === dupAt, lit(-1L)).otherwise($"id")
+ spark.range(0, 40, 1, splits)
+ .select(if (derivedKey) base.cast("string") else base as "k", $"id" as "v")
+ .toDF("k", "v")
+ .groupBy($"k")
+ .agg(first($"v") as "f", last($"v") as "l")
+ }
+ val spillConf = if (forceSpill) {
+ Seq("spark.sql.TungstenAggregate.testFallbackStartsAt" -> forceSpillFallback)
+ } else {
+ Nil
+ }
+ def run(enabled: Boolean): Seq[String] = withSQLConf(
+ (Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> enabled.toString,
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> twoLevelMap.toString,
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS.key -> "8") ++
+ spillConf ++ fixedPlanConfs): _*) {
+ query().collect().toSeq.map(_.toString()).sorted
+ }
+ withClue(s"splits=$splits derivedKey=$derivedKey dupAt=$dupAt " +
+ s"wholeStage=$wholeStage twoLevelMap=$twoLevelMap forceSpill=$forceSpill: ") {
+ assert(run(enabled = true) == run(enabled = false),
+ "adaptive partial aggregation changed an order-sensitive result")
+ }
+ }
+ }
+
+ test("fan-out below a split aggregate preserves the merge order") {
+ // A `GenerateExec` expands a collection without checking `shouldStop()`, so in the
+ // exchange-split shape the whole fan-out batch of the trigger input row is queued at once
+ // rather than one row at a time. Each queued row advances the frozen-map output by one row,
+ // and the queue is flushed only after the map fully drains, so a group whose rows straddle
+ // the freeze point still merges its map buffer before its pass-through buffers, matching a
+ // non-bypassed run.
+ //
+ // The colliding row is the first row of the trigger batch, so it is the first one queued: a
+ // design that emitted queued rows ahead of the frozen map would put it before its map buffer.
+ // Key 2 is inserted early (by id 1) and drained third, so id 4's first exploded element
+ // collides with it; the other two fan-out tests cover collisions on later batch elements.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 20, 1, parts)
+ .select($"id", explode(array(
+ when($"id" === 4, lit(2L)).otherwise($"id" * 2),
+ $"id" * 2 + 1)) as "k")
+ .select($"k", ($"id" * 100 + $"k") as "v")
+ .groupBy($"k").agg(first($"v") as "f", last($"v") as "l")
+ }
+ }
+
+ test("a wide fan-out batch stays queued behind the frozen map") {
+ // A colliding key must not merge before its map buffer. This batch is four rows wide and
+ // collides twice, so the colliding pass-through rows must both wait behind the frozen map for
+ // the whole map to drain; a design that let any part of the batch escape ahead of the map
+ // breaks the merge order for at least one collision.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 20, 1, parts)
+ .select($"id", explode(array(
+ $"id" * 4,
+ when($"id" === 2, lit(3L)).otherwise($"id" * 4 + 1),
+ $"id" * 4 + 2,
+ when($"id" === 2, lit(7L)).otherwise($"id" * 4 + 3))) as "k")
+ .select($"k", ($"id" * 100 + $"k") as "v")
+ .groupBy($"k").agg(first($"v") as "f", last($"v") as "l")
+ }
+ }
+
+ test("a frozen map larger than the fan-out batch preserves the merge order") {
+ // The queue bounds the held rows to the batch width regardless of the map size, and the flush
+ // waits for the whole map to drain. This query grows the map well past the batch width, so a
+ // design that flushed the held rows early would leave the colliding key's map buffer behind
+ // them. Every enabled cell must match the feature-off reference, so each compares directly
+ // against a non-bypassed run, across both the generated and interpreted paths.
+ for {
+ splits <- Seq(1, 2)
+ wholeStage <- Seq(true, false)
+ twoLevelMap <- Seq(true, false)
+ forceSpill <- Seq(true, false)
+ } {
+ val query = () => {
+ spark.range(0, 100, 1, splits)
+ .select($"id", explode(array(
+ $"id" * 2,
+ when($"id" === 16, lit(5L)).otherwise($"id" * 2 + 1))) as "k")
+ .select($"k", ($"id" * 100 + $"k") as "v")
+ .groupBy($"k").agg(first($"v") as "f", last($"v") as "l")
+ }
+ val spillConf = if (forceSpill) {
+ Seq("spark.sql.TungstenAggregate.testFallbackStartsAt" -> forceSpillFallback)
+ } else {
+ Nil
+ }
+ def run(enabled: Boolean): DataFrame = withSQLConf(
+ (Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> enabled.toString,
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> twoLevelMap.toString,
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS.key -> "32") ++
+ spillConf ++ fixedPlanConfs): _*) {
+ query()
+ }
+ val reference = run(enabled = false)
+ val adaptive = run(enabled = true)
+ withClue(s"splits=$splits wholeStage=$wholeStage " +
+ s"twoLevelMap=$twoLevelMap forceSpill=$forceSpill: ") {
+ checkAnswer(adaptive, reference)
+ }
+ }
+ }
+
+ test("results unchanged below a generator that cannot yield mid-fan-out") {
+ // `GenerateExec` expands a collection without checking `shouldStop()`, so it cannot bound the
+ // output buffer between the rows of one input row. Each passed-through row queues a copy and
+ // advances the frozen-map output by one row, so the whole fan-out batch is held behind the map
+ // and the memory is bounded by the batch width rather than by how many rows the child emits.
+ checkAdaptiveMatchesReference { parts =>
+ spark.range(0, 1, 1, parts)
+ .select(explode(sequence(lit(1), lit(500))) as "k")
+ .groupBy($"k").count()
+ }
+ }
+
+ /////////////////////////////////////////////////////////////////////////////
+ // Part 2: Triggering -- the bypass fires when, and only when, it should.
+ /////////////////////////////////////////////////////////////////////////////
+
+ test("pass-through fires for high-cardinality input, not for low-cardinality input") {
+ forEachCodegenAndMap() { clue =>
+ // Fully distinct keys: partial aggregation reduces nothing, so rows must bypass.
+ val highCard = () => spark.range(0, 200, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ assert(numBypassingRows(highCard) > 0,
+ "expected some rows to bypass partial aggregation for high-cardinality input")
+ }
+ // Few distinct keys, high reduction: partial aggregation is effective, nothing bypasses.
+ val lowCard = () => spark.range(0, 600, 1, 1)
+ .select(($"id" % 5).cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ assert(numBypassingRows(lowCard) == 0,
+ "expected no rows to bypass partial aggregation for low-cardinality input")
+ }
+ }
+ }
+
+ test("group-by-only pass-through fires for high-cardinality input") {
+ forEachCodegenAndMap() { clue =>
+ val distinctKeys = () => spark.range(0, 200, 1, 1).select($"id" as "k").distinct()
+ withClue(clue) {
+ assert(numBypassingRows(distinctKeys) > 0,
+ "expected group-by-only rows to bypass partial aggregation for high-cardinality input")
+ }
+ }
+ }
+
+ test("filtered aggregate functions are eligible for pass-through") {
+ // The filter clause does not change eligibility: a partial aggregate over `FILTER (WHERE ...)`
+ // functions still bypasses on high-cardinality input, and the per-row filter guard runs inside
+ // the pass-through single-row buffer update.
+ forEachCodegenAndMap() { clue =>
+ withTempView("t") {
+ spark.range(0, 200, 1, 1)
+ .select($"id".cast("string") as "k", ($"id" % 100) as "v")
+ .createOrReplaceTempView("t")
+ val df = () => spark.sql(
+ """SELECT k, sum(v) FILTER (WHERE v % 2 = 0) AS s
+ |FROM t GROUP BY k""".stripMargin)
+ withClue(clue) {
+ assert(numBypassingRows(df) > 0,
+ "expected filtered-aggregate rows to bypass partial aggregation for high-cardinality " +
+ "input")
+ }
+ }
+ }
+ }
+
+ test("pass-through fires for high-cardinality input below an Expand") {
+ // The static PR#28804 heuristic would have refused to skip whenever an Expand was present; our
+ // runtime decision skips because the expanded rows genuinely do not reduce. GROUPING SETS over
+ // two single-column, fully-distinct sets is used (rather than ROLLUP/CUBE) so there is no
+ // grand-total group lifting the compaction ratio above the threshold: every expanded row is a
+ // fresh key, so all configurations bypass.
+ forEachCodegenAndMap() { clue =>
+ withTempView("t") {
+ spark.range(0, 200, 1, 1)
+ .select($"id".as("k1"), ($"id" + 1000).as("k2"), $"id".as("v"))
+ .createOrReplaceTempView("t")
+ val gs = () => spark.sql(
+ """SELECT k1, k2, sum(v) AS s
+ |FROM t
+ |GROUP BY k1, k2 GROUPING SETS ((k1), (k2))""".stripMargin)
+ withClue(clue) {
+ assert(numBypassingRows(gs) > 0,
+ "expected rows below an Expand to bypass partial aggregation for high-cardinality " +
+ "input")
+ }
+ }
+ }
+ }
+
+ test("no pass-through when the feature is disabled") {
+ // The metric must stay zero across the whole matrix when the switch is off, even for input that
+ // would otherwise bypass.
+ for {
+ wholeStage <- Seq(true, false)
+ twoLevelMap <- Seq(true, false)
+ } {
+ withSQLConf(
+ (Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "false",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> twoLevelMap.toString) ++ fixedPlanConfs): _*) {
+ val df = () => spark.range(0, 200, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(s"wholeStage=$wholeStage twoLevelMap=$twoLevelMap") {
+ assert(numBypassingRows(df) == 0,
+ "no rows should bypass partial aggregation when the feature is disabled")
+ }
+ }
+ }
+ }
+
+ test("no pass-through for a global aggregation with no grouping keys") {
+ // Global aggregation is ineligible (`groupingExpressions` is empty): there is a single group,
+ // so there is nothing to stream through. The partial aggregate must never bypass regardless of
+ // codegen or map settings, even under a forced fallback.
+ forEachCodegenAndMap(regularFallback = 16) { clue =>
+ val df = () => spark.range(0, 200, 1, 1)
+ .agg(sum($"id") as "s", count(lit(1)) as "c")
+ withClue(clue) {
+ assert(numBypassingRows(df) == 0,
+ "a global aggregation is not eligible and must never bypass")
+ }
+ }
+ }
+
+ test("no pass-through for a session_window grouping key") {
+ // A batch `session_window` grouping is not streaming, but its partial aggregate feeds a
+ // `MergingSessionsExec` that merges overlapping sessions, and passing single-row buffers into
+ // it is untested. It is gated out in `adaptivePartialAggEnabled`. This input has fully
+ // distinct sessions (ratio 1.0) and a small `minRows`, so without the gate the periodic check
+ // would bypass and the `expectBypass = false` assertion would fail.
+ checkAdaptiveMatchesReference(
+ expectBypass = false,
+ build = { parts =>
+ spark.range(0, 40, 1, parts)
+ .select($"id" as "v", timestamp_seconds($"id" * 60) as "time")
+ .groupBy(session_window($"time", "10 seconds"))
+ .agg(sum($"v") as "s")
+ })
+ }
+
+ test("rows absorbed by the fast map count toward the compaction ratio") {
+ // The compaction ratio is measured at the operator level, so the rows the fast map absorbs
+ // must count in the numerator just as its keys count in the denominator. This input is
+ // dominated by a hot-key prefix that the fast map serves without ever reaching the regular
+ // map, followed by a short distinct tail that does reach it. Counting only the regular map's
+ // traffic would see the tail alone -- a ratio near 1 -- and bypass an aggregation that is in
+ // fact collapsing rows heavily.
+ forEachCodegenAndMap() { clue =>
+ // With the fast map on it holds 4 keys, so `k < 4` is served there and `k >= 4` falls
+ // through. 400 hot-key rows against 4 hot keys plus 20 tail keys is a ratio of about 17.5,
+ // far above the default, so nothing may bypass.
+ val df = () => spark.range(0, 420, 1, 1)
+ .select(when($"id" < 400, $"id" % 4).otherwise($"id" - 396) as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ assert(numBypassingRows(df) == 0,
+ "an aggregation collapsing ~17 rows per key must not bypass; fast-map hits are " +
+ "missing from the numerator if it does")
+ }
+ }
+ }
+
+ test("a distinct-heavy prefix commits the task even when later rows collapse") {
+ // The flip is one-way, so the decision is made from the rows seen so far, not the partition as
+ // a whole. Here the first `minRows` rows are all distinct, so the periodic check bypasses and
+ // the pass-through stays on permanently: the remaining rows -- which all collapse onto a single
+ // key and would have aggregated well -- stream through as single-row partial buffers. The
+ // overall compaction ratio (40 rows / 8 keys = 5.0) would keep aggregation, but the prefix has
+ // already committed the task. The mirror case (a compacting prefix with a distinct tail) is
+ // covered by the test above; this pins the other side of the same asymmetry.
+ forEachCodegenAndMap() { clue =>
+ val df = () => spark.range(0, 40, 1, 1)
+ .select(when($"id" < 8, $"id").otherwise(lit(0L)) as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ val c = runAndReadCounters(df)
+ assert(c.skipped == 32,
+ s"expected the 32 rows after the flip to bypass, got ${c.skipped}")
+ assert(c.partialOutputRows == 40,
+ s"expected every input row to stream through the partial, got ${c.partialOutputRows}")
+ }
+ }
+ }
+
+ test("the periodic check fires when the ratio shows no reduction, without spilling") {
+ // No forced regular-map spill: only the periodic check can trigger the bypass. Fully
+ // distinct keys give a compaction ratio of 1.0, below `minCompaction`, so rows bypass and
+ // the regular map never spills.
+ forEachCodegenAndMap() { clue =>
+ val df = () => spark.range(0, 200, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ val c = runAndReadCounters(df)
+ assert(c.skipped > 0,
+ "the periodic check should bypass fully distinct input")
+ assert(c.spillBytes == 0, "the periodic check must decide before any spill happens")
+ assert(c.tasksFallBacked == 0,
+ "the periodic check must not fall back to sort-based aggregation")
+ }
+ }
+ }
+
+ test("the spill check fires when the map would spill on high-cardinality input") {
+ // Force the regular map to fall back quickly. High-cardinality input that reaches the fallback
+ // point should bypass via the spill check rather than spilling. Use a `minRows` larger than the
+ // input so the periodic check cannot fire first and the spill check is the one exercised.
+ forEachCodegenAndMap(minRows = 100000, regularFallback = 16) { clue =>
+ val df = () => spark.range(0, 200, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ val c = runAndReadCounters(df)
+ assert(c.skipped > 0,
+ "the spill check should bypass high-cardinality input at the spill boundary")
+ // The whole point of the spill check is to bypass *instead of* falling back to sort-based
+ // aggregation, so the sorter is never created. `numTasksFallBacked` is the reliable
+ // per-operator signal for that (the `spillSize` metric on the interpreted path is derived
+ // from the task-cumulative memory-spill counter and can be inflated by unrelated spilling
+ // such as the downstream shuffle write, so it is not asserted here).
+ assert(c.tasksFallBacked == 0,
+ "the spill check must replace the sort fallback, not trigger it")
+ }
+ }
+ }
+
+ test("a new in-memory map epoch after a spill can still bypass") {
+ // A spill starts a new in-memory map epoch and restarts the row counters, so an input whose
+ // cardinality only turns unfavorable after an early spill is still caught. The first 100 rows
+ // repeat 5 keys and keep the aggregation effective while the forced fallback makes the map
+ // spill; the remaining 300 rows are fully distinct, so the new epoch is judged ineffective and
+ // the rest of the input is passed through. Both the spill and the bypass must be observable.
+ for {
+ wholeStage <- Seq(true, false)
+ twoLevelMap <- Seq(true, false)
+ } {
+ val fastCap = if (twoLevelMap) 4 else 1
+ withSQLConf(
+ (Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> twoLevelMap.toString,
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS.key -> "8",
+ "spark.sql.TungstenAggregate.testFallbackStartsAt" -> s"$fastCap, 40") ++
+ fixedPlanConfs): _*) {
+ val df = () => spark.range(0, 400, 1, 1)
+ .select(when($"id" < 100, $"id" % 5).otherwise($"id") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(s"wholeStage=$wholeStage twoLevelMap=$twoLevelMap") {
+ val c = runAndReadCounters(df)
+ assert(c.tasksFallBacked > 0,
+ "the low-cardinality prefix should still spill and fall back to sort")
+ assert(c.skipped > 0,
+ "the high-cardinality tail after the spill should be passed through")
+ }
+ }
+ }
+ }
+
+ test("without the feature the same input really does fall back to sort") {
+ // Sanity check for the spill check assertion above: with adaptive disabled, the identical
+ // high-cardinality input under the same forced fallback genuinely falls back to sort-based
+ // aggregation. This proves the spill check's `tasksFallBacked == 0` reflects the bypass and
+ // not merely an input that never reached the spill boundary.
+ for {
+ wholeStage <- Seq(true, false)
+ twoLevelMap <- Seq(true, false)
+ } {
+ val fastCap = if (twoLevelMap) 4 else 1
+ withSQLConf(
+ (Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "false",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> twoLevelMap.toString,
+ "spark.sql.TungstenAggregate.testFallbackStartsAt" -> s"$fastCap, 16") ++
+ fixedPlanConfs): _*) {
+ val df = () => spark.range(0, 200, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(s"wholeStage=$wholeStage twoLevelMap=$twoLevelMap") {
+ val c = runAndReadCounters(df)
+ assert(c.skipped == 0, "feature disabled: nothing should bypass")
+ assert(c.tasksFallBacked > 0,
+ "feature disabled: the forced fallback should trigger sort-based aggregation")
+ }
+ }
+ }
+ }
+
+ test("the spill check decides identically at the exact ratio boundary with codegen on and off") {
+ // The check before a spill evaluates the ratio over the rows already aggregated, excluding the
+ // failed insertion that becomes the first pass-through row, so both execution paths must judge
+ // the same row set and reach the same decision. `id % 40` over 400 rows gives 40 keys when the
+ // map fills at 50 aggregated rows, i.e. a compaction ratio of exactly 1.25: demanding 1.25 the
+ // aggregation is kept (`50 < 40 * 1.25` is false), demanding 1.3 it is bypassed.
+ Seq(1.25 -> false, 1.3 -> true).foreach { case (minCompaction, shouldBypass) =>
+ val skippedPerCodegen = Seq(true, false).map { wholeStage =>
+ withSQLConf(
+ (Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "false",
+ // A `minRows` larger than the input keeps the periodic check out of the picture.
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS.key -> "100000",
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_COMPACTION.key -> minCompaction.toString,
+ "spark.sql.TungstenAggregate.testFallbackStartsAt" -> "1, 50") ++
+ fixedPlanConfs): _*) {
+ val df = () => spark.range(0, 400, 1, 1)
+ .select(($"id" % 40).cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(s"minCompaction=$minCompaction wholeStage=$wholeStage") {
+ numBypassingRows(df)
+ }
+ }
+ }
+ withClue(s"minCompaction=$minCompaction skipped=$skippedPerCodegen") {
+ assert(skippedPerCodegen.forall(_ > 0) == shouldBypass,
+ s"expected bypass=$shouldBypass at the ratio boundary")
+ assert(skippedPerCodegen.map(_ > 0).distinct.length == 1,
+ "codegen and interpreted paths must reach the same decision at the boundary")
+ }
+ }
+ }
+
+ test("a very high minCompaction always bypasses once minRows has been processed") {
+ // Demanding an unreachable compaction ratio is the most aggressive setting: even a
+ // low-cardinality input that the default threshold keeps aggregating is bypassed at the first
+ // check point. The results must still match the feature-off reference.
+ forEachCodegenAndMap(minCompaction = 1000000.0) { clue =>
+ val df = () => spark.range(0, 600, 1, 1)
+ .select(($"id" % 5).cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ assert(numBypassingRows(df) > 0,
+ "an unreachable compaction ratio must bypass even a low-cardinality input")
+ }
+ }
+ }
+
+ test("minRows = 0 disables the periodic check but keeps the spill check") {
+ // `minRows = 0` is a sentinel for "never evaluate periodically". Without a forced regular-map
+ // spill there is no check point at all, so fully distinct input -- which the default settings
+ // bypass immediately -- must be aggregated all the way through. This is what proves the
+ // periodic check is genuinely off rather than merely deferred.
+ forEachCodegenAndMap(minRows = 0) { clue =>
+ val df = () => spark.range(0, 200, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ assert(numBypassingRows(df) == 0,
+ "minRows = 0 must disable the periodic check, so nothing may bypass without a spill")
+ }
+ }
+ }
+
+ test("minRows = 0 still bypasses at the spill boundary") {
+ // The other half of the sentinel: with the periodic check off, the spill check alone still
+ // bypasses instead of paying the spill I/O, which is the spill-only operating mode.
+ forEachCodegenAndMap(minRows = 0, regularFallback = 16) { clue =>
+ val df = () => spark.range(0, 200, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ val c = runAndReadCounters(df)
+ assert(c.skipped > 0,
+ "the spill check must still bypass when the periodic check is disabled")
+ assert(c.tasksFallBacked == 0,
+ "the spill check must replace the sort fallback, not trigger it")
+ }
+ }
+ }
+
+ test("minCompaction rejects values that cannot be generated as a Java literal") {
+ // The threshold is interpolated straight into the generated source, where a non-finite double
+ // renders as `InfinityD` -- not a valid Java literal. Reject it at configuration time rather
+ // than failing to compile the stage (or silently deoptimizing when codegen falls back).
+ Seq("Infinity", "-Infinity", "NaN", "1e309").foreach { v =>
+ val e = intercept[IllegalArgumentException] {
+ spark.conf.set(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_COMPACTION.key, v)
+ }
+ assert(e.getMessage.contains("finite"), s"expected a finiteness error for '$v': $e")
+ }
+ spark.conf.unset(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_COMPACTION.key)
+ }
+
+ test("a larger minRows defers the decision so a small high-cardinality input is not bypassed") {
+ // With `minRows` larger than the whole input and no regular-map spill forced, the periodic
+ // check point is never reached, so nothing bypasses even though the keys are fully distinct.
+ forEachCodegenAndMap(minRows = 100000) { clue =>
+ val df = () => spark.range(0, 200, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ assert(numBypassingRows(df) == 0,
+ "no bypass expected before `minRows` rows have been processed")
+ }
+ }
+ }
+
+ test("partial aggregate output row count reflects the bypass (independent of the skip metric)") {
+ // `numOutputRows` on the partial aggregate is the ground truth: it is driven by the normal
+ // aggregation output path, not by our self-reported `numBypassingRows` metric. This test cross
+ // checks the two and pins the observable data-side effect of bypassing.
+ val numRows = 200
+ forEachCodegenAndMap() { clue =>
+ // Fully distinct keys: once the bypass fires the operator stops collapsing rows, so the
+ // partial aggregate emits far more than the handful of keys a real aggregation would. Read
+ // all counters from a single execution so the metrics are not double-counted.
+ val highCard = () => spark.range(0, numRows, 1, 1)
+ .select($"id".cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ val c = runAndReadCounters(highCard)
+ assert(c.skipped > 0, "high-cardinality input should bypass")
+ // Every partial output row is either a real (aggregated) group or a bypassed row, so the
+ // partial output count must be at least the number of bypassed rows, and it climbs toward
+ // the input row count -- well above the heavy reduction a kept aggregation would give.
+ assert(c.partialOutputRows >= c.skipped,
+ s"partial output ${c.partialOutputRows} should be >= bypassed rows ${c.skipped}")
+ assert(c.partialOutputRows > numRows / 2,
+ s"partial output (${c.partialOutputRows}) should climb toward the input row count")
+ }
+
+ // Low-cardinality reference: partial aggregation stays effective, so its output equals the
+ // small number of distinct keys and nothing is bypassed.
+ val lowCard = () => spark.range(0, 600, 1, 1)
+ .select(($"id" % 5).cast("string") as "k", $"id" as "v")
+ .groupBy($"k")
+ .agg(sum($"v") as "s")
+ withClue(clue) {
+ val c = runAndReadCounters(lowCard)
+ assert(c.skipped == 0, "low-cardinality input should not bypass")
+ assert(c.partialOutputRows == 5,
+ "an effective partial aggregate should emit exactly the distinct key count")
+ }
+ }
+ }
+}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/AdaptivePartialAggregationBenchmark.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/AdaptivePartialAggregationBenchmark.scala
new file mode 100644
index 000000000000..0482128b5bf4
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/AdaptivePartialAggregationBenchmark.scala
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.spark.sql.execution.benchmark
+
+import org.apache.spark.benchmark.Benchmark
+import org.apache.spark.sql.DataFrame
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Benchmark comparing runtime adaptive partial aggregation (see
+ * [[SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED]]) against the static pre-shuffle partial
+ * aggregation. When the partial aggregation is not reducing rows, the operator streams the
+ * remaining rows through as single-row partial buffers instead of maintaining (and possibly
+ * spilling) a large aggregation map.
+ *
+ * Each scenario runs the query across the full matrix of whole-stage codegen on/off and the
+ * feature disabled (`adaptive = F`, the pre-change baseline) vs enabled (`adaptive = T`), over a
+ * {high, low}-cardinality x {no-spill, on-spill} grid:
+ * - high-cardinality, no spill: the periodic check bypasses, which should win.
+ * - low-cardinality, no spill: nothing bypasses, and the per-row guard the feature still adds
+ * shows up as a small overhead to quantify.
+ * - high-cardinality, forced regular-map spill: the spill check bypasses instead of spilling,
+ * which should win.
+ * - low-cardinality, forced regular-map spill: the compaction ratio is far above the threshold,
+ * so the spill check keeps aggregating and both runs spill identically (no regression).
+ *
+ * To run this benchmark:
+ * {{{
+ * 1. build/sbt "sql/Test/runMain
+ * org.apache.spark.sql.execution.benchmark.AdaptivePartialAggregationBenchmark"
+ * 2. generate result: SPARK_GENERATE_BENCHMARK_FILES=1 build/sbt "sql/Test/runMain
+ * org.apache.spark.sql.execution.benchmark.AdaptivePartialAggregationBenchmark"
+ * Results will be written to "benchmarks/AdaptivePartialAggregationBenchmark-results.txt".
+ * }}}
+ */
+object AdaptivePartialAggregationBenchmark extends SqlBasedBenchmark {
+
+ override def runBenchmarkSuite(mainArgs: Array[String]): Unit = {
+ // The upstream `CombineAdjacentAggregation` and `ReplaceHashWithSortAgg` rules would collapse
+ // or convert these single-partition hash aggregates, so both are disabled to keep the
+ // Partial+Final `HashAggregateExec` structure the adaptive feature governs.
+ val fixedPlanConfs = Seq(
+ SQLConf.COMBINE_ADJACENT_AGGREGATION_ENABLED.key -> "false",
+ SQLConf.REPLACE_HASH_WITH_SORT_AGG_ENABLED.key -> "false")
+
+ // Adds the (whole-stage codegen, adaptive switch) matrix for `query`. `extraConf` is applied
+ // to all four cases so the only differences are the two axes.
+ def addCodegenAdaptiveCases(
+ benchmark: Benchmark,
+ query: () => DataFrame,
+ extraConf: Seq[(String, String)] = Nil): Unit = {
+ for {
+ wholeStage <- Seq(true, false)
+ adaptive <- Seq(false, true)
+ } {
+ val adaptiveLabel = if (adaptive) "T" else "F"
+ val label = s"codegen = $wholeStage, adaptive = $adaptiveLabel"
+ benchmark.addCase(label) { _ =>
+ withSQLConf(
+ (Seq(
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> adaptive.toString) ++
+ fixedPlanConfs ++ extraConf): _*) {
+ query().noop()
+ }
+ }
+ }
+ }
+
+ // Fully distinct keys make partial aggregation useless, so the periodic check bypasses: the
+ // feature should be faster than the baseline that maintains a map entry per row.
+ runBenchmark("high-cardinality input, pass-through at the periodic check") {
+ val N = 8L << 20
+ val benchmark = new Benchmark("adaptive partial agg, high card, no spill", N,
+ output = output)
+ addCodegenAdaptiveCases(benchmark, () => distinctKeyedDf(N))
+ benchmark.run()
+ }
+
+ // 1000 distinct keys over a large input: partial aggregation reduces a lot, so the periodic
+ // check never activates pass-through. The two runs still differ: the adaptive path pays a
+ // small per-row overhead (the stop check, the bypass counter and the check-point compare)
+ // even when nothing bypasses. The measured difference is a few percent, not a functional
+ // regression.
+ runBenchmark("low-cardinality input, pass-through at the periodic check") {
+ val N = 16L << 20
+ val benchmark = new Benchmark("adaptive partial agg, low card, no spill", N,
+ output = output)
+ addCodegenAdaptiveCases(benchmark, () =>
+ spark.range(N).selectExpr("id % 1000 as k", "id as v").groupBy("k").agg("v" -> "sum"))
+ benchmark.run()
+ }
+
+ // Force the regular map to spill quickly and disable the periodic check (huge minRows). With
+ // fully distinct keys the compaction ratio is 1.0, so at the spill boundary the spill check
+ // bypasses instead of spilling; the baseline spills repeatedly and falls back to sort-based
+ // aggregation.
+ runBenchmark("high-cardinality input, pass-through at the spill check") {
+ val N = 8L << 20
+ val benchmark = new Benchmark("adaptive partial agg, high card, spill", N, output = output)
+ val spillCheckConf = Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS.key -> "0",
+ "spark.sql.TungstenAggregate.testFallbackStartsAt" -> "1, 1048576")
+ addCodegenAdaptiveCases(benchmark, () => distinctKeyedDf(N), extraConf = spillCheckConf)
+ benchmark.run()
+ }
+
+ // Force the regular map to spill quickly on low-cardinality input. With only 1000 distinct
+ // keys the compaction ratio is far above the threshold, so even at the spill boundary the
+ // spill check correctly keeps aggregating: both runs spill and fall back to sort-based
+ // aggregation identically (no regression).
+ runBenchmark("low-cardinality input, pass-through at the spill check") {
+ val N = 16L << 20
+ val benchmark = new Benchmark("adaptive partial agg, low card, spill", N, output = output)
+ val spillCheckConf = Seq(
+ SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_MIN_ROWS.key -> "0",
+ "spark.sql.TungstenAggregate.testFallbackStartsAt" -> "1, 1048576")
+ addCodegenAdaptiveCases(benchmark, () =>
+ spark.range(N).selectExpr("id % 1000 as k", "id as v").groupBy("k").agg("v" -> "sum"),
+ extraConf = spillCheckConf)
+ benchmark.run()
+ }
+ }
+
+ private def distinctKeyedDf(N: Long): DataFrame =
+ spark.range(N).selectExpr("id as k", "id as v").groupBy("k").agg("v" -> "sum")
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org