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


##########
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:
   This serde is not about `Cast` and now needs `isSharedSubexpression` 
imported back from `QueryPlanSerde`. The other internal-wrapper serdes live in 
`org.apache.comet.serde`, for example `CometCheckOverflow` in `math.scala` and 
`CometMakeDecimal` in `decimalExpressions.scala`. Moving it next to 
`CometCheckOverflow` keeps `CometCast.scala` to the cast and drops the new 
import line.



##########
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:
   I checked the shared-cast claim in `v3.5.8`, `v4.0.1` and `v4.1.1`. 
`ProjectExec.doConsume` emits `subExprsCode` before the output expressions, so 
in generated code the shared `Cast` throws `CAST_OVERFLOW` outside the `try` in 
`CheckOverflowInTableInsert.doGenCode`. The detection also uses Spark's own 
`EquivalentExpressions` on `op.expressions`, so two equal casts count as shared 
exactly when Spark shares them, and it is false outside 
`withSharedSubexpressions` or with the conf off. One gap, from reading the 
source and not run: `getCast` also matches `ExpressionProxy(c: Cast, ...)`. 
When a projection runs interpreted (`InterpretedUnsafeProjection` after a 
codegen fallback, or `spark.sql.codegen.factoryMode=NO_CODEGEN`), the proxy is 
evaluated inside `eval`'s `try`, so Spark still reports 
`CAST_OVERFLOW_IN_TABLE_INSERT` for `SELECT c, c` while Comet now reports 
`CAST_OVERFLOW`. That is a rare path, but the PR description and the doc 
comment say Comet reports what Spark does, so say
  "in generated code" there.



##########
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:
   The compatibility guide documents a different case: an expression below the 
cast that the projection repeats, where Spark reports the inner error (for 
example `DIVIDE_BY_ZERO`) and Comet reports `CAST_OVERFLOW_IN_TABLE_INSERT`. No 
test pins that, so a later change to `isSharedSubexpression` or to 
`EquivalentExpressions` handling would move it unnoticed. A case like `SELECT c 
div 0, c div 0` under `ANSI_ENABLED=true` into `int, d int` that asserts the 
Comet-side class would keep the doc and the behavior tied together.



##########
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:
   I could not find JVM code that throws 
`org.apache.spark.sql.comet.CastOverflowException` as a Java exception. `git 
grep CastOverflowException` shows only the class definition and the native 
`exception_class()` mapping, so it is created from native errors on the way 
out, and JVM-side Spark codegen throws plain `SparkArithmeticException`. This 
branch, plus the new public `SparkError::is_arithmetic_exception_class` and the 
per-error `class.replace('.', "/")` allocation, therefore looks unreachable. 
The unit tests cannot cover it either, because a `CometError::JavaException` 
needs a JVM `Global` reference, and the Scala test only reaches the 
`SparkArithmeticException` case. If there is a path that nests native, JVM and 
native so the class does arrive here, please add a test for it. If not, I would 
drop this commit and keep the exact `SparkArithmeticException` comparison.



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