Skip to content

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

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

sunchao wants to merge 4 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

A report that groups sales by region and category, by region alone and by category alone has three grouping sets. Spark uses Expand to copy every row three times. A partial sum(price * quantity) then multiplies the same inputs three times. DataFusion grouping sets evaluate aggregate arguments once per batch and reuse them across the three groups.

What changes are included in this PR?

For unfiltered COUNT, SUM, MIN, MAX or AVG, recognize a leading detail projection and copies that differ only by typed nulls in grouping keys and the corresponding ID bits. Keep the detail projection and pass the masks to DataFusion's partial aggregate. Restore Spark's nullable long ID before shuffle. The ID distinguishes stored nulls from subtotal nulls. Every row still updates every requested grouping set.

The rewrite defaults on. Set spark.comet.exec.aggregate.groupingSets.enabled=false to disable it independently. Both the grouping keys and the retained aggregate state fields must be fixed width. For example, COUNT over strings retains a counter, while MIN over strings retains a string. Only the former is eligible. Keep the original plan for grand totals, duplicate masks, arguments that depend on masked columns and plans eligible for partial aggregation bypass.

DataFusion checks its reservation after updating all masks for the batch. A variable-width key repeated across masks could exceed the Arrow offset limit before that check. Even with fixed-width state and the eight-mask cap, high-cardinality inputs can increase peak memory between checks.

Expose DataFusion's existing reduction factor denominator on grouped partial aggregates so the SQL UI shows how many rows the aggregate processed. The Spark plan still displays the original Expand.

How are these changes tested?

The focused Scala regression and all three native matcher tests passed. They cover mask validation, stored nulls, the independent switch, variable-width keys and state, and COUNT over strings.

I also ran eight masks over two partitions, each with 4,096 distinct 64 KiB keys. Retaining every key in every mask requires 2 GiB of string data for one partition. With 1,200 MiB of Spark off-heap memory, the previous revision failed with offset overflow, buffer size > 2147483647. Apache main and this revision returned the same 32,768 groups as Spark. The new revision processed 65,536 partial input rows using Expand. With fixed-width keys the counter fell to 8,192 and disabling the switch restored 65,536. The standalone check below compares the schema, each key identifier and length, grouping ID, grouping columns and count.

Benchmark against Apache main

I measured the branch at cc25f2ab0 independently. The baseline was Apache Comet main at ef771f2b. Both builds used stock Spark 4.0.4, Java 17.0.21.1, release native builds with jemalloc, native shuffle and AQE disabled. Each Spark application used local[8] on Linux ARM64 with a 12 GiB driver heap and 4 GiB of Spark off-heap memory.

For each input size, two jobs ran concurrently. Each ran both builds in separate JVMs, with the order reversed in the second job. Times include SQL planning through collecting all rows. Each time is the mean of the two job medians. Speedup divides the main time by the branch time. The last two columns show the ratios within each job. A negative saving means the branch took longer. These are single-host operator workloads. Shared host load and JVM variation can affect small differences.

For every measured execution the benchmark compared the schema and all result rows, including duplicates and nulls, with the same SQL on Spark with Comet disabled. All comparisons passed. Result digests also matched across builds and jobs. Verification, input preparation, Spark reference queries and warmups were outside the timer.

The smaller input used 16 data generation partitions and 16 shuffle partitions, one warmup and five measured collections per build, case and job. The larger input used 64 partitions for generation and shuffle, two warmups and seven measured collections. Spark chose the scan task count separately. Both sizes also had an untimed plan check. Spark generated the same deterministic Parquet values separately for each application.

Case Input rows Main (s) Branch (s) Saved (s) Speedup Main first Branch first
Regular 256,000,000 3.0267 2.6316 +0.3951 1.150× 1.160× 1.141×
Nullable random 256,000,000 3.3993 3.0099 +0.3894 1.129× 1.129× 1.130×
Grand total control 256,000,000 4.4894 4.4597 +0.0297 1.007× 0.987× 1.026×
Regular 16,000,000 0.2404 0.2208 +0.0196 1.089× 1.101× 1.078×
Nullable random 16,000,000 0.2517 0.2201 +0.0316 1.143× 1.117× 1.168×
Grand total control 16,000,000 0.2914 0.2896 +0.0019 1.006× 1.007× 1.006×

At 256 million input rows the two eligible queries have three masks. Ordinary expansion feeds 768 million rows to the partial aggregate. The branch counter recorded 256 million. It evaluates the decimal product once per input batch and still updates all three grouping sets. The grand total control kept all four projections and fed 1.024 billion rows to the partial aggregate. Both measured key distributions have few groups. The wide-key regression above exercises the fallback separately.

The only subsequent change to the measured commit adjusts the Scala test to inspect both sort and hash aggregates for MIN over strings.

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 asserts the executed paths.

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)
    if args.arm == "patch":
        assert "reduction_factor_total" in stats, stats
    detail = dict(
        seconds=seconds,
        rows=len(rows),
        sha256=digest,
        partial_metrics=stats,
        partial_input_rows=stats.get("reduction_factor_total"),
    )
    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, copies in [
        ("regular", query("region_id", "category_id", ""), 1),
        ("nullable_random", query("region_hash", "category_hash", ""), 1),
        ("grand_total_control", query("region_hash", "category_hash", ", ()"), 4),
    ]:
        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"])
            if args.arm == "patch":
                assert data["partial_input_rows"] == args.rows * copies, (case, data)
            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()
Reproduce the separate correctness check

Use the same spark-submit options as above with local[2] and replace bench.py with stress.py. Pass only --arm main or --arm patch to the script, matching the jar. Set spark.memory.offHeap.size=1200m.

"""Run with the same stock Spark settings as bench.py, local[2], 1200m off-heap."""
import argparse, json, hashlib
from pyspark.sql import SparkSession

p=argparse.ArgumentParser()
p.add_argument('--arm')
args=p.parse_args()
s=SparkSession.builder.appName("Grouping key offset boundary").getOrCreate()
flag='spark.comet.exec.aggregate.groupingSets.enabled'
for k,v in [('spark.sql.adaptive.enabled','false'),('spark.sql.shuffle.partitions','128'),
            ('spark.comet.batchSize','4096'),('spark.comet.exec.range.enabled','true'),
            ('spark.comet.exec.aggregate.skipPartial.enabled','false')]:
    s.conf.set(k,v)
def walk(n):
    yield n
    it=n.children().iterator()
    while it.hasNext():
        yield from walk(it.next())
def emit(**kw):
    print(json.dumps(kw,default=str),flush=True)

try:
    emit(event='settings',offheap=s.sparkContext.getConf().get('spark.memory.offHeap.size'),master=s.sparkContext.master)
    for wide in [False,True]:
        # Two identical partitions. The first eight bytes identify each key uniquely.
        key="rpad(lpad(cast(i as string), 8, '0'), 65536, 'x')" if wide else "i"
        projected="CAST(substring(k,1,8) AS BIGINT),length(k)" if wide else "k,8"
        sql=f"""SELECT {projected},a,b,c,grouping_id(),count(*) FROM
        (SELECT {key} AS k,i%2 AS a,i%3 AS b,i%5 AS c
         FROM (SELECT id%4096 AS i FROM range(0,8192,1,2)))
        GROUP BY GROUPING SETS ((k,a,b,c),(k,a,b),(k,a,c),(k,a),(k,b,c),(k,b),(k,c),(k))"""
        oracle=None
        for mode in (['spark','default'] if wide else ['spark','default','off']):
            s.conf.unset(flag)
            if mode=='off':s.conf.set(flag,'false')
            s.conf.set('spark.comet.enabled',str(mode!='spark').lower())
            df=s.sql(sql)
            plan=df._jdf.queryExecution().executedPlan()
            emit(event='plan',wide=wide,mode=mode,plan=str(plan))
            rows=sorted(json.dumps(list(x)) for x in df.collect())
            assert len(rows)==32768
            for r in rows:
                k,n,a,b,c,gid,count=json.loads(r)
                assert 0<=k<4096 and n==(65536 if wide else 8) and count==2 and 0<=gid<8
                assert [a,b,c]==[None if gid&mask else k%mod for mask,mod in [(4,2),(2,3),(1,5)]]
            assert len(set(rows))==len(rows)
            result=(df.schema.json(),rows)
            if oracle is None:oracle=result
            assert oracle==result
            partials=[n for n in walk(plan) if n.getClass().getSimpleName()=='CometHashAggregateExec' and 'Partial' in str(n.modes())]
            inputs=None
            stats={}
            if mode!='spark':
                assert len(partials)==1,str(plan)
                it=partials[0].metrics().iterator()
                while it.hasNext():
                    e=it.next()
                    stats[e._1()]=e._2().value()
                inputs=stats.get('reduction_factor_total')
                if args.arm=='patch':assert inputs==(65536 if wide or mode=='off' else 8192),stats
            else:assert not partials
            emit(event='checked',wide=wide,mode=mode,rows=len(rows),sha256=hashlib.sha256(json.dumps(result).encode()).hexdigest(),inputs=inputs,metrics=stats,parity=True)
finally:
    s.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
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