spark-test commented on code in PR #60674: URL: https://github.com/apache/spark/pull/60674#discussion_r4621897803
########## docs/core-migration-guide.md: ########## @@ -24,6 +24,8 @@ license: | ## Upgrading from Core 4.3 to 4.4 +- Since Spark 4.4, with artifact isolation on (the default in Spark Connect), the Python workers of a session also import the Python files that the application was started with (`--py-files` or `spark.submit.pyFiles`), after the session's own Python files and before installed packages. Before, they could import these files only on the executors on YARN. As a result, a module from these files can now take the place of 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: **Nit (P3):** This sentence misstates YARN's previous behavior in both directions. YARN's client puts these files on the `PYTHONPATH` of the application master as well as the executors (`resource-managers/yarn/src/main/scala/org/apache/spark/deploy/yarn/Client.scala:984-1009`), and the factory merges that into every worker's path, so in YARN cluster mode a driver-side worker, such as a UDTF's `analyze`, could already import them. A JVM driver in YARN client mode, such as a Spark Connect server started with `--master yarn --py-files deps.py`, gets no copies in its default files directory and no `PYTHONPATH` from YARN, so its driver-side workers still cannot import the files after this change. The PR description says so, and so does the factory's Scaladoc (`core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:163-164`), but the note does not. Wording such as "Before, they could import these files only on YARN's application master and executors. The Python workers of a YARN client-mode driver still cannot import them." would match the code. The first sentence of the config's doc (`core/src/main/scala/org/apache/spark/internal/config/Python.scala:100-102`) needs the same client-mode-driver qualifier. This extends existing discussions [1](https://github.com/apache/spark/pull/60674#issuecomment-6990356851), [2](https://github.com/apache/spark/pull/60674#discussion_r4617387632). **Verification:** - **Inspection:** The migration note's statement of the previous behavior names YARN's application master and executors, and both the note and the config's doc state that the Python workers of a YARN client-mode driver still cannot import the application's Python files, matching the factory's Scaladoc. ########## python/pyspark/sql/tests/connect/client/test_artifact.py: ########## @@ -179,6 +180,99 @@ def test_add_file(self): ) +class GlobalPyFilesTestsMixin: + """ + The Python files that the application was started with (spark.submit.pyFiles, as with + --py-files) stay importable in Python UDFs. + """ + + @classmethod + def with_global_py_files(cls, conf): + cls.global_py_files_dir = tempfile.mkdtemp(prefix="global_py_files") + paths = [] + for name, value in [ Review Comment: **Nit (P3):** This fixture writes only `.py` modules, so no test imports an application package on an executor that runs in its own JVM. On such an executor `SparkFiles.getRootDirectory()` is the relative `.`, and isolated workers start in `<root>/<session UUID>`. Now that the `.py` modules are copied into a directory under the local directory, only `getAbsoluteFile` at `core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:172` keeps an archive's entry valid there. If that call were dropped, or the archive path were built from the relative root another way, importing a package from `--py-files deps.zip` would fail with `ModuleNotFoundError` on every executor of a real cluster, while every new test still passes: `PythonGlobalPyFilesSuite`, which has the only zip, runs on a local master whose files directory is absolute. Writing a small zip package here and adding a batch UDF check that imports it would let `LocalClusterGlobalPyFilesTests` cover this. Keep the import out of `global_py_files_udf`, which the streaming test shares: streaming tasks still run with the default artifact state, whose workers cannot import an archive from the default files directory. **Verification:** - **Behavior:** On a local cluster with separate executor JVMs, a batch Python UDF in an isolated Spark Connect session imports a zip package listed in `spark.submit.pyFiles` and returns the value the package defines. - **Regression:** The new check fails if the package's PYTHONPATH entry is built relative to the executor's files root instead of as an absolute path. ########## core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala: ########## @@ -571,4 +603,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") + modules.foreach { module => + Files.copy(module.toPath, dir.toPath.resolve(module.getName)) Review Comment: **Blocking (P1):** Reading the code, this copy fails whenever `spark.submit.pyFiles` names the same `.py` file more than once, and that stops all Python execution in isolated sessions. spark-submit keeps a repeated entry, such as `--py-files /app/util.py,/app/util.py` or overlapping globs like `'/app/*.py,/app/util.py'`, and `SparkContext.addFile` only warns about the repeat, so the application starts with one copy of `util.py` in the default files directory. `globalPythonFilesPath` maps both entries to that copy (lines 173-176), so this loop copies it twice, and the second `Files.copy`, which passes no `REPLACE_EXISTING`, targets the file the first one created and fails with `FileAlreadyExistsException`. This runs in the factory's constructor, and `SparkEnv.createPythonWorker` caches nothing when the constructor fails. So with the default config, every Python UDF, UDTF and Python data source of every Spark Connect session fails, on the driver and on each executor, even when it never imports the file. The error names only the copy target, not the repeated entry, and each attempt leaves one more `pyfiles-*` directory behind until the JVM exits. On the base branch and in Spark 4.3.0, a JVM application such as a Spark Connect server runs with such a list, because `SparkContext` and YARN skip the repeat. Dropping repeated files after the mapping, for example with `.distinct` on the mapped files at lines 173-176, which keeps the order of first listing, avoids this. This extends an [existing discussion](https://github.com/apache/spark/pull/60674#discussion_r4617387590). **Verification:** - **Regression:** With `spark.submit.pyFiles` naming the same `.py` module twice and that module present in the default files directory, a Python UDTF in an isolated session imports it both in `analyze` on the driver and in `eval` on an executor, instead of failing with FileAlreadyExistsException. ########## core/src/main/scala/org/apache/spark/internal/config/Python.scala: ########## @@ -94,6 +94,21 @@ 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. " + + "Only these files are added, not the other files of the default files directory. Set " + + "to false when starting the application to restore the previous behavior, where these " + + "workers can only import the session's own Python files, except on the application " + + "master and executors on YARN, which puts the application's Python files on their " + + "PYTHONPATH.") + .version("4.0.6") Review Comment: **Nit (P3):** The config records `4.0.6` as the release that first ships it, but the migration-guide entry for the same change sits under "Upgrading from Core 4.3 to 4.4" and starts with "Since Spark 4.4" (`docs/core-migration-guide.md:27`). One of the two will tell users the wrong release for the change and its rollback setting. Whichever release the change first ships in, both should name it; to match the note, as the file's other new entry at `Python.scala:71` does: ```suggestion .version("4.4.0") ``` This extends an [existing discussion](https://github.com/apache/spark/pull/60674#issuecomment-6990356851). **Verification:** - **Inspection:** The config entry declares version `4.4.0`, and the migration guide still documents the change under the upgrade from Core 4.3 to 4.4. ########## sql/core/src/test/scala/org/apache/spark/sql/execution/python/PythonGlobalPyFilesSuite.scala: ########## @@ -0,0 +1,157 @@ +/* + * 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. + override protected def sparkConf: SparkConf = super.sparkConf + .set("spark.files", (globalPyFiles ++ otherFiles).mkString(",")) + .set("spark.submit.pyFiles", Review Comment: **Nit (P3):** Every name listed in `spark.submit.pyFiles` here, and in the PySpark fixture, also has a copy through `spark.files`, so no test lists a file without a copy in the default files directory. Real deployments rely on the factory skipping such files: on YARN the `.py` files are localized under `__pyfiles__`, a subdirectory, rather than in the executor's files directory, a YARN client-mode driver gets no copies, and `local:` files are never fetched. `.filter(_.isFile)` at `core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:175` is what keeps the copy loop from calling `Files.copy` on a missing file. If it regressed, every isolated session's factory on YARN with `.py` py-files would fail with `NoSuchFileException`, and every test would still pass. Listing one more `.py` name in `spark.submit.pyFiles` that is not in `spark.files`, while still expecting the existing imports in `analyze` and `eval` to succeed, would pin it. **Verification:** - **Behavior:** With `spark.submit.pyFiles` also naming a `.py` file that is not in `spark.files`, a Python UDTF in an isolated session still imports the application's other module and package in `analyze` and `eval`. - **Regression:** The suite fails if the factory tries to copy a listed file that has no copy in the default files directory. -- 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]
