Skip to content

perf: share aggregate inputs across compatible grouping sets - #7869

Draft
sunchao wants to merge 5 commits into
apache:mainfrom
sunchao:chao/native-grouping-sets-oss
Draft

sunchao wants to merge 5 commits into
apache:mainfrom
sunchao:chao/native-grouping-sets-oss

Conversation

@sunchao

@sunchao sunchao commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Which issue does this PR close?

No separate issue is linked yet. This draft tracks the proposal.

Rationale for this change

Consider a sales report with three grouping sets and SUM(price * quantity). Comet executes Spark's Expand by producing one batch per set for each input batch. Computing the product in the partial aggregate repeats the multiplication three times. All three sets read the same price and quantity.

What changes are included in this PR?

Comet projects eligible arguments once below Expand. Each grouping set reuses the resulting Arrow array. The aggregate still updates all three sets, using Spark's original keys, grouping IDs and batch order.

The batch boundaries matter under memory pressure. An earlier version moved the grouping masks into DataFusion's aggregate. That delayed the reservation check until after all masks, which could change where the aggregate emitted a partial sum. For example, a subtotal containing -1, then the maximum representable value and +1, fits when accumulated in order. Emitting the first batch's -1 separately makes the next partial overflow before the final merge. Keeping Expand preserves the original checks and addresses that regression. Existing sensitivity to partial boundaries in ordinary aggregation is outside this change.

The optimization defaults on. Set spark.comet.exec.aggregate.groupingSets.enabled=false to disable it. It applies to unfiltered partial COUNT, SUM, AVG, MIN and MAX above compatible Expand projections. A computed argument must be repeatable, use numeric or Boolean expressions, and read the same input columns across projections. If any computed argument reads a key that one grouping set masks, Comet keeps the original plan. Grand totals retain their ordinary Expand behavior.

Sharing keeps the computed arrays alive through the last grouping set. Queries that only aggregate plain columns, such as SUM(price), keep the original plan and should see no speedup from this change. The projection's compute time is attributed to the aggregate. There is no change to the SQL, shuffle schema or number of rows processed by the partial aggregate.

How are these changes tested?

I compared dbc5e67b with Apache main at ef771f2b, the common base used in the earlier reproduction. The tests used Spark 4.0.4 on Linux ARM64.

  • Both new tests in CometAggregateSuite passed. They cover stored nulls, grand totals and checked sums with a small task memory budget. Filter by grouping sets share partial aggregate inputs to run both.
  • The native test shares_only_unchanged_arguments_and_keeps_separate_batches passed. It checks the column mapping, rejects a masked input and verifies that both output batches reference the very same computed Arrow array.
  • I reran the exact SQL and memory settings that previously produced six wrong results and five exceptions. All eleven now match. In the two-batch decimal case the old rewrite emitted 8,200 partial rows and lost both subtotals. Main and this revision both emit 8,198 and return the correct subtotals.
  • Across 25 query and configuration combinations, the schema, detail rows and subtotals matched with Comet off, on main, and on the branch with sharing enabled and disabled. The checks include JVM and native shuffle, 384 KiB and 512 KiB task limits, a larger memory control, ANSI on and off, decimal SUM and AVG, and bigint SUM and TRY_SUM. Native plans confirm that computed arguments use a projection below Expand under pressure. A plain column needs no projection.
  • Separate eight-set checks with fixed-width and 64 KiB keys matched on all 32,768 result rows in each case.

Benchmark against Apache main

The table measures this implementation alone. Each case computes SUM(price * quantity) and COUNT(*). The regular and nullable random inputs use three grouping sets. The last case adds a grand total to the nullable input, so four grouping sets share the product. In all three cases the native plans show the projection below Expand.

Both builds used Java 17, release native libraries with jemalloc, Spark 4.0.4 in local[8], a 12 GiB driver heap, 4 GiB of Spark off-heap memory, native shuffle and AQE disabled. For each size, two concurrent jobs ran both builds in separate JVMs and reversed the order. Each time below is the mean of the two job medians from SQL planning through collecting all rows. Speedup divides the main time by the branch time. The last two columns give that ratio within each job.

The small input used 16 partitions for generation and shuffle, one warmup and five timed collections per build, job and case. The large input used 64 partitions, two warmups and seven timed collections. Each also had an untimed plan check. All 144 timed collections and all 36 warmups and all 24 plan checks matched the schema and every result row from the same SQL with Comet disabled. Result digests also matched across builds and jobs. Input generation and result verification were outside the timer.

Case Input rows Main (s) Branch (s) Saved (s) Speedup Main first Branch first
Regular 256,000,000 2.9341 2.6474 +0.2868 1.108× 1.115× 1.102×
Nullable random 256,000,000 3.3280 3.0268 +0.3012 1.100× 1.099× 1.100×
Grand total 256,000,000 4.3351 3.8663 +0.4688 1.121× 1.121× 1.122×
Regular 16,000,000 0.2455 0.2254 +0.0201 1.089× 1.085× 1.094×
Nullable random 16,000,000 0.2371 0.2248 +0.0123 1.055× 1.058× 1.051×
Grand total 16,000,000 0.2806 0.2607 +0.0199 1.076× 1.096× 1.057×

The branch was faster in both orders for every case. At 256 million rows it saved 0.287–0.469 seconds per collection. These are single-host measurements of queries with a repeated decimal product. The savings depend on the cost of the expression and the number of grouping sets that reuse it.

Reproduce the measurements

Use the two Spark 4.0 assembly jars with the matching native libraries packaged for your platform. Set MAIN_JAR and PATCH_JAR to their absolute paths. Save the Python below as bench.py. Start each invocation with a clean Spark configuration. Repeat with the order reversed in a second job. The script sets the relevant SQL options and checks the Spark plan and prints the native plan for inspection.

export JAVA_TOOL_OPTIONS="-XX:ActiveProcessorCount=8"
export RAYON_NUM_THREADS=8
export SPARK_LOCAL_IP=127.0.0.1

run() {
  jar=$1
  arm=$2
  shift 2
  spark-submit --master 'local[8]' --driver-memory 12g --driver-class-path "$jar" \
    --conf spark.plugins=org.apache.spark.CometPlugin \
    --conf spark.shuffle.manager=org.apache.spark.sql.comet.execution.shuffle.CometShuffleManager \
    --conf spark.sql.extensions=org.apache.comet.CometSparkSessionExtensions \
    --conf spark.driver.cores=8 --conf spark.driver.memoryOverhead=6g \
    --conf spark.executor.memoryOverhead=4g --conf spark.ui.enabled=false \
    --conf spark.ui.showConsoleProgress=false --conf spark.driver.host=127.0.0.1 \
    --conf spark.memory.offHeap.enabled=true --conf spark.memory.offHeap.size=4g \
    --conf spark.sql.shuffle.partitions=16 --conf spark.comet.enabled=true \
    --conf spark.comet.exec.enabled=true --conf spark.comet.shuffle.enabled=true \
    --conf spark.comet.shuffle.mode=native --conf spark.comet.nativeLoadRequired=true \
    bench.py --arm "$arm" "$@"
}
run "$MAIN_JAR" main
run "$PATCH_JAR" patch
run "$MAIN_JAR" main --rows 256000000 --partitions 64 --warmups 2 --repeats 7
run "$PATCH_JAR" patch --rows 256000000 --partitions 64 --warmups 2 --repeats 7
"""Run with the same Spark, Comet plugin, shuffle manager and resources in both arms.

spark-submit ... bench.py --arm main
spark-submit ... bench.py --arm patch

The default temporary Parquet directory is local to a single-host Spark runtime.
For a distributed runtime pass a fresh shared URI with --path in each arm.
Only the grouping queries are timed. Native explain logging is enabled once per case.
"""
import argparse
import hashlib
import json
from pathlib import Path
import statistics
import tempfile
import time

from pyspark.sql import SparkSession


def emit(kind, **fields):
    print(json.dumps(dict(event=kind, arm=args.arm, **fields), sort_keys=True), flush=True)


def walk(plan):
    yield plan
    children = plan.children().iterator()
    while children.hasNext():
        yield from walk(children.next())


def metrics(node):
    result = {}
    it = node.metrics().iterator()
    while it.hasNext():
        entry = it.next()
        result[entry._1()] = entry._2().value()
    return result


def collect(sql, native, explain=False):
    spark.conf.set("spark.comet.enabled", str(native).lower())
    spark.conf.set("spark.comet.explain.native.enabled", str(explain).lower())
    start = time.perf_counter()
    df = spark.sql(sql)
    rows = df.collect()
    seconds = time.perf_counter() - start
    # Preserve duplicates, nulls, exact decimal values, column types and nullability.
    result = (df.schema.json(), sorted(json.dumps(list(r), default=str) for r in rows))
    digest = hashlib.sha256(json.dumps(result).encode()).hexdigest()
    plan = df._jdf.queryExecution().executedPlan()
    nodes = list(walk(plan))
    names = [node.getClass().getSimpleName() for node in nodes]
    if not native:
        assert not any(n.startswith("Comet") and "Aggregate" in n for n in names), str(plan)
        return result, dict(seconds=seconds, rows=len(rows), sha256=digest, plan=str(plan))
    partials = [
        node for node, name in zip(nodes, names)
        if name == "CometHashAggregateExec" and "Partial" in str(node.modes())
    ]
    assert len(partials) == 1 and "CometExpandExec" in names, str(plan)
    stats = metrics(partials[0])
    assert stats.get("output_rows", 0) > 0, (str(plan), stats)
    detail = dict(
        seconds=seconds,
        rows=len(rows),
        sha256=digest,
        partial_metrics=stats,
    )
    if explain:
        detail["plan"] = str(plan)
    return result, detail


def query(region, category, masks):
    return f"""SELECT {region} AS region, {category} AS category, grouping_id() AS gid,
        SUM(price * quantity) AS revenue, COUNT(*) AS n
        FROM events
        GROUP BY GROUPING SETS (({region}, {category}), ({region}), ({category}){masks})"""


def run(path):
    settings = {
        "spark.sql.adaptive.enabled": "false",
        "spark.sql.shuffle.partitions": str(args.partitions),
        "spark.sql.ansi.enabled": "true",
        "spark.comet.shuffle.enabled": "true",
        "spark.comet.shuffle.mode": "native",
        "spark.comet.exec.aggregate.skipPartial.enabled": "false",
    }
    for k, v in settings.items():
        spark.conf.set(k, v)
    emit(
        "settings", settings=settings, spark=spark.version, rows=args.rows,
        partitions=args.partitions, repeats=args.repeats, warmups=args.warmups,
        master=spark.sparkContext.master,
    )
    spark.conf.set("spark.comet.enabled", "false")
    # Generate once per arm in Spark. The same file set feeds every query in an arm.
    spark.range(0, args.rows, 1, args.partitions).selectExpr(
        "id % 16 AS region_id",
        "(id DIV 16) % 64 AS category_id",
        "IF(id % 19 = 0, NULL, pmod(xxhash64(id, 101), 16)) AS region_hash",
        "IF(id % 13 = 0, NULL, pmod(xxhash64(id, 233), 64)) AS category_hash",
        "CAST(pmod(xxhash64(id, 51), 20001) - 10000 AS DECIMAL(8, 2)) AS price",
        "CAST(id % 17 AS INT) AS quantity",
    ).write.mode("errorifexists").parquet(path)
    spark.read.parquet(path).createOrReplaceTempView("events")
    for case, sql in [
        ("regular", query("region_id", "category_id", "")),
        ("nullable_random", query("region_hash", "category_hash", "")),
        ("grand_total", query("region_hash", "category_hash", ", ()")),
    ]:
        reference, oracle = collect(sql, native=False)
        emit("spark_oracle", case=case, sql=sql, **oracle)
        times = []
        for i in range(-args.warmups - 1, args.repeats):
            result, data = collect(sql, native=True, explain=(i == -args.warmups - 1))
            assert result == reference, (case, data["sha256"], oracle["sha256"])
            kind = "proof" if i == -args.warmups - 1 else "warmup" if i < 0 else "timing"
            emit(kind, case=case, trial=i, parity=True, **data)
            if i >= 0:
                times.append(data["seconds"])
        emit("summary", case=case, seconds=times, median_seconds=statistics.median(times),
             parity=True, sha256=oracle["sha256"], rows=oracle["rows"])


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--arm", choices=("main", "patch"), required=True)
    parser.add_argument("--path")
    parser.add_argument("--rows", type=int, default=16_000_000)
    parser.add_argument("--partitions", type=int, default=16)
    parser.add_argument("--repeats", type=int, default=5)
    parser.add_argument("--warmups", type=int, default=1)
    args = parser.parse_args()
    spark = SparkSession.builder.appName("Grouping sets").getOrCreate()
    try:
        if args.path:
            run(args.path)
        else:
            with tempfile.TemporaryDirectory(prefix="grouping-") as tmp:
                run((Path(tmp) / "events").as_uri())
    finally:
        spark.stop()

AI assistance

OpenAI Codex assisted with the implementation, tests, benchmarks and write-up.

Use DataFusion grouping masks in eligible partial aggregates and restore the Spark grouping ID before shuffle. Preserve Expand when copies differ in payload, duplicate a mask, include a grand total, or can use partial aggregation bypass.
DataFusion processes every mask before the next memory check. Keep Expand for variable-width keys or accumulator states to avoid overflowing Arrow offsets while collecting multiple copies. Let users turn sharing off independently when high cardinality makes the extra peak memory undesirable.
@github-actions github-actions Bot added enhancement New feature or request performance labels Dec 4, 2026
Project invariant arguments once before Expand. Preserve its grouping IDs, batch order and per-mask reservation checks so memory pressure cannot introduce a new overflow boundary. Cover array reuse and checked sums under pressure.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant