comphead commented on code in PR #7837:
URL: https://github.com/apache/datafusion-comet/pull/7837#discussion_r4788739135
##########
spark/src/main/scala/org/apache/spark/sql/comet/operators.scala:
##########
@@ -2466,6 +2473,12 @@ trait CometBaseAggregate[T <: BaseAggregateExec] extends
CometOperatorSerde[T] {
if (resultExpressions.map(_.toAttribute) == naturalOutput) {
return Some(builder.setHashAgg(hashAggBuilder).build())
}
+ // Spark folds a write's NOT NULL checks into the aggregate below a LIMIT,
and evaluates them
+ // only for the groups the limit reads. The native projection would check
every group.
+ if (resultExpressions.exists(_.exists(_.isInstanceOf[AssertNotNull]))) {
Review Comment:
`CollapseProject` folds the write's `Project` into the `Aggregate` whether
or not a `LIMIT` sits above it (the `case p @ Project(_, agg: Aggregate)` arm
in Spark 4.1.1's `Optimizer.scala`). So this gate keeps the final aggregate in
Spark for every `INSERT ... SELECT ... GROUP BY` into a `NOT NULL` column, even
though Spark evaluates every group there too. The comment says "below a LIMIT",
but the check does not look for one. Could this tag only aggregates whose
output a limit in the same stage consumes, the way `tagOffsetSkippedChecks`
does for projections? Then the common no-limit `GROUP BY` write would run
natively. If you keep it unconditional for now, the comment should say so and
point to a follow-up issue.
##########
native/spark-expr/src/predicate_funcs/assert_not_null.rs:
##########
@@ -0,0 +1,354 @@
+// 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.
+
+use std::fmt::{Display, Formatter};
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+use arrow::array::{new_empty_array, RecordBatch};
+use arrow::datatypes::{DataType, FieldRef, Schema};
+use datafusion::common::{internal_err, Result};
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::ColumnarValue;
+
+use crate::SparkError;
+
+/// Spark's `AssertNotNull`: returns its child unchanged, and fails if any row
is NULL.
+#[derive(Debug, Eq)]
+pub struct AssertNotNull {
+ child: Arc<dyn PhysicalExpr>,
+ /// Spark's `walkedTypePath.mkString("\n", "\n", "\n")`, reported in the
error.
+ walked_type_path: String,
+}
+
+impl Hash for AssertNotNull {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.child.hash(state);
+ self.walked_type_path.hash(state);
+ }
+}
+
+impl PartialEq for AssertNotNull {
+ fn eq(&self, other: &Self) -> bool {
+ self.child.eq(&other.child) && self.walked_type_path ==
other.walked_type_path
+ }
+}
Review Comment:
The hand-written `Hash` and `PartialEq` impls compare the same two fields a
derive would. `AtLeastNNonNulls` in the same directory derives `#[derive(Debug,
PartialEq, Eq, Hash)]` over `Vec<Arc<dyn PhysicalExpr>>`, so `#[derive(Debug,
PartialEq, Eq, Hash)]` here should compile and lets lines 38-49 go.
##########
spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala:
##########
@@ -2167,6 +2203,11 @@ case class CometExecRule(session: SparkSession,
queryStagePrep: Boolean = false)
val aggregateExpressions = agg.aggregateExpressions
val groupingExpressions = agg.groupingExpressions
+ // The aggregate serde leaves these to Spark; see
CometBaseAggregate.AssertNotNullInResult.
+ if (agg.resultExpressions.exists(_.exists(_.isInstanceOf[AssertNotNull])))
{
+ return false
+ }
Review Comment:
The same `exists(_.exists(_.isInstanceOf[AssertNotNull]))` predicate is
written three times: here, in `tagOffsetSkippedChecks` (line 1550) and in
`CometBaseAggregate` (`operators.scala` line 2478). A single helper next to the
serde, for example `CometAssertNotNull.containsCheck(exprs: Seq[Expression])`,
would keep the three call sites in sync and give the cross-reference comment
here one place to point to.
##########
spark/src/test/scala/org/apache/comet/CometAssertNotNullSuite.scala:
##########
@@ -0,0 +1,367 @@
+/*
+ * 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.comet
+
+import org.apache.spark.sql.{Column, CometTestBase, DataFrame}
+import org.apache.spark.sql.catalyst.expressions.{And, CaseWhen, Cast,
CreateNamedStruct, Divide, GetStructField, GreaterThan, If, IsNotNull, IsNull,
Literal, Or}
+import org.apache.spark.sql.catalyst.expressions.objects.AssertNotNull
+import org.apache.spark.sql.comet.CometBaseAggregate
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.functions.{col, sum, transform}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{DoubleType, IntegerType, NullType}
+
+import org.apache.comet.rules.CometExecRule
+
+/**
+ * `AssertNotNull` is a `NonSQLExpression`, so SQL file tests cannot call it.
These tests build it
+ * through the DataFrame API, as Spark's encoders and V2 table writes do.
+ */
+class CometAssertNotNullSuite extends CometTestBase {
+ import testImplicits._
+
+ private val allTypes = """SELECT * FROM VALUES
+ (true, cast(-128 AS TINYINT), 2147483647, cast(-9223372036854775808 AS
BIGINT),
+ cast('NaN' AS FLOAT), cast('-Infinity' AS DOUBLE),
+ cast('99999999999999999999.999999999999999999' AS DECIMAL(38, 18)),
+ cast(-0.01 AS DECIMAL(10, 2)), '你好, 世界', cast('こんにちは' AS BINARY),
+ DATE '0001-01-01', TIMESTAMP '1900-01-01 00:00:00 UTC',
+ TIMESTAMP_NTZ '9999-12-31 23:59:59.999999',
+ array(1, NULL), array(named_struct('x', cast(NULL AS INT), 'm', map('k',
1))),
+ map('ключ', array(1, NULL)),
+ named_struct('a', NULL, 'b', array(named_struct('c', 'é')),
+ 'm', map('k', cast(NULL AS INT)))),
+ (false, cast(127 AS TINYINT), -2147483648, cast(9223372036854775807 AS
BIGINT),
+ cast(-0.0 AS FLOAT), cast(1e308 AS DOUBLE),
+ cast('-99999999999999999999.999999999999999999' AS DECIMAL(38, 18)),
+ cast(99999999.99 AS DECIMAL(10, 2)), '', cast('' AS BINARY),
+ DATE '9999-12-31', TIMESTAMP '2262-04-11 23:47:16.854775 UTC',
+ TIMESTAMP_NTZ '0001-01-01 00:00:00',
+ array(), array(), map(), named_struct('a', 1, 'b', array(), 'm', map()))
+ AS t(b, i8, i32, i64, f, d, dec38, dec10, s, bin, dt, ts, ntz, arr,
arr_st, m, st)"""
+
+ private def assertNotNull(df: DataFrame, column: String, path: Seq[String]):
Column =
+ getColumnFromExpression(AssertNotNull(df.col(column).expr, path))
+
+ private def checkNative(df: => DataFrame): (SparkPlan, SparkPlan) =
+ checkSparkAnswerAndImpl(df, native = Seq("assertnotnull"))
+
+ /** Both engines fail with the same exception class and message, and Comet
fails natively. */
+ private def assertSameNotNullError(query: => DataFrame, checkNative: Boolean
= true): Unit = {
+ val df = query
+ if (checkNative) {
+ val plan = stripAQEPlan(df.queryExecution.executedPlan)
+ checkCometOperators(plan)
+ assertExpressionImpl(plan, native = Seq("assertnotnull"), dispatched =
Nil)
+ }
+ checkSparkAnswerMaybeThrows(df) match {
+ case (Some(sparkError), Some(cometError)) =>
+ assertSameNotNullViolation(sparkError, cometError)
+ case result => fail(s"Expected both Spark and Comet to fail, got
$result")
+ }
+ }
+
+ /** `query(passing)` matches Spark natively, and `query("true")` fails as
Spark does. */
+ private def checkPassesAndFails(passing: String)(query: String =>
DataFrame): Unit = {
+ checkNative(query(passing))
+ assertSameNotNullError(query("true"))
+ }
+
+ test("AssertNotNull returns non-null values of every type natively") {
+ withTempPath { dir =>
+ // Spark 3.5 refuses to write dates before 1582 unless told not to
rebase them.
+ withSQLConf(
+ SQLConf.PARQUET_REBASE_MODE_IN_WRITE.key -> "CORRECTED",
+ SQLConf.PARQUET_INT96_REBASE_MODE_IN_WRITE.key -> "CORRECTED") {
+ sql(allTypes).write.parquet(dir.getCanonicalPath)
+ }
+ withParquetTable(dir.getCanonicalPath, "tbl") {
+ val df = spark.table("tbl")
+ checkNative(df.select(df.columns.toSeq.map(c => assertNotNull(df, c,
Seq(c)).as(c)): _*))
+ }
+ }
+ }
+
+ test("AssertNotNull fails with Spark's error on a NULL") {
+ val input = sql("""SELECT * FROM VALUES
+ (1, 'a', named_struct('x', 1), array(1), map('k', 1)),
+ (2, 'b', named_struct('x', 2), array(CAST(NULL AS INT)), map('k',
CAST(NULL AS INT))),
+ (3, NULL, named_struct('x', NULL), array(3), map('k', 3)),
+ (NULL, 'd', NULL, NULL, NULL),
+ (5, 'e', named_struct('x', 5), array(5), map('k', 5)) AS t(i, s, st,
arr, m)""")
+ withTempPath { dir =>
+ input.repartition(1).write.parquet(dir.getCanonicalPath)
+ withParquetTable(dir.getCanonicalPath, "tbl") {
+ // A batch size of 2 puts each NULL in a later batch than the first.
+ withSQLConf(CometConf.COMET_BATCH_SIZE.key -> "2") {
+ for ((column, path) <- Seq(
+ "i" -> Seq("i"),
+ "s" -> Seq("top level Product or row object"),
+ "st" -> Seq("s", "a"),
+ "arr" -> Seq("arr"),
+ "m" -> Seq("m"),
+ "i" -> Seq("列_1", "😀 field"))) {
+ assertSameNotNullError {
+ val df = spark.table("tbl")
+ df.select(assertNotNull(df, column, path))
+ }
+ }
+ // NULLs inside a non-null struct, array or map pass; only the value
itself is checked.
+ val df = spark.table("tbl").where("i IS NOT NULL")
+ checkNative(df.select(Seq("st", "arr", "m").map(c =>
assertNotNull(df, c, Seq(c))): _*))
+ }
+ }
+ }
+ }
+
+ test("AssertNotNull in a branch Spark does not take is not evaluated") {
+ val input = sql("""SELECT * FROM VALUES
+ (1, named_struct('a', 1, 'b', 'x')),
+ (-1, NULL),
+ (2, named_struct('a', 2, 'b', NULL)) AS t(i, st)""")
+ withTempPath { dir =>
+ // One file, so the skipped NULL row shares a batch with rows the check
does run on.
+ input.repartition(1).write.parquet(dir.getCanonicalPath)
+ withParquetTable(dir.getCanonicalPath, "tbl") {
+ val df = spark.table("tbl")
+ val st = df.col("st").expr
+ val checkedA = AssertNotNull(GetStructField(st, 0, Some("a")),
Seq("st", "a"))
+ // How Spark writes a nullable struct into a struct column with a NOT
NULL field. Its NULL
+ // branch has the target type, where field `a` is not nullable.
+ val struct =
+ CreateNamedStruct(
+ Seq(Literal("a"), checkedA, Literal("b"), GetStructField(st, 1,
Some("b"))))
+ val rebuilt = If(IsNull(st), Literal(null, struct.dataType), struct)
+ checkNative(df.select(getColumnFromExpression(rebuilt)))
+
+ val caseWhen =
+ CaseWhen(Seq(GreaterThan(df.col("i").expr, Literal(0)) -> checkedA),
Some(Literal(0)))
+ checkNative(df.select(getColumnFromExpression(caseWhen)))
+
+ // AND and OR evaluate their right side only for rows the left side
has not decided.
+ val positive = GreaterThan(checkedA, Literal(0))
+ checkNative(df.select(getColumnFromExpression(And(IsNotNull(st),
positive))))
+ checkNative(df.select(getColumnFromExpression(Or(IsNull(st),
positive))))
+ }
+ }
+ }
+
+ // Spark's write plans put the check right before the shuffle that feeds the
writer.
+ test("AssertNotNull feeds native shuffle and aggregation") {
+ withParquetTable((0 until 100).map(i => (i, s"k${i % 7}")), "tbl") {
+ val df = spark.table("tbl")
+ val checked =
+ df.select(
+ assertNotNull(df, "_1", Seq("_1")).as("v"),
+ assertNotNull(df, "_2", Seq("_2")).as("k"))
+ val (_, cometPlan) = checkNative(checked.repartition(4, col("k")))
+ assert(
+ collect(cometPlan) { case s: CometShuffleExchangeExec => s }.nonEmpty,
+ s"expected native shuffle in:\n$cometPlan")
+ checkNative(checked.groupBy("k").agg(sum("v")))
+ }
+ // A NULL reaching the check fails the native shuffle write with Spark's
error.
+ withParquetTable((0 until 100).map(i => (i, if (i == 57) null else s"k${i
% 7}")), "nulls") {
+ assertSameNotNullError {
+ val df = spark.table("nulls")
+ df.select(
+ assertNotNull(df, "_1", Seq("_1")).as("v"),
+ assertNotNull(df, "_2", Seq("_2")).as("k"))
+ .repartition(4, col("k"))
+ }
+ }
+ }
+
+ test("AssertNotNull checks the value its child computes") {
+ withParquetTable(Seq((1, 1), (2, 0), (3, 3)), "tbl") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "false") {
+ // 2.0 / 0.0 is NULL without ANSI, from inputs that are not NULL.
+ checkPassesAndFails("_2 != 0") { predicate =>
+ val df = spark.table("tbl").where(predicate)
+ val ratio =
+ Divide(Cast(df.col("_1").expr, DoubleType),
Cast(df.col("_2").expr, DoubleType))
+ df.select(getColumnFromExpression(AssertNotNull(ratio,
Seq("ratio"))))
+ }
+ }
+ }
+ }
+
+ test("AssertNotNull on an empty input and on a NULL literal") {
+ withParquetTable(Seq((1, "a"), (2, "b"), (3, null)), "tbl") {
+ // With no row there is nothing to check. The filter may leave no batch
at all, so the
+ // Rust tests cover a NULL constant over an empty batch.
+ for (dataType <- Seq(IntegerType, NullType)) {
+ checkPassesAndFails("_1 > 10") { predicate =>
+ spark
+ .table("tbl")
+ .where(predicate)
+ .select(getColumnFromExpression(AssertNotNull(Literal(null,
dataType), Seq("c"))))
+ }
+ }
+ // A filter that removes the NULLs first leaves nothing to fail on.
+ val df = spark.table("tbl").where("_2 IS NOT NULL")
+ checkNative(df.select(assertNotNull(df, "_2", Seq("_2"))))
+ }
+ }
+
+ test("AssertNotNull on a low-cardinality string column") {
+ withTempPath { dir =>
+ // Few distinct values, so Parquet writes the column with a dictionary.
The scan may decode
+ // it; the Rust tests cover a dictionary array that reaches the check.
+ spark
+ .range(1000)
+ .selectExpr(
+ "id",
+ "CASE WHEN id = 999 THEN NULL WHEN id % 2 = 0 THEN 'ä' ELSE '日本' END
AS s")
+ .repartition(1)
+ .write
+ .parquet(dir.getCanonicalPath)
+ withParquetTable(dir.getCanonicalPath, "tbl") {
+ checkPassesAndFails("id < 999") { predicate =>
+ val df = spark.table("tbl").where(predicate)
+ df.select(assertNotNull(df, "s", Seq("s")))
+ }
+ }
+ }
+ }
+
+ test("AssertNotNull inside a lambda matches Spark") {
+ // How Spark writes array<int> into a column of array<int NOT NULL>.
+ withParquetTable(Seq((1, Seq(Option(1), Option(2))), (2, Seq(Option(3),
None))), "tbl") {
+ def checked(predicate: String): DataFrame =
+ spark
+ .table("tbl")
+ .where(predicate)
+ .select(
+ transform(
+ col("_2"),
+ x => getColumnFromExpression(AssertNotNull(x.expr, Seq("_2",
"element")))))
+ // The lambda runs in Comet through the JVM codegen dispatcher, not as a
native expression.
+ checkSparkAnswerAndImpl(checked("_1 = 1"), dispatched = Seq("transform"))
+ val failing = stripAQEPlan(checked("true").queryExecution.executedPlan)
+ checkCometOperators(failing)
+ assertExpressionImpl(failing, native = Nil, dispatched =
Seq("transform"))
+ assertSameNotNullError(checked("true"), checkNative = false)
+ }
+ }
+
+ test("AssertNotNull under a LIMIT checks only the rows the limit reads") {
+ withTempPath { dir =>
+ // One file in id order, so the limit reads rows in order and stops well
before the NULL in
+ // row 57.
+ spark
+ .range(100)
+ .selectExpr("CAST(IF(id = 57, NULL, id) AS INT) AS v")
+ .coalesce(1)
+ .write
+ .parquet(dir.getCanonicalPath)
+ withParquetTable(dir.getCanonicalPath, "tbl") {
+ for (aqe <- Seq(true, false)) {
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString) {
+ val df = spark.table("tbl")
+ val checked = df.select(assertNotNull(df, "v",
Seq("v")).as("v")).limit(5)
+ // A collect limit, and a local limit, which Spark puts under a
global limit.
+ checkNative(checked)
+ checkNative(checked.agg(sum("v")))
+ }
+ }
+ }
+ }
+ }
+
+ test("AssertNotNull after a sort with a LIMIT checks only the top rows") {
+ // Several files, so the top rows come from more than one partition. The
NULL sorts last.
+ withParquetTable((0 until 100).map(i => Tuple1(if (i == 42) None else
Some(i))), "tbl") {
+ val df = spark.table("tbl")
+ val sorted = df.orderBy(col("_1").asc_nulls_last)
+ val checked = sorted.select(assertNotNull(sorted, "_1",
Seq("_1")).as("v"))
+ checkNative(checked.limit(5))
+ checkNative(checked.limit(5).offset(2))
+ // The NULL sorts first, into the OFFSET rows, which Spark skips before
projecting.
+ val nullsFirst = df.orderBy(col("_1").asc_nulls_first)
+ checkNative(
+ nullsFirst.select(assertNotNull(nullsFirst, "_1",
Seq("_1")).as("v")).limit(5).offset(1))
+ }
+ // Spark projects only the global top rows. With the five-way local
parallelism, row 20 leads a
+ // partition, so it is in that top 5 but not the global top 5. Row 1 is
one of the OFFSET rows.
+ withParquetTable(
+ (0 until 100).map(i => (i, if (i == 1 || i == 20) None else Some(i))),
+ "t2") {
+ val sorted = spark.table("t2").orderBy("_1")
+ val checked = sorted.select(assertNotNull(sorted, "_2",
Seq("_2")).as("v"))
+ checkNative(checked.limit(5).offset(2))
+ }
+ }
+
+ test("AssertNotNull planned below an OFFSET stays in Spark") {
+ withTempPath { dir =>
+ // One file in id order, with the NULL in the first row, which the
OFFSET skips.
+ spark
+ .range(10)
+ .selectExpr("CAST(IF(id = 0, NULL, id) AS INT) AS v")
+ .coalesce(1)
+ .write
+ .parquet(dir.getCanonicalPath)
+ withParquetTable(dir.getCanonicalPath, "tbl") {
+ // coalesce(1) leaves nothing to shuffle before the OFFSET, so Spark
projects only the
+ // rows the OFFSET keeps. The aggregate keeps the OFFSET off the root,
where a collect
+ // would read every row.
+ val df = spark.table("tbl").coalesce(1)
+ val checked = df.select(assertNotNull(df, "v", Seq("v")).as("v"))
+ for (limited <- Seq(checked.offset(1), checked.limit(3).offset(1))) {
+ checkSparkAnswerAndFallbackReason(
+ limited.agg(sum("v")),
+ CometExecRule.OffsetSkippedCheckReason)
+ }
+ }
+ }
+ }
+
+ test("AssertNotNull folded into an aggregate keeps the aggregate in Spark") {
+ withParquetTable((0 until 20).map(i => (i % 5, i)), "tbl") {
+ // Spark merges the check into the aggregate's result expressions, as it
does for a write
+ // of GROUP BY ... LIMIT, and evaluates them only for the groups a limit
reads.
+ val grouped = spark.table("tbl").groupBy("_1").agg(sum("_2").as("s"))
+ val checked =
+ grouped.select(assertNotNull(grouped, "_1", Seq("k")).as("k"),
col("s"))
+ checkSparkAnswerAndFallbackReason(checked,
CometBaseAggregate.AssertNotNullInResult)
+ }
Review Comment:
This test pins the fallback reason but has no `LIMIT` and no NULL, so it
does not show the result the gate protects. Nothing tests the case the gate
exists for: a NULL group past a `LIMIT`, where Spark succeeds and a native
result projection would fail. A case like `groupBy(...).agg(...)`, with the
check on a column that is NULL only for a group the `LIMIT` does not read,
compared against Spark, would pin it. The same shape through `INSERT ... SELECT
... GROUP BY ... LIMIT` in `CometIcebergWriteActionSuite` would cover the real
write plan.
--
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]