sunchao commented on code in PR #7795:
URL: https://github.com/apache/datafusion-comet/pull/7795#discussion_r4746942774


##########
native/core/src/execution/jni_api.rs:
##########
@@ -1033,6 +1037,29 @@ pub extern "system" fn 
Java_org_apache_comet_Native_setOutputStream(
     })
 }
 
+/// Whether `avg` is built as `AvgDecimal` (a decimal result; any other result 
is Comet's Float64
+/// `Avg`, which cannot convert rows to states) and no order of adding its 
values can overflow the
+/// sum. Skipping changes the order in which the final aggregate adds a 
group's values, and a sum
+/// that leaves its precision stays null, so `[M, 1 - M]` in each of two tasks 
gives 1 + 1 when
+/// aggregated but overflows at 1 + M when skipped. Spark gives the sum 10 
more digits than the
+/// input up to precision 38, so a sum below 38 has all of them, and a group 
needs more than 10^10
+/// values before any partial sum can leave it.
+fn avg_decimal_cannot_overflow(avg: &Avg) -> bool {
+    let decimal_precision = |datatype: Option<&ProtoDataType>| match datatype {
+        Some(datatype) if datatype.type_id == DataTypeId::Decimal as i32 => {
+            match datatype.type_info.as_ref()?.datatype_struct.as_ref()? {
+                DatatypeStruct::Decimal(decimal) => Some(decimal.precision),
+                _ => None,
+            }
+        }
+        _ => None,
+    };
+    avg.child.is_some()
+        && decimal_precision(avg.datatype.as_ref()).is_some()
+        && decimal_precision(avg.sum_datatype.as_ref())
+            .is_some_and(|precision| precision < DECIMAL128_MAX_PRECISION as 
i32)

Review Comment:
   `sum_precision < 38` gives ten digits of headroom, but there is no group 
cardinality bound. For DECIMAL(12,0), set M = 999999999999 and seed the reducer 
with `(sum = 10^10 * M, count = 10^10)`, which fits DECIMAL(22,0). Another task 
sees `[M, -M]` for that key after its probe. Its grouped `(0, 2)` gives 
999999999799.0000. Skipping emits `(M, 1)` first, overflows the reducer, and 
`-M` cannot recover the sum. I reproduced NULL in legacy/try and an ANSI error 
with the PR accumulator for input precisions 12–27. Can we keep these AVGs out 
unless the group size is bounded or make merging overflow-safe? A test can seed 
the state directly without creating billions of rows.



##########
spark/src/test/scala/org/apache/spark/sql/benchmark/CometSkipPartialAvgBenchmark.scala:
##########
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.spark.sql.benchmark
+
+import org.apache.spark.benchmark.Benchmark
+import org.apache.spark.sql.comet.CometHashAggregateExec
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
+import org.apache.spark.sql.internal.SQLConf
+
+import org.apache.comet.CometConf
+
+/**
+ * Compare a high-cardinality `GROUP BY` with a decimal `AVG` with adaptive 
partial aggregation
+ * disabled and enabled. Use a native release build:
+ *
+ * {{{
+ * make benchmark-org.apache.spark.sql.benchmark.CometSkipPartialAvgBenchmark 
-- 8388608 5
+ * }}}
+ *
+ * Arguments are rows and iterations. The input is one file, read by one task, 
with two key
+ * layouts: `distinct`, where every key is distinct, and `repeating`, where 
the first eighth of
+ * the rows are distinct and then repeat seven more times, so skipping starts 
after the first
+ * 100,000 rows and shuffles every later row (#6466). Shuffle records and 
bytes come from an
+ * untimed execution.
+ */
+object CometSkipPartialAvgBenchmark extends CometBenchmarkBase {
+
+  private val query =
+    "SELECT sum(a), count(a) FROM (SELECT k, avg(d) a FROM parquetV1Table 
GROUP BY k)"
+
+  private def cometConf(skip: Boolean): Seq[(String, String)] = Seq(
+    CometConf.COMET_ENABLED.key -> "true",
+    CometConf.COMET_EXEC_ENABLED.key -> "true",
+    CometConf.COMET_SHUFFLE_ENABLED.key -> "true",
+    CometConf.COMET_SHUFFLE_MODE.key -> "native",
+    CometConf.COMET_EXEC_AGGREGATE_SKIP_PARTIAL_ENABLED.key -> skip.toString)
+
+  private def report(benchmark: Benchmark, layout: String, skip: Boolean): 
Unit = {
+    withSQLConf(cometConf(skip): _*) {
+      val plans = capturePlans(spark.sql(query).collect())
+      val shuffles = collectAcross(plans) { case e: CometShuffleExchangeExec 
=> e }
+      val aggregates = collectAcross(plans) { case a: CometHashAggregateExec 
=> a }
+      require(shuffles.nonEmpty && aggregates.nonEmpty, s"Expected a native 
plan:\n$plans")
+      val records = shuffles.map(_.metrics("shuffleRecordsWritten").value).sum
+      val bytes = shuffles.map(_.metrics("dataSize").value).sum

Review Comment:
   `dataSize` is the Arrow buffer accounting on the native writer input. It 
doesn't tell us what the shuffle actually wrote after encoding and compression. 
Can we use `shuffleBytesWritten` for the reported shuffle bytes? 
`CometNativeShuffleWriter` increments that metric from `partitionLengths.sum` 
or `Files.size(tempDataFilePath)`. Reporting the input size separately would 
also be useful.



##########
spark/src/test/scala/org/apache/spark/sql/benchmark/CometSkipPartialAvgBenchmark.scala:
##########
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.spark.sql.benchmark
+
+import org.apache.spark.benchmark.Benchmark
+import org.apache.spark.sql.comet.CometHashAggregateExec
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
+import org.apache.spark.sql.internal.SQLConf
+
+import org.apache.comet.CometConf
+
+/**
+ * Compare a high-cardinality `GROUP BY` with a decimal `AVG` with adaptive 
partial aggregation
+ * disabled and enabled. Use a native release build:
+ *
+ * {{{
+ * make benchmark-org.apache.spark.sql.benchmark.CometSkipPartialAvgBenchmark 
-- 8388608 5
+ * }}}
+ *
+ * Arguments are rows and iterations. The input is one file, read by one task, 
with two key
+ * layouts: `distinct`, where every key is distinct, and `repeating`, where 
the first eighth of
+ * the rows are distinct and then repeat seven more times, so skipping starts 
after the first
+ * 100,000 rows and shuffles every later row (#6466). Shuffle records and 
bytes come from an
+ * untimed execution.
+ */
+object CometSkipPartialAvgBenchmark extends CometBenchmarkBase {
+
+  private val query =
+    "SELECT sum(a), count(a) FROM (SELECT k, avg(d) a FROM parquetV1Table 
GROUP BY k)"
+
+  private def cometConf(skip: Boolean): Seq[(String, String)] = Seq(
+    CometConf.COMET_ENABLED.key -> "true",
+    CometConf.COMET_EXEC_ENABLED.key -> "true",
+    CometConf.COMET_SHUFFLE_ENABLED.key -> "true",
+    CometConf.COMET_SHUFFLE_MODE.key -> "native",
+    CometConf.COMET_EXEC_AGGREGATE_SKIP_PARTIAL_ENABLED.key -> skip.toString)
+
+  private def report(benchmark: Benchmark, layout: String, skip: Boolean): 
Unit = {
+    withSQLConf(cometConf(skip): _*) {
+      val plans = capturePlans(spark.sql(query).collect())
+      val shuffles = collectAcross(plans) { case e: CometShuffleExchangeExec 
=> e }
+      val aggregates = collectAcross(plans) { case a: CometHashAggregateExec 
=> a }
+      require(shuffles.nonEmpty && aggregates.nonEmpty, s"Expected a native 
plan:\n$plans")
+      val records = shuffles.map(_.metrics("shuffleRecordsWritten").value).sum
+      val bytes = shuffles.map(_.metrics("dataSize").value).sum
+      val skipped = 
aggregates.flatMap(_.metrics.get("skipped_aggregation_rows")).map(_.value).sum
+      require(skip || skipped == 0L)

Review Comment:
   `skip || skipped == 0L` accepts zero skipped rows whenever the optimization 
is enabled. If the gate declines this plan or the probe never fires, the 
benchmark can quietly time the ordinary path twice. Both layouts are designed 
to trigger skipping. Please assert `if (skip) skipped > 0L else skipped == 0L` 
and include the layout and count in the failure.



-- 
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