sarutak commented on code in PR #60366:
URL: https://github.com/apache/spark/pull/60366#discussion_r4624964283


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/conditionalExpressions.scala:
##########
@@ -141,6 +141,132 @@ case class If(predicate: Expression, trueValue: 
Expression, falseValue: Expressi
   )
 }
 
+/**
+ * Returns `child` when `condition` evaluates to true, and null otherwise, like
+ * `IF(condition, child, NULL)`. Unlike `If`, it also tells the operators that 
evaluate Python
+ * and external UDFs outside the expression tree (see `ExtractPythonUDFs` and
+ * `PlanExternalUDFs`) to evaluate a UDF inside `child` only for the rows 
where `condition` is
+ * true, so a UDF in a branch that a row does not take is not called for that 
row.
+ *
+ * The marker's `condition` is normally deterministic, so the operator can 
evaluate it again to
+ * decide which rows to send to the UDF. If it is not deterministic, the 
operator falls back to
+ * evaluating the UDF for every row (see `udfConditions`).
+ */
+case class EvalOnlyWhen(condition: Expression, child: Expression)
+  extends BinaryExpression with ConditionalExpression {
+
+  override def left: Expression = condition
+  override def right: Expression = child
+  override def dataType: DataType = child.dataType
+  override def nullable: Boolean = true
+
+  override def alwaysEvaluatedInputs: Seq[Expression] = condition :: Nil
+
+  override def withNewAlwaysEvaluatedInputs(
+      alwaysEvaluatedInputs: Seq[Expression]): EvalOnlyWhen = {
+    copy(condition = alwaysEvaluatedInputs.head)
+  }
+
+  // `child` is not always evaluated, and there is no other branch.
+  override def branchGroups: Seq[Seq[Expression]] = Nil
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    if (condition.dataType != BooleanType) {
+      DataTypeMismatch(
+        errorSubClass = "UNEXPECTED_INPUT_TYPE",
+        messageParameters = Map(
+          "paramIndex" -> ordinalNumber(0),
+          "requiredType" -> toSQLType(BooleanType),
+          "inputSql" -> toSQLExpr(condition),
+          "inputType" -> toSQLType(condition.dataType)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  override def eval(input: InternalRow): Any = {
+    if (java.lang.Boolean.TRUE.equals(condition.eval(input))) 
child.eval(input) else null
+  }
+
+  override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+    val condEval = condition.genCode(ctx)
+    val childEval = child.genCode(ctx)
+    val code =
+      code"""
+         |${condEval.code}
+         |boolean ${ev.isNull} = true;
+         |${CodeGenerator.javaType(dataType)} ${ev.value} = 
${CodeGenerator.defaultValue(dataType)};
+         |if (!${condEval.isNull} && ${condEval.value}) {
+         |  ${childEval.code}
+         |  ${ev.isNull} = ${childEval.isNull};
+         |  ${ev.value} = ${childEval.value};
+         |}
+       """.stripMargin
+    ev.copy(code = code)
+  }
+
+  override def toString: String = s"eval_only_when($condition, $child)"
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EVAL_ONLY_WHEN)
+
+  override def sql: String = s"(IF(${condition.sql}, ${child.sql}, NULL))"
+
+  override protected def withNewChildrenInternal(
+      newLeft: Expression, newRight: Expression): EvalOnlyWhen =
+    copy(condition = newLeft, child = newRight)
+}
+
+object EvalOnlyWhen {
+  /**
+   * Whether `e` contains a scalar Python UDF or an external UDF that the 
operators evaluating
+   * those UDFs lift out of a conditional branch (see `ExtractPythonUDFs` and 
`PlanExternalUDFs`),
+   * so that wrapping the branch in an `EvalOnlyWhen` marker changes when the 
UDF is evaluated.
+   * This applies the same scalar/external test those operators use, so a 
marker is added only
+   * when one of them will read it.
+   */
+  def hasLiftedUDF(e: Expression): Boolean =
+    e.containsAnyPattern(PYTHON_UDF, EXTERNAL_UDF) &&
+      e.exists(x => PythonUDF.isScalarPythonUDF(x) || 
x.isInstanceOf[ExternalUserDefinedFunction])
+
+  /**
+   * The condition under which the UDFs in `exprs` need to be evaluated, for 
each UDF that
+   * `isUDF` selects, keyed by `key`: the conjunction of the deterministic 
conditions of the
+   * enclosing `EvalOnlyWhen` markers, or None if some occurrence of the UDF 
is not inside a
+   * marker (or the occurrences' conditions differ). Returns an empty map when 
`exprs` contain
+   * no marker.
+   */
+  def udfConditions[K](
+      exprs: Seq[Expression],
+      isUDF: Expression => Boolean,
+      key: Expression => K): Map[K, Option[Expression]] = {
+    if (!exprs.exists(_.containsPattern(EVAL_ONLY_WHEN))) {
+      return Map.empty
+    }
+    val result = scala.collection.mutable.LinkedHashMap.empty[K, 
Option[Expression]]
+    def visit(e: Expression, cond: Option[Expression]): Unit = e match {
+      case EvalOnlyWhen(c, child) =>
+        visit(c, cond)
+        // A nested marker needs both conditions; keep it deterministic so the 
operator can
+        // re-evaluate it. If not, fall back to the outer condition (more 
rows, never fewer).
+        val inner = if (!c.deterministic) cond
+          else Some(cond.filter(_.deterministic).map(And(_, c)).getOrElse(c))

Review Comment:
   Done. Dropped the no-op `cond.filter(_.deterministic)`; it is now 
`cond.map(And(_, c)).getOrElse(c)`, and I adjusted the comment so it no longer 
implies a non-deterministic outer condition can reach that point.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/ConditionalUDFEvaluation.scala:
##########
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution
+
+import java.io.File
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.atomic.AtomicLong
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, 
GenericInternalRow,
+  JoinedRow, Predicate, UnsafeProjection}
+import org.apache.spark.sql.execution.python.HybridRowQueue
+import org.apache.spark.util.Utils
+
+/**
+ * Evaluates UDFs only for the input rows where a deterministic condition is 
true (see
+ * `EvalOnlyWhen`). The rows where it is false are not passed to `evaluate`; 
they are returned,
+ * in their input order among the evaluated rows, with null results (which an 
enclosing `if`
+ * reading the condition does not use).
+ *
+ * The leading run of skipped rows, before the first row that needs the UDF, 
is streamed directly
+ * and `evaluate` is not called for it, so a partition whose rows all skip the 
UDF (e.g. every
+ * outer row of a COUNT-bug subquery has matching inner rows) streams without 
buffering and
+ * without starting a UDF worker. Once a row needs the UDF, the rest of the 
partition is evaluated
+ * through `evaluate`, buffering (spilling to disk if needed) the skipped rows 
between evaluated
+ * ones to restore input order. `evaluate` sends rows to the UDF in batches, 
so a skipped row is
+ * held until the batch holding the next row that needs the UDF has been 
answered; the skipped
+ * rows after the last such row are held until the partition's input ends. A 
partition in which
+ * few rows need the UDF therefore buffers most of the rows after the first 
one.
+ *
+ * `evaluate` must consume each input row before pulling the next, since some 
callers do not copy
+ * the input rows; this iterator holds the first row that needs the UDF and 
does not advance the
+ * input past it until `evaluate` is pulled.
+ */
+private[sql] object ConditionalUDFEvaluation {
+
+  /**
+   * @param input the child rows, as unsafe rows
+   * @param condition decides which rows to evaluate; must be deterministic
+   * @param childOutput the attributes of the child rows, which `condition` 
refers to
+   * @param passThroughOutput the child columns passed through to the output 
(see
+   *                          `EvalPythonEvaluatorFactory`); a prefix of the 
output
+   * @param resultOutput the attributes of the UDF results, the rest of the 
output
+   * @param lockFree whether the queue of skipped rows has a single producer 
and a single
+   *                 consumer on different threads (a pipelined Python 
writer); false when the
+   *                 same thread drives `evaluate` and reads its results
+   * @param evaluate evaluates the UDFs over the given rows and returns, for 
each of them in
+   *                 order, its `passThroughOutput` columns followed by its 
results
+   */
+  def apply(
+      input: Iterator[InternalRow],
+      condition: Expression,
+      childOutput: Seq[Attribute],
+      passThroughOutput: Seq[Attribute],
+      resultOutput: Seq[Attribute],
+      context: TaskContext,
+      lockFree: Boolean)(
+      evaluate: Iterator[InternalRow] => Iterator[InternalRow]): 
Iterator[InternalRow] = {
+    val output = passThroughOutput ++ resultOutput
+    val predicate = Predicate.create(condition, childOutput)
+    predicate.initialize(context.partitionId())
+    // Project each skipped child row to the pass-through columns the output 
keeps, as the
+    // evaluator does for the rows it evaluates, then pad it with null results.
+    val passThrough = UnsafeProjection.create(passThroughOutput, childOutput)
+    passThrough.initialize(context.partitionId())
+    val nullResults = new GenericInternalRow(resultOutput.length)
+    val joined = new JoinedRow
+    val skippedProj = UnsafeProjection.create(output, output)
+    skippedProj.initialize(context.partitionId())
+    def skippedOut(childRow: InternalRow): InternalRow =
+      skippedProj(joined(passThrough(childRow), nullResults))
+
+    // Phase 1: stream the skipped rows before the first row that needs the 
UDF. `firstEvaluated`
+    // holds that row once found, to start phase 2 with it.
+    var firstEvaluated: InternalRow = null
+    val lead = new Iterator[InternalRow] {
+      private var nextOut: InternalRow = null
+
+      override def hasNext: Boolean = {
+        if (nextOut != null) return true
+        if (firstEvaluated != null) return false
+        while (input.hasNext) {

Review Comment:
   Done. The lead iterator is now `if (input.hasNext) { ... } else false`, so 
it handles one input row per call.
   



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