Skip to content

[SPARK-60241][PYTHON][CONNECT] Fall back to regular Python UDFs when a Spark Connect server doesn't have PyArrow - #59778

Open
lisancao wants to merge 9 commits into
apache:masterfrom
lisancao:SPARK-60241-fallback
Open

lisancao wants to merge 9 commits into
apache:masterfrom
lisancao:SPARK-60241-fallback

Conversation

@lisancao

@lisancao lisancao commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What changes were proposed in this pull request?

Right now a default Python UDF fails on a Spark Connect server whose Python doesn't have PyArrow. Falling back to a regular UDF (the slower path) is more graceful than stopping the work abruptly, and it reflects how the system already behaves on classic PySpark, which matters more as people migrate to Connect. Python UDTFs (SPARK-60828) and a clearer warning that the user sees are future work.

When a Spark Connect client sends an Arrow-optimized Python UDF (SQL_ARROW_BATCHED_UDF), the server now checks whether the Python that runs the UDF can run it, and creates a regular Python UDF (SQL_BATCHED_UDF) when it cannot, logging a warning. This is the check that classic PySpark runs in _create_py_udf since SPARK-51393, run where Spark Connect decides the UDF, SparkConnectPlanner.createUserDefinedPythonFunction, and it asks for what the Python worker needs: PyArrow, and pandas too with the legacy pandas conversion.

  • PythonUtils.checkArrowOptimization runs require_minimum_pyarrow_version(), after require_minimum_pandas_version() when pandas is required, with python -c, in the executable, environment, Python path and working directory that PythonWorkerFactory gives a Python worker: spark.sql.execution.pyspark.python if set, and the session's spark.pythonWorkerEnv.*. It waits at most PythonWorkerFactory.PROCESS_WAIT_TIMEOUT_MS (10 seconds) and kills the process after.
  • Each session checks once for each executable, environment and pandas requirement (SessionHolder.arrowOptimizationChecks). A check takes about half a second here, mostly importing PySpark, so only the first Arrow-optimized UDF that a session plans pays for it.
  • Only an ImportError from the check falls back, as in _create_py_udf. If the check cannot run (missing executable, timeout, any other error), the UDF stays Arrow-optimized, as it is today, and the server logs why.
  • The check requires pandas only with spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled. Since 4.1.0, that is the only case where an Arrow-optimized Python UDF needs pandas: the worker then runs ArrowBatchedUDFLegacyPandasHandler, which requires pandas and PyArrow, instead of ArrowBatchedUDFArrowHandler, which requires PyArrow only. Requiring pandas always, as _create_py_udf does, would switch servers that have PyArrow but not pandas, which work today, to regular UDFs.

Why are the changes needed?

A Spark Connect client runs that check in its own Python, and pyspark-client always has PyArrow, so the client always sends SQL_ARROW_BATCHED_UDF and the server uses the eval type as sent. Since 4.2.0, when Arrow optimization became the default (SPARK-54555), a default @udf therefore fails on a server whose Python lacks PyArrow:

pyspark.errors.exceptions.base.PySparkImportError: [PACKAGE_NOT_INSTALLED] PyArrow >= 18.0.0 must be installed; however, it was not found.

The PySpark Docker images are such a server (SPARK-60117, #59280). To reproduce, start a Connect server from apache/spark:4.2.0-scala2.13-java21-python3-ubuntu and run, from pyspark-client 4.2.0:

from pyspark.sql.functions import udf

@udf("int")
def plus_one(x):
    return x + 1

spark.range(3).select(plus_one("id")).collect()

Does this PR introduce any user-facing change?

Yes. On Spark Connect, a default Python UDF, or one with useArrow=True, now runs as a regular Python UDF instead of failing when the server's Python lacks PyArrow (or pandas, with the legacy pandas conversion), and the server logs, once per session:

WARN SparkConnectPlanner: Arrow optimization failed to enable because the server-side Python does not have the required packages installed. Falling back to non-Arrow-optimized UDFs. (session ..., Python python3: [PACKAGE_NOT_INSTALLED] PyArrow >= 18.0.0 must be installed; however, it was not found.)

As with classic's fallback, a regular UDF converts some return values differently from an Arrow-optimized one. The check runs in the server's (the driver's) Python, as classic's runs in the driver's: if only the executors' Python has PyArrow, these UDFs used to run Arrow-optimized and now run as regular UDFs, as they do in classic PySpark. The client's udf.evalType still reads 101. Clients don't need to upgrade: released pyspark-client 4.2.0 and 4.3.0 (RC2) get the fallback from a server with this change (see below).

How was this patch tested?

New tests, each also run on master:

  • PythonUDFSuite: the check passes with PyArrow, with or without pandas, and reports a missing pandas when it is required; reports a missing or too old PyArrow; throws when it cannot run (a missing executable, an import that raises something other than ImportError, and a hang past a 1-second timeout); and runs in the session's working directory, so a relative executable from an archive the session added, such as environment/bin/python, resolves as it does for the workers.
  • SparkConnectPlannerSuite: an Arrow-optimized UDF falls back without PyArrow, a registered one too; other eval types are left alone; it stays Arrow-optimized without pandas, and falls back without pandas once the legacy pandas conversion is enabled in the same session; it stays Arrow-optimized when the check cannot run; the check runs the executable from spark.sql.execution.pyspark.python; it runs, and logs the warning, once per session; and the same session checks again for another executable or environment. The tests that reuse a session also fail against versions of the change whose cache leaves out the executable, the environment or the pandas requirement. Six of these fail on master (101 instead of 100).
  • test_parity_arrow_python_udf.py, against a Connect server, with PyArrow (and separately pandas) hidden from the server's Python only, through spark.pythonWorkerEnv.PYTHONPATH, while the client keeps both: without PyArrow, the test fails on master with the error above, and now returns the right rows through BatchEvalPython; without pandas, UDFs over int, string, double, decimal, binary, date, timestamp, array, map and struct stay in ArrowEvalPython, on master and with this change; without pandas and with the legacy pandas conversion, the test fails on master with [PACKAGE_NOT_INSTALLED] Pandas >= 2.2.0 must be installed; however, it was not found., and now returns the right rows through BatchEvalPython.

Also ran released pyspark-client 4.2.0 and 4.3.0 (RC2) against a Connect server built from this branch, whose Python workers have neither PyArrow nor pandas installed: a default @udf returns the right rows, with the warning above in the server log, and useArrow=False keeps working.

Out of scope, for follow-ups: Python UDTFs (SQL_ARROW_TABLE_UDF, SPARK-60828), a warning that the client sees, and classic PySpark. Python UDFs inside higher-order functions still need PyArrow on the server, since they are lifted to SQL_ARROW_ELEMENTWISE_UDF whether or not they are Arrow-optimized (SPARK-58695).

Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code (Claude Opus 5.5) and OpenAI Codex (GPT-5)

@lisancao
lisancao marked this pull request as draft October 25, 2026 22:33
@lisancao lisancao changed the title [SPARK-60241][PYTHON][CONNECT] Fall back from Arrow Python UDFs when server packages are unavailable [SPARK-60241][PYTHON][CONNECT] Fall back to regular Python UDFs when a Spark Connect server doesn't have PyArrow Oct 25, 2026
@lisancao
lisancao marked this pull request as ready for review October 26, 2026 03:43
@lisancao

Copy link
Copy Markdown
Contributor Author

Cc @holdenk if you have some time could you take a look? There are some additional cases handled here in terms of 4.0 (needs pandas and pyArrow) and 4.1 not needing pandas.

Happy to change anything as needed.

@holdenk

holdenk commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Hey @lisancao yup I'll take a look, if you can rebase it that would be lovely. I've asked HyukjinKwon's robot to take a look first.

@holdenk holdenk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quick first pass, thanks for working on this. I can dig in more once the merge conflict is resolved.

Comment on lines +211 to +217
* @throws SparkException if the check fails otherwise, or does not finish within `timeoutMs`.
*/
private[spark] def checkArrowOptimization(
pythonExec: String,
envVars: Map[String, String],
requirePandas: Boolean = false,
timeoutMs: Long = PythonWorkerFactory.PROCESS_WAIT_TIMEOUT_MS): Option[String] = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: None for if it can is a bit of a funky return type and it's a combination None or exception I'd just go bool + exception personally and make sure we only call this once.

Comment on lines +222 to +231
val code =
s"""
|import sys
|from pyspark.sql.pandas.utils import ${checks.mkString(", ")}
|try:
| ${checks.map(_ + "()").mkString("; ")}
|except ImportError as e:
| print(e)
| sys.exit(3)
|""".stripMargin

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't love the inline Python here personally a helper python file is sort of the vibe I'd go with but nit again

Comment on lines +241 to +244
val pythonPath = mergePythonPaths(
sparkPythonPath, envVars.getOrElse("PYTHONPATH", ""), sys.env.getOrElse("PYTHONPATH", ""))
val process = Utils.executeCommand(
Seq(pythonExec, "-c", code), workingDir, envVars + ("PYTHONPATH" -> pythonPath))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should have a helper to launch a Python file this will drift from the main path

Comment on lines +255 to +261
process.exitValue() match {
case 0 => None
case 3 => Some(output.toString.trim)
case exitCode =>
throw new SparkException(
s"The Arrow optimization check in $pythonExec exited with code $exitCode")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah this is weird right? either throw or don't but don't have two seperate error paths.

Comment on lines +22 to +25
Upgrading from PySpark 4.3 to 4.4
---------------------------------
* In Spark 4.4, Spark Connect falls back to a regular Python UDF when the server's Python does not have PyArrow installed, instead of failing on an Arrow-optimized Python UDF (the default since Spark 4.2), and logs a warning on the server. With ``spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled`` enabled, it also falls back when the server's Python does not have pandas installed. Like Spark Classic, it checks the Python on the driver, so if only the executors have these packages installed, Arrow-optimized Python UDFs now run as regular Python UDFs. To keep them Arrow-optimized, install the packages on the driver as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need a migration note

@spark-test spark-test left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

For a Spark Connect server whose own Python runs the UDFs and lacks PyArrow, the change turns the [PACKAGE_NOT_INSTALLED] failure of a default @udf into a regular-UDF result through BatchEvalPython. It requires pandas only under the legacy pandas conversion, and it keeps the UDF Arrow-optimized when the check cannot run.

Two larger defects remain. First, the eval type is decided by probing the worker executable on the driver while planning, so cluster deployments whose executors have PyArrow but whose driver does not now run default UDFs on the slower path, with some return values converted differently, and registered functions and cached plans keep a decision made under older session settings. Local mode is not affected by the host case. Second, Arrow-optimized Python UDTFs, also on by default, still fail on the servers this change fixes for UDFs.

The smaller findings: the probe runs inside computeIfAbsent and can block a concurrent operation of the same session, it leaves an empty per-session directory on the driver, the scaladoc omits the IOException thrown when the executable cannot start, and two deliberate branches of the check have no failing test.

Two questions for the author follow.

Review-level concerns

  • Shared problem: Whether an Arrow-optimized Python function can run is a property of the Python on the executor that runs it, at the time it runs, but this change decides it once on the driver while planning. That one placement explains the downgrade on executors that have PyArrow, the decisions that registered functions and cached plans keep, the subprocess that blocks request threads, and the directory left on the driver. The UDTF follow-up needs the same decision. Making executor-side evaluation the single owner of the fallback, for scalar UDFs now and for UDTFs when they follow, keeps both on one set of host and timing semantics. None of these findings blocks landing on its own.

Cross-cutting observations

  • The per-session probe cost exists only because the check runs on the driver while each session plans, so where the fallback is finally decided also decides which cost the per-session cost question is about.

    The cost question can be answered on its own, but the answer should assume whichever placement the fallback ends up using.

Findings

6 total: 0 P0, 0 P1, 2 P2, 4 P3.

Non-blocking (P2)

  • Fallback is decided on the driver at planning time, not by the Python that runs the UDF — sql/connect/server/src/main/scala/org/apache/spark/sql/connect/planner/SparkConnectPlanner.scala:2349 — see inline.
  • Arrow-optimized Python UDTFs still fail on servers without PyArrow — sql/connect/server/src/main/scala/org/apache/spark/sql/connect/planner/SparkConnectPlanner.scala:2364 — see inline.

Nit (P3)

  • The probe runs inside computeIfAbsent and blocks concurrent planning in the session — sql/connect/server/src/main/scala/org/apache/spark/sql/connect/planner/SparkConnectPlanner.scala:2375 — see inline.

  • Two deliberate branches of the new check have no failing test — core/src/main/scala/org/apache/spark/api/python/PythonUtils.scala:220
    Two branches that the change implements on purpose have no assertion that fails when they regress.

    1. Legacy mode with PyArrow missing. Every case that hides or downgrades PyArrow (PythonUDFSuite "reports a missing or too old PyArrow", the SparkConnectPlannerSuite PyArrow tests, test_falls_back_without_pyarrow) runs without the pandas requirement, and every legacy or pandas-required case hides only pandas. If the check list in PythonUtils.checkArrowOptimization were built as pandas-only in legacy mode, a legacy-mode server with pandas but without PyArrow would keep SQL_ARROW_BATCHED_UDF and fail in the worker, and every new test would still pass.
    2. An invalid worker environment. No test plans or registers an Arrow-optimized UDF while PythonWorkerEnvironment.mergeValidated rejects the session's spark.pythonWorkerEnv.* values, although such a value can reach a session through writes that skip validateConfigChange, which only RuntimeConfig.set calls. Removing the Try in correctPythonEvalType would make df.schema, explain and RegisterFunction fail at planning, and changing forall to exists would fall back silently. In both cases the new tests stay green.

    Verification:

    • Regression: With PyArrow hidden and pandas required, the check reports PyArrow as not installed, and with the legacy pandas conversion on, an Arrow-optimized UDF falls back.
    • Behavior: With an invalid worker environment, planning, analysis and registration of an Arrow-optimized UDF succeed without a fallback, and executing it fails with INVALID_SPARK_CONFIG.
  • checkArrowOptimization scaladoc omits the IOException thrown when the executable cannot start — core/src/main/scala/org/apache/spark/api/python/PythonUtils.scala:211 — see inline.

  • The probe leaves an empty per-session directory on the driver — core/src/main/scala/org/apache/spark/api/python/PythonUtils.scala:236 — see inline.

Shared repair plans

Shared repair plan 1

Covered findings:

  • Fallback is decided on the driver at planning time, not by the Python that runs the UDF — sql/connect/server/src/main/scala/org/apache/spark/sql/connect/planner/SparkConnectPlanner.scala:2349
  • The probe runs inside computeIfAbsent and blocks concurrent planning in the session — sql/connect/server/src/main/scala/org/apache/spark/sql/connect/planner/SparkConnectPlanner.scala:2375
  • The probe leaves an empty per-session directory on the driver — core/src/main/scala/org/apache/spark/api/python/PythonUtils.scala:236

Recommended change: Stop rewriting the eval type in the Spark Connect planner: drop the planning-time check and the per-session result map. Keep the client's Arrow-optimized eval type in the plan. For Spark Connect sessions, let the Arrow-optimized UDF evaluator decide per partition on the executor, gated by an internal session conf that the Connect server enables and that stays off for classic sessions. A per-executor memo, keyed by the worker executable, merged worker environment, pandas requirement and working directory, runs the existing capability check once per key outside any map lock. When the check reports a missing package, the partition is evaluated through the pickled batch evaluator as a regular Python UDF and a warning is logged; otherwise the Arrow evaluator runs as today. Update the Spark Connect fallback tests and the PySpark Connect parity tests to cover the execution-time decision.

Why this works: The Python that runs a partition is checked where and when it runs, so a partition falls back only when its own worker cannot import the packages. Deployments whose executors have PyArrow keep the Arrow path even when the driver's Python lacks it, and servers without PyArrow still get the regular-UDF result. Because the plan no longer carries a decision, registered functions and cached plans follow each action's environment. Without a planning-time check, the driver neither blocks request threads on a subprocess nor creates a per-session files directory. The executor memo publishes each key's result through a per-key future, so concurrent tasks wait interruptibly and other keys are not blocked.

Scope: Moves the Arrow-to-regular fallback for Spark Connect from planning on the driver to Arrow-optimized UDF evaluation on the executors.

Compatibility: Only an ImportError from the check falls back, pandas is required only with the legacy pandas conversion, a check that cannot run keeps the UDF Arrow-optimized, and a fallen-back UDF uses regular-UDF return-value conversion, as the PR describes.

Risks: Explain output keeps showing ArrowEvalPython when partitions fall back, so the decision becomes visible only in executor logs and metrics, and tests that assert BatchEvalPython in explain output need result-based assertions instead. Executors with different Python installations evaluate their partitions with different return-value conversions; homogeneous executors behave consistently. Each executor pays one check per key at its first such task instead of the driver paying one per session, and new executors under dynamic allocation pay it again. The change touches shared sql/core execution code; the internal session conf keeps classic sessions unchanged and serves as a rollback switch.

Constraints: The pickled fallback must produce the same output attributes and row order as the Arrow evaluator, including when the operator receives columnar input. Pandas is required only when spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled is on, only an ImportError reported by the check triggers the fallback, and a check that cannot run keeps the Arrow path. No map lock may be held while a check runs.

Exclusions:

  • Python UDTFs, which a separate repair covers with the same decision point.
  • UDFs inside higher-order functions, which still need PyArrow because they are lifted to SQL_ARROW_ELEMENTWISE_UDF.
  • Classic PySpark, whose client-side check stays as is.

Success: On a Spark Connect deployment whose driver Python lacks PyArrow but whose executors have it, a default @udf runs through the Arrow path and returns the same rows as on the base branch. When the Python that runs the UDF lacks PyArrow, or lacks pandas with the legacy pandas conversion on, a default @udf returns the right rows as a regular Python UDF and a warning is logged. A registered function or a re-executed DataFrame follows a change to spark.sql.execution.pyspark.python, spark.pythonWorkerEnv.* or the legacy pandas conversion on the next action. Planning an Arrow-optimized Python UDF in a Spark Connect session runs no capability check on the driver and creates no per-session directory there. Classic sessions evaluate Arrow-optimized UDFs as on the base branch.

Verification:

  • Behavior: With PyArrow hidden from the workers' Python, a default @udf in a Spark Connect session returns the right rows and logs the fallback. With pandas hidden and the legacy pandas conversion on, the same holds. With pandas hidden and the legacy conversion off, the UDF stays on the Arrow path.
  • Regression: The fallback decision for a partition follows the worker Python and environment of the action that runs it: a function registered, or a DataFrame first executed, while the worker environment lacked PyArrow runs through the Arrow path after the session points spark.pythonWorkerEnv.PYTHONPATH at a Python that has it, and the reverse change makes it fall back.
  • Regression: Planning an Arrow-optimized UDF in a Spark Connect session runs no capability check and creates no files directory on the driver. Concurrent tasks that need the same capability check share one check, wait interruptibly, and do not block checks for other keys.
  • Compatibility: With the internal fallback conf off, as for classic sessions, Arrow-optimized UDF evaluation is unchanged on both the row and the columnar input paths.

Decision challenges

Each session probes the driver's Python while planning, also on servers that have PyArrow

On the base branch, planning a default @udf starts no process on the driver, and on a server without PyArrow the query then fails in the worker. With this change that failure becomes a correct result through BatchEvalPython, and some probing is needed to tell the two kinds of server apart. The probe runs per session and key, though: the first Arrow-optimized UDF that each Connect session plans starts a fresh python -c on the driver and waits for it on that ExecutePlan or AnalyzePlan thread, including on servers whose Python has PyArrow and needs no fallback. The PR description reports about 0.5 s. It can take longer on loaded hosts or network filesystems, up to the 10 s timeout, and no setting skips it. A session that changes a spark.pythonWorkerEnv.* value, such as a rotating token, probes again for each new value and keeps every result for the rest of the session.

Cheaper ways to get the same answer exist, each with a trade-off:

  • Share results across sessions for keys whose executable is absolute and whose session has no artifacts. This needs care, because the probe's working directory is on its sys.path, so session files can change its answer.
  • Probe the server-default key once at startup or when the session is created, off the planning thread.
  • Reuse a warm Python worker instead of starting a cold interpreter.

Do the Connect workloads this targets, such as platforms that open a session per job or per user, make the per-session cost worth one of these?

destroyForcibly() after a normal exit may close stderr under the redirect thread

Verified in the source: the finally block calls process.destroyForcibly() even after the process has exited normally. Utils.executeCommand starts a stderr redirect thread that this method never joins, Utils.processStreamByLine has no exception handling, and the Connect driver installs no default uncaught-exception handler (only Master, Worker and a non-local Executor do). Utils.executeAndGetOutput, which this code otherwise mirrors, does not destroy a process that has exited.

Not verified: whether the JDK closes the process's stderr stream under that still-reading thread, so that its next read throws IOException("Stream closed"). If it does, a probe that fails for a reason other than a missing package (exit code 1 with a traceback, or a kill at the timeout) prints a spurious stack trace on the server's stderr and loses the rest of its traceback from the log. The eval-type decision is unaffected.

Can you confirm how the stream behaves on the JDKs you target? If the race is real, destroying the process only when waitFor timed out, or reading stderr in a thread that the check joins before it destroys the process, would avoid it after a normal exit.

Not verified by this review (environment unavailable). Repro sketch:

In a Spark checkout with a JDK, add a temporary test to PythonUDFSuite. Write a pyarrow.py stub that prints 2000 lines to sys.stderr and then raises RuntimeError, and put its directory first on PYTHONPATH as the suite's withPythonModules does. Install a Thread.setDefaultUncaughtExceptionHandler that records exceptions from threads whose name starts with 'redirect stderr for command' (restore the previous handler afterwards), and attach a LogAppender at INFO for org.apache.spark.util.Utils. Call PythonUtils.checkArrowOptimization(pythonExec, envVars) 50 times, each expecting a SparkException containing 'exited with code 1', then sleep one second. The problem is confirmed if any IOException('Stream closed') was recorded or any call logged fewer than 2000 stderr lines. Reference: the same loop against a copy of the method that calls destroyForcibly() only when waitFor timed out should record none and log every line. Control: a stub containing 'import sys; sys.exit(1)', which exits with code 1 without writing to stderr, should record none with the current code.

Generated by Omnigent on Databricks

func = function,
dataType = transformDataType(udf.getOutputType),
pythonEvalType = udf.getEvalType,
pythonEvalType = correctPythonEvalType(udf.getEvalType, function),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking (P2): This fixes the eval type into the UDF when Connect plans or registers it, from a probe that correctPythonEvalType runs on the driver host with the session settings as of planning. The Python UDF runners instead resolve spark.sql.execution.pyspark.python, spark.pythonWorkerEnv.* and the legacy pandas conf on the executors at each action, and they install the environment at worker launch "so a cached plan cannot pin an older environment" (PythonUDFRunner.scala:44).

Two cases that work today regress:

  • Host: when the driver's Python at that executable path lacks PyArrow but the executors' Python has it, for example a Connect server started in client mode from an image without PyArrow whose executor image has it, default UDFs move from ArrowEvalPython to BatchEvalPython. That is the slower path, and return values whose conversion differs change silently: @udf('boolean') returning 1 gives True with Arrow and NULL without, per the return-type coercion goldens. The only signal is a server log, and the migration note does not say that results can change. Classic PySpark makes the same driver-side choice, but these Connect deployments run the UDFs Arrow-optimized today.
  • Time: a function registered, or a DataFrame kept in the session plan cache, while the worker Python lacked PyArrow keeps SQL_BATCHED_UDF after the session points spark.pythonWorkerEnv.PYTHONPATH or spark.sql.execution.pyspark.python at a Python that has it. In the other direction, one planned while PyArrow was present still fails after the session switches to a Python without it.

Local mode, where the driver runs the workers' Python, is not affected by the host case.

See Shared repair plan 1 in the review body.

* run.
*/
private def correctPythonEvalType(evalType: Int, function: SimplePythonFunction): Int = {
if (evalType == PythonEvalType.SQL_ARROW_BATCHED_UDF) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking (P2): Only SQL_ARROW_BATCHED_UDF is corrected here, but Python UDTFs reach the server the same way. spark.sql.execution.pythonUDTF.arrow.enabled defaults to true, both _create_py_udtf implementations choose SQL_ARROW_TABLE_UDF after checking only the client's own pandas and PyArrow, and createPythonUserDefinedTableFunction passes udtf.getEvalType through for inline and registered UDTFs. On the PR's own reproduction server (apache/spark:4.2.0-scala2.13-java21-python3-ubuntu), a default @udtf therefore still fails with [PACKAGE_NOT_INSTALLED] PyArrow, while a default @udf on that server now falls back.

The same fallback applies to UDTFs: SQL_ARROW_TABLE_UDF to SQL_TABLE_UDF, requiring pandas only under spark.sql.legacy.execution.pythonUDTF.pandas.conversion.enabled, decided at the same point as the UDF fallback. The description defers UDTFs to a follow-up; unless that exemption is accepted, the two Arrow-by-default function kinds behave differently on the same server.

Recommended change: Apply the execution-time fallback to Arrow-optimized Python UDTFs in Spark Connect sessions. When the capability check on the executor reports that its worker Python cannot import PyArrow (or pandas, with the UDTF legacy pandas conversion on), evaluate the partition with the row-based UDTF evaluation and log a warning; otherwise keep the Arrow path. Add Spark Connect UDTF tests with PyArrow and pandas hidden from the workers' Python, and mention UDTFs, including that their return values then convert as a regular Python UDTF's, in the migration guide note.

Why this works: UDTFs then fall back under the same rule as UDFs, decided by the Python that runs them, so a default @udtf on a server without PyArrow returns rows instead of failing, and servers whose workers have PyArrow keep the Arrow path.

Scope: Extends the execution-time Arrow fallback from Python UDFs to Python UDTFs in Spark Connect sessions.

Risks: Partitions of one UDTF can use different conversions when executors' Python installations differ. Explain output keeps showing the Arrow UDTF operator when partitions fall back. A UDTF partition that falls back converts return values as regular Python UDTFs do, which differs from the Arrow path for some values, as with the client-side fallback.

Constraints: The row-based fallback must produce the same output attributes as the Arrow UDTF evaluation. Pandas is required only with spark.sql.legacy.execution.pythonUDTF.pandas.conversion.enabled.

Exclusions:

  • UDTF analyze calls, which run on the driver and do not use the Arrow path.

Success: On a Spark Connect server whose workers' Python lacks PyArrow, a default @udtf returns the rows the same UDTF returns as a regular Python UDTF, through the row-based path, and a warning is logged. On a server whose workers' Python has PyArrow, Arrow-optimized UDTFs run as on the base branch.

Verification:

  • Behavior: With PyArrow hidden from the workers' Python, a default @udtf in a Spark Connect session, both inline and registered, returns the rows the same UDTF returns as a regular Python UDTF. With pandas hidden and the UDTF legacy pandas conversion on, it falls back as well, and with that conversion off it stays on the Arrow path.
  • Compatibility: With the internal fallback conf off, as for classic sessions, Arrow-optimized UDTF evaluation is unchanged.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is a real gap. A default @udtf still fails with [PACKAGE_NOT_INSTALLED] on a server built from this branch (reproduced on the 4.2.0 image), so the two Arrow-by-default function kinds do behave differently there for now.

I'd like to keep this PR to Python UDFs so it stays reviewable, and handle UDTFs separately: I filed SPARK-60828 for the UDTF fallback (SQL_ARROW_TABLE_UDF to SQL_TABLE_UDF, with pandas required only under spark.sql.legacy.execution.pythonUDTF.pandas.conversion.enabled), and I'll open the fix for it once this one lands. It will make the decision at the same point this PR ends up making it, so if the UDF fallback moves to the executors (the other P2 here), the UDTF change follows it rather than adding a second set of semantics.

.map(_.asScala.toMap)
.toOption
.forall { envVars =>
sessionHolder.arrowOptimizationChecks.computeIfAbsent(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (P3): computeIfAbsent holds the bin's lock while this mapping function runs, and the function starts the worker Python and waits for it: up to PROCESS_WAIT_TIMEOUT_MS (10 s) in waitFor, then up to another 10 s in reader.join. ConcurrentHashMap documents that other updates may block while the mapping function runs and asks for a short computation. Operations of one Connect session can plan concurrently, on ExecutePlan runner threads and on AnalyzePlan calls such as df.schema. A second operation that plans a UDF with the same key, or with a key that lands in the same bin, blocks entering the monitor, and interruptOperation or interruptTag cannot cancel it, because a thread waiting for a monitor ignores Thread.interrupt(). It waits about 0.5 s typically, and about 10 s when the import hangs until the check times out.

See Shared repair plan 1 in the review body.

* `PythonWorkerFactory` gives a Python worker launched with `envVars`.
*
* @return `None` if it can, and why it cannot otherwise.
* @throws SparkException if the check fails otherwise, or does not finish within `timeoutMs`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (P3): When pythonExec cannot be started (a missing or non-executable path, or a relative path that does not resolve in the working directory), Utils.executeCommand throws java.io.IOException from ProcessBuilder.start before the try block, and it propagates unwrapped, as the new "checkArrowOptimization throws when the check cannot run" test asserts for /nonexistent/python3. This line documents only SparkException, so a private[spark] caller that follows it would let a launch failure escape. canRunArrowOptimization catches NonFatal, so it is unaffected today.

Verification:

  • Inspection: The documented exceptions match what the check throws for a missing executable, a timeout and an unexpected exit code.

JobArtifactSet.getCurrentJobArtifactState.map(_.uuid).getOrElse("default")
val workingDir = if (jobArtifactUUID != "default") {
val dir = new File(SparkFiles.getRootDirectory(), jobArtifactUUID)
dir.mkdir()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (P3): On the driver, SparkFiles.getRootDirectory() is SparkEnv.driverTmpDir, which only SparkEnv.stop deletes. Closing a Connect session does not remove <root>/<session UUID>: ArtifactManager cleanup removes the file-server entries and the artifact path, and the executor's session cleanup deletes only under the executor's own root, which is the driver's root only in local mode. So on a cluster-mode server every session that plans a default @udf now leaves an empty directory behind, where before only sessions that added files or archives, or ran a Python planning worker such as a UDTF's analyze or a Python data source, did. The count grows with session churn over the server's lifetime.

See Shared repair plan 1 in the review body.

…mized Python UDFs

Add PythonUtils.checkArrowOptimization, which runs the PyArrow check that
_create_py_udf runs in a Python client, require_minimum_pyarrow_version(),
in a given Python executable, with the environment, Python path and
working directory that PythonWorkerFactory gives a Python worker. It
returns why the check failed, and throws if the check cannot run or does
not finish within PythonWorkerFactory.PROCESS_WAIT_TIMEOUT_MS.

Only PyArrow is checked: since 4.1.0, Arrow-optimized Python UDFs need
pandas only with the legacy pandas conversion.

The next commit uses it in the Spark Connect planner.
…the Spark Connect server lacks PyArrow

A Spark Connect client runs the check of SPARK-51393 in its own Python,
which always has PyArrow, so an Arrow-optimized Python UDF fails on a
server whose Python does not. SparkConnectPlanner now runs the check in
the Python that runs the UDF and creates a regular Python UDF when it
fails, logging a warning. Each session checks once for each Python
executable and environment, and keeps the UDF Arrow-optimized if the
check cannot run.
…nect server

Hide PyArrow, and separately pandas, from the server's Python workers
only, through spark.pythonWorkerEnv.PYTHONPATH, while the client keeps
both, as in the reported setup. Without PyArrow the UDF now falls back
and returns the right rows; without pandas it stays Arrow-optimized.
…n for another Python or environment

A session caches the result of the check by the Python executable and
its environment. Pin both halves of that key: within one session, a
PyArrow on the path of another environment makes the UDF Arrow-optimized
again, and another executable that hides PyArrow makes it fall back
again.
… migration guide

Under "Upgrading from PySpark 4.3 to 4.4", for branch-4.x. Besides the
fallback itself, note that the server checks the Python on the driver,
so a cluster where only the executors have PyArrow now runs these UDFs
as regular Python UDFs.
…name its conf in the migration guide

Format the planner for scalafmt and the end-to-end test for ruff, which
CI's linters require. Read the legacy pandas conversion through
SQLConf.legacyPandasConversionUDF, as the planner reads the worker's
executable, instead of importing SQLConf for it. Build the check's Python
from one list of checks, so that no blank line is left when pandas is not
required, and say in the check's comments and errors that it may check
pandas too.

In the migration guide, keep the sentence on PyArrow and add one for
pandas that names spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled.
@lisancao
lisancao force-pushed the SPARK-60241-fallback branch from 0c67d54 to 6fddee1 Compare November 5, 2026 02:30
@lisancao

lisancao commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @holdenk! Rebased onto master, and removed the migration note in 6fddee1.

Before I rework the check: the review bot suggests deciding the fallback on the executors, when the UDF runs, instead of on the driver while planning (in its review). If we keep it on the driver, it's more aligned with classic and out of the shared execution path. Which would you prefer?

If it stays on the driver, the check can go into a small module under pyspark/sql/worker and run through PythonPlannerRunner, like UDTF analyze and Python data sources, so it starts the same way as the workers and can fork from the daemon. It'll return a Boolean and throw errors for anything unexpected, as you suggested.

UDTFs are purposely excluded from this PR for scope and will be in a follow-up (SPARK-60828).

@holdenk

holdenk commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

I think on the driver makes more sense, we assume that the driver and executors have roughly equivalent envs.

@holdenk

holdenk commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Hey @lisancao workflows won't currently run "Unable to re-run one or more workflows. Check if the workflows are already running, are more than 30 days old, or are disabled." can you double check your config

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants