dongjoon-hyun commented on code in PR #60366: URL: https://github.com/apache/spark/pull/60366#discussion_r4624062058
########## 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) { + val row = input.next() + if (predicate.eval(row)) { + firstEvaluated = row + return false + } + nextOut = skippedOut(row) + return true + } + false + } + + override def next(): InternalRow = { + if (!hasNext) Iterator.empty.next() + val row = nextOut + nextOut = null + row + } + } + + // Phase 2: from the first row that needs the UDF onward, evaluate through `evaluate` and + // interleave the skipped rows back in input order. Built lazily, so a partition that never + // needs the UDF never reaches it (no buffering, no worker). + def buffered(): Iterator[InternalRow] = { + if (firstEvaluated == null) return Iterator.empty + val remaining = Iterator.single(firstEvaluated) ++ input + + // In pipelined mode the writer thread adds skipped rows (while pulling `evaluated`) and the + // task thread removes them, one producer and one consumer, so use the lock-free queue (as + // the Python evaluator does); otherwise the synchronized one. + val skipped = HybridRowQueue( + context.taskMemoryManager(), + new File(Utils.getLocalDir(SparkEnv.get.conf)), + passThroughOutput.length, + lockFree = lockFree) + context.addTaskCompletionListener[Unit](_ => skipped.close()) + // For each evaluated row, in order, the number of skipped rows right before it. + val gaps = new ConcurrentLinkedQueue[java.lang.Long]() + val numSkipped = new AtomicLong(0L) + @volatile var inputDone = false + + val evaluated = new Iterator[InternalRow] { + private var nextRow: InternalRow = null + private var pending = 0L + + override def hasNext: Boolean = { + while (nextRow == null && remaining.hasNext) { + val row = remaining.next() + if (predicate.eval(row)) { + gaps.add(pending) + pending = 0L + nextRow = row + } else { + skipped.add(passThrough(row)) Review Comment: **Buffering:** Once a partition reaches its first row that needs the UDF, every later row that skips it is queued here until the batch holding the next evaluated row is answered. That batch is sent only after `maxRecordsPerBatch` evaluated rows or at the end of the input. This is not limited to the queries this PR fixes. A UDF that handles `NULL`, e.g. `udf(sum(x))`, also gets the marker, since its zero-row result `udf(NULL)` is not folded. For such a query, which works on master, a partition where 0.1% of the outer rows have no matching rows would queue about 10M rows here (spilling to disk) for each Arrow batch of 10,000 evaluated rows. On master, about one batch of rows is in flight at a time. The description lists this as a cost, but it may be avoidable: `evalAggExprOnZeroTups` replaces every attribute with `NULL`, so the arguments of a marked UDF do not depend on the row. When every UDF of the node is deterministic and has no references, evaluating them once for the first row that needs them and reusing the results would stream every row in order without this queue. For the general case, the backlog could be bounded by ending the current `evaluate` call once `skipped` grows past a threshold and starting a new one for the remaining rows. What do you think? ########## sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala: ########## @@ -1763,6 +1763,142 @@ class SubquerySuite extends SharedSparkSession Row(1) :: Row(1) :: Row(null) :: Row(null) :: Nil) } + test("SPARK-61482: a Python UDF over an aggregate in COUNT-bug handling runs only where " + + "it is needed") { + import IntegratedUDFTestUtils._ + + assume(shouldTestPythonUDFs) + + val inv = TestFailingPythonUDF(name = "inv") + registerTestUDF(inv, spark) + + // Every outer row has matching inner rows, so count(*) is never 0. Before this change the + // Python UDF was lifted out of the conditional branch and inv(0) from the zero-row result + // was evaluated for every outer row, failing even here; now it runs only for outer rows + // without matching inner rows, of which there are none. + withTempView("lo", "ri") { + Seq(2, 3, 6).toDF("a").createOrReplaceTempView("lo") + Seq((2, 3.0), (2, 3.0), (3, 2.0), (6, 1.0)).toDF("c", "d").createOrReplaceTempView("ri") + + checkAnswer( + sql("SELECT lo.a, (SELECT sum(x) FROM (SELECT inv(count(*)) AS x FROM ri " + + "WHERE ri.c = lo.a)) FROM lo ORDER BY lo.a"), + Row(2, 50) :: Row(3, 100) :: Row(6, 100) :: Nil) + // The same in a LATERAL subquery. + checkAnswer( + sql("SELECT lo.a, t.x FROM lo, LATERAL (SELECT inv(count(*)) AS x FROM ri " + + "WHERE ri.c = lo.a) t ORDER BY lo.a"), + Row(2, 50) :: Row(3, 100) :: Row(6, 100) :: Nil) + + // With the config off, the UDF is evaluated for every row again and the query fails. + withSQLConf( + SQLConf.DECORRELATE_INNER_QUERY_COUNT_BUG_EVAL_UDF_CONDITIONALLY_ENABLED.key -> "false") { + val e = intercept[Exception] { + sql("SELECT lo.a, (SELECT sum(x) FROM (SELECT inv(count(*)) AS x FROM ri " + + "WHERE ri.c = lo.a)) FROM lo").collect() + } + assert(e.getMessage.contains("ZeroDivisionError")) + } + } + } + + test("SPARK-61482: a Python UDF over an aggregate is evaluated for the non-matching outer " + + "rows and interleaved with the matching ones in input order") { + import IntegratedUDFTestUtils._ + + assume(shouldTestPythonUDFs) + + // A non-failing identity UDF, so a non-matching outer row evaluates udf(0) = 0 and the query + // returns results. Odd `a` have no matching `ri` row, so the conditional branch is taken and + // the UDF is evaluated for them; even `a` match, so the UDF is skipped and the row streams. + val udf = TestPythonUDF(name = "udf") + registerTestUDF(udf, spark) + + withTempView("lo", "ri") { + // Interleave matching and non-matching outer rows so phase 2 of ConditionalUDFEvaluation + // buffers skipped rows between evaluated ones and must restore input order. + (1 to 8).toDF("a").createOrReplaceTempView("lo") + Seq(2, 4, 6, 8).toDF("c").createOrReplaceTempView("ri") + + // A small batch size forces several batches of evaluated rows, so the interleaving and the + // per-batch buffering of skipped rows are exercised rather than a single batch. + withSQLConf(SQLConf.PYTHON_UDF_MAX_RECORDS_PER_BATCH.key -> "2") { + val expected = (1 to 8).map(a => Row(a, if (a % 2 == 0) 1 else 0)) + // Nested so that it is decorrelated through DecorrelateInnerQuery's domain join (a single + // top-level aggregate would go through constructLeftJoins; see SPARK-61660). + checkAnswer( + sql("SELECT lo.a, (SELECT sum(x) FROM (SELECT udf(count(*)) AS x FROM ri " + + "WHERE ri.c = lo.a)) FROM lo ORDER BY lo.a"), + expected) + // The same through a LATERAL join. + checkAnswer( + sql("SELECT lo.a, t.x FROM lo, LATERAL (SELECT udf(count(*)) AS x FROM ri " + + "WHERE ri.c = lo.a) t ORDER BY lo.a"), + expected) + // The same restricted with IN, keeping a mix of matching and non-matching rows. + checkAnswer( + sql("SELECT lo.a, (SELECT sum(x) FROM (SELECT udf(count(*)) AS x FROM ri " + + "WHERE ri.c = lo.a)) FROM lo WHERE lo.a IN (2, 3, 6, 7) ORDER BY lo.a"), Review Comment: **Test coverage:** This query is a scalar subquery with a literal `IN` list on the outer table, not an `IN` subquery. The description says the `IN` subquery form is fixed as well, but no test runs a query such as `SELECT lo.a FROM lo WHERE 50 IN (SELECT inv(count(*)) FROM ri WHERE ri.c = lo.a)`, which goes through `RewritePredicateSubquery` and a semi join. Could you add that form, and an `EXISTS` case, which the description says is unaffected? ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala: ########## @@ -889,7 +892,17 @@ object DecorrelateInnerQuery extends PredicateHelper { val newAttr = a.newInstance() val ref = newAttr.toAttribute.withNullability(true) expressions += newAttr - Alias(If(IsNull(alwaysTrueRef), default, ref), a.name)(a.exprId) + val noMatch = IsNull(alwaysTrueRef) + // Python and external UDFs are evaluated before this Project for every row + // of the join, outside the If. Mark them so that they are evaluated only for + // the rows that take this branch (unless turned off by the config above). + val onZeroTups = + if (evalUdfConditionally && EvalOnlyWhen.hasLiftedUDF(default)) { + EvalOnlyWhen(noMatch, default) Review Comment: **Design question:** Only this rewrite produces the marker, while the cause is that `ExtractPythonUDFs` and `PlanExternalUDFs` lift a UDF out of any conditional branch. The same failure remains in CASE 2 and CASE 3 of `constructLeftJoins` (the `TODO(SPARK-61660)`, which would also need a `CaseWhen` drop rule) and in a user-written `CASE WHEN x = 0 THEN 0 ELSE inv(x) END`. `udfConditions` and `ConditionalUDFEvaluation` already handle a condition per UDF. Could `udfConditions` read the deterministic conditions of `If` / `CaseWhen` branches directly, behind a config if needed? That would cover all of these without the `EvalOnlyWhen` expression and its `SimplifyConditionals` rules. It would also change the evaluation counts of more user queries, so I'd like to hear your view before SPARK-61660 adds a second producer of the marker. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonExec.scala: ########## @@ -78,9 +80,28 @@ trait EvalPythonExec extends UnaryExecNode { override def producedAttributes: AttributeSet = AttributeSet(resultAttrs) + /** + * If defined, the UDFs are evaluated only for the child rows where this deterministic + * condition is true, and their results are null for the other rows (see `EvalOnlyWhen`). + */ + def evalCondition: Option[Expression] = None + protected override def doExecute(): RDD[InternalRow] = { val inputRDD = child.execute().map(_.copy()) - if (conf.usePartitionEvaluator) { + if (evalCondition.isDefined) { + val condition = evalCondition.get + val factory = evaluatorFactory + val childOutput = child.output + val passThrough = requiredChildOutput + val results = resultAttrs + inputRDD.mapPartitionsWithIndexInternal { (index, iter) => + val pipelined = SparkEnv.get.conf.get(PYTHON_UDF_PIPELINED_EXECUTION) Review Comment: **Test coverage:** With `spark.python.udf.pipelined.enabled`, the writer thread pulls `evaluated` and writes `skipped` (lock-free), `gaps` and `numSkipped`, while the task thread reads them. No test runs that path: `ConditionalUDFEvaluationSuite` passes `lockFree = true` but drives `evaluate` on the same thread, and the `SubquerySuite` tests use `SQL_BATCHED_UDF` with the default, non-pipelined setting. No test executes the `ArrowEvalPythonExec` row path with a condition either; `ExtractPythonUDFsSuite` checks only `supportsColumnar`. Could you add an end-to-end case with a scalar pandas or Arrow UDF (e.g. `TestScalarPandasUDF`), and one in a suite that enables pipelined execution in its `SparkConf`? It is a core config, so `withSQLConf` does not change it. ########## 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 = Review Comment: **Minor:** Each skipped row goes through two projections: `passThrough` copies the pass-through columns into an `UnsafeRow`, and `skippedProj` copies them again with the null results through `JoinedRow`. Phase 1 is the path of most rows (the outer rows with matching rows), so a single `UnsafeProjection.create(passThroughOutput ++ resultOutput.map(a => Literal.create(null, a.dataType)), childOutput)` would halve the copies there. In phase 2, `skipped` could store that output row (with `output.length` fields), so the second projection would not be needed either. ########## 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: **Nit:** The `cond` passed to `visit` is always `None` or a deterministic marker condition, since `inner` adds `c` only when `c.deterministic`. So `cond.filter(_.deterministic)` never filters anything. `cond.map(And(_, c)).getOrElse(c)` is enough, and the comment above would then not suggest that a non-deterministic outer condition can reach this point. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFs.scala: ########## @@ -299,11 +299,27 @@ object ExtractPythonUDFs extends Rule[LogicalPlan] with Logging { private def extract(plan: LogicalPlan): LogicalPlan = { val pythonUDFArrowFallbackOnUDT = conf.pythonUDFArrowFallbackOnUDT - val udfs = ExpressionSet( + val udfs0 = ExpressionSet( collectEvaluableUDFsFromExpressions(plan.expressions, pythonUDFArrowFallbackOnUDT)) // ignore the PythonUDF that come from second/third aggregate, which is not used .filter(udf => udf.references.subsetOf(plan.inputSet)) .toSeq.asInstanceOf[Seq[PythonUDF]] + // Evaluate together only the UDFs that need the same condition (see `EvalOnlyWhen`), and + // the others in later calls of `extract`. + val conditions = EvalOnlyWhen.udfConditions( + plan.expressions, + isScalarPythonUDF, + e => canonicalizeDeterministic(e.asInstanceOf[PythonUDF])) + def conditionOf(udf: PythonUDF): Option[Expression] = + conditions.getOrElse(canonicalizeDeterministic(udf), None) + val udfs = udfs0.headOption.map(conditionOf) match { Review Comment: **Minor:** The condition of the group is computed here from the first UDF, and again for each child at L351 (`udfs.headOption.flatMap(conditionOf)`). Computing it once, e.g. `val groupCondition = udfs0.headOption.flatMap(conditionOf)`, and filtering with a small `sameCondition` helper would drop the `None` case here and make the eval node use the same value that selected the group. ########## 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: **Nit:** The body of this `while` always returns, so it runs at most once. `if (input.hasNext) { ... } else false` would show that each call handles one input row. -- 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]
