parthchandra commented on code in PR #3580:
URL: https://github.com/apache/datafusion-comet/pull/3580#discussion_r2843561540


##########
spark/src/test/scala/org/apache/comet/CometCastSuite.scala:
##########
@@ -1526,20 +1553,11 @@ class CometCastSuite extends CometTestBase with 
AdaptiveSparkPlanHelper {
                 if (CometSparkSessionExtensions.isSpark40Plus) {
                   // for Spark 4 we expect to sparkException carries the 
message
                   assert(sparkMessage.contains("SQLSTATE"))
-                  if 
(sparkMessage.startsWith("[NUMERIC_VALUE_OUT_OF_RANGE.WITH_SUGGESTION]")) {
-                    assert(
-                      sparkMessage.replace(".WITH_SUGGESTION] ", 
"]").startsWith(cometMessage))
-                  } else if (cometMessage.startsWith("[CAST_INVALID_INPUT]") 
|| cometMessage
-                      .startsWith("[CAST_OVERFLOW]")) {
-                    assert(
-                      sparkMessage.startsWith(
-                        cometMessage
-                          .replace(
-                            "If necessary set \"spark.sql.ansi.enabled\" to 
\"false\" to bypass this error.",
-                            "")))
-                  } else {
-                    assert(sparkMessage.startsWith(cometMessage))
-                  }
+                  // we compare a subset of the error message. Comet grabs the 
query
+                  // context eagerly so it displays the call site at the
+                  // line of code where the cast method was called, whereas 
spark grabs the context
+                  // lazily and displays the call site at the line of code 
where the error is checked.
+                  assert(sparkMessage.startsWith(cometMessage.substring(0, 
40)))

Review Comment:
   I used 40 as an arbitrary number to get enough of the error message. There 
is no special significance.



##########
spark/src/main/spark-4.0/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.comet.shims
+
+import org.apache.spark.QueryContext
+import org.apache.spark.SparkException
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+
+/**
+ * Spark 4.0-specific implementation for converting error types to proper 
Spark exceptions.
+ */
+trait ShimSparkErrorConverter {
+
+  /**
+   * Convert error type string and parameters to appropriate Spark exception. 
Version-specific
+   * implementations call the correct QueryExecutionErrors.* methods.
+   *
+   * @param errorType
+   *   The error type from JSON (e.g., "DivideByZero")
+   * @param errorClass
+   *   The Spark error class (e.g., "DIVIDE_BY_ZERO")
+   * @param params
+   *   Error parameters from JSON
+   * @param context
+   *   QueryContext array with SQL text and position information
+   * @param summary
+   *   Formatted summary string showing error location
+   * @return
+   *   Throwable (specific exception type from QueryExecutionErrors), or None 
if unknown
+   */
+  def convertErrorType(
+      errorType: String,
+      _errorClass: String,
+      params: Map[String, Any],
+      context: Array[QueryContext],
+      _summary: String): Option[Throwable] = {
+
+    errorType match {
+
+      case "DivideByZero" =>
+        Some(QueryExecutionErrors.divideByZeroError(context.headOption.orNull))
+
+      case "RemainderByZero" =>
+        // SPARK 4.0 REMOVED remainderByZeroError  so we use generic 
arithmetic exception
+        Some(
+          new SparkException(
+            errorClass = "REMAINDER_BY_ZERO",
+            messageParameters = params.map { case (k, v) => (k, v.toString) },
+            cause = null))
+
+      case "IntervalDividedByZero" =>
+        
Some(QueryExecutionErrors.intervalDividedByZeroError(context.headOption.orNull))
+
+      case "BinaryArithmeticOverflow" =>
+        Some(
+          QueryExecutionErrors.binaryArithmeticCauseOverflowError(
+            params("value1").toString.toShort,

Review Comment:
   I believe that should not happen. The original Spark exception has these 
values declared as `short`.



##########
native/spark-expr/src/query_context.rs:
##########
@@ -0,0 +1,360 @@
+// 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.
+
+//! Query execution context for error reporting
+//!
+//! This module provides QueryContext which mirrors Spark's SQLQueryContext
+//! for providing SQL text, line/position information, and error location
+//! pointers in exception messages.
+
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+
+/// Based on Spark's SQLQueryContext for error reporting.
+///
+/// Contains information about where an error occurred in a SQL query,
+/// including the full SQL text, line/column positions, and object context.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct QueryContext {
+    /// Full SQL query text
+    #[serde(rename = "sqlText")]
+    pub sql_text: Arc<String>,
+
+    /// Start offset in SQL text (0-based, character index)
+    #[serde(rename = "startIndex")]
+    pub start_index: i32,
+
+    /// Stop offset in SQL text (0-based, character index, inclusive)
+    #[serde(rename = "stopIndex")]
+    pub stop_index: i32,
+
+    /// Object type (e.g., "VIEW", "Project", "Filter")
+    #[serde(rename = "objectType", skip_serializing_if = "Option::is_none")]
+    pub object_type: Option<String>,
+
+    /// Object name (e.g., view name, column name)
+    #[serde(rename = "objectName", skip_serializing_if = "Option::is_none")]
+    pub object_name: Option<String>,
+
+    /// Line number in SQL query (1-based)
+    pub line: i32,
+
+    /// Column position within the line (0-based)
+    #[serde(rename = "startPosition")]
+    pub start_position: i32,
+}
+
+impl QueryContext {
+    #[allow(clippy::too_many_arguments)]
+    pub fn new(
+        sql_text: String,
+        start_index: i32,
+        stop_index: i32,
+        object_type: Option<String>,
+        object_name: Option<String>,
+        line: i32,
+        start_position: i32,
+    ) -> Self {
+        Self {
+            sql_text: Arc::new(sql_text),
+            start_index,
+            stop_index,
+            object_type,
+            object_name,
+            line,
+            start_position,
+        }
+    }
+
+    /// Generate a summary string showing SQL fragment with error location.
+    /// (From SQLQueryContext.summary)
+    ///
+    /// Format example:
+    /// ```text
+    /// == SQL of VIEW v1 (line 1, position 8) ==
+    /// SELECT a/b FROM t
+    ///        ^^^
+    /// ```
+    pub fn format_summary(&self) -> String {
+        let start_idx = self.start_index.max(0) as usize;
+        let stop_idx = (self.stop_index + 1).max(0) as usize;
+
+        // Extract the problematic fragment
+        let fragment = if start_idx < self.sql_text.len() && stop_idx <= 
self.sql_text.len() {
+            &self.sql_text[start_idx..stop_idx]

Review Comment:
   Good catch. Fixed to use char index. Added a unit test



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