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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -743,16 +743,32 @@ 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.
+  //       It is copied only when the replaced node has one with an origin: a 
node without a
+  //       context, such as a non-ANSI `Divide` that the analyzer turns into 
an interval
+  //       division, or with one built from an empty "Origin", would otherwise 
leave the
+  //       expression that replaces it, which raises in every mode, without a 
usable one.

Review Comment:
   nit: This comment is on the trait, so it covers every `SupportQueryContext` 
(`Cast`, `Sum`, `ElementAt`, ANSI arithmetic, ...), but "which raises in every 
mode" only holds for the interval expressions. Most of the others raise only 
under ANSI. How about scoping it to the example, e.g. "would otherwise leave 
the expression that replaces it, such as an interval division, which raises in 
every mode, without a usable one"?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/IntervalExpressionsSuite.scala:
##########
@@ -514,6 +519,79 @@ 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, 
TRY) or none (LEGACY).
+    val castContext = "== SQL (line 1, position 1) ==\ncast"
+    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 / -1BD")(DivideYMInterval(ymMin, Literal(Decimal(-1)))),
+      withQuery("ym / 0")(DivideYMInterval(ymMin, Literal(0))),
+      withQuery("dt / -1L")(DivideDTInterval(dtMin, Literal(-1L))),
+      withQuery("dt / -1BD")(DivideDTInterval(dtMin, Literal(Decimal(-1)))),
+      withQuery("dt / -1.0D")(DivideDTInterval(dtMin, Literal(-1.0d))),
+      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 (newExpr, context) =>
+      // Each form gets an instance of its own, since `copyTagsFrom` changes 
the instance that a
+      // rule returns, so that a failure tells which form lost the 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: the 
expression takes the
+      // context of an ANSI or a TRY cast, and keeps its own under a LEGACY 
cast, which has none,
+      // and under an ANSI cast built outside `withOrigin`, whose context has 
no origin.
+      val replacingCasts = Seq(
+        sameTypeCast(newExpr(), EvalMode.ANSI) -> castContext,
+        sameTypeCast(newExpr(), EvalMode.TRY) -> castContext,
+        sameTypeCast(newExpr(), EvalMode.LEGACY) -> context,
+        { val e = newExpr(); Cast(e, e.dataType, None, EvalMode.ANSI) } -> 
context
+      ).map { case (cast, expected) =>
+        val plan = Project(Seq(Alias(cast, "c")()), OneRowRelation())
+        SimplifyCasts(plan).expressions.head.children.head -> expected

Review Comment:
   nit: Nothing here checks that `SimplifyCasts` actually removed the cast. If 
it kept one, `.children.head` would be the `Cast` itself, and evaluating it 
would make the division raise with its own context. The LEGACY form and the 
ANSI form built outside `withOrigin` expect `context`, so they would still pass 
without testing the `copyTagsFrom` branches for a context that is missing or 
has no origin. Only the ANSI and TRY forms would fail. How about asserting that 
the result is not a `Cast`?
   
   ```scala
   val replaced = SimplifyCasts(plan).expressions.head.children.head
   assert(!replaced.isInstanceOf[Cast], s"SimplifyCasts kept $cast")
   replaced -> expected
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -743,16 +743,32 @@ 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.
+  //       It is copied only when the replaced node has one with an origin: a 
node without a
+  //       context, such as a non-ANSI `Divide` that the analyzer turns into 
an interval
+  //       division, or with one built from an empty "Origin", would otherwise 
leave the
+  //       expression that replaces it, which raises in every mode, without a 
usable one.
   override def copyTagsFrom(other: Expression): Unit = {
     other match {
-      case s: SupportQueryContext =>
+      case s: SupportQueryContext if 
s.queryContext.exists(SupportQueryContext.hasOrigin) =>
         queryContext = s.queryContext
       case _ =>
     }
     super.copyTagsFrom(other)
   }
 }
 
+object SupportQueryContext {
+  /**
+   * Whether `context` comes from an origin. A SQL context built from an empty 
"Origin" has no
+   * text and no start index. This test is O(1), unlike 
`SQLQueryContext.isValid`, which counts
+   * the code points of a text with supplementary characters, so it can run on 
every transform.

Review Comment:
   nit: `SQLQueryContext.isValid` calls `hasSupplementary(text)`, i.e. 
`text.codePointCount(0, text.length)`, every time, not only for a text with 
supplementary characters. That is O(1) only for a Latin-1 string. A text with 
any non-Latin-1 character, e.g. a CJK alias or comment, makes it O(L) even 
without supplementary characters. How about "unlike `SQLQueryContext.isValid`, 
which counts the code points of any non-Latin-1 text"?



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