dongjoon-hyun commented on code in PR #60285:
URL: https://github.com/apache/spark/pull/60285#discussion_r4532502769


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -699,14 +699,23 @@ trait SupportQueryContext extends Expression with 
Serializable {
   //       empty "Origin" during rule transforms since "Origin"s are not 
serialized to executors
   //       for better performance. Thus, we need to copy the original query 
context during
   //       transforms. The query context string is considered as a "tag" on 
the expression here.
+  //       Like the tags of `TreeNode.copyTagsFrom`, it is copied only when 
this expression has
+  //       no context of its own: `None`, or one regenerated from an empty 
"Origin". A rule that
+  //       replaces a node with an existing expression, such as a child, then 
keeps the context
+  //       of the expression that raises the error instead of taking the 
context of the node.
   override def copyTagsFrom(other: Expression): Unit = {
     other match {
-      case s: SupportQueryContext =>
+      case s: SupportQueryContext if !hasOwnQueryContext =>
         queryContext = s.queryContext
       case _ =>
     }
     super.copyTagsFrom(other)
   }
+
+  private def hasOwnQueryContext: Boolean = queryContext.exists {
+    case c: SQLQueryContext => c.isValid
+    case _ => true

Review Comment:
   The new rule applies to every `SupportQueryContext` expression (ANSI `Add`, 
`Cast`, `Sum`, `ElementAt`, ...) and to `DataFrameQueryContext` (the `case _ => 
true` branch), but the new tests cover only the interval expressions. For 
example:
   
   - SQL in ANSI mode with `c INT`: for `SELECT CAST(c + 2147483647 AS INT) 
FROM t`, the `ARITHMETIC_OVERFLOW` fragment changes from `CAST(c + 2147483647 
AS INT)` to `c + 2147483647`.
   - DataFrame API in ANSI mode: for `(col("a") / 0).cast("double")`, the 
fragment changes from the `cast` call site to the division call site.
   
   These are user-visible changes. Could you add regression tests that pin down 
this behavior?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -699,14 +699,23 @@ trait SupportQueryContext extends Expression with 
Serializable {
   //       empty "Origin" during rule transforms since "Origin"s are not 
serialized to executors
   //       for better performance. Thus, we need to copy the original query 
context during
   //       transforms. The query context string is considered as a "tag" on 
the expression here.
+  //       Like the tags of `TreeNode.copyTagsFrom`, it is copied only when 
this expression has
+  //       no context of its own: `None`, or one regenerated from an empty 
"Origin". A rule that
+  //       replaces a node with an existing expression, such as a child, then 
keeps the context
+  //       of the expression that raises the error instead of taking the 
context of the node.
   override def copyTagsFrom(other: Expression): Unit = {
     other match {
-      case s: SupportQueryContext =>
+      case s: SupportQueryContext if !hasOwnQueryContext =>
         queryContext = s.queryContext
       case _ =>
     }
     super.copyTagsFrom(other)
   }
+
+  private def hasOwnQueryContext: Boolean = queryContext.exists {
+    case c: SQLQueryContext => c.isValid

Review Comment:
   `SQLQueryContext.isValid` is a `def`, and it calls `hasSupplementary(text)`, 
i.e. `text.codePointCount(0, text.length)`. This is O(1) for a Latin-1 string, 
but O(L) once the SQL text contains any non-Latin-1 character (e.g. a CJK alias 
or comment), because the `String` is then stored as UTF-16.
   
   Since `copyTagsFrom` runs on every `withNewChildren` / `mapChildren` / 
`transform` / `makeCopy` of a `SupportQueryContext` node (ANSI `Add`, `Cast`, 
`Sum`, ...), this adds O(N * R * L) character scans to analysis and 
optimization of large generated SQL, where it was O(1) before.
   
   Could we make this check O(1)? For example, cache the validity in 
`SQLQueryContext` as a `lazy val`, or check only `sqlText.isDefined && 
originStartIndex.isDefined`, which is enough to filter out the all-`None` 
context regenerated from an empty `Origin` on executors.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/intervalExpressions.scala:
##########
@@ -733,10 +733,17 @@ case class MultiplyDTInterval(
  * The division of an interval by a number. The interpreted path and the 
generated code both call
  * the `IntervalMathUtils.divide` overload for the interval type and the kind 
of the divisor, which
  * holds the checks and the error, so that the two paths cannot drift apart.
+ *
+ * The division raises on overflow and on a zero divisor in every mode, so it 
always keeps the

Review Comment:
   nit: "it always keeps the query context" does not hold in one case. When its 
own context is invalid (e.g. built under an empty `CurrentOrigin`, or with 
`spark.sql.dataFrameQueryContext.enabled=false`), `copyTagsFrom` copies `None` 
from a replaced non-ANSI node, and `getContextOrNull()` returns `null`. Then 
`getQueryContext(null)` returns an empty array, while before this PR the 
exception had one (empty) `SQLQueryContext`.
   
   Could we adjust the wording, or handle this case?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/IntervalExpressionsSuite.scala:
##########
@@ -514,6 +517,67 @@ class IntervalExpressionsSuite extends SparkFunSuite with 
ExpressionEvalHelper {
     }
   }
 
+  test("SPARK-61352: an interval error keeps its query context") {
+    // The helpers evaluate a serialized copy of the expression, as an 
executor does. `TreeNode`
+    // does not serialize `origin`, so the copy must carry the context itself. 
Each expression is
+    // built inside `withOrigin` and evaluated outside it: evaluated inside, 
the copy would read
+    // the origin back from `CurrentOrigin` and the test could not fail.
+    def withQuery(query: String)(expr: => Expression): (Expression, String) = {
+      val o = Origin(
+        line = Some(1),
+        startPosition = Some(7),
+        startIndex = Some(7),
+        stopIndex = Some(7 + query.length - 1),
+        sqlText = Some(s"select $query"))
+      (withOrigin(o)(expr), s"== SQL (line 1, position 8) ==\nselect $query")
+    }
+    // A cast to the type of the expression, with a context of its own (ANSI) 
or none (LEGACY).
+    def sameTypeCast(expr: Expression, evalMode: EvalMode.Value): Expression = 
{
+      val o = Origin(
+        line = Some(1),
+        startPosition = Some(0),
+        startIndex = Some(0),
+        stopIndex = Some(3),
+        sqlText = Some("cast"))
+      withOrigin(o)(Cast(expr, expr.dataType, None, evalMode))
+    }
+    val ser = new JavaSerializer(new SparkConf()).newInstance()
+
+    val ymMin = Literal(Period.ofMonths(Int.MinValue))
+    val dtMin = Literal(Duration.of(Long.MinValue, ChronoUnit.MICROS))
+    Seq(
+      withQuery("ym / -1")(DivideYMInterval(ymMin, Literal(-1))),
+      withQuery("ym / -1.0D")(DivideYMInterval(ymMin, Literal(-1.0d))),
+      withQuery("ym / 0")(DivideYMInterval(ymMin, Literal(0))),
+      withQuery("dt / -1L")(DivideDTInterval(dtMin, Literal(-1L))),
+      withQuery("dt / -1BD")(DivideDTInterval(dtMin, Literal(Decimal(-1)))),
+      withQuery("dt / 0")(DivideDTInterval(dtMin, Literal(0))),
+      withQuery("make_ym_interval(2147483647, 0)")(
+        MakeYMInterval(Literal(Int.MaxValue), Literal(0))),
+      withQuery("make_dt_interval(2147483647)")(
+        MakeDTInterval(Literal(Int.MaxValue), Literal(0), Literal(0),
+          Literal(Decimal(0, Decimal.MAX_LONG_DIGITS, 6))))
+    ).foreach { case (expr, context) =>
+      // A rule that replaces a node calls `copyTagsFrom` on the replacement, 
as `SimplifyCasts`
+      // does when it replaces a cast to the same type with its child.
+      val replacingCasts = Seq(EvalMode.ANSI, EvalMode.LEGACY).map { evalMode 
=>

Review Comment:
   The rule returns `child`, which is the same instance as `expr`, and 
`copyTagsFrom` mutates `expr` in place before `rebuilt` serializes it (line 
570). So the forms are not independent: if `copyTagsFrom` regresses to an 
unconditional overwrite, `transformDown` sets the context of `expr` itself to 
`cast` or `None`, and `expr`, `rebuilt`, and both `replacingCasts` fail 
together. This makes it hard to tell which path regressed.
   
   Could we build a fresh instance for each form, e.g. by passing a factory 
instead of `expr`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/intervalExpressions.scala:
##########
@@ -733,10 +733,17 @@ case class MultiplyDTInterval(
  * The division of an interval by a number. The interpreted path and the 
generated code both call
  * the `IntervalMathUtils.divide` overload for the interval type and the kind 
of the divisor, which
  * holds the checks and the error, so that the two paths cannot drift apart.
+ *
+ * The division raises on overflow and on a zero divisor in every mode, so it 
always keeps the
+ * query context. It keeps it as a `SupportQueryContext` field rather than 
reading `origin` when
+ * it evaluates: `origin` is not serialized, so a copy of the expression 
deserialized on an
+ * executor, where an interpreted or a non-whole-stage projection is built, 
has an empty one.
  */
-trait IntervalDivide extends BinaryExpression {
+trait IntervalDivide extends BinaryExpression with SupportQueryContext {

Review Comment:
   `MultiplyYMInterval` / `MultiplyDTInterval` in the same file still call 
`Math.multiplyExact` / `Math.toIntExact` directly, so an overflow raises a 
plain `java.lang.ArithmeticException` without an error condition or a query 
context in every mode, e.g. `SELECT interval 2147483647 month * 2` (see 
`interval.sql.out`). `IntervalMathUtils.add` / `subtract` / `negate` also pass 
`null` as the context.
   
   Shall we apply the same mechanism (`IntervalMathUtils` + the 
`SupportQueryContext` field) to these sibling operators, here or in a follow-up 
JIRA?



##########
sql/core/src/test/scala/org/apache/spark/sql/errors/QueryExecutionErrorsSuite.scala:
##########
@@ -843,6 +843,53 @@ class QueryExecutionErrorsSuite
     }
   }
 
+  test("SPARK-61352: an interval error keeps its query context in non-ANSI 
mode") {
+    // The division and the `make_*_interval` functions raise in every mode. 
Without whole-stage
+    // codegen the projection is built on the executor from a deserialized 
copy of the expression.
+    // The expressions read a column, so that they are not constant-folded on 
the driver.
+    // `SimplifyCasts` replaces a cast to the type of the expression with the 
expression, which
+    // keeps its own context although the non-ANSI cast has none.
+    def expectedContext(query: String, fragment: String): ExpectedContext = {

Review Comment:
   nit: `expectedContext` and the `ymDivide` / `dtDivide` queries duplicate 
`QueryExecutionAnsiErrorsSuite` (lines 123-128). Could we move them to a shared 
test helper so that the two suites don't drift apart?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -699,14 +699,23 @@ trait SupportQueryContext extends Expression with 
Serializable {
   //       empty "Origin" during rule transforms since "Origin"s are not 
serialized to executors
   //       for better performance. Thus, we need to copy the original query 
context during
   //       transforms. The query context string is considered as a "tag" on 
the expression here.
+  //       Like the tags of `TreeNode.copyTagsFrom`, it is copied only when 
this expression has
+  //       no context of its own: `None`, or one regenerated from an empty 
"Origin". A rule that
+  //       replaces a node with an existing expression, such as a child, then 
keeps the context
+  //       of the expression that raises the error instead of taking the 
context of the node.
   override def copyTagsFrom(other: Expression): Unit = {
     other match {
-      case s: SupportQueryContext =>
+      case s: SupportQueryContext if !hasOwnQueryContext =>

Review Comment:
   This seems to change the error context of a SQL UDF body, which is not 
mentioned in the PR description. If I read the code correctly:
   
   - `SessionCatalog.makeSQLFunctionPlan` wraps the body as `Cast(body, 
returnType)`, and this `Cast` is built under `withOrigin(f.origin)` 
(`Analyzer.scala`, around line 2994), so it carries the call-site context.
   - For `CREATE FUNCTION foo(x INT) RETURNS DOUBLE RETURN 1 / x` and `SELECT 
foo(c) FROM t` with `c = 0` (a non-foldable argument), `SimplifyCasts` removes 
the same-type `Cast`.
   - Before this PR, the `Divide` took the context of the `Cast` (fragment 
`foo(c)` in the user query). With this PR, it keeps its own context (fragment 
`1 / x`, indexed into the function body text), so the `== SQL ==` block would 
show the function body instead of the user query.
   
   The existing golden files don't show this because the constant-argument 
cases fail earlier in `ConstantFolding`. Is this intended? If so, could you 
mention it in the PR description and add a test for it?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -699,14 +699,23 @@ trait SupportQueryContext extends Expression with 
Serializable {
   //       empty "Origin" during rule transforms since "Origin"s are not 
serialized to executors
   //       for better performance. Thus, we need to copy the original query 
context during
   //       transforms. The query context string is considered as a "tag" on 
the expression here.
+  //       Like the tags of `TreeNode.copyTagsFrom`, it is copied only when 
this expression has
+  //       no context of its own: `None`, or one regenerated from an empty 
"Origin". A rule that
+  //       replaces a node with an existing expression, such as a child, then 
keeps the context
+  //       of the expression that raises the error instead of taking the 
context of the node.
   override def copyTagsFrom(other: Expression): Unit = {
     other match {
-      case s: SupportQueryContext =>
+      case s: SupportQueryContext if !hasOwnQueryContext =>
         queryContext = s.queryContext
       case _ =>
     }
     super.copyTagsFrom(other)
   }
+
+  private def hasOwnQueryContext: Boolean = queryContext.exists {

Review Comment:
   This duplicates the filter in `Origin.getQueryContext` 
(`sql/api/.../trees/origin.scala`):
   
   ```scala
   Some(context).filter {
     case s: SQLQueryContext => s.isValid
     case _ => true
   }
   ```
   
   If the definition of a reportable context changes in only one place later, 
analysis-time errors and `copyTagsFrom` will disagree. How about a shared 
helper in `sql/api` that both use?



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