akupchinskiy commented on code in PR #7813:
URL: https://github.com/apache/datafusion-comet/pull/7813#discussion_r4771639768


##########
spark/src/main/scala/org/apache/spark/sql/comet/CometWindowExec.scala:
##########
@@ -545,6 +581,29 @@ object CometWindowExec extends 
CometOperatorSerde[WindowExec] {
       case _ =>
     }
 
+    // Spark accepts a frame whose lower bound lies after its upper bound when 
one of them is
+    // CURRENT ROW, such as `2 FOLLOWING AND CURRENT ROW`, and evaluates every 
frame as empty.
+    // DataFusion computes a range whose start is past its end for it, and its 
sliding
+    // accumulator fails on that range. A NaN RANGE offset gives a bound Spark 
compares as the
+    // largest value, so a NaN lower bound also makes every frame empty, while 
the native frame
+    // computes a NaN bound and reaches the same reversed range.
+    f match {
+      case SpecifiedWindowFrame(_, lb, ub) if Seq(lb, ub).exists(isNaNBound) =>
+        withFallbackReason(
+          windowExpr,
+          s"Window frame with a NaN offset is not supported: ${lb.sql} AND 
${ub.sql}")
+        return None
+      case SpecifiedWindowFrame(_, lb, ub)
+          if (ub == CurrentRow && boundSignum(lb) > 0) ||
+            (lb == CurrentRow && boundSignum(ub) < 0) =>

Review Comment:
   Yep, 1 is fine, it just ends up as an empty range. Only 2+ goes wrong, so I 
limited the fallback to that and added a test for the offset 1 case.



##########
spark/src/main/scala/org/apache/spark/sql/comet/CometWindowExec.scala:
##########
@@ -43,6 +43,42 @@ object CometWindowExec extends 
CometOperatorSerde[WindowExec] {
   override def enabledConfig: Option[ConfigEntry[Boolean]] = Some(
     CometConf.COMET_EXEC_WINDOW_ENABLED)
 
+  // The sign Spark encodes the direction of a frame bound in: negative for 
PRECEDING, positive
+  // for FOLLOWING. 0 for CURRENT ROW, and for a bound this serde cannot 
evaluate, which it
+  // rejects when it serializes the bound.
+  private def boundSignum(bound: Expression): Int = bound match {

Review Comment:
   Oh right, rangeBoundLiteral already rejects those. Made it ROWS only and 
dropped boundSignum.



##########
spark/src/main/scala/org/apache/spark/sql/comet/CometWindowExec.scala:
##########
@@ -545,6 +581,29 @@ object CometWindowExec extends 
CometOperatorSerde[WindowExec] {
       case _ =>
     }
 
+    // Spark accepts a frame whose lower bound lies after its upper bound when 
one of them is
+    // CURRENT ROW, such as `2 FOLLOWING AND CURRENT ROW`, and evaluates every 
frame as empty.
+    // DataFusion computes a range whose start is past its end for it, and its 
sliding
+    // accumulator fails on that range. A NaN RANGE offset gives a bound Spark 
compares as the
+    // largest value, so a NaN lower bound also makes every frame empty, while 
the native frame
+    // computes a NaN bound and reaches the same reversed range.

Review Comment:
   You're right, I only thought about ASC there. The fallback still covers it 
but the comment was wrong, fixed it and added DESC to the test.



##########
spark/src/test/scala/org/apache/comet/exec/CometWindowExecSuite.scala:
##########
@@ -492,6 +492,75 @@ class CometWindowExecSuite extends CometTestBase {
     }
   }
 
+  test("window: frame with a lower bound after its upper bound falls back") {
+    // Spark accepts these because one bound is CURRENT ROW, and every frame 
is empty. DataFusion's
+    // sliding accumulator panicked on the reversed range ("attempt to 
subtract with overflow").
+    withTempDir { dir =>
+      withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") {
+        sql("""
+          SELECT CAST(id AS INT) AS i, timestamp_seconds(1735689600 + id * 
86400) AS ts,
+            date_add(DATE '2025-01-01', CAST(id AS INT)) AS d, CAST(id AS 
DOUBLE) AS x
+          FROM range(1, 4)
+        """).repartition(1).write.mode("overwrite").parquet(dir.toString)
+      }
+      withTempView("reversed") {
+        spark.read.parquet(dir.toString).createOrReplaceTempView("reversed")
+        withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") {
+          for ((column, frame) <- Seq(
+              "i" -> "RANGE BETWEEN 2 FOLLOWING AND CURRENT ROW",
+              "i" -> "RANGE BETWEEN CURRENT ROW AND 2 PRECEDING",
+              "i" -> "ROWS BETWEEN 2 FOLLOWING AND CURRENT ROW",
+              "i" -> "ROWS BETWEEN CURRENT ROW AND 2 PRECEDING",
+              "ts" -> "RANGE BETWEEN INTERVAL '1' DAY FOLLOWING AND CURRENT 
ROW",
+              "ts" -> "RANGE BETWEEN CURRENT ROW AND INTERVAL '1' DAY 
PRECEDING",
+              "d" -> "RANGE BETWEEN 1 FOLLOWING AND CURRENT ROW",
+              "d" -> "RANGE BETWEEN CURRENT ROW AND 1 PRECEDING",
+              "x" -> "RANGE BETWEEN CAST('Infinity' AS DOUBLE) FOLLOWING AND 
CURRENT ROW",
+              "x" -> "RANGE BETWEEN CURRENT ROW AND CAST('Infinity' AS DOUBLE) 
PRECEDING")) {
+            val df = sql(s"""
+              SELECT $column, COUNT(*) OVER (ORDER BY $column $frame) AS c,
+                SUM(i) OVER (ORDER BY $column $frame) AS s
+              FROM reversed
+            """)
+            val (_, cometPlan) = checkSparkAnswerAndFallbackReason(
+              df,
+              "Window frame with a lower bound after its upper bound is not 
supported")
+            assert(collect(cometPlan) { case w: CometWindowExec => w 
}.isEmpty, cometPlan)
+          }
+          // A NaN offset is neither before nor after CURRENT ROW for the sign 
check, and a NaN
+          // lower bound made the native frame fail the same way (Spark: empty 
frames).
+          for (frame <- Seq(
+              "RANGE BETWEEN CAST('NaN' AS DOUBLE) FOLLOWING AND CURRENT ROW",
+              "RANGE BETWEEN CAST('NaN' AS DOUBLE) PRECEDING AND CURRENT ROW",
+              "RANGE BETWEEN CURRENT ROW AND CAST('NaN' AS DOUBLE) FOLLOWING",
+              "RANGE BETWEEN 1 PRECEDING AND CAST('NaN' AS DOUBLE) 
FOLLOWING")) {
+            val df = sql(s"""
+              SELECT x, COUNT(*) OVER (ORDER BY x $frame) AS c, SUM(x) OVER 
(ORDER BY x $frame) AS s
+              FROM reversed
+            """)
+            val (_, cometPlan) = checkSparkAnswerAndFallbackReason(
+              df,
+              "Window frame with a NaN offset is not supported")
+            assert(collect(cometPlan) { case w: CometWindowExec => w 
}.isEmpty, cometPlan)
+          }
+          // A zero offset is not after CURRENT ROW, and an infinite offset in 
the right
+          // direction is an ordinary bound.
+          for ((column, frame) <- Seq(
+              "i" -> "RANGE BETWEEN 0 FOLLOWING AND CURRENT ROW",
+              "i" -> "RANGE BETWEEN CURRENT ROW AND 0 PRECEDING",
+              "i" -> "ROWS BETWEEN 0 FOLLOWING AND CURRENT ROW",
+              "x" -> "RANGE BETWEEN CAST('Infinity' AS DOUBLE) PRECEDING AND 
CURRENT ROW",
+              "x" -> "RANGE BETWEEN CURRENT ROW AND CAST('Infinity' AS DOUBLE) 
FOLLOWING",
+              "x" -> "RANGE BETWEEN CAST('-Infinity' AS DOUBLE) FOLLOWING AND 
CURRENT ROW")) {

Review Comment:
   Hadn't tried infinite keys, thanks. It now just falls back for any 
non-finite offset (NaN or ±Inf), and I added ±Inf keys to the test data.



##########
native/core/src/execution/planner/window.rs:
##########
@@ -524,6 +555,23 @@ impl PhysicalPlanner {
         };
 
         let window_frame = WindowFrame::new_bounds(units, lower_bound, 
upper_bound);
+        // Spark accepts a frame whose lower bound lies after its upper bound 
when one of them
+        // is CURRENT ROW, such as `2 FOLLOWING AND CURRENT ROW`, and 
evaluates every frame as
+        // empty. DataFusion computes a range whose start is past its end for 
it, and its
+        // sliding accumulator fails on that range, so refuse the frame here; 
the JVM side falls
+        // back to Spark before it gets this far.
+        if bound_is_nan(&window_frame.start_bound) || 
bound_is_nan(&window_frame.end_bound) {
+            return Err(GeneralError(format!(
+                "Window frame with a NaN offset is not supported: {} AND {}",
+                window_frame.start_bound, window_frame.end_bound
+            )));
+        }
+        if lower_bound_after_upper_bound(&window_frame.start_bound, 
&window_frame.end_bound) {
+            return Err(GeneralError(format!(
+                "Window frame lower bound {} lies after its upper bound {}",
+                window_frame.start_bound, window_frame.end_bound
+            )));
+        }

Review Comment:
   Agreed, removed the native guard and its planner test. The Scala fallback is 
the only check now.



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