spark-test commented on code in PR #60674:
URL: https://github.com/apache/spark/pull/60674#discussion_r4623220829
##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -139,15 +141,46 @@ private[spark] class PythonWorkerFactory(
conf.get(PYTHON_FACTORY_IDLE_WORKER_MAX_POOL_SIZE)
@GuardedBy("self")
private var lastActivityNs = 0L
+
+ // Before the monitor thread starts, because it can fail.
+ private val pythonPath = PythonUtils.mergePythonPaths(
+ PythonUtils.sparkPythonPath,
+ envVars.getOrElse("PYTHONPATH", ""),
+ sys.env.getOrElse("PYTHONPATH", ""),
+ globalPythonFilesPath)
+
new MonitorThread().start()
@GuardedBy("self")
private val simpleWorkers = new mutable.WeakHashMap[PythonWorker, Process]()
- private val pythonPath = PythonUtils.mergePythonPaths(
- PythonUtils.sparkPythonPath,
- envVars.getOrElse("PYTHONPATH", ""),
- sys.env.getOrElse("PYTHONPATH", ""))
+ /**
+ * SPARK-62000: The Python path of the Python files that the application was
started with, for
+ * the workers of a session with artifact isolation, like the global JARs
that the class loader
+ * of such a session inherits (SPARK-51537). The workers add the session's
own files in front
+ * of it. It takes the copies of these files in the default files directory,
where spark-submit
+ * and `SparkContext` put them outside YARN, so that it works on every host.
It adds only these
+ * files, not the rest of that directory. YARN also puts them on the
PYTHONPATH of its
+ * application master and executors, but not of a client-mode driver.
+ */
+ private def globalPythonFilesPath: String = {
+ val jobArtifactUUID = envVars.getOrElse("SPARK_JOB_ARTIFACT_UUID",
"default")
+ if (jobArtifactUUID == "default" ||
+ !conf.get(PYTHON_ISOLATED_SESSION_GLOBAL_PY_FILES_ENABLED)) {
+ ""
+ } else {
+ val rootDir = new File(SparkFiles.getRootDirectory()).getAbsoluteFile
+ val files = conf.get(SUBMIT_PYTHON_FILES)
+ .map(path => new File(rootDir, new
File(Utils.resolveURI(path).getPath).getName))
+ .distinct
+ .filter(_.isFile)
+ val (modules, packages) = files.partition(_.getName.endsWith(".py"))
+ // A package is imported from its archive, and a module from a
directory, which holds
+ // only the modules.
+ PythonUtils.mergePythonPaths(packages.map(_.getPath) ++
Review Comment:
**Non-blocking (P2):** This adds every listed file that is not a `.py` file
to the PYTHONPATH that an isolated session's workers start with. Outside YARN,
that includes every jar that `--packages` resolves for an internal application
such as the Spark Connect server, because spark-submit adds those jars to
`spark.submit.pyFiles` and, in client mode, to `spark.files`
(core/src/main/scala/org/apache/spark/deploy/SparkSubmit.scala:371-373,
580-584). Python reads an archive's whole central directory the first time an
import passes it, which happens while the process starts because these entries
precede the standard library, and keeps that index for the life of the process.
On an executor, each forked worker then reads every such archive again on
its first task: the session folder arrives as `<files root>/./<session UUID>`,
so `setup_spark_files` changes `sys.path` and invalidates the import caches,
and `_invalidate_import_caches` keeps only the zipimporters of Spark's own
archives (python/pyspark/worker_util.py:91-119, 214-226). A check with this
PR's pyspark sources on Python 3.12 saw both reads for a listed jar; with the
driver's folder, the first task read it again only when the session had its own
Python archive. With `spark.python.worker.reuse=false`, every task pays the
second read.
On the base branch these workers read none of these archives. SPARK-60855
took the 5,261-entry spark-core jar off this same path for this cost, which it
measured at about 8 to 14 ms of each new worker's first task, and every worker
keeps each index in memory. Jars that `--packages` resolves can be much larger;
how large the cost is for real jar sets, and whether the memory can push
workers past `spark.executor.pyspark.memory`, was not measured. The PR
description says the jars go on the path as YARN does, while the setting's doc
and the migration note name only `--py-files` and `spark.submit.pyFiles`; none
of them states the cost.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60674#issuecomment-6994262776).
**Recommended change:** Keep the file kinds and state their cost. In the
SPARK-62000 entry of the core migration guide (docs/core-migration-guide.md,
line 27), say that every listed file that is not a `.py` file, including the
jars that `--packages` resolves for applications such as the Spark Connect
server, goes on the Python path of every Python worker that gets these files in
an isolated session, that these workers read the index of each such archive
when they start, so large archives make the first Python tasks of each session
start later and use more memory, and that setting
`spark.python.isolatedSession.globalPyFiles.enabled` to `false` avoids it. In
the PR description, state the same cost next to the sentence about `--packages`
jars, name the alternative that avoids it, which is adding only listed archives
that contain Python modules, and give the reason the change keeps every listed
file, such as matching YARN.
**Why this works:** Stating the cost, with the alternative the change
rejects and why, lets reviewers weigh the trade-off, and naming `--packages`
jars where users read about the change and its rollback setting makes it
discoverable to users who would not connect those jars with `--py-files`.
**Risks:** Isolated sessions of applications that list large archives keep
paying a read of every listed archive in each of these Python workers, and its
memory, until the author changes which files go on the path; the setting turns
the whole change off.
**Constraints:** Describe the cost in words or with numbers the author
measures, because the review measured only synthetic jars on one Python version.
**Exclusions:**
- Adding only listed archives that contain Python modules, which would
remove most of the cost but changes the declared decision to treat every listed
non-.py file as YARN does, is left to the author.
**Verification:**
- **Inspection:** The migration note's entry for the change says that every
listed file that is not a .py file, including the jars that --packages
resolves, is put on the Python path of every Python worker that gets these
files in an isolated session and read when that worker starts, that large
archives make those workers start later and use more memory, and that turning
the setting off avoids it.
- **Inspection:** The PR description states that cost, names the alternative
of adding only listed archives that contain Python modules, and gives the
reason the change keeps every listed file.
##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -139,15 +141,46 @@ private[spark] class PythonWorkerFactory(
conf.get(PYTHON_FACTORY_IDLE_WORKER_MAX_POOL_SIZE)
@GuardedBy("self")
private var lastActivityNs = 0L
+
+ // Before the monitor thread starts, because it can fail.
+ private val pythonPath = PythonUtils.mergePythonPaths(
+ PythonUtils.sparkPythonPath,
+ envVars.getOrElse("PYTHONPATH", ""),
+ sys.env.getOrElse("PYTHONPATH", ""),
+ globalPythonFilesPath)
Review Comment:
**Blocking (P1):** This puts the listed archives and the directory of copied
`.py` modules on the PYTHONPATH that an isolated session's daemon and simple
workers start with, and Python searches PYTHONPATH before the standard library.
While it starts, before it serves any task, the daemon imports `select`,
`signal`, `socket`, `traceback`, `uuid`, `types` and `typing`
(python/pyspark/daemon.py:17-35), and loading pyspark imports more of the
standard library (python/pyspark/util.py:18-33). A listed module, or a
top-level module or package of a listed archive, named like one of these
modules or a module they import in turn takes the standard-library module's
place, and the worker exits.
A repro with this PR's pyspark sources on Python 3.12 ran the daemon's
start-up imports with `python -m` in a session folder, with PYTHONPATH built
the way this factory builds it. A listed `types.py`, `token.py`, `signal.py` or
`platform.py`, or a zip that bundles an enum34-like `enum` package, failed
inside the standard library: for example, `uuid` calls `platform.system()`
while pyspark loads cloudpickle. A listed `helpers.py`, a plain zip, and the
same start without these entries, as on the base branch, all succeeded.
With the default setting, every Python UDF, UDTF, pandas function and Python
data source of every isolated session then fails, on the driver and on the
executors, including ones that never import the file; only the foreachBatch and
streaming listener workers, which are started without the session's artifact
state, keep starting. This holds wherever the default files directory has
copies of the listed files: in client mode outside YARN, and on a YARN
client-mode driver that PySpark starts. On the base branch these workers start
whatever is listed, because none of the listed files is on their path. The PR
description and the migration note say that the files come before installed
packages, but not that they also come before the standard library.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60674#issuecomment-6990356851),
[2](https://github.com/apache/spark/pull/60674#discussion_r4617387590).
**Recommended change:** Keep the start-time placement and state its
consequence. In the SPARK-62000 entry of the core migration guide
(docs/core-migration-guide.md, line 27), say that the application's Python
files come after the session's own Python files and before both the standard
library and installed packages, and that a listed `.py` module, or a top-level
module or package of a listed archive, named like a standard-library module
that the Python worker imports while it starts, such as `types.py`, `token.py`
or `signal.py`, stops every Python worker that gets these files in each
isolated session, so such a file has to be renamed or
`spark.python.isolatedSession.globalPyFiles.enabled` set to `false`. In the PR
description, state the same failure next to the sentence about installed
packages, name the alternative that avoids it, which is adding these files in
the Python worker's per-task file setup after its start-up imports, as sessions
without isolation do, and give the reas
on the change keeps the start-time placement, such as matching YARN's
container PYTHONPATH.
**Why this works:** Stating the start-up failure, with the alternative the
change rejects and why, lets reviewers weigh the trade-off and puts it where
users read about the change and its rollback setting, and correcting the
precedence statement removes the note's suggestion that only installed packages
can be replaced.
**Risks:** Users whose listed files include such a name still cannot run
Python UDFs, Python UDTFs, pandas functions or Python data sources in any
isolated session until they rename the file or set
`spark.python.isolatedSession.globalPyFiles.enabled` to `false` at start-up;
the documentation tells them both, and the setting rolls the whole change back.
**Constraints:** Keep the session's own Python files first and the
application's files after Spark's own Python paths and any user PYTHONPATH, as
the PR declares. Give the module names as examples, because which names stop
the workers depends on the Python version and on what pyspark imports while a
worker starts.
**Exclusions:**
- Moving the application's entries into the Python worker's per-task file
setup, which would remove the failure but changes the declared start-time
placement, is left to the author.
**Verification:**
- **Inspection:** The migration note's entry for the change says that the
application's Python files come before the standard library and installed
packages, and that a listed module or a top-level module of a listed archive
named like a standard-library module the Python worker imports while starting,
such as types.py or token.py, stops every Python worker that gets these files
in each isolated session unless the file is renamed or the setting is turned
off.
- **Inspection:** The PR description states that failure, names the
alternative of adding the files in the Python worker's per-task setup after its
start-up imports, and gives the reason the change keeps them on the start-time
PYTHONPATH.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/PythonGlobalPyFilesSuite.scala:
##########
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.python
+
+import java.io.File
+import java.nio.file.{Files, Paths}
+import java.util.zip.{ZipEntry, ZipOutputStream}
+
+import org.apache.spark.SparkConf
+import
org.apache.spark.internal.config.Python.PYTHON_ISOLATED_SESSION_GLOBAL_PY_FILES_ENABLED
+import org.apache.spark.sql.{QueryTest, Row}
+import
org.apache.spark.sql.IntegratedUDFTestUtils.{createUserDefinedPythonTableFunction,
shouldTestPythonUDFs}
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.util.Utils
+
+/**
+ * Tests that the Python workers of a session with artifact isolation, as in
Spark Connect, can
+ * import the Python files that the application was started with
(`spark.submit.pyFiles`).
+ */
+class PythonGlobalPyFilesSuite extends QueryTest with SharedSparkSession {
+
+ private lazy val filesDir = Utils.createTempDir()
+
+ // The application's Python files: a module, a package in a zip file, and a
module whose name
+ // a session can also use.
+ private lazy val globalPyFiles: Seq[String] = {
+ val dir = filesDir
+ val module = new File(dir, "global_py_files_module.py")
+ Files.writeString(module.toPath, "value = 'global module'")
+ val clash = new File(dir, "global_py_files_clash.py")
+ Files.writeString(clash.toPath, "value = 'global clash'")
+ val pkg = new File(dir, "global_py_files_pkg.zip")
+ val out = new ZipOutputStream(Files.newOutputStream(pkg.toPath))
+ try {
+ out.putNextEntry(new ZipEntry("global_py_files_pkg/__init__.py"))
+ out.write("value = 'global package'".getBytes("UTF-8"))
+ out.closeEntry()
+ } finally {
+ out.close()
+ }
+ Seq(module, clash, pkg).map(_.getAbsolutePath)
+ }
+
+ // Other files of the application: a module that is not one of its Python
files, and one
+ // named like a module of the standard library that a Python worker imports
when it starts.
+ private lazy val otherFiles: Seq[String] = {
+ val unlisted = new File(filesDir, "global_py_files_unlisted.py")
+ Files.writeString(unlisted.toPath, "value = 'unlisted'")
+ val token = new File(filesDir, "token.py")
+ Files.writeString(token.toPath, "raise ImportError('shadowed the standard
library')")
+ Seq(unlisted, token).map(_.getAbsolutePath)
+ }
+
+ // As spark-submit does with --py-files and --files outside YARN, except
that the Python files
+ // are named by paths that do not exist: the workers must use the copies in
the default files
+ // directory, as on the executors of other hosts. The list also names a
module twice, and a
+ // module that has no copy in that directory, as on YARN.
+ override protected def sparkConf: SparkConf = super.sparkConf
+ .set("spark.files", (globalPyFiles ++ otherFiles).mkString(","))
+ .set("spark.submit.pyFiles",
+ (globalPyFiles :+ globalPyFiles.head :+
"global_py_files_without_copy.py")
+ .map(f => new File("/nonexistent", new
File(f).getName).getPath).mkString(","))
+
+ private val udtfName = "global_py_files_udtf"
+
+ // `analyze` runs in a Python worker on the driver, and `eval` in one on an
executor.
+ private val udtfScript =
+ s"""
+ |from pyspark.sql.functions import AnalyzeResult
+ |from pyspark.sql.types import StringType, StructType
+ |
+ |class $udtfName:
+ | @staticmethod
+ | def analyze():
+ | import global_py_files_module
+ | import global_py_files_pkg
+ | try:
+ | import global_py_files_unlisted
+ | raise Exception("Imported a file that is not a Python file
of the application")
+ | except ModuleNotFoundError:
+ | pass
+ | return AnalyzeResult(
+ | schema=StructType()
+ | .add("module", StringType())
+ | .add("package", StringType())
+ | .add("clash", StringType()))
+ |
+ | def eval(self):
+ | import global_py_files_clash
+ | import global_py_files_module
+ | import global_py_files_pkg
+ | try:
+ | import global_py_files_unlisted
+ | raise Exception("Imported a file that is not a Python file
of the application")
+ | except ModuleNotFoundError:
+ | pass
+ | yield (
+ | global_py_files_module.value,
+ | global_py_files_pkg.value,
+ | global_py_files_clash.value)
+ |""".stripMargin
+
+ /** Runs the UDTF in `session`, under its artifact state, as Spark Connect
does. */
+ private def runUDTF(session: SparkSession): Seq[Row] = {
+ session.udtf.registerPython(
+ udtfName, createUserDefinedPythonTableFunction(udtfName, udtfScript,
returnType = None))
+ session.artifactManager.withResources {
+ session.sql(s"SELECT * FROM $udtfName()").collect().toSeq
+ }
+ }
+
+ test("SPARK-62000: Isolated session imports the Python files of the
application") {
+ assume(shouldTestPythonUDFs)
+ val session = spark.newSession()
+ assert(session.artifactManager.state !== null)
+ assert(runUDTF(session) === Seq(Row("global module", "global package",
"global clash")))
+ }
+
+ test("SPARK-62000: Python files of the session take precedence over those of
the application") {
+ assume(shouldTestPythonUDFs)
+ val session = spark.newSession()
+ withTempDir { dir =>
+ val clash = new File(dir, "global_py_files_clash.py")
+ Files.writeString(clash.toPath, "value = 'session clash'")
+ session.artifactManager.addArtifact(
+ Paths.get("pyfiles/global_py_files_clash.py"), clash.toPath, None)
+ assert(runUDTF(session) === Seq(Row("global module", "global package",
"session clash")))
+ }
+ }
+
+ test("SPARK-62000: Isolated session misses the Python files of the
application if disabled") {
+ assume(shouldTestPythonUDFs)
+ val conf = spark.sparkContext.conf
+ conf.set(PYTHON_ISOLATED_SESSION_GLOBAL_PY_FILES_ENABLED, false)
+ try {
+ // A new session has new Python workers, which read the config when they
start.
Review Comment:
**Nit (P3):** No Python code reads this setting: the JVM-side factory reads
it once, when it is built, and keeps the computed path
(core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:146-150),
and SparkEnv keeps one factory per worker environment, which includes the
session's artifact UUID
(core/src/main/scala/org/apache/spark/SparkEnv.scala:334-337). A new session is
needed because it gets a new factory; a worker that an existing session's
factory starts after the setting changes keeps the old path, which this comment
suggests it would not.
```suggestion
// A new session gets a new Python worker factory, which reads the
config when it is created.
```
**Verification:**
- **Inspection:** The comment before the flag-off test creates its new
session says that a new session gets a new Python worker factory, which reads
the setting when it is created, and does not say that the Python workers read
the setting.
##########
core/src/main/scala/org/apache/spark/internal/config/Python.scala:
##########
@@ -94,6 +94,22 @@ private[spark] object Python {
.booleanConf
.createWithDefault(false)
+ val PYTHON_ISOLATED_SESSION_GLOBAL_PY_FILES_ENABLED =
+ ConfigBuilder("spark.python.isolatedSession.globalPyFiles.enabled")
+ .internal()
+ .doc("When true, the Python workers of a session with artifact
isolation, such as a " +
+ "Spark Connect session, can also import the Python files that the
application was " +
+ "started with (--py-files or spark.submit.pyFiles), after the
session's own files, " +
+ "except the workers of a YARN client-mode driver, which gets no copies
of these " +
Review Comment:
**Nit (P3):** Reading the code, this exception holds only for a driver
started from the JVM, such as a Spark Connect server started with `--master
yarn`. When PySpark starts a YARN client-mode driver, for example with `pyspark
--master yarn --conf spark.api.mode=connect --py-files dep.py`, PySpark's
`SparkContext` copies each `spark.submit.pyFiles` entry that is missing from
the default files directory into it (python/pyspark/core/context.py:361-373),
and the in-process Connect server it starts runs isolated sessions, so the
factory finds those copies, and that driver's UDTF `analyze` and Python data
source planning workers now import `dep.py` ahead of installed packages.
The doc's first sentence also claims more than the code does in two places.
An application submitted to a standalone master with `--deploy-mode cluster`
gets `spark.submit.pyFiles` but no copies, because spark-submit merges the
Python files into `spark.files` only in client mode
(core/src/main/scala/org/apache/spark/deploy/SparkSubmit.scala:580-584), so its
workers still cannot import them. And the Spark Connect foreachBatch and
streaming listener workers are started without the session's artifact UUID
(core/src/main/scala/org/apache/spark/api/python/StreamingPythonRunner.scala:91-92),
so they keep their previous path. Users of a PySpark-started YARN driver are
told the change does not reach them, and users of the other two are told
imports work where they still fail with ModuleNotFoundError.
Describing the boundary the way the code decides it would cover all three:
the Python workers that run in an isolated session's folder, such as those of
Python UDFs, UDTFs and data sources, can import the listed files that have a
copy in the default files directory, which spark-submit makes in client mode
outside YARN and PySpark makes when it starts the driver; a JVM driver on YARN
in client mode and an application in standalone cluster deploy mode get no
copies, and workers started without the session's artifact state, such as the
foreachBatch and streaming listener workers, keep their previous path. The
migration note's sentence that the Python workers of a YARN client-mode driver
still cannot import the files, which came from the earlier review's suggested
wording, and the factory's Scaladoc at
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:161-164
need the same change, and so does the PR description.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60674#issuecomment-6990356851),
[2](https://github.com/apache/spark/pull/60674#discussion_r4621897803).
**Verification:**
- **Inspection:** The doc of
spark.python.isolatedSession.globalPyFiles.enabled, the migration note's entry
for the change and the factory's Scaladoc describe the files as importable by
the workers that run in an isolated session's folder when the files have a copy
in the default files directory, say that a JVM driver on YARN in client mode
and standalone cluster deploy mode get no copies while a driver that PySpark
starts does, and say that the Spark Connect foreachBatch and streaming listener
workers keep their previous path.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]