Skip to content

perf: coalesce large fixed-width broadcasts in parallel on the driver - #7870

Open
sunchao wants to merge 3 commits into
apache:mainfrom
sunchao:chao/parallel-broadcast-assembly-oss
Open

sunchao wants to merge 3 commits into
apache:mainfrom
sunchao:chao/parallel-broadcast-assembly-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

The driver combines small compressed Arrow IPC streams before broadcasting a hash join build. Combining them saves each consuming task from opening a reader per input batch, but a fragmented build can leave the driver decoding, appending and encoding on a single thread while the probe waits. Producer batching can reduce the number of inputs for certain shuffle reads. File scans and other producers can still deliver thousands of streams.

What changes are included in this PR?

Add an opt-in setting, spark.comet.exec.broadcastExchange.parallelCoalesce.enabled. One exchange per driver can combine four contiguous groups of small streams concurrently. Workers use the existing Arrow coalescer, preallocate fixed-width destination vectors and emit their streams in input order. The broadcast format is unchanged.

The first version targets hash broadcasts with at least 16 streams and an estimated 64 MiB of INT, BIGINT, FLOAT, DOUBLE or BOOLEAN data. It checks estimated driver headroom, limits Arrow allocations separately in each worker and avoids splits with expensive per-stream rounding. A worker allocator refusal, a schema mismatch or an over-limit combined wire size leaves the original inputs available for ordinary coalescing. Other failures propagate after all workers exit.

The setting defaults to false. The driver checks cancellation during parallel work, between input streams on serial retry, and before publishing the broadcast. It joins workers before releasing the driver slot. The exchange metric numParallelCoalesceGroups reports four for a selected parallel result and zero for ordinary coalescing.

Driver heap checks are estimates. Each worker allocator limit covers Arrow buffers only. Even with shared executor decoding, DataFusion can copy multiple batches into one build batch per concurrent hash join task. For the 96 MiB value payload below, eight concurrent tasks could allocate about 768 MiB of extra value buffers on one executor. This estimate excludes validity bits and hash tables. The benchmark did not measure peak memory or network traffic across executors.

How are these changes tested?

All four focused UtilsSuite tests passed. They cover nulls, order, schema mismatch, allocator refusal and a vector capacity failure in a separate JVM with a 64 KiB limit. The new test goes through production admission, cancels while workers own buffers, verifies allocator usage returns to baseline and reacquires the slot for a four-group exchange. It forces serial retry at the wire limit, verifies cancellation during that retry and checks that a normal retry still succeeds.

Benchmark against Apache main

I measured the branch at 05ac57e6f 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.

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.

Each job ran one warmup and five timed collections per build and case. Input rows count the build side. The probe returned all 4,096 matching rows.

Case Input rows Main (s) Branch (s) Saved (s) Speedup Main first Branch first
Ordered 6,291,456 0.8085 0.5712 +0.2373 1.415× 1.397× 1.435×
Nullable 6,291,456 0.7943 0.5363 +0.2580 1.481× 1.489× 1.473×
Small control 65,536 0.0833 0.0838 -0.0005 0.994× 0.989× 1.000×

Both large joins used four ordered groups on the branch. The exchange received 3,072 batches of 2,048 rows. Mean median exchange buildTime fell from 401.5 to 97.5 ms for ordered input and from 389.0 to 87.5 ms for nullable input. That time is already included in the table. The small control stayed serial and took 0.5 ms longer on average.

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 with spark-submit against Apache Comet main and the patched jar.

Use the Comet session extension and at least four driver cores. Each arm runs a
separate stock Spark reference for every case, then times complete Comet joins.
Pass a separate writable --parquet URI per arm to replace the generated build
with a file scan. File creation and verification stay outside the timings.
"""

import argparse
import hashlib
import json
import statistics
import time

from pyspark.sql import SparkSession


def emit(kind, **fields):
    print(json.dumps(dict(benchmark="broadcast", kind=kind, **fields)), flush=True)


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


def metrics(exchange):
    values = {}
    it = exchange.metrics().iterator()
    while it.hasNext():
        pair = it.next()
        values[pair._1()] = pair._2().value()
    return values


def run(name, n, payload):
    build = f"SELECT id AS k, {payload} AS v FROM range(0, {n}, 1, 128)"
    spark.conf.set("spark.comet.enabled", "false")
    if args.parquet:
        path = f"{args.parquet.rstrip('/')}/{name}"
        spark.sql(build).write.mode("errorifexists").parquet(path)
        spark.read.parquet(path).createOrReplaceTempView("build_table")
        build = "SELECT * FROM build_table"

    # Return every probe row to compare values and nulls exactly, including both
    # endpoints of the build. Keep the same probe parallelism in every arm.
    sql = f"""
        SELECT /*+ BROADCAST(d) */ p.id, d.k, d.v
        FROM range(0, 4096, 1, 8) p JOIN ({build}) d
        ON ((p.id * {n - 1}L) DIV 4095L) = d.k
    """
    df = spark.sql(sql)
    expected = sorted(tuple(row) for row in df.collect())
    assert len(expected) == 4096, len(expected)
    assert "CometBroadcastExchange" not in df._jdf.queryExecution().executedPlan().toString()
    schema = df.schema.json()
    digest = hashlib.sha256(json.dumps(expected).encode()).hexdigest()
    emit("reference", arm=args.arm, case=name, sql=sql, rows=len(expected),
         schema=schema, sha256=digest, first=expected[0], last=expected[-1])

    spark.conf.set("spark.comet.enabled", "true")
    elapsed = []
    builds = []
    for trial in range(-args.warmups, args.runs):
        start = time.perf_counter()
        df = spark.sql(sql)
        result = df.collect()
        seconds = time.perf_counter() - start
        assert df.schema.json() == schema, (df.schema.json(), schema)
        assert sorted(tuple(row) for row in result) == expected, "Spark result mismatch"

        plan = df._jdf.queryExecution().executedPlan()
        operators = list(nodes(plan))
        exchanges = [node for node in operators if
                     node.getClass().getSimpleName() == "CometBroadcastExchangeExec"]
        if trial == -args.warmups:
            emit("plan", arm=args.arm, case=name, plan=plan.toString())
        assert len(exchanges) == 1, plan.toString()
        assert any(node.getClass().getSimpleName() == "CometBroadcastHashJoinExec"
                   for node in operators), plan.toString()
        m = metrics(exchanges[0])
        assert m["numCoalescedRows"] == n, m
        active = m.get("numParallelCoalesceGroups", 0)
        emit("trial", arm=args.arm, case=name, trial=trial, warmup=trial < 0,
             seconds=seconds, metrics=m, parallel_groups=active, parity=True,
             rows=len(result), sha256=digest)
        assert active == (4 if args.arm == "patch" and name != "small" else 0), m
        if trial >= 0:
            elapsed.append(seconds)
            builds.append(m["buildTime"] / 1000.0)
    emit("summary", arm=args.arm, case=name, parity=True, sha256=digest,
         seconds=elapsed, median_seconds=statistics.median(elapsed),
         build_seconds=builds, median_build_seconds=statistics.median(builds))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--arm", choices=["main", "patch"], required=True)
    parser.add_argument("--warmups", type=int, default=1)
    parser.add_argument("--runs", type=int, default=5)
    parser.add_argument("--rows", type=int, default=6291456)
    parser.add_argument("--parquet")
    parser.add_argument("--cases", nargs="+", choices=["ordered", "nullable", "small"],
                        default=["ordered", "nullable", "small"])
    args = parser.parse_args()
    settings = {
        "spark.sql.adaptive.enabled": "false",
        "spark.comet.exec.enabled": "true",
        "spark.comet.exec.range.enabled": "true",
        "spark.comet.exec.broadcastExchange.enabled": "true",
        "spark.comet.batchSize": "2048",
        "spark.comet.exec.broadcastExchange.parallelCoalesce.enabled": "true",
    }
    builder = SparkSession.builder
    for key, value in settings.items():
        builder = builder.config(key, value)
    spark = builder.getOrCreate()
    try:
        sc = spark.sparkContext
        emit("settings", arm=args.arm, spark=spark.version, app=sc.applicationId,
             cores=sc.getConf().get("spark.driver.cores", None),
             heap=sc.getConf().get("spark.driver.memory", None),
             overhead=sc.getConf().get("spark.driver.memoryOverhead", None),
             codec=sc.getConf().get("spark.io.compression.codec", "lz4"),
             settings={key: spark.conf.get(key) for key in settings})
        for case in args.cases:
            expr = ("CASE WHEN hash(id, 1) % 5 = 0 THEN NULL "
                    "ELSE CAST(hash(id) AS BIGINT) END" if case == "nullable" else "id * 3L")
            run(case, 65536 if case == "small" else args.rows, expr)
    finally:
        spark.stop()

AI assistance

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

…roadcasts

Combine contiguous Arrow IPC inputs in four ordered groups. Keep this opt-in and fall back to serial assembly when driver headroom, the schema or the resulting wire size rules out the split.
Arrow checks its process-wide per-vector cap while sizing a fixed-width vector. Treat a refusal there like an oversized append. Exercise the actual limit in an isolated JVM and verify the original streams remain available to serial fallback.
Check cancellation between input streams even when a parallel attempt retries serially. Exercise admission, cancellation with live buffers, cleanup and reuse of the driver slot. Explain the cost of combining shared batches in each join task.
@github-actions github-actions Bot added enhancement New feature or request performance labels Dec 4, 2026
@sunchao
sunchao marked this pull request as ready for review December 5, 2026 00:19
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