cloud-fan commented on code in PR #60611:
URL: https://github.com/apache/spark/pull/60611#discussion_r4632413794


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/WholeStageCodegenExec.scala:
##########
@@ -1245,6 +1245,10 @@ case class CollapseCodegenStages(
         // The children of SortMergeAsOfJoin should do codegen separately.
         j.withNewChildren(j.children.map(
           child => InputAdapter(insertWholeStageCodegen(child))))
+      case b: BinByExec =>

Review Comment:
   **Nit (P3):** No test fails if this case is lost. By my reading of the code, 
without it the generic `case p => 
p.withNewChildren(p.children.map(insertInputAdapter))` 
(WholeStageCodegenExec.scala:1252) keeps a codegen-capable child, such as the 
fusion test's ProjectExec over RangeExec, inside BIN BY's stage with no 
InputAdapter. BinByExec.doProduce never calls the child's `produce`; it reads 
`inputs[0]`, which `inputRDDs` fills with `child.execute()` 
(BinByExec.scala:95). So the child would run interpreted while the results and 
BIN BY's numOutputRows stay the same.
   
   The stage checks in 'BIN BY codegen fuses wide output and bin filtering' 
(BinBySuite.scala:614-615) only ask whether a FilterExec and a ProjectExec are 
among the stage's nodes, which still holds, and no other test looks at the 
boundary. An assertion that BIN BY's child in its stage is an InputAdapter over 
its own WholeStageCodegenExec would catch it.
   
   **Verification:**
   - **Regression:** With BIN BY codegen on, the fusion test's plan shows BIN 
BY's child behind an InputAdapter, the child's projection in a separate 
generated stage, and no RangeExec in BIN BY's stage, and the assertion fails if 
the BinByExec case in CollapseCodegenStages' stage-boundary rule 
(WholeStageCodegenExec.scala:1248-1251) is removed.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/BinByExec.scala:
##########
@@ -87,6 +89,127 @@ case class BinByExec(
   override protected def withNewChildInternal(newChild: SparkPlan): BinByExec =
     copy(child = newChild)
 
+  override def supportCodegen: Boolean = 
conf.getConf(SQLConf.ENABLE_BIN_BY_CODEGEN)
+
+  // BIN BY starts its generated stage and reads the child rows through an 
iterator.
+  override def inputRDDs(): Seq[RDD[InternalRow]] = child.execute() :: Nil
+
+  // The loop returns after each output row that reaches the stage output, so 
the row needs no copy.
+  override def needCopyResult: Boolean = false
+
+  // The bin loop reads the stage's input, so it stops at a LIMIT fused above 
it.
+  override protected def canCheckLimitNotReached: Boolean = true
+
+  /**
+   * Generates the bin loop. The current input row and the state of its next 
bin are fields, so the
+   * loop can return after any bin and continue with the next bin on the next 
call.
+   */
+  override protected def doProduce(ctx: CodegenContext): String = {
+    val input = ctx.addMutableState(
+      javaType = "scala.collection.Iterator",
+      variableName = "input",
+      initFunc = v => s"$v = inputs[0];",
+      forceInline = true
+    )
+    val row = ctx.addMutableState("InternalRow", "binByRow", forceInline = 
true)
+    val hasMoreBins =
+      ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "hasMoreBins", 
forceInline = true)
+    val nullRange = ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, 
"nullRange", forceInline = true)
+    val start = ctx.addMutableState(CodeGenerator.JAVA_LONG, "rangeStart", 
forceInline = true)
+    val end = ctx.addMutableState(CodeGenerator.JAVA_LONG, "rangeEnd", 
forceInline = true)
+    val total = ctx.addMutableState(CodeGenerator.JAVA_LONG, "total", 
forceInline = true)
+    val index = ctx.addMutableState(CodeGenerator.JAVA_LONG, "binIndex", 
forceInline = true)
+    val nextStart = ctx.addMutableState(CodeGenerator.JAVA_LONG, "nextStart", 
forceInline = true)
+    val binsSinceKillCheck =
+      ctx.addMutableState(CodeGenerator.JAVA_INT, "binsSinceKillCheck", 
forceInline = true)
+    val rsIdx = bindOrdinal(rangeStart)
+    val reIdx = bindOrdinal(rangeEnd)
+    val zone = 
timeZoneId.map(DateTimeUtils.getZoneId).getOrElse(ZoneOffset.UTC)
+    val zoneRef = ctx.addReferenceObj(
+      objName = "zoneId", obj = zone, className = classOf[ZoneId].getName)
+    val formatter = ctx.addReferenceObj(
+      objName = "formatter",
+      obj = TimestampFormatter.getFractionFormatter(zone),
+      className = classOf[TimestampFormatter].getName
+    )
+    val taskContext = ctx.addMutableState(
+      javaType = "TaskContext",
+      variableName = "taskContext",
+      initFunc = v => s"$v = TaskContext.get();",
+      forceInline = true
+    )
+    // The loop checks for a task kill every this many bins, across input rows.
+    val killCheckInterval = 1024
+    val dateTimeUtils = DateTimeUtils.getClass.getName.stripSuffix("$")
+    val errors = QueryExecutionErrors.getClass.getName.stripSuffix("$")
+    val bucket = ctx.freshName("bucket")
+    val binStart = ctx.freshName("binStart")
+    val binEnd = ctx.freshName("binEnd")
+    val ratio = ctx.freshName("ratio")
+    val numOutput = metricTerm(ctx, "numOutputRows")
+
+    val appended = Seq(binStart, binEnd, ratio).zip(appendedAttributes).map {
+      case (value, attr) =>
+        ExprCode(JavaCode.isNullGlobal(nullRange), JavaCode.variable(value, 
attr.dataType))
+    }
+    ctx.INPUT_ROW = row
+    ctx.currentVars = Seq.fill(child.output.length)(null) ++ appended
+    val outputVars = buildOutputExpressions(childLen = child.output.length, 
ratioNullable = true)
+      .map(_.genCode(ctx))
+
+    // The state of the next bin changes before `consume`, because the parent 
code can skip the
+    // rest of the loop body with `continue`.

Review Comment:
   **Nit (P3):** The CodegenSupport.doConsume contract says an operator must 
not assume an outer loop it can jump out of with `continue` 
(WholeStageCodegenExec.scala:343-344), and the fused parents follow it. 
FilterExec and aggregate FILTER clauses wrap their `continue` checks in `do { 
... } while (false)`, and LIMIT's doConsume is a plain `if`. So no parent skips 
the rest of this loop body, and the comment teaches maintainers the opposite of 
the contract. The code is right. What the ordering needs is for the next-bin 
state to be current when the stop check after `consume` (BinByExec.scala:208) 
returns, so the next call continues with the next bin.
   
   ```suggestion
       // The state of the next bin changes before `consume`, so it is current 
when the stop check
       // after `consume` returns and the next call continues with the next bin.
   ```
   
   **Verification:**
   - **Inspection:** The comment before the generated bin loop in 
BinByExec.doProduce gives a reason for updating the next-bin state before 
`consume` that agrees with the CodegenSupport.doConsume contract 
(WholeStageCodegenExec.scala:343-344), under which parent code never jumps out 
of a producer's loop with `continue`.



##########
sql/core/src/test/scala/org/apache/spark/sql/BinBySuite.scala:
##########
@@ -554,6 +579,231 @@ class BinBySuite extends QueryTest with 
SharedSparkSession {
     }
   }
 
+  gridTest("BIN BY codegen fuses wide output and bin filtering")(Seq(false, 
true)) { split =>
+    withSQLConf(
+        SQLConf.BIN_BY_ENABLED.key -> "true",
+        SQLConf.ENABLE_BIN_BY_CODEGEN.key -> "true",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC",
+        SQLConf.WHOLESTAGE_SPLIT_CONSUME_FUNC_BY_OPERATOR.key -> 
split.toString) {
+      withTempView("bin_by_codegen") {
+        spark.range(start = 0L, end = 1000L, step = 1L, numPartitions = 1)
+          .selectExpr(
+            "id",
+            "concat('payload-', id) AS payload",
+            "named_struct('ids', array(id, id + 1), 'label', concat('row-', 
id)) AS nested",
+            "TIMESTAMP '2024-01-01 00:02:00' AS ts_start",
+            "TIMESTAMP '2024-01-01 00:17:00' AS ts_end",
+            "CAST(id + 1 AS FLOAT) AS f",
+            "CAST(id * 2 + 1 AS DOUBLE) AS d")
+          .createOrReplaceTempView("bin_by_codegen")
+        val query =
+          """SELECT id, payload, nested, f, d, bin_start, bin_end, 
bin_distribute_ratio
+            |FROM bin_by_codegen BIN BY (
+            |  RANGE ts_start TO ts_end BIN WIDTH INTERVAL '5' MINUTE
+            |  ALIGN TO TIMESTAMP '2024-01-01 00:00:00' DISTRIBUTE UNIFORM (f, 
d))
+            |WHERE bin_start >= TIMESTAMP '2024-01-01 00:05:00'""".stripMargin
+        val expected = withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> 
"false") {
+          sql(query).collect().toSeq
+        }
+        assert(expected.length == 3000)
+        val generated = sql(query)
+        val plan = generated.queryExecution.executedPlan
+        val stage = binByCodegenStage(plan)
+          .getOrElse(fail(s"BIN BY was not code generated:\n$plan"))
+        assert(stageNodes(stage).exists(_.isInstanceOf[FilterExec]))
+        assert(stageNodes(stage).exists(_.isInstanceOf[ProjectExec]))
+        checkAnswer(generated, expected)
+        assert(stageNodes(stage).collectFirst {
+          case b: BinByExec => b.metrics("numOutputRows").value
+        }.contains(4000L))
+      }
+    }
+  }
+
+  gridTest("BIN BY codegen handles mixed null and zero-length 
ranges")(Seq(false, true)) {
+    codegen =>
+      withSQLConf(
+          SQLConf.BIN_BY_ENABLED.key -> "true",
+          SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC",
+          SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+        val df = sql(
+          """SELECT id, bin_start, bin_end, bin_distribute_ratio, f, d
+            |FROM VALUES
+            |  (1, NULL, TIMESTAMP '2024-01-01 00:10:00', 100.0F, 200.0D),
+            |  (2, TIMESTAMP '2024-01-01 00:00:00', NULL, 100.0F, 200.0D),
+            |  (3, TIMESTAMP '2024-01-01 00:02:00', TIMESTAMP '2024-01-01 
00:02:00',
+            |    100.0F, 200.0D),
+            |  (4, TIMESTAMP '2024-01-01 00:00:00', TIMESTAMP '2024-01-01 
00:10:00',
+            |    NULL, 200.0D),
+            |  (5, TIMESTAMP '2024-01-01 00:00:00', TIMESTAMP '2024-01-01 
00:10:00',
+            |    100.0F, NULL),
+            |  (6, NULL, NULL, 100.0F, 200.0D)
+            |  AS t(id, ts_start, ts_end, f, d)
+            |BIN BY (
+            |  RANGE ts_start TO ts_end BIN WIDTH INTERVAL '5' MINUTE
+            |  ALIGN TO TIMESTAMP '2024-01-01 00:00:00' DISTRIBUTE UNIFORM (f, 
d))
+            |""".stripMargin)
+        checkAnswer(df, Seq(
+          Row(1, null, null, null, null, null),
+          Row(2, null, null, null, null, null),
+          Row(3, tsAt("2024-01-01 00:00:00"), tsAt("2024-01-01 00:05:00"),
+            1.0, 100.0f, 200.0),
+          Row(4, tsAt("2024-01-01 00:00:00"), tsAt("2024-01-01 00:05:00"),
+            0.5, null, 100.0),
+          Row(4, tsAt("2024-01-01 00:05:00"), tsAt("2024-01-01 00:10:00"),
+            0.5, null, 100.0),
+          Row(5, tsAt("2024-01-01 00:00:00"), tsAt("2024-01-01 00:05:00"),
+            0.5, 50.0f, null),
+          Row(5, tsAt("2024-01-01 00:05:00"), tsAt("2024-01-01 00:10:00"),
+            0.5, 50.0f, null),
+          Row(6, null, null, null, null, null)))
+      }
+  }
+
+  test("BIN BY codegen preserves nondeterministic payloads across bins and 
under LIMIT") {
+    withSQLConf(
+        SQLConf.BIN_BY_ENABLED.key -> "true",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") {
+      withTempView("bin_by_codegen") {
+        spark.range(start = 0L, end = 100L, step = 1L, numPartitions = 1)
+          .selectExpr(
+            "id",
+            "rand(42) AS payload",
+            "TIMESTAMP '2024-01-01 00:00:00' AS ts_start",
+            "TIMESTAMP '2024-01-01 00:10:00' AS ts_end",
+            "100.0D AS value")
+          .createOrReplaceTempView("bin_by_codegen")
+        val query =
+          """SELECT id, payload, value, bin_start FROM bin_by_codegen BIN BY (
+            |  RANGE ts_start TO ts_end BIN WIDTH INTERVAL '5' MINUTE
+            |  ALIGN TO TIMESTAMP '2024-01-01 00:00:00' DISTRIBUTE UNIFORM 
(value))
+            |""".stripMargin
+        val expected = withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> 
"false") {
+          sql(query).collect().toSeq
+        }
+        checkAnswer(sql(query), expected)
+        assert(expected.groupBy(_.getLong(0)).values.forall { bins =>
+          bins.length == 2 && bins.map(_.getDouble(1)).distinct.length == 1
+        })
+        checkAnswer(sql(query).limit(5), expected.take(5))
+      }
+    }
+  }
+
+  gridTest("BIN BY stops expanding a row at a LIMIT in the same 
stage")(Seq(false, true)) {
+    codegen =>
+      withSQLConf(
+          SQLConf.BIN_BY_ENABLED.key -> "true",
+          SQLConf.ENABLE_BIN_BY_CODEGEN.key -> codegen.toString,
+          SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+          SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") {
+        // One input row spans 1000 one-minute bins. Both paths stop after the 
5 bins that the
+        // LIMIT takes.
+        val df = sql(
+          """SELECT count(*) FROM (
+            |  SELECT bin_start FROM VALUES
+            |    (TIMESTAMP '2024-01-01 00:00:00', TIMESTAMP '2024-01-01 
16:40:00', 100.0D)
+            |    AS t(ts_start, ts_end, value)
+            |  BIN BY (
+            |    RANGE ts_start TO ts_end BIN WIDTH INTERVAL '1' MINUTE
+            |    ALIGN TO TIMESTAMP '2024-01-01 00:00:00' DISTRIBUTE UNIFORM 
(value))
+            |  LIMIT 5)""".stripMargin)
+        checkAnswer(df, Row(5L))
+        val plan = df.queryExecution.executedPlan
+        assert(binByCodegenStage(plan).isDefined == codegen, plan)
+        val binBy = plan.collectFirst { case b: BinByExec => b }
+          .getOrElse(fail(s"No BinByExec in plan:\n$plan"))
+        assert(binBy.metrics("numOutputRows").value == 5L)
+      }
+  }
+
+  gridTest("BIN BY stops at a top-level LIMIT after the bins it 
returns")(Seq(false, true)) {
+    codegen =>
+      withSQLConf(
+          SQLConf.BIN_BY_ENABLED.key -> "true",
+          SQLConf.ENABLE_BIN_BY_CODEGEN.key -> codegen.toString,
+          SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+          SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") {
+        // One input row spans 1000 one-minute bins. The LIMIT runs outside 
the generated stage,
+        // so the bins go to the stage output.
+        val df = sql(
+          """SELECT bin_start FROM VALUES
+            |  (TIMESTAMP '2024-01-01 00:00:00', TIMESTAMP '2024-01-01 
16:40:00', 100.0D)
+            |  AS t(ts_start, ts_end, value)
+            |BIN BY (
+            |  RANGE ts_start TO ts_end BIN WIDTH INTERVAL '1' MINUTE
+            |  ALIGN TO TIMESTAMP '2024-01-01 00:00:00' DISTRIBUTE UNIFORM 
(value))
+            |LIMIT 20""".stripMargin)
+        assert(df.collect().length == 20)
+        val plan = df.queryExecution.executedPlan
+        assert(binByCodegenStage(plan).isDefined == codegen, plan)
+        val binBy = plan.collectFirst { case b: BinByExec => b }
+          .getOrElse(fail(s"No BinByExec in plan:\n$plan"))
+        assert(binBy.metrics("numOutputRows").value == 20L)
+      }
+  }
+
+  test("BIN BY returns the bins a LIMIT takes before a later bin boundary 
overflows") {
+    withSQLConf(SQLConf.BIN_BY_ENABLED.key -> "true") {
+      withTempView("bin_by_overflow") {
+        val rangeStart = DateTimeUtils.microsToLocalDateTime(Long.MaxValue - 
3L)
+        Seq((rangeStart, DateTimeUtils.microsToLocalDateTime(Long.MaxValue), 
1.0d))
+          .toDF("ts_start", "ts_end", "value")
+          .createOrReplaceTempView("bin_by_overflow")
+        // The end of the third bin is not representable. LIMIT 1 reads only 
the first bin.

Review Comment:
   **Nit (P3):** By the code's arithmetic, the third bin's end is 
representable. With one-microsecond bins aligned to -1 microseconds, the row's 
first bin index is Long.MaxValue - 2 
(DateTimeUtils.timeBucketFromTimestampDTInterval), the first two bins end at 
Long.MaxValue - 2 and Long.MaxValue - 1, and the third would end at -1 + 
(Long.MaxValue + 1) = Long.MaxValue, the row's own ts_end. What overflows is 
the index increment: `Math.addExact(index, 1L)` (BinByExec.scala:194), and 
`MathUtils.addExact(k, 1L)` on the iterator path, receive Long.MaxValue. 
Someone who adjusts this fixture would look for an unrepresentable boundary, 
and could change the data so the third bin no longer overflows; the test would 
then stop checking that a LIMIT avoids a later overflow.
   
   ```suggestion
           // Computing the third bin's end overflows the bin index. LIMIT 1 
reads only the first bin.
   ```
   
   **Verification:**
   - **Inspection:** The comment in the BinBySuite test 'BIN BY returns the 
bins a LIMIT takes before a later bin boundary overflows' says that computing 
the third bin's end overflows the bin index, which matches its data: 
one-microsecond bins from Long.MaxValue - 3 aligned to -1 microseconds, where 
the third bin needs index Long.MaxValue + 1 while its end, Long.MaxValue, is 
representable.



##########
sql/core/src/test/scala/org/apache/spark/sql/BinBySuite.scala:
##########
@@ -554,6 +579,231 @@ class BinBySuite extends QueryTest with 
SharedSparkSession {
     }
   }
 
+  gridTest("BIN BY codegen fuses wide output and bin filtering")(Seq(false, 
true)) { split =>
+    withSQLConf(
+        SQLConf.BIN_BY_ENABLED.key -> "true",
+        SQLConf.ENABLE_BIN_BY_CODEGEN.key -> "true",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC",
+        SQLConf.WHOLESTAGE_SPLIT_CONSUME_FUNC_BY_OPERATOR.key -> 
split.toString) {

Review Comment:
   **Nit (P3):** Neither grid case splits BIN BY's consume. `consume` moves a 
parent's code into its own method only when the parent uses every output of the 
producer (WholeStageCodegenExec.scala:207-212). Here BIN BY's parent is a 
FilterExec, whose `usedInputs` is empty, and the ProjectExec above it never 
reads ts_start or ts_end. So the '(true)' case generates the same BIN BY code 
as the '(false)' case; the conf only changes how the child stage's RangeExec 
feeds its ProjectExec.
   
   Now that BIN BY starts its own stage, its consume splits only under a parent 
that uses every BIN BY column, such as the partial aggregate of `SELECT 
DISTINCT *` over BIN BY. That path is on by default and passes BIN BY's per-bin 
values and the shared NULL-range flag as method arguments, and by my reading no 
BIN BY test compiles or runs it. Adding such a query to this grid, with a row 
whose range is NULL, would make the '(true)' case test it.
   
   **Verification:**
   - **Behavior:** With BIN BY codegen on, a query whose partial aggregate in 
BIN BY's generated stage uses every BIN BY output column, over rows that 
include a NULL range and multi-bin ranges, returns the same rows with consume 
splitting on and off as with whole-stage codegen off.
   - **Regression:** With consume splitting on, the generated code of that BIN 
BY stage has a separate consume method for the aggregate above BIN BY, and with 
splitting off it has none, so the two grid cases generate different code at BIN 
BY's consume.



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