sunchao opened a new pull request, #7870: URL: https://github.com/apache/datafusion-comet/pull/7870
## 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. Executors may need extra work or memory to combine multiple batches. Driver heap checks are estimates and each hard allocator limit covers Arrow buffers only. The exchange metric `numParallelCoalesceGroups` reports four for a selected parallel result and zero for ordinary coalescing. ## How are these changes tested? `UtilsSuite` exercises nullable input, row order, the exact wire limit, intact serial retry inputs, Arrow allocation refusal, cancellation and differing group schemas. All three focused Scala tests passed. The vector-capacity case runs in an isolated JVM with a 64 KiB Arrow allocation limit per vector. ### Benchmark against Apache main The baseline was [Apache Comet main at ef771f2b](https://github.com/apache/datafusion-comet/commit/ef771f2b875ece9a79b3295cd5cc2db87275c04c). 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.8937 | 0.5970 | +0.2967 | 1.497× | 1.453× | 1.544× | | Nullable | 6,291,456 | 0.8714 | 0.5866 | +0.2848 | 1.486× | 1.474× | 1.497× | | Small control | 65,536 | 0.1034 | 0.1086 | -0.0053 | 0.952× | 1.071× | 0.842× | Both large joins used four ordered groups on the branch. With batches of 2,048 rows, the exchange received 3,072 batches. The mean of the two median exchange `buildTime` values fell from 428.5 to 105.0 ms on the ordered case and from 402.0 to 92.5 ms on the nullable case. This metric is part of SQL time. The small control stayed serial. Its mean was 5.3 ms slower, with opposite directions between orders. More streams can increase decoding work on the consuming side. This run exercises the join and driver assembly on one host. It leaves the cost across many executors and peak driver memory under concurrent broadcasts unmeasured. <details> <summary>Reproduce the measurements</summary> 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. ```sh 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 ``` ```python """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() ``` </details> ## AI assistance OpenAI Codex assisted with the implementation, tests, benchmarks and write-up. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
