sarutak commented on code in PR #60366: URL: https://github.com/apache/spark/pull/60366#discussion_r4624962804
########## 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: Thanks -- I took your first suggestion. Since `evalAggExprOnZeroTups` replaces every attribute in the zero-row result with its value over zero rows, a marked UDF's arguments do not depend on the outer row. `ConditionalUDFEvaluation` now detects when every UDF of the eval node is deterministic with no references (`resultIsRowIndependent`), evaluates the first row that needs the UDF once, reads the evaluator to the end (so the Python worker is released and its accumulator updates are received), and reuses the result for the rest, streaming the partition in input order without the queue. So `udf(sum(x))` and the like no longer buffer. A marked UDF still takes the buffering path when it is non-deterministic, shares an eval node with a non-deterministic marked UDF, or is chained over a UDF of another eval type (its argument is then that node's result, a reference). The general bound (ending `evaluate` past a threshold) I left to a follow-up, since it now applies only to those cases. Pi nned by `ConditionalUDFEvaluationSuite` ("reuses the first evaluated result for every kept row when resultIsConstant", which also checks the evaluator is read to the end). ########## 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: Added. `SubquerySuite` now has a scalar pandas form ("a scalar pandas UDF over an aggregate is evaluated through the row path", `assume(shouldTestPandasUDFs)`), which asserts the plan has an `ArrowEvalPythonExec` carrying the condition with `supportsColumnar` false. A new `ConditionalUDFPipelinedSuite` sets `spark.python.udf.pipelined.enabled` in its `SparkConf` and runs a non-deterministic UDF over interleaved rows, asserting the `BatchEvalPythonExec` carries the condition and a non-deterministic UDF, so it takes the buffered path and the pipelined setting makes the writer thread fill the lock-free queue while the task thread drains it. With the reuse above, a deterministic marked UDF no longer reaches the queue, so the pipelined path is covered by the non-deterministic case. ########## 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: You're right, that was a scalar subquery with a literal `IN` list. Replaced it with a real `IN` subquery, `... WHERE 100 IN (SELECT inv(count(*)) FROM ri WHERE ri.c = lo.a)`, which `RewritePredicateSubquery` turns into a semi join: with all outer rows matching it returns results and its plan has the marker, and it fails with the config off. An outer row with no matching row genuinely evaluates inv(0), so it still fails (also asserted). Added an `EXISTS` test too: its output is pruned before `ExtractPythonUDFs` runs, so it has no marker and is unaffected by the config. ########## 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: Good question. I'd like to keep the `EvalOnlyWhen` marker for this PR and pursue the general approach you describe as a separate, config-gated follow-up: - The marker keeps this change scoped to the count-bug zero-row result, a shape the optimizer generates with a known, simple condition (`isnull(alwaysTrue)`). Reading `If` / `CaseWhen` conditions directly in `udfConditions` would change the evaluation counts of any user query with a UDF in a conditional branch, and turn a user-written `CASE WHEN x = 0 THEN 0 ELSE inv(x) END` from failing into succeeding -- a much broader behavior change that wants its own config, a migration-guide entry, and a test matrix over nested and short-circuiting `CaseWhen`. - It would also have to derive the per-UDF branch condition from whatever shape the optimizer has rewritten the `If` / `CaseWhen` into by the time `ExtractPythonUDFs` runs, and handle a branch condition that is not evaluable there or itself holds a UDF, where the marker gives a stable , simple condition. To avoid entrenching the marker: I'd do SPARK-61660 (the `constructLeftJoins` CASE 2/3 path) through that general mechanism rather than a second marker producer, so the marker does not spread. Does that sound reasonable? I'm happy to prototype the general reader if you'd rather see it as code. ########## 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: Done. Phase 1 (the common path) now uses a single `UnsafeProjection(passThroughOutput ++ null literals, childOutput)`, and phase 2 stores the whole output row in the queue, so the second projection is gone. The reuse path likewise builds a kept row in one projection, with the cached results as literals. ########## 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: Done. The group's condition is computed once as `groupCondition = udfs0.headOption.flatMap(conditionOf)`, the group is filtered with a small `sameCondition` helper, and the eval node uses `groupCondition`. -- 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]
