Skip to content

perf: share partial counts and averages across disjoint integer ranges - #7868

Open
sunchao wants to merge 4 commits into
apache:mainfrom
sunchao:chao/disjoint-range-aggregates-oss
Open

sunchao wants to merge 4 commits into
apache:mainfrom
sunchao:chao/disjoint-range-aggregates-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 PR tracks the proposal.

Rationale for this change

A latency histogram can count requests and average payload sizes in each of eight disjoint bands. Evaluating three filtered aggregates per band means applying 24 filters to every batch. Once we know a row belongs to exactly one band, we can classify the row once and update just three grouped accumulators.

What changes are included in this PR?

Add an opt-in physical rewrite under spark.comet.exec.aggregate.disjointRanges.enabled (default false). It requires an otherwise supported Comet partial aggregate, matching projected guards on one integer key, an input filter equal to the union of those ranges, and the same COUNT or supported AVG expressions in each range. Comet checks that the filter lists the same bands as the projected guards. After proving that condition, Comet replaces adjacent bands with one interval at the scan. If there are gaps it retains the original filter.

The grouped partial emits compact per-range states. A projection restores the original buffer order and fills other ranges with zero. A local merge emits the expected partial row even on an empty partition. The shuffle and final aggregate are unchanged. The extra local work can outweigh savings on small inputs.

COUNT alone keeps DataFusion's grouped partial. With AVG, Comet indexes a fixed array of numeric states by range ID and emits each occupied range once at partition end. DataFusion can emit and clear an ordinary grouped partial when memory is tight. Merging those separately rounded sums can change AVG after cancellation. Keeping one running sum per range prevents that split. The operator reserves the retained numeric state in the task memory pool. The native peak_mem_used metric records the highest reservation for that state per task. Temporary Arrow buffers can use additional memory. Comet records the output rows, batches and Arrow bytes on both return paths, including the single empty batch when no range is populated.

AVG is limited to byte, short, integer and unscaled decimals of precision at most nine. Up to 2²² input rows, each batch subtotal is exact for those values. For larger batches the operator filters each range and uses the same Arrow sum as scalar Comet AVG. Ordinary AVG is unchanged. The compatibility target is Comet's filtered AVG with the same input batches. Spark's row-by-row floating-point accumulation can itself differ on some inputs.

How are these changes tested?

Two focused Scala tests and three native operator tests passed on e052394c. The validation used the updated native library with the unchanged JVM classes from 8f531f960. The Scala tests compare with Spark, check plan selection, exercise AQE and cache scans, and cover empty inputs, nulls, predicate boundaries, multi-column COUNT and cancellation. The native tests check memory pressure, an oversized batch whose low bits depend on Arrow's summation order, and the metrics for both empty and nonempty output.

I also compared the schema and values with Spark and Apache main for regular ranges, nullable random inputs and an overlap control. All matched. In the eight-range example a task returned eight rows in one 288-byte batch and reserved 328 bytes for its states. Spark SQL displayed 656 bytes across two tasks because it summed their peaks. The native plan reports the batch and byte counts.

With a 40 KiB pool the pressure test forces DataFusion to emit two rounded states for one range. Their sums combine to 1. The new operator returns 0 in one state and releases the reservation. Before the metrics change, a separate SQL check over DECIMAL(9,0) also returned 0.0000 with matching counts and schema on Spark, main and the branch. The plan confirmed that the enabled run used the rewrite.

Benchmark against Apache main

The timings below are from 8f531f960, before the output and reservation metrics change. I repeated the correctness and metrics checks on the newer revision. 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 and native shuffle. AQE was 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 1.1768 0.5291 +0.6477 2.224× 2.230× 2.218×
Nullable random 256,000,000 2.0717 0.7663 +1.3054 2.703× 2.729× 2.678×
Overlap control 256,000,000 0.5384 0.5558 -0.0175 0.969× 0.955× 0.983×
Regular 32,000,000 0.2513 0.1668 +0.0845 1.507× 1.487× 1.526×
Nullable random 32,000,000 0.3385 0.1771 +0.1614 1.912× 1.942× 1.883×
Overlap control 32,000,000 0.1220 0.1184 +0.0036 1.031× 1.059× 1.003×

Both eligible eight-band queries used the range partial and a local PartialMerge. Apache main evaluated 24 filtered aggregate expressions. A separate native plan check confirmed that both eligible inputs executed CometRangeAggregateExec with eight ranges. The overlap control kept the filtered scalar partial.

The overlapping-range control was 17.5 ms slower at 256 million rows in the comparison with main. The ranges share an endpoint, so the rewrite declined the plan in every trial. The 32-million-row control went the other way.

I checked the large control again with the same branch jar, input and JVM on each side of the flag comparison. Each of two jobs ran four warmup pairs followed by 30 measured pairs. I alternated which setting went first and reversed the starting order in the second job. All results matched Spark. The physical plans matched after normalizing IDs and temporary paths. Averaging the two job medians gave 0.5777 s disabled and 0.5659 s enabled (2.05% faster enabled). Across 60 pairs, the median enabled time minus disabled time was -1.6 ms. The enabled run took longer in 26 pairs.

To repeat the additional comparison, use the branch jar and the large input settings below. Keep just the overlap control. Within one Spark application, set spark.comet.exec.aggregate.disjointRanges.enabled before each call to collect, alternating the order of true and false in successive pairs. Use a fresh DataFrame each time. The control must have no grouped partial in either setting.

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 spark-submit and identical Spark/Comet settings for --arm main and --arm patch.

Use a separate fresh shared --path per arm for distributed Spark. The default
temporary directory works with a single-host Spark runtime. Each arm generates
the same deterministic Parquet data once. Only SQL planning and collection are
timed. Every result is checked against a Spark run with Comet disabled.
"""
import argparse
import hashlib
import json
from pathlib import Path
import statistics
import tempfile
import time

from pyspark.sql import SparkSession


FEATURE = "spark.comet.exec.aggregate.disjointRanges.enabled"


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


def walk(plan):
    yield plan
    name = plan.getClass().getSimpleName()
    if name == "AdaptiveSparkPlanExec":
        yield from walk(plan.executedPlan())
    elif name.endswith("QueryStageExec"):
        yield from walk(plan.plan())
    else:
        children = plan.children().iterator()
        while children.hasNext():
            yield from walk(children.next())


def metrics(node):
    result = {}
    entries = node.metrics().iterator()
    while entries.hasNext():
        pair = entries.next()
        if pair._1() in ("output_rows", "elapsed_compute", "spill_count", "spilled_bytes"):
            result[pair._1()] = pair._2().value()
    return result


def range_query(key, value, bands, factored=False):
    tests = [f"({key} BETWEEN {lo} AND {hi})" for lo, hi in bands]
    guards = [f"({test} <=> true)" for test in tests]
    source = [value] + [f"{g} AS b{i}" for i, g in enumerate(guards)]
    domain = " OR ".join(guards)
    if factored:
        domain = f"{key} IS NOT NULL AND (" + " OR ".join(tests) + ")"
    outputs = [
        f"{fn} FILTER (WHERE b{i}) AS {label}{i}"
        for i in range(len(bands))
        for label, fn in (("n", "count(*)"), ("valid", f"count({value})"), ("mean", f"avg({value})"))
    ]
    return f"SELECT {', '.join(outputs)} FROM (SELECT {', '.join(source)} FROM events WHERE {domain})"


def collect(sql, native, expected_active, detail):
    spark.conf.set("spark.comet.enabled", str(native).lower())
    start = time.perf_counter()
    df = spark.sql(sql)
    rows = df.collect()
    seconds = time.perf_counter() - start
    assert len(rows) == 1
    result = (df.schema.json(), tuple(rows[0]))
    digest = hashlib.sha256(json.dumps(result).encode()).hexdigest()
    plan = df._jdf.queryExecution().executedPlan()
    aggregates = [n for n in walk(plan) if n.getClass().getSimpleName() == "CometHashAggregateExec"]
    modes = [str(n.modes()) for n in aggregates]
    grouped = [n for n in aggregates if n.groupingExpressions().size() > 0]
    merges = [m for m in modes if "PartialMerge" in m]
    active = len(grouped) == len(merges) == 1
    assert bool(aggregates) == native, str(plan)
    assert len(grouped) == len(merges) == int(expected_active), str(plan)
    if native:
        assert any("Partial" in m and "Merge" not in m for m in modes), str(plan)
    info = dict(seconds=seconds, sha256=digest, active=active, modes=modes)
    if detail:
        info.update(plan=str(plan), output=list(rows[0]), schema=df.schema.json(),
                    aggregate_metrics=[metrics(n) for n in aggregates])
    return result, info


def run(path):
    settings = {
        "spark.sql.adaptive.enabled": str(args.aqe).lower(),
        "spark.sql.ansi.enabled": "true",
        "spark.sql.shuffle.partitions": str(args.partitions),
        "spark.comet.shuffle.enabled": "true",
        "spark.comet.shuffle.mode": "native",
        "spark.comet.exec.aggregate.skipPartial.enabled": "false",
        FEATURE: str(args.arm == "patch").lower(),
    }
    for key, value in settings.items():
        spark.conf.set(key, value)
    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")
    spark.range(0, args.rows, 1, args.partitions).selectExpr(
        "CAST((id DIV 4096) % 80 AS INT) AS ordered_k",
        "CAST(id % 1009 AS INT) AS full_v",
        "IF(id % 47 = 0, NULL, CAST(pmod(xxhash64(id), 96) AS INT)) AS random_k",
        "IF(id % 13 = 0, NULL, CAST(pmod(xxhash64(id, 1), 2001) - 1000 AS INT)) AS nullable_v",
    ).write.mode("errorifexists").parquet(path)
    spark.read.parquet(path).createOrReplaceTempView("events")
    bands = [(lo, lo + 9) for lo in range(0, 80, 10)]
    cases = [
        ("regular", range_query("ordered_k", "full_v", bands), True),
        ("nullable_random", range_query("random_k", "nullable_v", bands, factored=True), True),
        ("overlap_control", range_query("random_k", "nullable_v", [(0, 10), (10, 19)]), False),
    ]
    for case, sql, eligible in cases:
        reference, oracle = collect(sql, native=False, expected_active=False, detail=True)
        emit("spark_oracle", case=case, sql=sql, **oracle)
        expected = eligible and args.arm == "patch"
        times = []
        for trial in range(-args.warmups - 1, args.repeats):
            proof = trial == -args.warmups - 1
            result, info = collect(sql, native=True, expected_active=expected, detail=proof)
            assert result == reference, (case, result, reference)
            event = "proof" if proof else "warmup" if trial < 0 else "timing"
            emit(event, case=case, trial=trial, parity=True, **info)
            if trial >= 0:
                times.append(info["seconds"])
        emit("summary", case=case, seconds=times, median_seconds=statistics.median(times),
             parity=True, active=expected, sha256=oracle["sha256"], rows=1)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--arm", required=True, choices=("main", "patch"))
    parser.add_argument("--path")
    parser.add_argument("--rows", type=int, default=32_000_000)
    parser.add_argument("--partitions", type=int, default=16)
    parser.add_argument("--repeats", "--runs", type=int, default=5)
    parser.add_argument("--warmups", type=int, default=1)
    parser.add_argument("--aqe", action="store_true")
    args = parser.parse_args()
    spark = SparkSession.builder.appName("Disjoint range aggregation").getOrCreate()
    try:
        if args.path:
            run(args.path)
        else:
            with tempfile.TemporaryDirectory(prefix="ranges-") 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.

"""Decimal cancellation across aligned input batches. Run in a fresh JVM per build."""
import argparse, json, tempfile, hashlib
from decimal import Decimal
from pathlib import Path
from pyspark.sql import SparkSession
p=argparse.ArgumentParser()
p.add_argument('--arm')
args=p.parse_args()
s=SparkSession.builder.appName('Decimal range cancellation').getOrCreate()
flag='spark.comet.exec.aggregate.disjointRanges.enabled'
for k,v in [('spark.sql.adaptive.enabled','false'),('spark.sql.ansi.enabled','true'),
            ('spark.sql.files.maxPartitionBytes','1g'),('spark.comet.batchSize','256'),
            ('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:
    with tempfile.TemporaryDirectory() as d:
        path=(Path(d)/'batches').as_uri()
        s.conf.set('spark.comet.enabled','false')
        n=1<<24
        start=n+256
        end=start+4096*256
        s.range(0,end+n,1,1).selectExpr(
            f'CASE WHEN id >= {n} AND id < {start} THEN 5 ELSE 1 END AS k',
            f'CAST(CASE WHEN id < {n} THEN 536870912 WHEN id >= {end} THEN -536870912 WHEN id >= {start} AND id % 256 = 0 THEN 1 ELSE 0 END AS DECIMAL(9,0)) AS v'
        ).write.option('parquet.block.size',536870912).parquet(path)
        s.read.parquet(path).createOrReplaceTempView('bands')
        sql="""SELECT avg(v) FILTER (WHERE a),count(v) FILTER (WHERE a),
                      avg(v) FILTER (WHERE b),count(v) FILTER (WHERE b)
               FROM (SELECT v, ((k BETWEEN 0 AND 2) <=> true) AS a,
                               ((k BETWEEN 3 AND 6) <=> true) AS b
                     FROM bands WHERE ((k BETWEEN 0 AND 2) <=> true)
                                   OR ((k BETWEEN 3 AND 6) <=> true))"""
        oracle=None
        for mode in (['spark','disabled','enabled'] if args.arm=='patch' else ['spark','disabled']):
            s.conf.set('spark.comet.enabled',str(mode!='spark').lower())
            s.conf.set(flag,str(mode=='enabled').lower())
            df=s.sql(sql)
            rows=df.collect()
            plan=df._jdf.queryExecution().executedPlan()
            aggs=[n for n in walk(plan) if n.getClass().getSimpleName()=='CometHashAggregateExec']
            grouped=[n for n in aggs if n.groupingExpressions().size()>0]
            merge=[n for n in aggs if 'PartialMerge' in str(n.modes())]
            result=(df.schema.json(),[tuple(r) for r in rows])
            emit(event='result',mode=mode,rows=rows,schema=df.schema.json(),plan=str(plan))
            assert bool(aggs)==(mode!='spark')
            assert len(grouped)==len(merge)==int(mode=='enabled')
            assert result[1]==[(Decimal('0.0000'),2*n+4096*256,Decimal('0.0000'),256)],result
            if oracle is None:oracle=result
            assert oracle==result
            emit(event='checked',mode=mode,parity=True,sha256=hashlib.sha256(json.dumps(result,default=str).encode()).hexdigest())
finally:
    s.stop()

AI assistance

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

When projected filters cover exactly the rows consumed by a scalar aggregate, classify each row once and aggregate by range. Restore the scalar buffers in the same partition. Preserve per-batch rounding for integral averages and the guard columns needed by adaptive cache scans. Keep the rewrite opt-in while evaluating its cost on small inputs.
Use the proven range IDs directly. A grouped hash table can emit early under memory pressure and change how partial sums round. Keep the same batch subtotals as scalar AVG, including oversized cached batches, without changing ordinary grouped aggregates.

Cover early emission, oversized input and nullable multi-argument counts. Document the eligible query shape and move the new setting and tests next to the related aggregation options.
@github-actions github-actions Bot added enhancement New feature or request performance area:aggregation Hash aggregates, aggregate expressions labels Dec 4, 2026
@sunchao
sunchao marked this pull request as ready for review December 5, 2026 00:19
…gates

Record each returned Arrow batch, including the empty batch. Publish the peak reservation for the fixed range states with the same metric as grouped aggregation. Check both paths in the native operator tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:aggregation Hash aggregates, aggregate expressions enhancement New feature or request performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant