sunchao opened a new pull request, #7869:
URL: https://github.com/apache/datafusion-comet/pull/7869

   ## 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](https://github.com/apache/datafusion/blob/55.2.0/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs#L839-L908)
 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.
   
   Keep the existing plan for grand totals, duplicate masks, unsupported 
aggregates, arguments that depend on masked columns, and plans eligible for 
partial aggregation bypass. Limit this path to eight masks because DataFusion 
checks the hash table memory reservation only after processing all masks for 
the batch. This bounds how many batches' worth of groups can be inserted 
between checks. Peak memory can still increase on high-cardinality keys.
   
   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?
   
   * Rust matcher cases cover exact ID bits, duplicate masks, grand totals, 
changed payloads, arguments reading masked keys or IDs, and the mask limit.
   * The CometAggregateSuite case checks parity with Spark, including stored 
nulls and decimal arithmetic. It checks how many rows reached the partial 
aggregate for eligible grouping sets, a grand total and opt-in partial bypass.
   
   Both Rust tests and the focused Scala test passed.
   
   ### 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.
   
   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.0002 | 2.6114 | +0.3888 | 1.149× | 1.140× | 
1.158× |
   | Nullable random | 256,000,000 | 3.3975 | 2.9770 | +0.4205 | 1.141× | 
1.143× | 1.140× |
   | Grand total control | 256,000,000 | 4.4261 | 4.4031 | +0.0230 | 1.005× | 
1.025× | 0.986× |
   | Regular | 16,000,000 | 0.2554 | 0.2414 | +0.0140 | 1.058× | 1.045× | 
1.073× |
   | Nullable random | 16,000,000 | 0.2471 | 0.2395 | +0.0076 | 1.032× | 1.042× 
| 1.022× |
   | Grand total control | 16,000,000 | 0.2911 | 0.3067 | -0.0156 | 0.949× | 
0.899× | 1.005× |
   
   The two eligible queries have three grouping sets. At 256 million input 
rows, main expands to 768 million rows before the partial aggregate. The 
branch's `reduction_factor_total` counter recorded 256 million. The Parquet 
scan supplies the same rows on both builds. The native aggregate evaluates the 
decimal product once per input batch and still updates all three grouping sets. 
The grand total control kept four projections and the counter recorded 1.024 
billion rows. The Spark plan still shows Expand because the change happens in 
the native planner.
   
   The smaller grand total control was 15.6 ms slower on average. The two 
orders disagreed on the direction for this control at both sizes. The branch 
selects eligible plans automatically. High-cardinality keys can allocate more 
group state between reservation checks. Both measured key distributions have a 
small number of groups. These results do not establish a peak memory bound for 
wider keys.
   
   <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
   run "$MAIN_JAR" main --rows 256000000 --partitions 64 --warmups 2 --repeats 7
   run "$PATCH_JAR" patch --rows 256000000 --partitions 64 --warmups 2 
--repeats 7
   ```
   
   ```python
   """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()
   ```
   
   </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]

Reply via email to