This is an automated email from the ASF dual-hosted git repository.
viirya pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 7a8799e87c01 [SPARK-61445][SQL] Pass through only the required child
columns in Python UDF evaluation and return Python results directly in columnar
mode
7a8799e87c01 is described below
commit 7a8799e87c01f9b101c48008255c427de730970c
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Wed Nov 11 11:47:50 2026 -0800
[SPARK-61445][SQL] Pass through only the required child columns in Python
UDF evaluation and return Python results directly in columnar mode
### What changes were proposed in this pull request?
This is a follow-up of SPARK-60325 (#59582), as discussed there.
`BatchEvalPython` / `ArrowEvalPython` (and their physical nodes) always
output `child.output ++ resultAttrs`. Column pruning only narrows their child
to the columns used above plus the UDF arguments, so every remaining child
column, including each argument, is copied into a `HybridRowQueue` and joined
with the result of its row, even when the parent drops it, e.g.
`df.select(udf(a))` or `df.select(udf(c1, ..., c8))`. With columnar input
(`spark.sql.execution.arrow.pythonUDF.columnarIn [...]
This PR makes the Python UDF evaluation pass through only the child columns
its parent uses, like the Python UDTF nodes do:
- `BaseEvalPython` gets `requiredChildOutput`, and its output becomes
`requiredChildOutput ++ resultAttrs`. `ExtractPythonUDFs` sets it to
`child.output`, and a new case of `ColumnPruning` (which runs again right after
`ExtractPythonUDFs`) narrows it to the columns that the `Project` above uses
and prunes the child to those and the UDF arguments.
- `EvalPythonExec` gets the same field. In the row evaluator shared by
`BatchEvalPythonExec` and `ArrowEvalPythonExec`, the queue holds only the
pass-through columns, and without any it is not created: the results from
Python are the output rows.
- In the columnar evaluator of `ArrowEvalPythonExec`, the queue holds only
the pass-through columns, and without any, the result batches from Python are
returned as they are, instead of being joined by row and converted back. Their
vectors are reused for the next batch (`ReusedArrowColumnVector`), which
consumers that respect the `ColumnVector` contract handle, e.g.
`ColumnarToRowExec`, a stacked `ArrowEvalPythonExec` and the Arrow cache, which
copy what they keep. These batches are s [...]
- `InProcessArrowEvalPythonExec` keeps passing through its whole child, and
the planner puts a `ProjectExec` above it when the logical node is pruned.
Whether the columnar path is used is still fixed when the plan is built
(SPARK-60306).
### Why are the changes needed?
To avoid copying, buffering and joining columns that are discarded right
after the evaluation, and to give the zero-copy output back to the columnar
path when nothing is passed through, which SPARK-60325 had to drop for
correctness.
A local benchmark (`local[1]`, a pandas UDF over 8 string columns,
selecting only its result, noop sink, median of 5 runs; the columnar input
reads an Arrow-cached relation):
| Input | Path | Before | After |
|---|---|---|---|
| 1M rows, 8 x ~64 B | row | 0.632 s | 0.583 s |
| 1M rows, 8 x ~64 B | columnar | 0.509 s | 0.379 s |
| 500K rows, 8 x ~256 B | row | 0.573 s | 0.577 s |
| 500K rows, 8 x ~256 B | columnar | 0.605 s | 0.458 s |
The columnar path gains about 25%. On the row path, the queue is a small
part of the cost.
### Does this PR introduce _any_ user-facing change?
No, other than the plans: `BatchEvalPython` / `ArrowEvalPython` show the
columns they pass through in `EXPLAIN`, like `BatchEvalPythonUDTF` /
`ArrowEvalPythonUDTF`, and the columns used only as UDF arguments are no longer
in their output.
### How was this patch tested?
New tests:
- `ExtractPythonUDFsSuite`: the columns that batched, scalar pandas and
scalar Arrow iterator UDF evaluations pass through, when only the results are
used, with other or the argument columns, through filters, under an aggregate,
and for stacked evaluations; and the logical node and its pruned child.
- `ArrowColumnarPythonUDFSuite`: without pass-through columns, the output
batches are the Python result batches (over reused vectors, not sliced to
`maxRecordsPerBatch`), the results are correct with codegen on and off, over
fresh and reused input vectors, with column references or expressions as the
UDF inputs, with a filter, a projection and a limit above, and every input
batch is released; with some pass-through columns; and stacked UDFs without
pass-through columns. The test Arrow [...]
- `test_arrow_python_udf_cached.py`: pandas and Arrow iterator UDFs (one
returning other batch sizes than its input), a scalar pandas UDF and an
Arrow-optimized UDF without pass-through columns, with a filter above; stacked
UDFs; caching the results.
Also ran `FilterPushdownSuite`, `ColumnPruningSuite`,
`ArrowCachedPythonUDFSuite`, `PythonUDFSuite`, `BatchEvalPythonExecSuite`,
`ExtractPythonUDFFromLambdaSuite`, `InProcessPythonUDFSuite`,
`PythonUDTFSuite`, and `pyspark.sql.tests.arrow.test_arrow_python_udf`,
`test_arrow_udf_scalar`, `pyspark.sql.tests.pandas.test_pandas_udf_scalar`,
`test_pipelined_udf`, `pyspark.sql.tests.test_udf`, `test_inprocess_udf`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)
Closes #60327 from viirya/SPARK-61445.
Authored-by: Liang-Chi Hsieh <[email protected]>
Signed-off-by: Liang-Chi Hsieh <[email protected]>
---
.../tests/arrow/test_arrow_python_udf_cached.py | 98 +++++++++++++++++-
.../spark/sql/catalyst/optimizer/Optimizer.scala | 8 ++
.../plans/logical/pythonLogicalOperators.scala | 30 +++++-
.../catalyst/optimizer/FilterPushdownSuite.scala | 4 +-
.../execution/InsertSortForLimitAndOffset.scala | 21 +++-
.../spark/sql/execution/SparkStrategies.scala | 21 ++--
.../sql/execution/python/ArrowEvalPythonExec.scala | 29 ++++--
.../sql/execution/python/BatchEvalPythonExec.scala | 18 +++-
.../ColumnarArrowEvalPythonEvaluatorFactory.scala | 110 +++++++++++++-------
.../python/EvalPythonEvaluatorFactory.scala | 40 +++++--
.../sql/execution/python/EvalPythonExec.scala | 19 +++-
.../sql/execution/python/ExtractPythonUDFs.scala | 4 +-
.../InProcessArrowEvalPythonEvaluatorFactory.scala | 5 +-
.../python/InProcessArrowEvalPythonExec.scala | 14 ++-
.../execution/python/ArrowBackedDataSourceV2.scala | 63 ++++++-----
.../python/ArrowColumnarPythonUDFSuite.scala | 115 ++++++++++++++++++++-
.../python/BatchEvalPythonExecSuite.scala | 15 +--
.../execution/python/ExtractPythonUDFsSuite.scala | 67 +++++++++++-
.../python/InProcessEvaluatorTestUtils.scala | 2 +-
.../python/InProcessPythonRuntimeSuite.scala | 6 +-
20 files changed, 573 insertions(+), 116 deletions(-)
diff --git a/python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py
b/python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py
index ee6d4eb3e6b2..8c6d5105637c 100644
--- a/python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py
+++ b/python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py
@@ -17,9 +17,10 @@
import datetime
import unittest
+from typing import Iterator
from pyspark.sql import Row
-from pyspark.sql.functions import col, udf
+from pyspark.sql.functions import arrow_udf, col, pandas_udf, udf
from pyspark.testing.sqlutils import ReusedSQLTestCase
from pyspark.testing.utils import (
assertDataFrameEqual,
@@ -75,10 +76,12 @@ class ArrowPythonUDFCachedInputTests(ReusedSQLTestCase):
finally:
super().tearDownClass()
- def _assert_columnar_arrow_eval(self, df, expected_nodes):
+ def _assert_columnar_arrow_eval(self, df, expected_nodes,
pass_through_columns=None):
# Assert the executed plan contains exactly `expected_nodes`
ArrowEvalPythonExec
# operators and every one of them takes the columnar input path --
otherwise the
- # test silently stops exercising the code this suite exists to pin.
+ # test silently stops exercising the code this suite exists to pin. If
+ # `pass_through_columns` is given, also assert that every one of them
passes through
+ # the child columns of those names.
nodes = []
stack = [df._jdf.queryExecution().executedPlan()]
while stack:
@@ -95,6 +98,10 @@ class ArrowPythonUDFCachedInputTests(ReusedSQLTestCase):
self.assertEqual(len(nodes), expected_nodes, "unexpected number of
ArrowEvalPythonExec")
for node in nodes:
self.assertTrue(node.supportsColumnar(), "expected the columnar
input path")
+ if pass_through_columns is not None:
+ required = node.requiredChildOutput()
+ names = [required.apply(i).name() for i in
range(required.size())]
+ self.assertEqual(names, pass_through_columns, "unexpected
pass-through columns")
def _assert_udf_on_cached_strings(self):
df = self.spark.createDataFrame(
@@ -128,7 +135,7 @@ class ArrowPythonUDFCachedInputTests(ReusedSQLTestCase):
df = self.spark.createDataFrame([(1, "a"), (2, "b")], schema="i long,
s string").cache()
try:
result = df.select(col("s"), udf(lambda x: x + 1,
"long")(col("i")))
- self._assert_columnar_arrow_eval(result, expected_nodes=1)
+ self._assert_columnar_arrow_eval(result, expected_nodes=1,
pass_through_columns=["s"])
assertDataFrameEqual(result, [Row("a", 2), Row("b", 3)])
finally:
df.unpersist()
@@ -187,6 +194,89 @@ class ArrowPythonUDFCachedInputTests(ReusedSQLTestCase):
finally:
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, pass_through_columns=[]
+ )
+ assertDataFrameEqual(result, expected)
+ # With a filter on the result above.
+ filtered = result.where(col("r") % 7 == 0)
+ assertDataFrameEqual(filtered, [r for r in expected if
r.r % 7 == 0])
+ finally:
+ df.unpersist()
+
+ def test_stacked_udfs_without_pass_through_columns(self):
+ # The outer UDF reads the result batches of the inner one, which are
loaded into the
+ # same vectors for every batch, and neither passes through a column.
+ import pandas as pd
+
+ @pandas_udf("long")
+ def pandas_times_two(s: pd.Series) -> pd.Series:
+ return s * 2
+
+ plus_one = udf(lambda x: x + 1, "long")
+ df = self.spark.range(0, 10000, 1, 2).cache()
+ try:
+ with
self.sql_conf({"spark.sql.execution.arrow.maxRecordsPerBatch": "1000"}):
+ result =
df.select(pandas_times_two(plus_one(col("id"))).alias("r"))
+ self._assert_columnar_arrow_eval(result, expected_nodes=2,
pass_through_columns=[])
+ assertDataFrameEqual(result, [Row(r=(i + 1) * 2) for i in
range(10000)])
+ finally:
+ df.unpersist()
+
+ def test_cache_results_of_udf_without_pass_through_columns(self):
+ # The results of Python are the output batches, which are cached by
copying them.
+ df = self.spark.range(0, 10000, 1, 2).cache()
+ try:
+ result = df.select(udf(lambda x: x + 1,
"long")(col("id")).alias("r"))
+ self._assert_columnar_arrow_eval(result, expected_nodes=1,
pass_through_columns=[])
+ cached = result.cache()
+ try:
+ self.assertEqual(cached.count(), 10000)
+ assertDataFrameEqual(cached, [Row(r=i + 1) for i in
range(10000)])
+ finally:
+ cached.unpersist()
+ finally:
+ df.unpersist()
+
if __name__ == "__main__":
from pyspark.testing import main
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
index 7c24f977fb4d..8fb1b7c9b787 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
@@ -1565,6 +1565,14 @@ 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(e.requiredChildOutput.filter(p.references.contains))
+ p.copy(child = newEval.withNewChildren(Seq(prunedChild(e.child,
newEval.references))))
+
// Eliminate unneeded attributes from right side of a Left Existence Join.
case j @ Join(_, right, LeftExistence(_), _, _) =>
j.copy(right = prunedChild(right, j.references))
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/pythonLogicalOperators.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/pythonLogicalOperators.scala
index 31e7d9402968..7e443e1e40d5 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/pythonLogicalOperators.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/pythonLogicalOperators.scala
@@ -287,9 +287,18 @@ trait BaseEvalPython extends UnaryNode {
def udfs: Seq[PythonUDF]
+ /**
+ * The columns of the child that are passed through to the output. Starts as
the whole output
+ * of the child, and is narrowed by column pruning to those that the parent
uses.
+ */
+ def requiredChildOutput: Seq[Attribute]
+
def resultAttrs: Seq[Attribute]
- override def output: Seq[Attribute] = child.output ++ resultAttrs
+ /** Returns a copy that passes through `requiredChildOutput` of the child. */
+ def withRequiredChildOutput(requiredChildOutput: Seq[Attribute]):
BaseEvalPython
+
+ override def output: Seq[Attribute] = requiredChildOutput ++ resultAttrs
override def producedAttributes: AttributeSet = AttributeSet(resultAttrs)
@@ -313,23 +322,42 @@ trait BaseEvalPythonUDTF extends UnaryNode {
/**
* A logical plan that evaluates a [[PythonUDF]]
+ *
+ * @param udfs the Python UDFs to evaluate
+ * @param requiredChildOutput the columns of the child that are passed through
to the output
+ * @param resultAttrs the attributes of the results of the UDFs
+ * @param child the child plan
*/
case class BatchEvalPython(
udfs: Seq[PythonUDF],
+ requiredChildOutput: Seq[Attribute],
resultAttrs: Seq[Attribute],
child: LogicalPlan) extends BaseEvalPython {
+ override def withRequiredChildOutput(requiredChildOutput: Seq[Attribute]):
BatchEvalPython =
+ copy(requiredChildOutput = requiredChildOutput)
+
override protected def withNewChildInternal(newChild: LogicalPlan):
BatchEvalPython =
copy(child = newChild)
}
/**
* A logical plan that evaluates a [[PythonUDF]] with Apache Arrow.
+ *
+ * @param udfs the Python UDFs to evaluate
+ * @param requiredChildOutput the columns of the child that are passed through
to the output
+ * @param resultAttrs the attributes of the results of the UDFs
+ * @param child the child plan
+ * @param evalType the eval type of the UDFs
*/
case class ArrowEvalPython(
udfs: Seq[PythonUDF],
+ requiredChildOutput: Seq[Attribute],
resultAttrs: Seq[Attribute],
child: LogicalPlan,
evalType: Int) extends BaseEvalPython {
+ override def withRequiredChildOutput(requiredChildOutput: Seq[Attribute]):
ArrowEvalPython =
+ copy(requiredChildOutput = requiredChildOutput)
+
override protected def withNewChildInternal(newChild: LogicalPlan):
ArrowEvalPython =
copy(child = newChild)
}
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala
index 1abbf245dddf..f122b23dbb6c 100644
---
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala
@@ -909,9 +909,9 @@ class FilterPushdownSuite extends PlanTest {
val f = AttributeReference("f", IntegerType)()
def evalPython(child: LogicalPlan): LogicalPlan =
if (evalType == PythonEvalType.SQL_BATCHED_UDF) {
- BatchEvalPython(Seq(pythonUDF), Seq(f), child)
+ BatchEvalPython(Seq(pythonUDF), child.output, Seq(f), child)
} else {
- ArrowEvalPython(Seq(pythonUDF), Seq(f), child, evalType)
+ ArrowEvalPython(Seq(pythonUDF), child.output, Seq(f), child,
evalType)
}
// f > 5 cannot be pushed, so the throwable condition after it stays
above too. b > 1
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/InsertSortForLimitAndOffset.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/InsertSortForLimitAndOffset.scala
index 88f0de2555f7..b1c0ff18f796 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/InsertSortForLimitAndOffset.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/InsertSortForLimitAndOffset.scala
@@ -75,12 +75,29 @@ object InsertSortForLimitAndOffset extends Rule[SparkPlan] {
case p: UnaryExecNode if
p.isInstanceOf[LocalLimitExec] ||
p.isInstanceOf[WholeStageCodegenExec] ||
- p.isInstanceOf[FilterExec] ||
- p.isInstanceOf[EvalPythonExec] =>
+ p.isInstanceOf[FilterExec] =>
extractOrderingAndPropagateOrderingColumns(p.child) match {
case Some((ordering, newChild)) => Some((ordering,
p.withNewChildren(Seq(newChild))))
case _ => None
}
+ case p: EvalPythonExec =>
+ extractOrderingAndPropagateOrderingColumns(p.child) match {
+ case Some((ordering, newChild)) =>
+ // The evaluation passes through only the columns of its child that
its parent uses, so
+ // we must also pass through the ordering columns that it does not.
+ val newEval =
p.withNewChildren(Seq(newChild)).asInstanceOf[EvalPythonExec]
+ val missingCols = ordering.flatMap(_.references).distinct
+ .filterNot(newEval.outputSet.contains)
+ if (missingCols.isEmpty) {
+ Some((ordering, newEval))
+ } else {
+ val newEvalWithCols =
+ newEval.withRequiredChildOutput(newEval.requiredChildOutput ++
missingCols)
+ newEvalWithCols.copyTagsFrom(p)
+ Some((ordering, newEvalWithCols))
+ }
+ case _ => None
+ }
case p: ProjectExec =>
extractOrderingAndPropagateOrderingColumns(p.child) match {
case Some((ordering, newChild)) =>
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
index f4de8cf89bcf..7c4382cf1d35 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
+++
b/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
+ }
+ case ArrowEvalPython(udfs, requiredChildOutput, resultAttrs, child,
evalType) =>
+ ArrowEvalPythonExec(
+ udfs, requiredChildOutput, resultAttrs, planLater(child), evalType)
:: Nil
+ case BatchEvalPython(udfs, requiredChildOutput, resultAttrs, child) =>
+ BatchEvalPythonExec(udfs, requiredChildOutput, resultAttrs,
planLater(child)) :: Nil
case BatchEvalPythonUDTF(udtf, requiredChildOutput, resultAttrs, child)
=>
BatchEvalPythonUDTFExec(udtf, requiredChildOutput, resultAttrs,
planLater(child)) :: Nil
case ArrowEvalPythonUDTF(udtf, requiredChildOutput, resultAttrs, child,
evalType) =>
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowEvalPythonExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowEvalPythonExec.scala
index 2a7df7844b0c..9277d6342b88 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowEvalPythonExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowEvalPythonExec.scala
@@ -83,6 +83,7 @@ private[spark] class BatchIterator[T](iter: Iterator[T],
batchSize: Int)
*/
case class ArrowEvalPythonExec(
udfs: Seq[PythonUDF],
+ requiredChildOutput: Seq[Attribute],
resultAttrs: Seq[Attribute],
child: SparkPlan,
evalType: Int) extends EvalPythonExec with PythonSQLMetrics {
@@ -117,10 +118,12 @@ case class ArrowEvalPythonExec(
// and columnar input is enabled, accept columnar input: the UDF inputs of a
// batch whose columns are ArrowColumnVectors are serialized to IPC directly,
// bypassing the ColumnarToRow -> ArrowWriter round-trip. Each input batch is
- // released once it has been written to Python, and the pass-through columns
- // are copied as rows and joined with the results, which are converted back
to
- // columnar batches. This node then outputs only columnar batches, so the
- // planner inserts a ColumnarToRowExec above it for a row-based parent.
+ // released once it has been written to Python. Without pass-through columns,
+ // the result batches from Python are returned as they are; otherwise the
+ // pass-through columns are copied as rows and joined with the results, which
+ // are converted back to columnar batches. This node then outputs only
+ // columnar batches, so the planner inserts a ColumnarToRowExec above it for
+ // a row-based parent.
// Otherwise it reads rows from its child, even from one that also supports
// columnar, such as the scan of the Arrow cache. Either way, the choice is
// fixed when the plan is built.
@@ -142,8 +145,8 @@ case class ArrowEvalPythonExec(
new ColumnarArrowEvalPythonEvaluatorFactory(
child.output,
udfs,
- output,
- output.toStructType,
+ requiredChildOutput,
+ resultAttrs,
conf.arrowMaxRecordsPerBatch,
conf.arrowMaxBytesPerBatch,
evalType,
@@ -158,7 +161,8 @@ case class ArrowEvalPythonExec(
new ArrowEvalPythonEvaluatorFactory(
child.output,
udfs,
- output,
+ requiredChildOutput,
+ resultAttrs,
conf.arrowMaxRecordsPerBatch,
evalType,
conf.sessionLocalTimeZone,
@@ -169,6 +173,10 @@ case class ArrowEvalPythonExec(
sessionUUID)
}
+ override def withRequiredChildOutput(
+ requiredChildOutput: Seq[Attribute]): ArrowEvalPythonExec =
+ copy(requiredChildOutput = requiredChildOutput)
+
override protected def withNewChildInternal(newChild: SparkPlan): SparkPlan =
copy(child = newChild)
@@ -189,7 +197,8 @@ case class ArrowEvalPythonExec(
class ArrowEvalPythonEvaluatorFactory(
childOutput: Seq[Attribute],
udfs: Seq[PythonUDF],
- output: Seq[Attribute],
+ passThroughOutput: Seq[Attribute],
+ resultOutput: Seq[Attribute],
batchSize: Int,
evalType: Int,
sessionLocalTimeZone: String,
@@ -198,7 +207,7 @@ class ArrowEvalPythonEvaluatorFactory(
pythonMetrics: Map[String, SQLMetric],
jobArtifactUUID: Option[String],
sessionUUID: Option[String])
- extends EvalPythonEvaluatorFactory(childOutput, udfs, output) {
+ extends EvalPythonEvaluatorFactory(childOutput, udfs, passThroughOutput,
resultOutput) {
override def evaluate(
funcs: Seq[(ChainedPythonFunctions, Long)],
@@ -207,7 +216,7 @@ class ArrowEvalPythonEvaluatorFactory(
schema: StructType,
context: TaskContext): Iterator[InternalRow] = {
- val outputTypes =
output.drop(childOutput.length).map(_.dataType.transformRecursively {
+ val outputTypes = resultOutput.map(_.dataType.transformRecursively {
case udt: UserDefinedType[_] => udt.sqlType
})
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/BatchEvalPythonExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/BatchEvalPythonExec.scala
index 3707543ee57e..4080aae02dbc 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/BatchEvalPythonExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/BatchEvalPythonExec.scala
@@ -37,7 +37,11 @@ import org.apache.spark.sql.types.{BinaryType, DataType,
StringType, StructField
/**
* A physical plan that evaluates a [[PythonUDF]]
*/
-case class BatchEvalPythonExec(udfs: Seq[PythonUDF], resultAttrs:
Seq[Attribute], child: SparkPlan)
+case class BatchEvalPythonExec(
+ udfs: Seq[PythonUDF],
+ requiredChildOutput: Seq[Attribute],
+ resultAttrs: Seq[Attribute],
+ child: SparkPlan)
extends EvalPythonExec with PythonPickleBatchMetrics {
private[this] val jobArtifactUUID =
JobArtifactSet.getCurrentJobArtifactState.map(_.uuid)
@@ -55,7 +59,8 @@ case class BatchEvalPythonExec(udfs: Seq[PythonUDF],
resultAttrs: Seq[Attribute]
new BatchEvalPythonEvaluatorFactory(
child.output,
udfs,
- output,
+ requiredChildOutput,
+ resultAttrs,
batchSize,
maxBytesPerBatch,
pythonMetrics,
@@ -67,6 +72,10 @@ case class BatchEvalPythonExec(udfs: Seq[PythonUDF],
resultAttrs: Seq[Attribute]
conf.getConf(SQLConf.PYTHON_UDF_ROW_SIZE_GUARD_MAX_ROW_HEAP_FRACTION))
}
+ override def withRequiredChildOutput(
+ requiredChildOutput: Seq[Attribute]): BatchEvalPythonExec =
+ copy(requiredChildOutput = requiredChildOutput)
+
override protected def withNewChildInternal(newChild: SparkPlan):
BatchEvalPythonExec =
copy(child = newChild)
}
@@ -74,7 +83,8 @@ case class BatchEvalPythonExec(udfs: Seq[PythonUDF],
resultAttrs: Seq[Attribute]
class BatchEvalPythonEvaluatorFactory(
childOutput: Seq[Attribute],
udfs: Seq[PythonUDF],
- output: Seq[Attribute],
+ passThroughOutput: Seq[Attribute],
+ resultOutput: Seq[Attribute],
batchSize: Int,
maxBytesPerBatch: Long,
pythonMetrics: Map[String, SQLMetric],
@@ -83,7 +93,7 @@ class BatchEvalPythonEvaluatorFactory(
binaryAsBytes: Boolean,
rowSizeGuardEnabled: Boolean = false,
rowSizeGuardMaxRowHeapFraction: Double = -1.0)
- extends EvalPythonEvaluatorFactory(childOutput, udfs, output) {
+ extends EvalPythonEvaluatorFactory(childOutput, udfs, passThroughOutput,
resultOutput) {
// This lazy val is first used in a task, even when the factory is built on
the driver.
private lazy val rowSizeGuardMaxRowBytes = if
(rowSizeGuardMaxRowHeapFraction > 0) {
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala
index 5ecb4b113472..390b66b04320 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala
@@ -24,6 +24,7 @@ import scala.jdk.CollectionConverters._
import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory,
SparkEnv, TaskContext}
import org.apache.spark.api.python.ChainedPythonFunctions
import org.apache.spark.internal.config.Python.PYTHON_UDF_PIPELINED_EXECUTION
+import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.errors.QueryExecutionErrors
import org.apache.spark.sql.execution.RowToColumnConverter
@@ -54,12 +55,13 @@ import org.apache.spark.util.Utils
* reuse `WritableColumnVector`s across batches, the Arrow cache releases
* the vectors of a batch when the next one is read, and the Python output
* of a stacked [[ArrowEvalPythonExec]] is loaded into the same vectors for
- * every batch. So both paths copy the pass-through columns into a
- * [[HybridRowQueue]], release a batch with closeIfFreeable once it has been
- * written to Python, join the results by row and convert the joined rows
- * back to [[ColumnarBatch]]. Input batches without rows are released and
- * skipped, so that the UDFs are not called with empty input, as on the row
- * path.
+ * every batch. So both paths release a batch with closeIfFreeable once it
+ * has been written to Python. If no column of the child is passed through,
+ * the result batches from Python are the output batches. Otherwise the
+ * pass-through columns are copied into a [[HybridRowQueue]], joined with the
+ * results by row, and the joined rows are converted back to
+ * [[ColumnarBatch]]. Input batches without rows are released and skipped, so
+ * that the UDFs are not called with empty input, as on the row path.
*
* TODO: Add a physical plan rule that inserts a ProjectExec before
* ArrowEvalPythonExec to pre-evaluate complex UDF input expressions
@@ -69,8 +71,8 @@ import org.apache.spark.util.Utils
private[python] class ColumnarArrowEvalPythonEvaluatorFactory(
childOutput: Seq[Attribute],
udfs: Seq[PythonUDF],
- output: Seq[Attribute],
- outputSchema: StructType,
+ passThroughOutput: Seq[Attribute],
+ resultOutput: Seq[Attribute],
batchSize: Int,
maxBytesPerBatch: Long,
evalType: Int,
@@ -82,6 +84,10 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
sessionUUID: Option[String])
extends PartitionEvaluatorFactory[ColumnarBatch, ColumnarBatch] {
+ // The output is the pass-through columns of the child followed by the
results of the UDFs.
+ private val output = passThroughOutput ++ resultOutput
+ private val outputSchema = output.toStructType
+
override def createEvaluator()
: PartitionEvaluator[ColumnarBatch, ColumnarBatch] =
new ColumnarArrowEvalPythonPartitionEvaluator
@@ -140,7 +146,7 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
StructField(s"_$i", dt)
}.toArray)
- val outputTypes = output.drop(childOutput.length).map(
+ val outputTypes = resultOutput.map(
_.dataType.transformRecursively {
case udt: UserDefinedType[_] => udt.sqlType
})
@@ -150,8 +156,25 @@ 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.
+ // The result batches are as large as the ones Python returns, unless
+ // maxRecordsPerOutputBatch or maxBytesPerOutputBatch slices them, and
are not cut by
+ // maxRecordsPerBatch or maxBytesPerBatch as the rows converted back
below are. So a
+ // parent that takes columnar input, e.g. a stacked evaluation or the
Arrow cache, gets
+ // them at that size, as it gets the batches of any other columnar
child. A stacked
+ // evaluation does not split its input batches yet either.
+ evalPython(nonEmptyIter, context, pyFuncs, argMetas, allInputs.toSeq,
udfInputSchema,
+ inputColumnIndices, onInputRow = None).map { batch =>
+ validateOutputTypes(batch, outputTypes)
+ batch
+ }
+ } else {
+ evalWithRowQueue(nonEmptyIter, context, pyFuncs, argMetas,
+ allInputs.toSeq, udfInputSchema, outputTypes, inputColumnIndices)
+ }
}
private def resolveColumnIndices(
@@ -166,39 +189,23 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
}
/**
- * Uses HybridRowQueue for pass-through, joins rows, then
- * converts back to ColumnarBatch via RowToColumnConverter.
+ * Sends the UDF inputs of the batches to Python and returns the result
batches, calling
+ * `onInputRow` with each input row before its batch is released.
*/
- private def evalWithRowQueue(
+ private def evalPython(
inputIter: Iterator[ColumnarBatch],
context: TaskContext,
pyFuncs: Seq[(ChainedPythonFunctions, Long)],
argMetas: Array[Array[ArgumentMetadata]],
allInputs: Seq[Expression],
udfInputSchema: StructType,
- outputTypes: Seq[DataType],
- inputColumnIndices: Option[Array[Int]]
+ inputColumnIndices: Option[Array[Int]],
+ onInputRow: Option[InternalRow => Unit]
): Iterator[ColumnarBatch] = {
-
- // In pipelined mode the queue's add() runs in the writer thread and
remove() runs in
- // the task thread; use lock-free mode to skip per-row synchronization.
- val pipelined = SparkEnv.get.conf.get(PYTHON_UDF_PIPELINED_EXECUTION)
- val queue = HybridRowQueue(
- context.taskMemoryManager(),
- new File(Utils.getLocalDir(SparkEnv.get.conf)),
- childOutput.length,
- lockFree = pipelined)
- context.addTaskCompletionListener[Unit] { _ => queue.close() }
-
- val unsafeProj = UnsafeProjection.create(
- childOutput, childOutput)
-
- val resultIter = if (inputColumnIndices.isDefined) {
+ if (inputColumnIndices.isDefined) {
// Simple column refs: the writer sends Arrow-backed batches directly.
val bufferedIter = new WrittenBatchReleasingIterator(inputIter, {
batch =>
- batch.rowIterator().asScala.foreach { row =>
- queue.add(unsafeProj(row).copy())
- }
+ onInputRow.foreach(f => batch.rowIterator().asScala.foreach(f))
true
})
val pyRunner =
@@ -218,7 +225,7 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
// for the next batch, which releases it.
val batchIter = new WrittenBatchReleasingIterator(inputIter, _ =>
true).map { batch =>
batch.rowIterator().asScala.map { row =>
- queue.add(unsafeProj(row).copy())
+ onInputRow.foreach(_(row))
projection(row)
}
}
@@ -231,6 +238,39 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
pyRunner.compute(
batchIter, context.partitionId(), context)
}
+ }
+
+ /**
+ * Uses HybridRowQueue for pass-through, joins rows, then
+ * converts back to ColumnarBatch via RowToColumnConverter.
+ */
+ private def evalWithRowQueue(
+ inputIter: Iterator[ColumnarBatch],
+ context: TaskContext,
+ pyFuncs: Seq[(ChainedPythonFunctions, Long)],
+ argMetas: Array[Array[ArgumentMetadata]],
+ allInputs: Seq[Expression],
+ udfInputSchema: StructType,
+ outputTypes: Seq[DataType],
+ inputColumnIndices: Option[Array[Int]]
+ ): Iterator[ColumnarBatch] = {
+
+ // In pipelined mode the queue's add() runs in the writer thread and
remove() runs in
+ // the task thread; use lock-free mode to skip per-row synchronization.
+ val pipelined = SparkEnv.get.conf.get(PYTHON_UDF_PIPELINED_EXECUTION)
+ val queue = HybridRowQueue(
+ context.taskMemoryManager(),
+ new File(Utils.getLocalDir(SparkEnv.get.conf)),
+ passThroughOutput.length,
+ lockFree = pipelined)
+ context.addTaskCompletionListener[Unit] { _ => queue.close() }
+
+ // Copies the pass-through columns of an input row before its batch is
released.
+ val unsafeProj = UnsafeProjection.create(passThroughOutput, childOutput)
+
+ val resultIter = evalPython(inputIter, context, pyFuncs, argMetas,
allInputs,
+ udfInputSchema, inputColumnIndices,
+ onInputRow = Some(row => queue.add(unsafeProj(row).copy())))
val joined = new JoinedRow
val resultProj = UnsafeProjection.create(output, output)
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonEvaluatorFactory.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonEvaluatorFactory.scala
index 8730adc12b42..1364bd6c864f 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonEvaluatorFactory.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonEvaluatorFactory.scala
@@ -30,12 +30,22 @@ 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 passThroughOutput the columns of the child that are passed through
to the output
+ * @param resultOutput the columns of the results of the UDFs, one for each UDF
+ */
abstract class EvalPythonEvaluatorFactory(
childOutput: Seq[Attribute],
udfs: Seq[PythonUDF],
- output: Seq[Attribute])
+ protected val passThroughOutput: Seq[Attribute],
+ protected val resultOutput: Seq[Attribute])
extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+ /** The output rows: the pass-through columns followed by the results of the
UDFs. */
+ protected val output: Seq[Attribute] = passThroughOutput ++ resultOutput
+
protected def evaluate(
funcs: Seq[(ChainedPythonFunctions, Long)],
argMetas: Array[Array[ArgumentMetadata]],
@@ -112,8 +122,17 @@ abstract class EvalPythonEvaluatorFactory(
val joinedRows = evaluateJoined(pyFuncs, argMetas, iter,
allInputs.toSeq, schema, context)
if (joinedRows.isDefined) return joinedRows.get
- // The queue used to buffer input rows so we can drain it to
- // combine input with output from Python.
+ val projection = MutableProjection.create(allInputs.toSeq, childOutput)
+ projection.initialize(context.partitionId())
+
+ if (passThroughOutput.isEmpty) {
+ // No column of the child is passed through, so the results are the
output rows.
+ val resultProj = UnsafeProjection.create(resultOutput, resultOutput)
+ return evaluate(pyFuncs, argMetas, iter.map(projection), schema,
context).map(resultProj)
+ }
+
+ // The queue used to buffer the passed-through columns of the input rows
so we can drain it
+ // to combine them with output from Python.
// In pipelined mode, add() runs in the writer thread and remove() in
the task thread.
// Use lock-free mode to avoid synchronized overhead (memory visibility
is guaranteed
// by the blocking socket I/O between the two threads).
@@ -121,18 +140,25 @@ abstract class EvalPythonEvaluatorFactory(
val queue = HybridRowQueue(
context.taskMemoryManager(),
new File(Utils.getLocalDir(SparkEnv.get.conf)),
- childOutput.length,
+ passThroughOutput.length,
lockFree = pipelined)
context.addTaskCompletionListener[Unit] { ctx =>
queue.close()
}
- val projection = MutableProjection.create(allInputs.toSeq, childOutput)
- projection.initialize(context.partitionId())
+ // The queue copies each row it adds, so a projection may reuse its
output row.
+ val passThrough: InternalRow => UnsafeRow =
+ if (passThroughOutput.map(_.exprId) == childOutput.map(_.exprId)) {
+ _.asInstanceOf[UnsafeRow]
+ } else {
+ val passThroughProj = UnsafeProjection.create(passThroughOutput,
childOutput)
+ passThroughProj.initialize(context.partitionId())
+ passThroughProj(_)
+ }
// Add rows to queue to join later with the result.
val projectedRowIter = iter.map { inputRow =>
- queue.add(inputRow.asInstanceOf[UnsafeRow])
+ queue.add(passThrough(inputRow))
projection(inputRow)
}
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonExec.scala
index 6e4ebe640ad6..d8771c049045 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonExec.scala
@@ -37,11 +37,13 @@ object EvalPythonExec {
* A physical plan that evaluates a [[PythonUDF]], one partition of tuples at
a time.
*
* Python evaluation works by sending the necessary (projected) input data via
a socket to an
- * external Python process, and combine the result from the Python process
with the original row.
+ * external Python process, and combine the result from the Python process
with the columns of the
+ * original row that are passed through (`requiredChildOutput`).
*
- * For each row we send to Python, we also put it in a queue first. For each
output row from Python,
- * we drain the queue to find the original input row. Note that if the Python
process is way too
- * slow, this could lead to the queue growing unbounded and spill into disk
when run out of memory.
+ * For each row we send to Python, we also put its pass-through columns in a
queue first. For each
+ * output row from Python, we drain the queue to find them. Note that if the
Python process is way
+ * too slow, this could lead to the queue growing unbounded and spill into
disk when run out of
+ * memory. If no column is passed through, the results from Python are the
output rows.
*
* Here is a diagram to show how this works:
*
@@ -61,11 +63,18 @@ 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]
+ /** Returns a copy that passes through `requiredChildOutput` of the child. */
+ def withRequiredChildOutput(requiredChildOutput: Seq[Attribute]):
EvalPythonExec
+
protected def evaluatorFactory: EvalPythonEvaluatorFactory
- override def output: Seq[Attribute] = child.output ++ resultAttrs
+ override def output: Seq[Attribute] = requiredChildOutput ++ resultAttrs
override def producedAttributes: AttributeSet = AttributeSet(resultAttrs)
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFs.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFs.scala
index a784718084f2..baee252fe5ee 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFs.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFs.scala
@@ -343,7 +343,7 @@ object ExtractPythonUDFs extends Rule[LogicalPlan] with
Logging {
log"${MDC(REASON, "UDT input or return type")}. " +
log"Falling back to non-Arrow-optimized UDF execution.")
}
- BatchEvalPython(validUdfs, resultAttrs, child)
+ BatchEvalPython(validUdfs, child.output, resultAttrs, child)
case PythonEvalType.SQL_SCALAR_PANDAS_UDF
| PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF
| PythonEvalType.SQL_ARROW_BATCHED_UDF
@@ -355,7 +355,7 @@ object ExtractPythonUDFs extends Rule[LogicalPlan] with
Logging {
| PythonEvalType.SQL_SCALAR_ARROW_UDF
| PythonEvalType.SQL_SCALAR_ARROW_INPROCESS_UDF
| PythonEvalType.SQL_SCALAR_ARROW_ITER_UDF =>
- ArrowEvalPython(validUdfs, resultAttrs, child, evalType)
+ ArrowEvalPython(validUdfs, child.output, resultAttrs, child,
evalType)
case _ =>
throw SparkException.internalError("Unexpected UDF evalType")
}
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowEvalPythonEvaluatorFactory.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowEvalPythonEvaluatorFactory.scala
index 3a13c63cc1c2..959546805fd8 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowEvalPythonEvaluatorFactory.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowEvalPythonEvaluatorFactory.scala
@@ -59,7 +59,8 @@ import org.apache.spark.util.Utils
class InProcessArrowEvalPythonEvaluatorFactory(
childOutput: Seq[Attribute],
udfs: Seq[PythonUDF],
- output: Seq[Attribute],
+ passThroughOutput: Seq[Attribute],
+ resultOutput: Seq[Attribute],
batchSize: Int,
maxBytes: Long,
timeZoneId: String,
@@ -69,7 +70,7 @@ class InProcessArrowEvalPythonEvaluatorFactory(
tracebackWithLocals: Boolean,
fullValidation: Boolean,
metrics: Map[String, SQLMetric])
- extends EvalPythonEvaluatorFactory(childOutput, udfs, output) {
+ extends EvalPythonEvaluatorFactory(childOutput, udfs, passThroughOutput,
resultOutput) {
private[python] def runtimeSession:
InProcessPythonRuntime.InterpreterSession =
InProcessPythonRuntime.currentSession
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowEvalPythonExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowEvalPythonExec.scala
index c591544e8f1e..10192fb969c4 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowEvalPythonExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowEvalPythonExec.scala
@@ -30,6 +30,10 @@ case class InProcessArrowEvalPythonExec(
resultAttrs: Seq[Attribute],
child: SparkPlan) extends EvalPythonExec with PythonSQLMetrics {
+ // The in-process evaluator joins the results with the whole input row, or
reads the input
+ // back from Arrow, so it passes through the whole child; the planner drops
what is unused.
+ override def requiredChildOutput: Seq[Attribute] = child.output
+
// The keys of `PythonSQLMetrics` without `pythonBootTime`, since there are
no workers to
// start, and with descriptions of in-process execution. Times are summed in
nanoseconds
// across tasks, since a registration or a batch can take less than a
millisecond.
@@ -54,12 +58,20 @@ case class InProcessArrowEvalPythonExec(
override protected def evaluatorFactory: EvalPythonEvaluatorFactory = {
new InProcessArrowEvalPythonEvaluatorFactory(
- child.output, udfs, output, conf.arrowMaxRecordsPerBatch,
conf.arrowMaxBytesPerBatch,
+ child.output, udfs, requiredChildOutput, resultAttrs,
conf.arrowMaxRecordsPerBatch,
+ conf.arrowMaxBytesPerBatch,
conf.sessionLocalTimeZone, conf.arrowUseLargeVarTypes,
conf.pysparkHideTraceback,
conf.pysparkSimplifiedTraceback, conf.pysparkTracebackWithLocals,
conf.getConf(SQLConf.PYTHON_UDF_IN_PROCESS_FULL_VALIDATION),
pythonMetrics)
}
+ // It passes through the whole child, which includes any required columns.
+ override def withRequiredChildOutput(
+ requiredChildOutput: Seq[Attribute]): InProcessArrowEvalPythonExec = {
+ assert(requiredChildOutput.forall(child.outputSet.contains))
+ this
+ }
+
override protected def withNewChildInternal(newChild: SparkPlan): SparkPlan =
copy(child = newChild)
}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowBackedDataSourceV2.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowBackedDataSourceV2.scala
index e21038d695d3..0d3cae279ccd 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowBackedDataSourceV2.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowBackedDataSourceV2.scala
@@ -20,8 +20,6 @@ import java.nio.charset.StandardCharsets.UTF_8
import java.util
import java.util.concurrent.atomic.AtomicInteger
-import scala.jdk.CollectionConverters._
-
import org.apache.arrow.memory.BufferAllocator
import org.apache.arrow.vector._
@@ -115,9 +113,12 @@ private class ArrowBackedTable(options:
CaseInsensitiveStringMap)
}
}
-/** Scan builder / Scan / Batch implementation. */
+/**
+ * Scan builder / Scan / Batch implementation. If the option `pruneColumns` is
true, the scan reads
+ * only the columns that the query requires.
+ */
private class ArrowBackedScanBuilder(options: CaseInsensitiveStringMap)
- extends ScanBuilder with Scan with Batch {
+ extends ScanBuilder with SupportsPushDownRequiredColumns with Scan with
Batch {
private val numRows =
options.getInt("numRows", ArrowBackedDataSourceV2.DEFAULT_NUM_ROWS)
@@ -128,7 +129,14 @@ private class ArrowBackedScanBuilder(options:
CaseInsensitiveStringMap)
override def toBatch: Batch = this
- override def readSchema(): StructType = ArrowBackedDataSourceV2.SCHEMA
+ private val supportsColumnPruning = options.getBoolean("pruneColumns", false)
+ private var requiredSchema = ArrowBackedDataSourceV2.SCHEMA
+
+ override def pruneColumns(requiredSchema: StructType): Unit = {
+ if (supportsColumnPruning) this.requiredSchema = requiredSchema
+ }
+
+ override def readSchema(): StructType = requiredSchema
override def planInputPartitions(): Array[InputPartition] = {
val rowsPerPartition = numRows / numPartitions
@@ -152,7 +160,8 @@ private class ArrowBackedScanBuilder(options:
CaseInsensitiveStringMap)
override def createReaderFactory(): PartitionReaderFactory = {
new ArrowBackedReaderFactory(
- columnar, reuseVectors, batchSize, arrowIdColumn, emptyBatches)
+ columnar, reuseVectors, batchSize, arrowIdColumn, emptyBatches,
+ requiredSchema.fieldNames.map(ArrowBackedDataSourceV2.SCHEMA.fieldIndex))
}
}
@@ -172,13 +181,15 @@ private case class ArrowPartition(start: Int, end: Int)
* @param emptyBatches if true, the reader with fresh vectors also returns
* [[ArrowBackedDataSourceV2.NUM_EMPTY_BATCHES]] batches without rows,
first, in the middle and
* last.
+ * @param columnIndices the indices of the columns of the schema to read
*/
private class ArrowBackedReaderFactory(
columnar: Boolean,
reuseVectors: Boolean,
batchSize: Int,
arrowIdColumn: Boolean,
- emptyBatches: Boolean)
+ emptyBatches: Boolean,
+ columnIndices: Array[Int])
extends PartitionReaderFactory {
override def supportColumnarReads(
@@ -187,7 +198,8 @@ private class ArrowBackedReaderFactory(
override def createReader(
partition: InputPartition): PartitionReader[InternalRow] = {
val ArrowPartition(start, end) = partition
- val inner = new ArrowBackedPartitionReader(start, end, batchSize,
arrowIdColumn)
+ val inner = new ArrowBackedPartitionReader(
+ start, end, batchSize, columnIndices, arrowIdColumn)
// Wrap columnar reader as row reader.
new PartitionReader[InternalRow] {
private var rowIter: java.util.Iterator[InternalRow] = _
@@ -206,9 +218,10 @@ private class ArrowBackedReaderFactory(
partition: InputPartition): PartitionReader[ColumnarBatch] = {
val ArrowPartition(start, end) = partition
if (reuseVectors) {
- new ReusingArrowPartitionReader(start, end, batchSize)
+ new ReusingArrowPartitionReader(start, end, batchSize, columnIndices)
} else {
- new ArrowBackedPartitionReader(start, end, batchSize, arrowIdColumn,
emptyBatches)
+ new ArrowBackedPartitionReader(
+ start, end, batchSize, columnIndices, arrowIdColumn, emptyBatches)
}
}
}
@@ -219,7 +232,8 @@ private class ArrowBackedReaderFactory(
* may: a batch is only valid until the next one. Its columns are
[[ReusedArrowColumnVector]]s,
* whose closeIfFreeable is a no-op.
*/
-private class ReusingArrowPartitionReader(start: Int, end: Int, batchSize: Int)
+private class ReusingArrowPartitionReader(
+ start: Int, end: Int, batchSize: Int, columnIndices: Array[Int])
extends PartitionReader[ColumnarBatch] {
private var current = start
private val allocator = ArrowUtils.rootAllocator.newChildAllocator(
@@ -228,8 +242,9 @@ private class ReusingArrowPartitionReader(start: Int, end:
Int, batchSize: Int)
ArrowUtils.toArrowSchema(ArrowBackedDataSourceV2.SCHEMA, null,
errorOnDuplicatedFieldNames = true, largeVarTypes = false),
allocator)
- private val batch = new ColumnarBatch(
- root.getFieldVectors.asScala.map(new ReusedArrowColumnVector(_):
ColumnVector).toArray)
+ private val batch = new ColumnarBatch(columnIndices.map { i =>
+ new ReusedArrowColumnVector(root.getFieldVectors.get(i)): ColumnVector
+ })
override def next(): Boolean = {
if (current >= end) return false
@@ -278,12 +293,14 @@ private class ReusingArrowPartitionReader(start: Int,
end: Int, batchSize: Int)
* not an [[ArrowColumnVector]]. If `emptyBatches` is true, the reader also
returns
* [[ArrowBackedDataSourceV2.NUM_EMPTY_BATCHES]] batches without rows: before
the first batch,
* after half of the batches and after the last one. Some of them are adjacent
if there are fewer
- * than two batches.
+ * than two batches. The batches have the columns at `columnIndices`, the
first of which counts the
+ * releases; the others are closed.
*/
private class ArrowBackedPartitionReader(
start: Int,
end: Int,
batchSize: Int,
+ columnIndices: Array[Int],
arrowIdColumn: Boolean = true,
emptyBatches: Boolean = false)
extends PartitionReader[ColumnarBatch] {
@@ -380,15 +397,15 @@ private class ArrowBackedPartitionReader(
allocator, "data", count)
// Wrap in ArrowColumnVectors
- val columns: Array[ColumnVector] = Array(
- if (arrowIdColumn) {
- new ReleaseCountingArrowColumnVector(idVector)
- } else {
- new ReleaseCountingColumnVector(new ArrowColumnVector(idVector))
- },
- new ArrowColumnVector(nameVector),
- new ArrowColumnVector(valueVector),
- new ArrowColumnVector(dataVector))
+ val vectors = Array[ValueVector](idVector, nameVector, valueVector,
dataVector)
+
vectors.indices.filterNot(columnIndices.contains).foreach(vectors(_).close())
+ val columns: Array[ColumnVector] = columnIndices.zipWithIndex.map {
+ case (0, pos) if !arrowIdColumn =>
+ val vector = new ArrowColumnVector(idVector)
+ if (pos == 0) new ReleaseCountingColumnVector(vector) else vector
+ case (i, 0) => new ReleaseCountingArrowColumnVector(vectors(i))
+ case (i, _) => new ArrowColumnVector(vectors(i))
+ }
currentBatch = new ColumnarBatch(columns, count)
allBatches.synchronized {
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala
index 997cfb45a156..05946b745e57 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala
@@ -23,6 +23,7 @@ import
org.apache.spark.internal.config.Python.PYTHON_UDF_PIPELINED_EXECUTION
import org.apache.spark.sql.{DataFrame, IntegratedUDFTestUtils}
import org.apache.spark.sql.catalyst.expressions.AttributeReference
import org.apache.spark.sql.execution.{ColumnarToRowExec, SparkPlan,
SQLExecution, WholeStageCodegenExec}
+import org.apache.spark.sql.execution.vectorized.ReusedArrowColumnVector
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types.{StringType, StructType}
@@ -51,7 +52,8 @@ class ArrowColumnarPythonUDFSuite extends SharedSparkSession {
reuseVectors: Boolean = false,
batchSize: Int = ArrowBackedDataSourceV2.BATCH_SIZE,
arrowIdColumn: Boolean = true,
- emptyBatches: Boolean = false) = {
+ emptyBatches: Boolean = false,
+ pruneColumns: Boolean = false) = {
spark.read
.format(arrowSource)
.option("numRows", numRows.toString)
@@ -60,6 +62,7 @@ class ArrowColumnarPythonUDFSuite extends SharedSparkSession {
.option("batchSize", batchSize.toString)
.option("arrowIdColumn", arrowIdColumn.toString)
.option("emptyBatches", emptyBatches.toString)
+ .option("pruneColumns", pruneColumns.toString)
.load()
}
@@ -416,6 +419,116 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
}
}
+ test("Without pass-through columns, the results of Python are the output
batches") {
+ assume(shouldTestPandasUDFs)
+ val pandasUDF = TestScalarPandasUDF(name = "arrow_direct_udf", returnType
= Some(StringType))
+ registerTestUDF(pandasUDF, spark)
+
+ val numRows = 2000
+ val numBatches = 20
+ // On a string column, the cast of the test UDF is removed, so the UDF
inputs are column
+ // references; on an expression, the row fallback path is taken.
+ for {
+ codegen <- Seq(true, false)
+ reuseVectors <- Seq(true, false)
+ (input, suffix) <- Seq(("name", ""), ("concat(name, '_')", "_"))
+ } withSQLConf(
+ SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString,
+ // The joined rows would be sliced to this, but the results of Python
are not.
+ SQLConf.ARROW_EXECUTION_MAX_RECORDS_PER_BATCH.key -> "30") {
+ withClue(s"codegen=$codegen, reuseVectors=$reuseVectors, input=$input:
") {
+ // The scan reads only the arguments, so that it stays columnar under
the evaluation.
+ val result = readArrowSource(numRows = numRows, batchSize = numRows /
numBatches,
+ reuseVectors = reuseVectors, pruneColumns = true)
+ .selectExpr(s"arrow_direct_udf($input) as u")
+ val arrowExec =
singleArrowEvalPythonExec(result.queryExecution.executedPlan)
+ assert(arrowExec.requiredChildOutput.isEmpty)
+ assert(arrowExec.output == arrowExec.resultAttrs)
+ assert(arrowExec.child.output.map(_.name) == Seq("name"))
+
+ // Each input batch has one result batch from Python, over the vectors
of its reader.
+ val batches = SQLExecution.withSQLConfPropagated(spark) {
+ arrowExec.executeColumnar().mapPartitionsInternal(_.map { batch =>
+ (batch.numRows(),
batch.column(0).isInstanceOf[ReusedArrowColumnVector])
+ }).collect().toSeq
+ }
+ assert(batches == Seq.fill(numBatches)((numRows / numBatches, true)))
+
+ ArrowBackedDataSourceV2.resetBatchCounters()
+ assert(result.collect().map(_.getString(0)).toSeq ==
+ (0 until numRows).map(id => s"row_$id$suffix"))
+ if (!reuseVectors) {
+ // A batch is released before the next one is read.
+ assert(ArrowBackedDataSourceV2.returnedBatches.get == numBatches)
+ assert(ArrowBackedDataSourceV2.releasedBatches.get == numBatches)
+ assert(ArrowBackedDataSourceV2.maxUnreleasedBatches.get == 1)
+ }
+
+ // A filter and a projection above, and a limit.
+ assert(result.where("u like 'row_1%'").selectExpr("concat(u,
'!')").collect()
+ .map(_.getString(0)).toSet ==
+ (0 until numRows).map(id =>
s"row_$id$suffix").filter(_.startsWith("row_1"))
+ .map(_ + "!").toSet)
+ assert(result.limit(10).collect().map(_.getString(0)).toSeq ==
+ (0 until 10).map(id => s"row_$id$suffix"))
+ }
+ }
+ }
+
+ test("Only the pass-through columns used above are copied with columnar
input") {
+ assume(shouldTestPandasUDFs)
+ withSQLConf(SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true") {
+ val pandasUDF = TestScalarPandasUDF(name = "arrow_some_udf", returnType
= Some(StringType))
+ registerTestUDF(pandasUDF, spark)
+
+ val numRows = 2000
+ Seq(true, false).foreach { reuseVectors =>
+ val result = readArrowSource(numRows = numRows, batchSize = 100,
+ reuseVectors = reuseVectors, pruneColumns = true)
+ .selectExpr("id", "arrow_some_udf(name) as u")
+ val arrowExec =
singleArrowEvalPythonExec(result.queryExecution.executedPlan)
+ assert(arrowExec.supportsColumnar)
+ assert(arrowExec.requiredChildOutput.map(_.name) == Seq("id"))
+ assert(arrowExec.child.output.map(_.name).toSet == Set("id", "name"))
+
+ val rows = result.collect()
+ assert(rows.map(_.getInt(0)).toSeq == (0 until numRows))
+ assert(rows.forall(row => row.getString(1) == s"row_${row.getInt(0)}"))
+ }
+ }
+ }
+
+ test("Stacked Python UDFs without pass-through columns over an Arrow-backed
source") {
+ assume(shouldTestPythonUDFs && shouldTestPandasUDFs)
+ withSQLConf(SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true") {
+ val innerUDF = TestPythonUDF(name = "arrow_inner_direct_udf",
+ returnType = Some(StringType), pythonEvalType =
PythonEvalType.SQL_ARROW_BATCHED_UDF)
+ val outerUDF = TestScalarPandasUDF(
+ name = "arrow_outer_direct_udf", returnType = Some(StringType))
+ registerTestUDF(innerUDF, spark)
+ registerTestUDF(outerUDF, spark)
+
+ val numRows = 2000
+ Seq(true, false).foreach { reuseVectors =>
+ val result = readArrowSource(numRows = numRows, batchSize = 100,
+ reuseVectors = reuseVectors, pruneColumns = true)
+ .selectExpr("arrow_outer_direct_udf(arrow_inner_direct_udf(name)) as
u")
+ val plan = result.queryExecution.executedPlan
+ val execs = collectNodes[ArrowEvalPythonExec](plan)
+ assert(execs.length == 2, s"Expected two ArrowEvalPythonExecs in
plan:\n$plan")
+ assert(execs.forall(e => e.supportsColumnar &&
e.requiredChildOutput.isEmpty))
+ // The outer one sends the result batches of the inner one to Python
as they are.
+ val outerExec =
execs.find(_.child.isInstanceOf[ArrowEvalPythonExec]).getOrElse(
+ fail(s"Expected stacked ArrowEvalPythonExecs in plan:\n$plan"))
+
assert(outerExec.udfs.head.children.forall(_.isInstanceOf[AttributeReference]))
+
+ assert(result.collect().map(_.getString(0)).toSeq ==
+ (0 until numRows).map(id => s"row_$id"))
+ }
+ }
+ }
+
test("Arrow-backed source: multiple UDF columns") {
assume(shouldTestPandasUDFs)
withSQLConf(SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true") {
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/BatchEvalPythonExecSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/BatchEvalPythonExecSuite.scala
index 74b80cfc3202..2290d7011466 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/BatchEvalPythonExecSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/BatchEvalPythonExecSuite.scala
@@ -121,7 +121,8 @@ class BatchEvalPythonExecSuite extends SharedSparkSession
val factory = new BatchEvalPythonEvaluatorFactory(
childOutput = Seq(taskAttr),
udfs = Seq(pythonUdf),
- output = Seq.empty,
+ passThroughOutput = Seq.empty,
+ resultOutput = Seq.empty,
batchSize = 1,
maxBytesPerBatch = -1L,
pythonMetrics = Map.empty,
@@ -172,6 +173,7 @@ class BatchEvalPythonExecSuite extends SharedSparkSession
udfDeterministic = true)
class TestBatchEvalPythonExec extends BatchEvalPythonExec(
Seq(pythonUdf),
+ Seq(taskAttr),
Seq(AttributeReference("result", StringType)()),
LocalTableScanExec(Seq(taskAttr), Nil, None)) {
def testEvaluatorFactory: BatchEvalPythonEvaluatorFactory =
@@ -202,7 +204,8 @@ class BatchEvalPythonExecSuite extends SharedSparkSession
(new BatchEvalPythonEvaluatorFactory(
childOutput = Seq(taskAttr),
udfs = Seq.empty,
- output = Seq.empty,
+ passThroughOutput = Seq.empty,
+ resultOutput = Seq.empty,
batchSize = 1,
maxBytesPerBatch = -1L,
pythonMetrics = Map.empty,
@@ -425,7 +428,7 @@ class BatchEvalPythonExecSuite extends SharedSparkSession
case f @ FilterExec(
And(_: AttributeReference, _: AttributeReference),
InputAdapter(_: BatchEvalPythonExec)) => f
- case b @ BatchEvalPythonExec(_, _, WholeStageCodegenExec(FilterExec(_:
In, _))) => b
+ case b @ BatchEvalPythonExec(_, _, _,
WholeStageCodegenExec(FilterExec(_: In, _))) => b
}
assert(qualifiedPlanNodes.size == 2)
}
@@ -435,7 +438,7 @@ class BatchEvalPythonExecSuite extends SharedSparkSession
.where("dummyPythonUDF(a, dummyPythonUDF(a, b)) and a in (3, 4)")
val qualifiedPlanNodes = df.queryExecution.executedPlan.collect {
case f @ FilterExec(_: AttributeReference, InputAdapter(_:
BatchEvalPythonExec)) => f
- case b @ BatchEvalPythonExec(_, _, WholeStageCodegenExec(FilterExec(_:
In, _))) => b
+ case b @ BatchEvalPythonExec(_, _, _,
WholeStageCodegenExec(FilterExec(_: In, _))) => b
}
assert(qualifiedPlanNodes.size == 2)
}
@@ -447,7 +450,7 @@ class BatchEvalPythonExecSuite extends SharedSparkSession
case f @ FilterExec(
And(_: AttributeReference, _: GreaterThan),
InputAdapter(_: BatchEvalPythonExec)) => f
- case b @ BatchEvalPythonExec(_, _, WholeStageCodegenExec(_: FilterExec))
=> b
+ case b @ BatchEvalPythonExec(_, _, _, WholeStageCodegenExec(_:
FilterExec)) => b
}
assert(qualifiedPlanNodes.size == 2)
}
@@ -460,7 +463,7 @@ class BatchEvalPythonExecSuite extends SharedSparkSession
case f @ FilterExec(
And(_: AttributeReference, _: GreaterThan),
InputAdapter(_: BatchEvalPythonExec)) => f
- case b @ BatchEvalPythonExec(_, _, WholeStageCodegenExec(_: FilterExec))
=> b
+ case b @ BatchEvalPythonExec(_, _, _, WholeStageCodegenExec(_:
FilterExec)) => b
}
assert(qualifiedPlanNodes.size == 2)
}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFsSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFsSuite.scala
index 4c4273006b92..682d8a302f97 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFsSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFsSuite.scala
@@ -17,13 +17,15 @@
package org.apache.spark.sql.execution.python
+import org.apache.spark.sql.{DataFrame, Row}
import org.apache.spark.sql.catalyst.plans.logical.{ArrowEvalPython,
BatchEvalPython, Limit, LocalLimit}
import org.apache.spark.sql.execution.{FileSourceScanExec, SparkPlan}
import org.apache.spark.sql.execution.datasources.v2.BatchScanExec
import org.apache.spark.sql.execution.datasources.v2.parquet.ParquetScan
-import org.apache.spark.sql.functions.col
+import org.apache.spark.sql.functions.{col, count}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DoubleType, LongType, StringType,
StructType}
class ExtractPythonUDFsSuite extends SharedSparkSession {
import testImplicits._
@@ -236,5 +238,66 @@ class ExtractPythonUDFsSuite extends SharedSparkSession {
case _ =>
}
}
-}
+ // A relation with the columns a, b and c, which are not aliases of other
columns.
+ private def threeColumns: DataFrame = spark.createDataFrame(
+ java.util.List.of(Row("Hello", 4L, 1.0)),
+ new StructType().add("a", StringType).add("b", LongType).add("c",
DoubleType))
+
+ test("Python UDF evaluation passes through only the columns of its child
that are used") {
+ val df = threeColumns
+ val arrowIterUDF = new MyDummyScalarArrowIterUDF
+ // The physical nodes evaluating the UDFs, with the names of the columns
they pass through.
+ // Adaptive execution is disabled to see the plan below an exchange before
it runs.
+ def passThrough(df: DataFrame): Seq[(String, Seq[String])] =
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ df.queryExecution.executedPlan.collect {
+ case e: EvalPythonExec =>
+ assert(e.output == e.requiredChildOutput ++ e.resultAttrs)
+ assert(e.requiredChildOutput.forall(e.child.outputSet.contains))
+ (e.nodeName, e.requiredChildOutput.map(_.name))
+ }
+ }
+
+ Seq(
+ ("BatchEvalPython", batchedPythonUDF),
+ ("ArrowEvalPython", scalarPandasUDF),
+ ("ArrowEvalPython", arrowIterUDF)).foreach { case (nodeName, udf) =>
+ withClue(s"$nodeName: ") {
+ // The arguments are not passed through unless the parent uses them.
+ assert(passThrough(df.select(udf(col("a")))) == Seq(nodeName -> Nil))
+ assert(passThrough(df.select(col("b"), udf(col("a")))) == Seq(nodeName
-> Seq("b")))
+ assert(passThrough(df.select(col("a"), udf(col("a")))) == Seq(nodeName
-> Seq("a")))
+ assert(passThrough(df.withColumn("u", udf(col("a")))) ==
+ Seq(nodeName -> Seq("a", "b", "c")))
+ // Through a filter on the result, and a filter on the result alone.
+ assert(passThrough(df.select(udf(col("a")).as("u"),
col("c")).where(col("u"))) ==
+ Seq(nodeName -> Seq("c")))
+ assert(passThrough(df.where(udf(col("a"))).select(col("b"))) ==
+ Seq(nodeName -> Seq("b")))
+ // Under an aggregate.
+ assert(passThrough(df.groupBy(col("b")).agg(count(udf(col("a"))))) ==
+ Seq(nodeName -> Seq("b")))
+ }
+ }
+
+ // Stacked evaluations of different eval types: the lower one passes
through only the
+ // argument of the upper one, its result.
+ val stacked = df.select(scalarPandasUDF(batchedPythonUDF(col("a"))))
+ assert(passThrough(stacked) == Seq("ArrowEvalPython" -> Nil,
"BatchEvalPython" -> Nil))
+ val stacked2 = df.select(col("c"),
scalarPandasUDF(batchedPythonUDF(col("a"))))
+ assert(passThrough(stacked2) ==
+ Seq("ArrowEvalPython" -> Seq("c"), "BatchEvalPython" -> Seq("c")))
+ }
+
+ test("The logical Python UDF evaluation passes through only the columns used
by its parent") {
+ val df = threeColumns
+ val evals = df.select(col("b"), scalarPandasUDF(col("a")))
+ .queryExecution.optimizedPlan.collect { case e: ArrowEvalPython => e }
+ assert(evals.length == 1)
+ assert(evals.head.requiredChildOutput.map(_.name) == Seq("b"))
+ assert(evals.head.output == evals.head.requiredChildOutput ++
evals.head.resultAttrs)
+ // The child is pruned to the columns passed through and the arguments.
+ assert(evals.head.child.output.map(_.name).toSet == Set("a", "b"))
+ }
+}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessEvaluatorTestUtils.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessEvaluatorTestUtils.scala
index 1fba384fc4b6..0ae2633e1ef9 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessEvaluatorTestUtils.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessEvaluatorTestUtils.scala
@@ -98,7 +98,7 @@ private[python] object InProcessEvaluatorTestUtils {
def iterator(): Iterator[InternalRow] = {
// The byte limit always applies; 64 MB is its default.
- new InProcessArrowEvalPythonEvaluatorFactory(Seq(column), Seq.empty,
Seq(column),
+ new InProcessArrowEvalPythonEvaluatorFactory(Seq(column), Seq.empty,
Seq(column), Seq.empty,
batchSize, 64L << 20, "UTC", false, false, false, false, true,
allMetrics()) {
override private[python] def runtimeSession = session
}.evaluateBatches(Seq.empty, Array.empty, rows,
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessPythonRuntimeSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessPythonRuntimeSuite.scala
index 9fb3712a7636..3ca4c2c95ece 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessPythonRuntimeSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessPythonRuntimeSuite.scala
@@ -141,7 +141,8 @@ class InProcessPythonRuntimeSuite extends SparkFunSuite {
val metrics = allMetrics()
val context = TaskContext.empty()
class TestEvaluator extends InProcessArrowEvalPythonEvaluatorFactory(
- Seq.empty, Seq.empty, Seq.empty, 10, 0L, "UTC", false, false, false,
false, true, metrics) {
+ Seq.empty, Seq.empty, Seq.empty, Seq.empty, 10, 0L, "UTC", false,
false, false, false, true,
+ metrics) {
override private[python] def runtimeSession:
InProcessPythonRuntime.InterpreterSession =
runtime
@@ -166,7 +167,8 @@ class InProcessPythonRuntimeSuite extends SparkFunSuite {
PythonEvalType.SQL_SCALAR_ARROW_INPROCESS_UDF, true)
var lookups = 0
class TestEvaluator extends InProcessArrowEvalPythonEvaluatorFactory(
- Seq.empty, Seq(udf), Seq.empty, 10, 0L, "UTC", false, false, false,
false, true, metrics) {
+ Seq.empty, Seq(udf), Seq.empty, Seq.empty, 10, 0L, "UTC", false,
false, false, false, true,
+ metrics) {
override private[python] def runtimeSession:
InProcessPythonRuntime.InterpreterSession = {
lookups += 1
runtime
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]