spark-test commented on code in PR #60674:
URL: https://github.com/apache/spark/pull/60674#discussion_r4626790930
##########
docs/core-migration-guide.md:
##########
@@ -22,6 +22,10 @@ license: |
* Table of contents
{:toc}
+## Upgrading from Core 4.4 to 4.5
+
+- Since Spark 4.5, with artifact isolation on (the default in Spark Connect),
the Python workers that run in the folder of a session, such as those of Python
UDFs, UDTFs and data sources, also import the Python files that the application
was started with (`--py-files` or `spark.submit.pyFiles`): the modules and the
`.zip`, `.egg` and `.jar` archives among them, when they have a copy in the
default files directory. spark-submit makes these copies in client mode outside
YARN, and PySpark does when it starts the driver; a JVM driver on YARN in
client mode and an application in standalone cluster deploy mode get none. The
workers add these files when they set up a task, after the session's own Python
files and before the standard library and installed packages, as the workers of
a session without isolation add the default files directory. Before, they could
import these files only on YARN's application master and executors. As a
result, a module from these files can now take the place o
f an installed package with the same name. To restore the previous behavior,
set `spark.python.isolatedSession.globalPyFiles.enabled` to `false` when
starting the application. (See
[SPARK-62000](https://issues.apache.org/jira/browse/SPARK-62000) for more
details.)
Review Comment:
**Non-blocking (P2):** This entry, and the doc of
`spark.python.isolatedSession.globalPyFiles.enabled`
(`core/src/main/scala/org/apache/spark/internal/config/Python.scala:100-113`),
describe the files as those given with `--py-files` or `spark.submit.pyFiles`.
For Python applications and for applications such as the Spark Connect server,
spark-submit also adds every jar that `--packages` resolves to
`spark.submit.pyFiles`, and in client mode outside YARN to `spark.files`
(`core/src/main/scala/org/apache/spark/deploy/SparkSubmit.scala:371-373,
580-584`). So a Connect server started with `--packages`, for example for Delta
Lake, and no `--py-files` now puts every resolved jar on the path of every
Python worker of its isolated sessions, ahead of installed packages. Each such
worker reads every jar's index the first time an import passes it, and again
after a later task changes its path. The time and memory grow with the jars'
entry counts: for scale, indexing a synthetic 5,000-entry
jar takes about 15 ms and 3 MiB on Python 3.12, and Python 3.13 and later also
index jars with more than 65,535 entries, which Python 3.12 skips. Keeping
these jars matches what PySpark adds for a session without isolation, and the
PR description states the cost, but a user reading this entry has no reason to
think it applies to `--packages`.
Please say here and in the setting's doc that the listed archives include
the jars that `--packages` resolves for applications such as the Spark Connect
server, that every Python worker of an isolated session reads the index of each
listed archive, so large archives make its first tasks slower and use memory,
and that setting `spark.python.isolatedSession.globalPyFiles.enabled` to
`false` when starting the application avoids it.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60674#discussion_r4623220829).
**Verification:**
- **Inspection:** The core migration guide's entry for the change and the
doc of `spark.python.isolatedSession.globalPyFiles.enabled` both say that the
listed archives include the jars that `--packages` resolves for applications
such as the Spark Connect server, that every Python worker of an isolated
session reads the index of each listed archive, so large archives make its
first tasks slower and use more memory, and that setting the config to `false`
when starting the application avoids it.
##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -278,6 +323,9 @@ private[spark] class PythonWorkerFactory(
val workerEnv = pb.environment()
workerEnv.putAll(envVars.asJava)
workerEnv.put("PYTHONPATH", pythonPath)
+ if (globalPythonPath.nonEmpty) {
Review Comment:
**Nit (P3):** This is the simple-worker copy of the environment code,
separate from the daemon's at `PythonWorkerFactory.scala:406-408`, and it is
the only launch when `spark.python.use.daemon` is `false` and on Windows
(`PythonWorkerFactory.scala:112-115`). No new test sets
`spark.python.use.daemon`, so `PythonGlobalPyFilesSuite` and the PySpark global
Python files tests start every worker through the daemon. Deleting lines
326-328 would keep every test green while an isolated session without the
daemon went back to `ModuleNotFoundError` in `analyze`, `eval` and UDFs. A
suite case that turns the daemon off for a new session, as the flag-off case
does for its setting, and checks the imports and the start-time `PYTHONPATH`
would cover it.
**Verification:**
- **Regression:** With `spark.python.use.daemon` set to false for a new
isolated session, a Python UDTF imports the application's Python module and zip
package on the driver in `analyze` and in `eval`, its workers' start-time
PYTHONPATH holds none of these files, and the case fails when the simple-worker
launch does not pass them.
##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -571,4 +622,28 @@ private[spark] object PythonWorkerFactory {
val IDLE_WORKER_TIMEOUT_NS = TimeUnit.MINUTES.toNanos(1) // kill idle
workers after 1 minute
private[spark] val defaultDaemonModule = "pyspark.daemon"
+
+ // The directory that holds copies of the application's Python modules, and
their paths.
+ @GuardedBy("this")
+ private var globalPythonModules: Option[(Seq[String], File)] = None
+
+ /**
+ * Returns a directory under the local directory that holds copies of
`modules`, the
+ * application's Python modules, and nothing else, like `__pyfiles__` on
YARN. It is created
+ * once for each set of modules, which does not change while an application
runs.
+ */
+ private def globalPythonModulesDirectory(conf: SparkConf, modules:
Seq[File]): File =
+ synchronized {
+ val paths = modules.map(_.getPath)
+ globalPythonModules.collect {
+ case (cachedPaths, dir) if cachedPaths == paths && dir.isDirectory =>
dir
+ }.getOrElse {
+ val dir = Utils.createTempDir(Utils.getLocalDir(conf), "pyfiles")
Review Comment:
**Non-blocking (P2):** This directory goes under Spark's local root
directory, which lives as long as the JVM
(`core/src/main/scala/org/apache/spark/util/Utils.scala:789-796`), and
`Utils.createTempDir` only registers it for deletion at JVM shutdown, while the
companion object keeps only the latest `(paths, dir)` pair. On the driver the
module paths sit in the per-context `userFiles-<uuid>` directory
(`core/src/main/scala/org/apache/spark/SparkEnv.scala:861-866`), so a JVM that
stops its SparkContext and starts another, such as a local-mode service, a
PySpark process that recreates its session or a test JVM, misses the cache,
copies the modules into a new directory and leaves the previous one on disk
until the JVM exits. `SparkEnv.stop` deletes the driver's per-context files
directory for exactly this reason
(`core/src/main/scala/org/apache/spark/SparkEnv.scala:311-324`), but not this
one. Executors run one application per JVM, so they are not affected.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60674#discussion_r4617387590).
See **Shared repair plan 1** in the review body.
##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -571,4 +622,28 @@ private[spark] object PythonWorkerFactory {
val IDLE_WORKER_TIMEOUT_NS = TimeUnit.MINUTES.toNanos(1) // kill idle
workers after 1 minute
private[spark] val defaultDaemonModule = "pyspark.daemon"
+
+ // The directory that holds copies of the application's Python modules, and
their paths.
+ @GuardedBy("this")
+ private var globalPythonModules: Option[(Seq[String], File)] = None
+
+ /**
+ * Returns a directory under the local directory that holds copies of
`modules`, the
+ * application's Python modules, and nothing else, like `__pyfiles__` on
YARN. It is created
+ * once for each set of modules, which does not change while an application
runs.
+ */
+ private def globalPythonModulesDirectory(conf: SparkConf, modules:
Seq[File]): File =
+ synchronized {
+ val paths = modules.map(_.getPath)
+ globalPythonModules.collect {
+ case (cachedPaths, dir) if cachedPaths == paths && dir.isDirectory =>
dir
Review Comment:
**Nit (P3):** Every test JVM sees one set of the application's modules and
never removes the directory, so both conditions on this line can be dropped
with every test green. Without `cachedPaths == paths`, a driver JVM that starts
a second SparkContext, whose module paths are new, or an application whose
module list changes, would hand isolated workers the earlier copies: stale code
when a module kept its name, `ModuleNotFoundError` when the list changed.
Without `dir.isDirectory`, a long-running JVM whose directory was removed, for
example by a temp-file cleaner, would put a missing directory on the path.
See **Shared repair plan 1** in the review body.
##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -139,16 +141,59 @@ private[spark] class PythonWorkerFactory(
conf.get(PYTHON_FACTORY_IDLE_WORKER_MAX_POOL_SIZE)
@GuardedBy("self")
private var lastActivityNs = 0L
- 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", ""))
+ // Before the monitor thread starts, because it can fail.
+ private val globalPythonPath = globalPythonFilesPath
+
+ new MonitorThread().start()
+
+ @GuardedBy("self")
+ private val simpleWorkers = new mutable.WeakHashMap[PythonWorker, Process]()
+
+ /**
+ * 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 get it in
`SPARK_GLOBAL_PYTHON_PATH`
+ * and add it when they set up the files of a task, as the workers of a
session without
+ * isolation add the default files directory and its archives. The session's
own files still
+ * come first, because the workers start in the session's folder, which
Python puts first on
+ * sys.path, and add the session's archives in front of these files.
+ * It is not on the PYTHONPATH that the workers start with, so a file named
like a module of
+ * the standard library cannot stop them from starting.
+ *
+ * It takes the copies of these files in the default files directory, so
that it works on every
+ * host. spark-submit makes them in client mode outside YARN, and PySpark
when it starts the
+ * driver. A JVM driver on YARN in client mode and an application in
standalone cluster deploy
+ * mode get no copies. It adds only the modules and the `.zip`, `.egg` and
`.jar` archives, as
+ * PySpark does, not the rest of that directory.
Review Comment:
**Nit (P3):** PySpark puts the whole default files directory on the path:
its driver inserts `SparkFiles.getRootDirectory()`
(`python/pyspark/core/context.py:351-352`), and the workers of a session
without isolation add `spark_files_dir` (`python/pyspark/worker_util.py:224`),
as this Scaladoc itself says a few lines earlier. Only the extension list
matches PySpark's `PACKAGE_EXTENSIONS`, so a maintainer could take the
restriction to the listed files for parity with PySpark and put the directory
back. Suggested wording:
```suggestion
* mode get no copies. It adds only the modules and the archives with
PySpark's extensions,
* `.zip`, `.egg` and `.jar`, not the rest of that directory, which
PySpark puts on its path.
```
**Verification:**
- **Inspection:** The Scaladoc of the method that builds an isolated
session's application Python path no longer says that PySpark adds only the
listed modules and archives, and it says that PySpark and the workers of a
session without isolation put the whole default files directory on their path.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/PythonGlobalPyFilesSuite.scala:
##########
@@ -0,0 +1,179 @@
+/*
+ * 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()
+ }
+ // Named like modules of the standard library that a Python worker imports
when it starts:
+ // the workers must not have them on their path until they have started.
+ val token = new File(dir, "token.py")
+ Files.writeString(token.toPath, "raise ImportError('shadowed the standard
library')")
+ val shadow = new File(dir, "global_py_files_shadow.zip")
+ val shadowOut = new ZipOutputStream(Files.newOutputStream(shadow.toPath))
+ try {
+ shadowOut.putNextEntry(new ZipEntry("signal/__init__.py"))
+ shadowOut.write("raise ImportError('shadowed the standard
library')".getBytes("UTF-8"))
+ shadowOut.closeEntry()
+ } finally {
+ shadowOut.close()
+ }
+ Seq(module, clash, pkg, token, shadow).map(_.getAbsolutePath)
+ }
+
+ // Another file of the application: a module that is not one of its Python
files.
+ private lazy val otherFiles: Seq[String] = {
+ val unlisted = new File(filesDir, "global_py_files_unlisted.py")
+ Files.writeString(unlisted.toPath, "value = 'unlisted'")
+ Seq(unlisted).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
+ |
+ |def check_start_path():
+ | # The application's Python files are added after the worker has
started.
+ | import os
+ | added = [p for p in
os.environ["SPARK_GLOBAL_PYTHON_PATH"].split(os.pathsep) if p]
+ | start = os.environ.get("PYTHONPATH", "").split(os.pathsep)
+ | if not added or any(p in start for p in added):
+ | raise Exception(f"Unexpected start path {start} for {added}")
+ |
+ |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
+ | check_start_path()
+ | 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
+ | check_start_path()
+ | 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") {
Review Comment:
**Nit (P3):** This test, like `test_global_py_files_session_precedence` in
`python/pyspark/sql/tests/connect/client/test_artifact.py`, clashes a session
`.py` file with an application module. That file lands in the session's folder,
which is the worker's working directory and so `sys.path[0]`, so the session
wins whatever `setup_spark_files` does with the application's entries. What
keeps a session's archives ahead of the application's files is only that the
loop over `SPARK_GLOBAL_PYTHON_PATH` runs before the session's files directory
and includes are inserted (`python/pyspark/worker_util.py:217-233`). If those
loops were swapped, a session `.zip` added with `addArtifacts(...,
pyfile=True)` would silently lose a clash to the application's module, and
every test would still pass. A case in `GlobalPyFilesPrecedenceTestsMixin`
whose session, a new one of its own, adds a zip holding a module named like one
of the application's would cover it, locally and on the local cluster.
**Verification:**
- **Regression:** In an isolated Spark Connect session that adds, as a
Python file, a zip archive holding a module with the same name as one of the
application's modules, a Python UDF imports the session's version, locally and
on executors in their own JVMs, and the case fails if the worker adds the
application's files after the session's archives.
##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -139,16 +141,59 @@ private[spark] class PythonWorkerFactory(
conf.get(PYTHON_FACTORY_IDLE_WORKER_MAX_POOL_SIZE)
@GuardedBy("self")
private var lastActivityNs = 0L
- 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", ""))
+ // Before the monitor thread starts, because it can fail.
+ private val globalPythonPath = globalPythonFilesPath
+
+ new MonitorThread().start()
+
+ @GuardedBy("self")
+ private val simpleWorkers = new mutable.WeakHashMap[PythonWorker, Process]()
+
+ /**
+ * 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 get it in
`SPARK_GLOBAL_PYTHON_PATH`
+ * and add it when they set up the files of a task, as the workers of a
session without
+ * isolation add the default files directory and its archives. The session's
own files still
+ * come first, because the workers start in the session's folder, which
Python puts first on
+ * sys.path, and add the session's archives in front of these files.
+ * It is not on the PYTHONPATH that the workers start with, so a file named
like a module of
+ * the standard library cannot stop them from starting.
+ *
+ * It takes the copies of these files in the default files directory, so
that it works on every
+ * host. spark-submit makes them in client mode outside YARN, and PySpark
when it starts the
+ * driver. A JVM driver on YARN in client mode and an application in
standalone cluster deploy
+ * mode get no copies. It adds only the modules and the `.zip`, `.egg` and
`.jar` archives, as
+ * PySpark does, not the rest of that directory.
+ */
+ 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
Review Comment:
**Non-blocking (P2):** On an executor `SparkFiles.getRootDirectory()` is
`.`, so this makes each listed archive `<container dir>/./<name>`. On YARN the
same archive is linked into the container directory and is already on the
executors' start-time `PYTHONPATH` as `<container dir>/<name>`
(`resource-managers/yarn/src/main/scala/org/apache/spark/deploy/yarn/Client.scala:984-1009`),
`--packages` jars included. `add_path` (`python/pyspark/worker_util.py:64-70`)
compares strings exactly, so `setup_spark_files` inserts the second spelling,
and Python keeps a zipimporter and an index per spelling: every Python worker
of an isolated session on a YARN executor reads and keeps each archive's index
twice, on its first task and after each later path change, with time and memory
that grow with the archives' entry counts. On the base branch those workers
read it once, through YARN's entry, and the earlier revision avoided the
duplicate because Python normalizes and de-duplicates the start-time
`PYTHONPATH`.
Leaving out any listed archive whose canonical path matches an absolute
entry of the start-time `PYTHONPATH` that the factory already builds
(`pythonPath`) would remove the second read. Comparing canonical paths rather
than normalized strings also covers a YARN local dir reached through a symlink,
where `$PWD` and the JVM's working directory are spelled differently.
**Verification:**
- **Regression:** An isolated session whose Python workers start with an
absolute PYTHONPATH entry that names a listed archive's copy under another
spelling of the same path, such as through a `/./` segment or a symlinked
directory, as YARN's entries do on its executors, imports that archive's
package in a UDTF's `analyze` and `eval`, and each worker has exactly one
`sys.path` entry for the archive after task setup.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/PythonGlobalPyFilesSuite.scala:
##########
@@ -0,0 +1,179 @@
+/*
+ * 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] = {
Review Comment:
**Nit (P3):** Every archive this suite and `GlobalPyFilesTestsMixin` list is
a lower-case `.zip` (`global_py_files_pkg.zip`, `global_py_files_shadow.zip`),
while `globalPythonFilesPath` also adds `.egg` and `.jar` archives and matches
the extension ignoring case
(`core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:187-189`).
Dropping `.egg` or `.jar` from that list, or the `toLowerCase(Locale.ROOT)`
call, would keep every new test green, while an application started with
`--py-files deps.egg`, with `--py-files DEPS.ZIP` or with a listed jar that
ships a Python package would lose those imports in isolated sessions again.
Listing an `.egg`, a `.jar` and an archive with an upper-case extension here,
each holding its own package, and importing them in `analyze` and `eval` would
cover all three.
**Verification:**
- **Regression:** A Python UDTF in an isolated session imports a package
from a listed `.egg` archive, one from a listed `.jar` archive and one from a
listed archive whose extension is upper case, in `analyze` and `eval`, and the
case fails if the `.egg` or `.jar` kind or the case-insensitive match is
dropped.
--
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]