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


##########
sql/core/src/test/scala/org/apache/spark/sql/BinBySuite.scala:
##########
@@ -838,3 +1000,9 @@ class BinBySuite extends QueryTest with SharedSparkSession 
{
     }
   }
 }
+
+/** Runs [[BinBySuite]] with BIN BY code-gen disabled, so BIN BY emits one bin 
at a time. */

Review Comment:
   **Nit (P3):** The subclass only changes the session default of 
`spark.sql.codegen.binBy.enabled`. Two inherited grid tests set the conf 
themselves: 'BIN BY codegen fuses wide output and bin filtering' forces it to 
true and asserts a generated BIN BY stage (BinBySuite.scala:580-582), and 'BIN 
BY stops expanding a row at a LIMIT in the same stage' runs both values 
(BinBySuite.scala:694-696). In this suite they run generated BIN BY exactly as 
in BinBySuite, so the doc overstates what the suite covers, and those cases add 
no iterator-path coverage.
   
   **Verification:**
   - **Inspection:** The codegen-off subclass excludes every BinBySuite test 
case that sets spark.sql.codegen.binBy.enabled itself, by its full name 
including each gridTest parameter suffix, and the subclass doc describes only 
the tests it still runs.
   - **Behavior:** Running BinByWithoutCodegenSuite reports each of those cases 
as ignored with the '(excluded)' suffix and runs the rest.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/BinByExec.scala:
##########
@@ -87,6 +89,116 @@ case class BinByExec(
   override protected def withNewChildInternal(newChild: SparkPlan): BinByExec =
     copy(child = newChild)
 
+  override def supportCodegen: Boolean = 
conf.getConf(SQLConf.ENABLE_BIN_BY_CODEGEN)
+
+  override def inputRDDs(): Seq[RDD[InternalRow]] = {
+    child.asInstanceOf[CodegenSupport].inputRDDs()
+  }
+
+  override protected def doProduce(ctx: CodegenContext): String = {
+    child.asInstanceOf[CodegenSupport].produce(ctx, this)
+  }
+
+  // Evaluate child expressions once per input row, before expanding it into 
bins.
+  override def usedInputs: AttributeSet = child.outputSet
+
+  // One input row makes many output rows, so each output row needs a copy.
+  override def needCopyResult: Boolean = true
+
+  // The bin loop stops at a LIMIT fused above it.
+  override protected def canCheckLimitNotReached: Boolean = true
+
+  override def doConsume(ctx: CodegenContext, input: Seq[ExprCode], row: 
ExprCode): String = {
+    val start = input(bindOrdinal(rangeStart))
+    val end = input(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
+    )
+    // A long expansion of one input row checks for a task kill every this 
many bins.
+    val killCheckInterval = 1024
+    val dateTimeUtils = DateTimeUtils.getClass.getName.stripSuffix("$")
+    val errors = QueryExecutionErrors.getClass.getName.stripSuffix("$")
+    val nullRange = ctx.freshName("nullRange")
+    val total = ctx.freshName("total")
+    val bucket = ctx.freshName("bucket")
+    val index = ctx.freshName("index")
+    val nextStart = ctx.freshName("nextStart")
+    val binStart = ctx.freshName("binStart")
+    val binEnd = ctx.freshName("binEnd")
+    val ratio = ctx.freshName("ratio")
+    val hasNext = ctx.freshName("hasNext")
+    val binsSinceKillCheck = ctx.freshName("binsSinceKillCheck")
+    val numOutput = metricTerm(ctx, "numOutputRows")
+
+    val appended = Seq(binStart, binEnd, ratio).zip(appendedAttributes).map {
+      case (value, attr) =>
+        ExprCode(JavaCode.isNullVariable(nullRange), JavaCode.variable(value, 
attr.dataType))
+    }
+    ctx.currentVars = input ++ appended
+    val outputVars = buildOutputExpressions(childLen = input.length, 
ratioNullable = true)
+      .map(_.genCode(ctx))
+
+    s"""
+       |boolean $nullRange = ${start.isNull} || ${end.isNull};
+       |long $total = 0L;
+       |long $index = 0L;
+       |long $nextStart = 0L;
+       |if (!$nullRange) {
+       |  if (${start.value} > ${end.value}) {
+       |    throw (RuntimeException) $errors.binByInvalidRangeError(
+       |      $formatter.format(${start.value}), 
$formatter.format(${end.value}));
+       |  }
+       |  try {
+       |    $total = java.lang.Math.subtractExact(${end.value}, 
${start.value});
+       |    scala.Tuple2 $bucket = 
$dateTimeUtils.timeBucketFromTimestampDTInterval(
+       |      ${binWidthMicros}L, ${start.value}, ${originMicros}L, $zoneRef);
+       |    $index = $bucket._1$$mcJ$$sp();
+       |    $nextStart = $bucket._2$$mcJ$$sp();
+       |  } catch (java.lang.ArithmeticException e) {
+       |    throw $errors.binByOverflowError();
+       |  }
+       |}
+       |boolean $hasNext = true;
+       |int $binsSinceKillCheck = 0;
+       |while ($limitNotReachedCond $hasNext) {

Review Comment:
   **Non-blocking (P2):** This loop emits every bin of the input row before it 
returns, and `supportCodegen` fuses BIN BY wherever it sits in the plan. So 
when the bins go to the stage output rather than to an operator that buffers 
its whole input, `WholeStageCodegenExec` appends a copy of each one to 
`BufferedRowIterator.currentRows` before the next operator reads any of them. 
That happens under a shuffle, a write, an aggregate without codegen such as 
`ObjectHashAggregateExec`, `collect`, and a top-level `LIMIT`, `show()`, 
`take()`, or `head()`, which run `CollectLimitExec` outside the stage. It also 
happens under a fused grouped partial aggregate when 
`spark.sql.execution.aggregate.adaptivePartialAggregation.enabled` is true, 
because that aggregate outputs pass-through rows from inside its `doConsume` 
(HashAggregateExec.scala:1274-1287). The iterator path streams one bin per pull.
   
   For one row spanning 30 days with one-second bins, about 2.6 million bins, 
the generated stage holds all of them as copied `UnsafeRow`s outside execution 
memory, where the base branch holds one, so a task can run out of memory. 
`SELECT * FROM t BIN BY (...) LIMIT 20` also expands and counts all of them to 
return 20 rows. The PR description cites `GenerateExec` and the join match 
loops, but their output per input row is bounded by data the task already 
holds, while a BIN BY row's bin count is bounded only by its range divided by 
the bin width.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/BinByExec.scala:
##########
@@ -87,6 +89,116 @@ case class BinByExec(
   override protected def withNewChildInternal(newChild: SparkPlan): BinByExec =
     copy(child = newChild)
 
+  override def supportCodegen: Boolean = 
conf.getConf(SQLConf.ENABLE_BIN_BY_CODEGEN)
+
+  override def inputRDDs(): Seq[RDD[InternalRow]] = {
+    child.asInstanceOf[CodegenSupport].inputRDDs()
+  }
+
+  override protected def doProduce(ctx: CodegenContext): String = {
+    child.asInstanceOf[CodegenSupport].produce(ctx, this)
+  }
+
+  // Evaluate child expressions once per input row, before expanding it into 
bins.
+  override def usedInputs: AttributeSet = child.outputSet
+
+  // One input row makes many output rows, so each output row needs a copy.
+  override def needCopyResult: Boolean = true
+
+  // The bin loop stops at a LIMIT fused above it.
+  override protected def canCheckLimitNotReached: Boolean = true
+
+  override def doConsume(ctx: CodegenContext, input: Seq[ExprCode], row: 
ExprCode): String = {
+    val start = input(bindOrdinal(rangeStart))
+    val end = input(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
+    )
+    // A long expansion of one input row checks for a task kill every this 
many bins.
+    val killCheckInterval = 1024
+    val dateTimeUtils = DateTimeUtils.getClass.getName.stripSuffix("$")
+    val errors = QueryExecutionErrors.getClass.getName.stripSuffix("$")
+    val nullRange = ctx.freshName("nullRange")
+    val total = ctx.freshName("total")
+    val bucket = ctx.freshName("bucket")
+    val index = ctx.freshName("index")
+    val nextStart = ctx.freshName("nextStart")
+    val binStart = ctx.freshName("binStart")
+    val binEnd = ctx.freshName("binEnd")
+    val ratio = ctx.freshName("ratio")
+    val hasNext = ctx.freshName("hasNext")
+    val binsSinceKillCheck = ctx.freshName("binsSinceKillCheck")
+    val numOutput = metricTerm(ctx, "numOutputRows")
+
+    val appended = Seq(binStart, binEnd, ratio).zip(appendedAttributes).map {
+      case (value, attr) =>
+        ExprCode(JavaCode.isNullVariable(nullRange), JavaCode.variable(value, 
attr.dataType))
+    }
+    ctx.currentVars = input ++ appended
+    val outputVars = buildOutputExpressions(childLen = input.length, 
ratioNullable = true)
+      .map(_.genCode(ctx))
+
+    s"""
+       |boolean $nullRange = ${start.isNull} || ${end.isNull};
+       |long $total = 0L;
+       |long $index = 0L;
+       |long $nextStart = 0L;
+       |if (!$nullRange) {
+       |  if (${start.value} > ${end.value}) {
+       |    throw (RuntimeException) $errors.binByInvalidRangeError(
+       |      $formatter.format(${start.value}), 
$formatter.format(${end.value}));
+       |  }
+       |  try {
+       |    $total = java.lang.Math.subtractExact(${end.value}, 
${start.value});
+       |    scala.Tuple2 $bucket = 
$dateTimeUtils.timeBucketFromTimestampDTInterval(
+       |      ${binWidthMicros}L, ${start.value}, ${originMicros}L, $zoneRef);
+       |    $index = $bucket._1$$mcJ$$sp();
+       |    $nextStart = $bucket._2$$mcJ$$sp();
+       |  } catch (java.lang.ArithmeticException e) {
+       |    throw $errors.binByOverflowError();
+       |  }
+       |}
+       |boolean $hasNext = true;
+       |int $binsSinceKillCheck = 0;
+       |while ($limitNotReachedCond $hasNext) {
+       |  if (++$binsSinceKillCheck == $killCheckInterval) {

Review Comment:
   **Nit (P3):** No test reaches this branch. The largest single-row expansion 
under codegen is the 1000-bin row in 'BIN BY stops expanding a row at a LIMIT 
in the same stage', which stops after 5 bins, and no test cancels a BIN BY job. 
If the check were dropped, or the counter reset broke, a cancelled task would 
keep expanding a long row while every test in BinBySuite and 
BinByWithoutCodegenSuite still passed. `DataFrameRangeSuite`'s 'Cancelling 
stage in a query with Range.' covers the equivalent check in `RangeExec`.
   
   **Verification:**
   - **Behavior:** With BIN BY codegen on and BIN BY feeding an aggregate in 
its stage, one input row that expands into more than 1024 bins runs BIN BY in a 
generated stage and returns the same results and numOutputRows as the run 
without whole-stage codegen.
   - **Regression:** With BIN BY codegen on, cancelling the stage of an 
ungrouped count over a BIN BY row that expands into an effectively unbounded 
number of bins makes the job fail as cancelled and leaves no task running. 
Removing the kill check from the generated loop makes this test fail.



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