dongjoon-hyun commented on code in PR #60327:
URL: https://github.com/apache/spark/pull/60327#discussion_r4540738753


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonExec.scala:
##########
@@ -61,11 +63,15 @@ object EvalPythonExec {
  */
 trait EvalPythonExec extends UnaryExecNode {
   def udfs: Seq[PythonUDF]
+
+  /** The columns of the child that are passed through to the output. */
+  def requiredChildOutput: Seq[Attribute]
+
   def resultAttrs: Seq[Attribute]
 
   protected def evaluatorFactory: EvalPythonEvaluatorFactory
 
-  override def output: Seq[Attribute] = child.output ++ resultAttrs
+  override def output: Seq[Attribute] = requiredChildOutput ++ resultAttrs

Review Comment:
   **[1] A LIMIT or OFFSET in the middle of a query over a sort now fails with 
`INTERNAL_ERROR_ATTRIBUTE_NOT_FOUND`.**
   
   `InsertSortForLimitAndOffset` walks through an `EvalPythonExec` with only 
`withNewChildren` (`InsertSortForLimitAndOffset.scala:75-83`), which relied on 
this `output` growing with the child. Now `ColumnPruning` narrows 
`requiredChildOutput` when the ordering columns are not used above, so a column 
that the rule adds below this node is dropped here, and the `ProjectExec` 
above, which the rule also extends, cannot bind it. With the test UDF of 
`InsertSortForLimitAndOffsetSuite`:
   
   ```scala
   val df = 1.to(10).map(v => v -> v).toDF("c1", "c2").orderBy($"c1" % 8)
   df.select(pythonTestUDF($"c2")).limit(2).distinct().collect()
   ```
   
   `requiredChildOutput` of the `BatchEvalPythonExec` is empty, the rule adds 
`c1` to the `ProjectExec` below it and to the one above it, and the one above 
fails with `[INTERNAL_ERROR_ATTRIBUTE_NOT_FOUND] Could not find c1#... in 
[pythonUDF0#...]`. The CI of `a95c49d` shows this for "middle LIMIT preserves 
data ordering with the extra sort" and "middle OFFSET preserves data ordering 
with the extra sort".
   
   Could the rule add the missing ordering columns to `requiredChildOutput`? 
For example, with a `withRequiredChildOutput` on `EvalPythonExec` like the 
logical one:
   
   ```scala
   case p: EvalPythonExec =>
     extractOrderingAndPropagateOrderingColumns(p.child).map { case (ordering, 
newChild) =>
       val missing = AttributeSet(ordering.flatMap(_.references)) -- p.outputSet
       (ordering, p.withRequiredChildOutput(p.requiredChildOutput ++ missing, 
newChild))
     }
   ```
   
   `InProcessArrowEvalPythonExec` passes through `child.output`, so it already 
works.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala:
##########
@@ -927,13 +927,22 @@ abstract class SparkStrategies extends 
QueryPlanner[SparkPlan] {
    */
   object PythonEvals extends Strategy {
     override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match {
-      case ArrowEvalPython(udfs, output, child, 
PythonEvalType.SQL_SCALAR_ARROW_INPROCESS_UDF) =>
+      case e @ ArrowEvalPython(
+          udfs, requiredChildOutput, resultAttrs, child,
+          PythonEvalType.SQL_SCALAR_ARROW_INPROCESS_UDF) =>
         InProcessPythonUDFBuilder.checkConfiguration(conf)
-        InProcessArrowEvalPythonExec(udfs, output, planLater(child)) :: Nil
-      case ArrowEvalPython(udfs, output, child, evalType) =>
-        ArrowEvalPythonExec(udfs, output, planLater(child), evalType) :: Nil
-      case BatchEvalPython(udfs, output, child) =>
-        BatchEvalPythonExec(udfs, output, planLater(child)) :: Nil
+        // The in-process evaluator passes through the whole child, so drop 
what is not required.
+        val exec = InProcessArrowEvalPythonExec(udfs, resultAttrs, 
planLater(child))
+        if (requiredChildOutput == child.output) {
+          exec :: Nil
+        } else {
+          ProjectExec(e.output, exec) :: Nil

Review Comment:
   **[4] Nit: the in-process evaluator could honor `requiredChildOutput` 
itself.**
   
   This branch adds a `ProjectExec` because `InProcessArrowEvalPythonExec` pins 
`requiredChildOutput` to `child.output` 
(`InProcessArrowEvalPythonExec.scala:35`). That in turn is because 
`evaluateBatches` projects each joined row with 
`UnsafeProjection.create(output, output)` 
(`InProcessArrowEvalPythonEvaluatorFactory.scala:142`), which holds only while 
`output` is the whole child followed by the results, as the scaladoc of 
`evaluateJoined` (`EvalPythonEvaluatorFactory.scala:59-63`) still says. Binding 
that projection to `childOutput ++ resultOutput` instead would let this node 
take `requiredChildOutput` like the others, remove this branch and the 
override, and keep `evaluateJoined` right for any set of pass-through columns. 
It is fine to leave as is, since the `ProjectExec` is cheap.



##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py:
##########
@@ -188,6 +189,87 @@ def 
test_udf_on_timestamps_cached_under_different_time_zone(self):
             df.unpersist()
 
 
+    def test_udfs_without_pass_through_columns(self):

Review Comment:
   **[2] `ruff format` fails on this file, which fails the Python linter.**
   
   The CI of `a95c49d` failed at "Python linter" with "1 file would be 
reformatted": `ruff format` drops one of the two blank lines above this method 
(L190-L191) and adds a second blank line before `if __name__ == "__main__":` 
(L272-L273). `dev/reformat-python` should fix both.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala:
##########
@@ -150,8 +156,19 @@ private[python] class 
ColumnarArrowEvalPythonEvaluatorFactory(
         batch.numRows() > 0
       }
 
-      evalWithRowQueue(nonEmptyIter, context, pyFuncs, argMetas,
-        allInputs.toSeq, udfInputSchema, outputTypes, 
resolveColumnIndices(allInputs.toSeq))
+      val inputColumnIndices = resolveColumnIndices(allInputs.toSeq)
+      if (passThroughOutput.isEmpty) {
+        // The vectors of a result batch are valid until the next one is 
requested, which a
+        // consumer respecting the contract of ColumnVector does not rely on 
beyond that.
+        evalPython(nonEmptyIter, context, pyFuncs, argMetas, allInputs.toSeq, 
udfInputSchema,

Review Comment:
   **[3] Question: without pass-through columns, nothing bounds the batches 
this node hands to a columnar parent anymore.**
   
   The row queue path rebuilds its batches in `rowsToColumnarBatches` 
(L298-L327), which cuts them by `maxRecordsPerBatch` and `maxBytesPerBatch`. 
Here a parent reads the result batches of Python as they are, which only 
`maxRecordsPerOutputBatch` and `maxBytesPerOutputBatch` slice, and both are 
unset by default. A UDF stacked on this one sends each of its input batches to 
Python as one Arrow batch, and the Arrow cache keeps one cached batch per input 
batch. So the output of a scalar iterator UDF that yields its input as one 
batch, such as `yield pd.concat(list(it)) + 1`, or of one whose results are 
much larger than its input, now reaches a UDF stacked on it, or the cache, as 
one batch.
   
   This carries [item 9 of 
#59582](https://github.com/apache/spark/pull/59582#discussion_r4437566798), 
which you planned to fix separately, over to stacked UDFs. Is that intended? If 
so, could the comment here say so? Otherwise, slicing these batches by 
`maxRecordsPerBatch` and `maxBytesPerBatch` would keep the earlier bounds.



##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py:
##########
@@ -188,6 +189,87 @@ def 
test_udf_on_timestamps_cached_under_different_time_zone(self):
             df.unpersist()
 
 
+    def test_udfs_without_pass_through_columns(self):
+        # Only the results are selected, so no column is passed through, and 
the result batches
+        # of Python are the output batches, including those of iterator UDFs, 
which may return
+        # batches of other sizes than their input.
+        import pandas as pd
+        import pyarrow as pa
+        import pyarrow.compute as pc
+
+        @pandas_udf("long")
+        def pandas_plus_one(it: Iterator[pd.Series]) -> Iterator[pd.Series]:
+            for s in it:
+                yield s + 1
+
+        @arrow_udf("long")
+        def arrow_plus_one(it: Iterator[pa.Array]) -> Iterator[pa.Array]:
+            for a in it:
+                # Splits each batch in two.
+                half = len(a) // 2
+                yield pc.add(a[:half], 1)
+                yield pc.add(a[half:], 1)
+
+        @pandas_udf("long")
+        def pandas_times_two(s: pd.Series) -> pd.Series:
+            return s * 2
+
+        num_rows = 10000
+        df = self.spark.range(0, num_rows, 1, 2).selectExpr("id", "id * 10 AS 
v").cache()
+        cases = [
+            ("pandas_iter", pandas_plus_one, lambda i: i + 1),
+            ("arrow_iter", arrow_plus_one, lambda i: i + 1),
+            ("pandas", pandas_times_two, lambda i: i * 2),
+            ("udf", udf(lambda x: x + 1, "long"), lambda i: i + 1),
+        ]
+        try:
+            with 
self.sql_conf({"spark.sql.execution.arrow.maxRecordsPerBatch": "1000"}):
+                for name, f, g in cases:
+                    with self.subTest(udf=name):
+                        expected = [Row(r=g(i)) for i in range(num_rows)]
+                        result = df.select(f(col("id")).alias("r"))
+                        self._assert_columnar_arrow_eval(result, 
expected_nodes=1)

Review Comment:
   **[5] Nit: these tests would also pass if the columns were still passed 
through.**
   
   This test and the two below check that each evaluation is columnar and that 
the results are right, which also holds when the pass-through columns go 
through the row queue. An optional argument of `_assert_columnar_arrow_eval` 
that checks `node.requiredChildOutput().isEmpty()` would pin the case these 
tests describe.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1565,6 +1565,15 @@ object ColumnPruning extends Rule[LogicalPlan] {
     // prune unrequired nested fields from `Generate`.
     case GeneratorNestedColumnAliasing(rewrittenPlan) => rewrittenPlan
 
+    // Pass through only the columns of the child of a Python UDF evaluation 
that the parent uses,
+    // and prune the child to those and the arguments of the UDFs. The child 
is pruned here, as
+    // the rule does not visit this Project again.
+    case p @ Project(_, e: BaseEvalPython)
+        if !e.requiredChildOutput.forall(p.references.contains) =>
+      val newEval = e.withRequiredChildOutput(

Review Comment:
   **[6] Nit: `withRequiredChildOutput` does not need `newChild`.**
   
   Its only caller passes `e.child`, which `withNewChildren` replaces on the 
next line. Without that parameter (`pythonLogicalOperators.scala:299-300` and 
the two overrides), this could read:
   
   ```scala
   val newEval = 
e.withRequiredChildOutput(e.requiredChildOutput.filter(p.references.contains))
   p.copy(child = newEval.withNewChildren(Seq(prunedChild(e.child, 
newEval.references))))
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonEvaluatorFactory.scala:
##########
@@ -30,12 +30,24 @@ import 
org.apache.spark.sql.execution.python.EvalPythonExec.ArgumentMetadata
 import org.apache.spark.sql.types.{DataType, StructField, StructType}
 import org.apache.spark.util.Utils
 
+/**
+ * @param childOutput the output of the child, which the input rows have
+ * @param udfs the Python UDFs to evaluate
+ * @param output the output rows: the columns of the child that are passed 
through, followed by
+ *               one column for the result of each UDF
+ */
 abstract class EvalPythonEvaluatorFactory(
     childOutput: Seq[Attribute],
     udfs: Seq[PythonUDF],
     output: Seq[Attribute])
   extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
 
+  /** The columns of the child that are passed through to the output. */
+  protected val passThroughOutput: Seq[Attribute] = 
output.dropRight(udfs.length)

Review Comment:
   **[7] Nit: both evaluator factories split `output` by position.**
   
   Here and in `ColumnarArrowEvalPythonEvaluatorFactory.scala:87-89`, 
`dropRight(udfs.length)` and `takeRight(udfs.length)` rebuild 
`requiredChildOutput` and `resultAttrs` from `output`, which the nodes already 
have. Passing those two to the factories, and building `output` from them, 
would remove the duplicate and the reliance on the order of `output`.



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