FreakingMind commented on code in PR #7661:
URL: https://github.com/apache/datafusion-comet/pull/7661#discussion_r4676789441


##########
spark/src/main/scala/org/apache/comet/expressions/CometCast.scala:
##########
@@ -645,3 +645,31 @@ object CometCast
       .getOrElse(Compatible())
   }
 }
+
+/**
+ * Spark rethrows the child's error unchanged when the optimizer has replaced 
the cast
+ * (SPARK-42286), and never sees the error of a cast that subexpression 
elimination evaluates
+ * before it. So only a `Cast` child that the operator does not share is 
wrapped.
+ */
+object CometCheckOverflowInTableInsert extends 
CometExpressionSerde[CheckOverflowInTableInsert] {

Review Comment:
   Makes sense, moved it next to `CometCheckOverflow` in math.scala and 
registered it beside `CheckOverflow`. Moved the Rust file to 
`math_funcs/internal/` as well so the two sides match. CometCast.scala is 
untouched now.
   



##########
spark/src/main/scala/org/apache/comet/expressions/CometCast.scala:
##########
@@ -645,3 +645,31 @@ object CometCast
       .getOrElse(Compatible())
   }
 }
+
+/**
+ * Spark rethrows the child's error unchanged when the optimizer has replaced 
the cast
+ * (SPARK-42286), and never sees the error of a cast that subexpression 
elimination evaluates
+ * before it. So only a `Cast` child that the operator does not share is 
wrapped.
+ */
+object CometCheckOverflowInTableInsert extends 
CometExpressionSerde[CheckOverflowInTableInsert] {
+
+  override def convert(
+      expr: CheckOverflowInTableInsert,
+      inputs: Seq[Attribute],
+      binding: Boolean): Option[ExprOuterClass.Expr] = {
+    expr.child match {
+      case cast: Cast if !isSharedSubexpression(cast) =>

Review Comment:
   Good find. I went a bit further than the wording: with `NO_CODEGEN` the 
serde now keeps the wrapper on a shared cast, so Comet gives 
`CAST_OVERFLOW_IN_TABLE_INSERT` there too. SQLQueryTestSuite runs files in that 
mode, so I'd rather match it than document it. The shared cast test now also 
runs with whole-stage codegen off, subexpression elimination off and 
`NO_CODEGEN`, and it passes on 3.5, 4.0 and 4.1, so the interpreted case is 
confirmed by running it. What's left is the fallback after a compile failure, 
which we can't see at plan time. The doc comment and the description say 
"generated code" now.
   



##########
native/spark-expr/src/conversion_funcs/check_overflow_in_table_insert.rs:
##########
@@ -0,0 +1,349 @@
+// 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::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+use datafusion::common::{DataFusionError, Result};
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion_comet_common::error_chain;
+use datafusion_comet_jni_bridge::errors::CometError;
+
+use crate::{SparkError, SparkErrorWithContext};
+
+/// Spark's `CheckOverflowInTableInsert`: evaluates the cast that a table 
insert added and turns
+/// any `SparkArithmeticException` from it into 
`CAST_OVERFLOW_IN_TABLE_INSERT`, which names the
+/// column instead of the value and carries no query context.
+#[derive(Debug)]
+pub struct CheckOverflowInTableInsert {
+    child: Arc<dyn PhysicalExpr>,
+    from_type: String,
+    to_type: String,
+    column_name: String,
+}
+
+impl CheckOverflowInTableInsert {
+    pub fn new(
+        child: Arc<dyn PhysicalExpr>,
+        from_type: String,
+        to_type: String,
+        column_name: String,
+    ) -> Self {
+        Self {
+            child,
+            from_type,
+            to_type,
+            column_name,
+        }
+    }
+
+    fn table_insert_error(&self) -> DataFusionError {
+        SparkError::CastOverflowInTableInsert {
+            from_type: self.from_type.clone(),
+            to_type: self.to_type.clone(),
+            column_name: self.column_name.clone(),
+        }
+        .into()
+    }
+}
+
+impl PartialEq for CheckOverflowInTableInsert {
+    fn eq(&self, other: &Self) -> bool {
+        self.child.eq(&other.child)
+            && self.from_type == other.from_type
+            && self.to_type == other.to_type
+            && self.column_name == other.column_name
+    }
+}
+
+impl Eq for CheckOverflowInTableInsert {}
+
+impl Hash for CheckOverflowInTableInsert {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.child.hash(state);
+        self.from_type.hash(state);
+        self.to_type.hash(state);
+        self.column_name.hash(state);
+    }
+}
+
+impl Display for CheckOverflowInTableInsert {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        write!(
+            f,
+            "CheckOverflowInTableInsert({}, column: {})",
+            self.child, self.column_name
+        )
+    }
+}
+
+impl PhysicalExpr for CheckOverflowInTableInsert {
+    fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        self.child.fmt_sql(f)
+    }
+
+    fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
+        self.child.data_type(input_schema)
+    }
+
+    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+        self.child.nullable(input_schema)
+    }
+
+    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+        match self.child.evaluate(batch) {
+            Err(e) if is_arithmetic_error(&e) => 
Err(self.table_insert_error()),
+            other => other,
+        }
+    }
+
+    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+        vec![&self.child]
+    }
+
+    fn with_new_children(
+        self: Arc<Self>,
+        children: Vec<Arc<dyn PhysicalExpr>>,
+    ) -> Result<Arc<dyn PhysicalExpr>> {
+        match children.as_slice() {
+            [child] => Ok(Arc::new(Self::new(
+                Arc::clone(child),
+                self.from_type.clone(),
+                self.to_type.clone(),
+                self.column_name.clone(),
+            ))),
+            _ => Err(DataFusionError::Internal(
+                "CheckOverflowInTableInsert should have exactly one 
child".to_string(),
+            )),
+        }
+    }
+}
+
+/// Whether Spark raises this error as a `SparkArithmeticException`: a native 
`SparkError`, or an
+/// exception thrown by a child that runs Spark's own code through the JVM 
codegen dispatcher.
+/// Like the JNI layer, it takes the first Spark error in the `source()` chain.
+fn is_arithmetic_error(error: &DataFusionError) -> bool {
+    error_chain(error)
+        .find_map(|e| {
+            if let Some(CometError::JavaException { class, .. }) = 
e.downcast_ref::<CometError>() {
+                Some(SparkError::is_arithmetic_exception_class(

Review Comment:
   You're right, I didn't find a path either. Dropped the commit, it's back to 
comparing with `SparkArithmeticException` only.
   



##########
spark/src/test/scala/org/apache/comet/parquet/CometParquetWriterSuite.scala:
##########
@@ -1694,6 +1695,173 @@ class CometParquetWriterSuite extends 
CometParquetWriterTestBase {
     }
   }
 
+  private def withInsertWriter(nativeWriter: Boolean)(f: => Unit): Unit =
+    if (nativeWriter) withNativeWriter(f) else f
+
+  private def assertCometInsert(plan: SparkPlan, nativeWriter: Boolean): Unit =
+    if (nativeWriter) {
+      assertHasCometNativeWriteExec(plan)
+    } else {
+      assert(plan.exists(_.isInstanceOf[CometProjectExec]), plan.treeString)
+    }
+
+  private def withNarrowingTables(sourceType: String, targetType: String, 
values: Seq[String])(
+      f: => Unit): Unit =
+    withTable("comet_narrow_source", "comet_narrow_target") {
+      sql(s"CREATE TABLE comet_narrow_source(c $sourceType) USING parquet")
+      sql(s"CREATE TABLE comet_narrow_target(c $targetType) USING parquet")
+      withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+        sql(s"INSERT INTO comet_narrow_source VALUES ${values.map(v => 
s"($v)").mkString(", ")}")
+      }
+      withClue(s"$sourceType -> $targetType: ")(f)
+    }
+
+  /** Runs `select` into the target in Spark and in Comet, and returns Spark's 
error. */
+  private def assertInsertFailsAsSpark(
+      select: String,
+      nativeWriter: Boolean): SparkThrowable with Throwable = {
+    val insert = s"INSERT INTO comet_narrow_target SELECT $select FROM 
comet_narrow_source"
+    def sparkError(e: Throwable): SparkThrowable with Throwable =
+      causeChain(e)
+        .collect { case t: SparkThrowable with Throwable => t }
+        .lastOption
+        .getOrElse(fail(s"$insert did not raise a SparkThrowable", e))
+    var expected: SparkThrowable with Throwable = null
+    withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+      expected = sparkError(intercept[Exception](sql(insert)))
+    }
+    withInsertWriter(nativeWriter) {
+      val (plan, e) = captureFailedWritePlan(sql(insert))
+      assertCometInsert(plan, nativeWriter)
+      assert(!causeChain(e).exists(_.isInstanceOf[CometNativeException]), e)
+      val actual = sparkError(e)
+      assert(actual.getClass == expected.getClass)
+      assert(actual.getErrorClass == expected.getErrorClass)
+      assert(actual.getSqlState == expected.getSqlState)
+      assert(actual.getMessage == expected.getMessage)
+    }
+    expected
+  }
+
+  for (nativeWriter <- Seq(false, true)) {
+    test(s"a narrowing INSERT stays in Comet (native writer: $nativeWriter)") {
+      val inserts = Seq(
+        ("bigint", "int", Seq("1", "NULL", "2147483647", "-2147483648")),
+        ("int", "tinyint", Seq("127", "-128")),
+        ("bigint", "smallint", Seq("32767", "-32768")),
+        ("double", "bigint", Seq("1.5", "-2.9", "NULL")),
+        ("decimal(20,2)", "decimal(10,2)", Seq("1.25", "-99999999.99", 
"NULL")),
+        ("decimal(20,2)", "int", Seq("1.99", "-7.5")),
+        ("struct<x: bigint>", "struct<x: int>", Seq("named_struct('x', 1)", 
"NULL")),
+        ("array<bigint>", "array<int>", Seq("array(1, NULL, -2)", "NULL")),
+        ("map<bigint, bigint>", "map<int, int>", Seq("map(1, 2147483647)", 
"NULL")))
+      inserts.foreach { case (sourceType, targetType, values) =>
+        withNarrowingTables(sourceType, targetType, values) {
+          withTable("comet_narrow_expected") {
+            sql(s"CREATE TABLE comet_narrow_expected(c $targetType) USING 
parquet")
+            withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+              sql("INSERT INTO comet_narrow_expected SELECT c FROM 
comet_narrow_source")
+            }
+            withInsertWriter(nativeWriter) {
+              val plan = captureWritePlan(
+                sql("INSERT INTO comet_narrow_target SELECT c FROM 
comet_narrow_source"))
+              assertCometInsert(plan, nativeWriter)
+            }
+            checkAnswer(spark.table("comet_narrow_target"), 
spark.table("comet_narrow_expected"))
+          }
+        }
+      }
+    }
+
+    test(
+      s"a narrowing INSERT that overflows fails as Spark does (native writer: 
$nativeWriter)") {
+      val overflows = Seq(
+        ("bigint", "int", "3000000000"),
+        ("bigint", "int", "-2147483649"),
+        ("int", "tinyint", "128"),
+        ("bigint", "smallint", "-32769"),
+        ("double", "int", "double('NaN')"),
+        ("double", "bigint", "double('Infinity')"),
+        ("double", "bigint", "1e20"),
+        ("double", "decimal(10,2)", "1e12"),
+        ("decimal(20,2)", "decimal(10,2)", "123456789012.34"),
+        ("decimal(20,2)", "int", "3000000000.5"),
+        ("struct<x: bigint>", "struct<x: int>", "named_struct('x', 
3000000000)"),
+        ("array<bigint>", "array<int>", "array(1, 3000000000)"),
+        ("map<bigint, bigint>", "map<int, int>", "map(3000000000, 1)"),
+        ("map<bigint, bigint>", "map<int, int>", "map(1, 3000000000)"))
+      overflows.foreach { case (sourceType, targetType, value) =>
+        withNarrowingTables(sourceType, targetType, Seq(value)) {
+          val error = assertInsertFailsAsSpark("c", nativeWriter)
+          assert(error.getErrorClass == "CAST_OVERFLOW_IN_TABLE_INSERT", error)
+        }
+      }
+
+      // Spark reports any arithmetic error under the cast as an overflow of 
the column.
+      withNarrowingTables("bigint", "int", Seq("1")) {
+        withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+          val error = assertInsertFailsAsSpark("c div 0", nativeWriter)
+          assert(error.getErrorClass == "CAST_OVERFLOW_IN_TABLE_INSERT", error)
+        }
+      }
+
+      // Other errors under the cast keep their class and query context.
+      withNarrowingTables("string", "int", Seq("'abc'")) {
+        withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+          val error = assertInsertFailsAsSpark("CAST(c AS BIGINT)", 
nativeWriter)
+          assert(error.getErrorClass == "CAST_INVALID_INPUT", error)
+          assert(error.getQueryContext.nonEmpty, error)
+        }
+      }
+    }
+
+    test(
+      s"a narrowing INSERT with a shared cast fails as Spark does (native 
writer: $nativeWriter)") {
+      // Subexpression elimination evaluates the cast that both columns share 
before the checks,
+      // so Spark reports the cast's own error unless it is off.
+      val cases = Seq(true -> "CAST_OVERFLOW", false -> 
"CAST_OVERFLOW_IN_TABLE_INSERT")
+      cases.foreach { case (eliminate, errorClass) =>
+        withNarrowingTables("bigint", "int, d int", Seq("3000000000")) {
+          withSQLConf(SQLConf.SUBEXPRESSION_ELIMINATION_ENABLED.key -> 
eliminate.toString) {
+            val error = assertInsertFailsAsSpark("c, c", nativeWriter)
+            assert(error.getErrorClass == errorClass, error)
+          }
+        }
+      }

Review Comment:
   Added a test for it. One thing: `c div 0, c div 0` into `int, d int` doesn't 
hit this case, because both columns get the same cast and that cast becomes the 
shared subexpression. Comet then sends it without the wrapper and matches 
Spark's `DIVIDE_BY_ZERO`. So the test writes into `int, d smallint`. It checks 
that Spark gives `DIVIDE_BY_ZERO`, gives `CAST_OVERFLOW_IN_TABLE_INSERT` with 
elimination off, and that Comet's error is the same as the second one. I also 
narrowed the guide entry to arithmetic errors, and the tests now assert that 
the check runs natively (or through the dispatcher for arrays and maps, where 
it sits inside `transform`).
   



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