spark-test commented on code in PR #60674:
URL: https://github.com/apache/spark/pull/60674#discussion_r4617387608


##########
python/pyspark/sql/tests/connect/client/test_artifact_localcluster.py:
##########
@@ -37,6 +41,20 @@ def master(cls):
         return os.environ.get("SPARK_CONNECT_TESTING_REMOTE", 
"local-cluster[2,2,512]")
 
 
+class LocalClusterGlobalPyFilesTests(

Review Comment:
   **Non-blocking (P2):** This class can deliver `global_py_files_module` only 
by starting the server itself with `spark.files` and `spark.submit.pyFiles`. 
Yet, unlike `GlobalPyFilesTests` in `test_artifact.py`, it has no 
`@unittest.skipIf(is_remote_only(), ...)`. The scheduled 
`.github/workflows/build_python_connect.yml` installs `pyspark-client` and sets 
`SPARK_CONNECT_TESTING_REMOTE=sc://localhost`. It runs this module in both its 
local and local-cluster steps, against a server it started without those files. 
Against an existing server, the builder applies the conf only as silent session 
configs (`python/pyspark/sql/connect/session.py:243-267`). Reading the code, 
all three tests therefore fail there with ModuleNotFoundError in every 
scheduled run. That workflow runs only on schedule and on manual dispatch, so 
this PR's CI will not show it. Adding the same skip fixes it. The module 
imports only `os` today, so it also needs `import unittest` and `from 
pyspark.util import is_remote_o
 nly`.
   
   **Verification:**
   - **Regression:** With only the pure-Python Spark Connect client installed, 
and the tests pointed at a pre-started server through 
`SPARK_CONNECT_TESTING_REMOTE`, the local-cluster global Python files tests are 
skipped rather than failing with ModuleNotFoundError.
   - **Compatibility:** With full PySpark and `SPARK_CONNECT_TESTING_REMOTE` 
unset, the local-cluster global Python files tests still run against the 
local-cluster server they start, and pass.



##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -147,7 +148,32 @@ private[spark] class PythonWorkerFactory(
   private val pythonPath = PythonUtils.mergePythonPaths(
     PythonUtils.sparkPythonPath,
     envVars.getOrElse("PYTHONPATH", ""),
-    sys.env.getOrElse("PYTHONPATH", ""))
+    sys.env.getOrElse("PYTHONPATH", ""),
+    globalPythonFilesPath)
+
+  /**
+   * 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. Only the files in the default files directory are used: 
spark-submit and
+   * `SparkContext` put them there, except on YARN, which puts them on 
PYTHONPATH instead.
+   */
+  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))
+        .filter(_.isFile)
+      val (modules, packages) = files.partition(_.getName.endsWith(".py"))
+      // A module is imported from its directory, and a package from its 
archive.
+      PythonUtils.mergePythonPaths(
+        packages.map(_.getPath) ++ modules.headOption.map(_ => 
rootDir.getPath): _*)

Review Comment:
   **Non-blocking (P2):** Appending `rootDir` here puts the whole default files 
directory on the PYTHONPATH of every isolated session's workers, not just the 
application's `.py` files. Outside YARN, that directory also holds every 
`--files` file and unpacked archive, and files that sessions without isolation 
add later with `addFile`. On an executor that ran a task without an artifact 
state, it also holds the files of every session: 
`JobArtifactSet.getActiveOrDefault` ships `sc.allAddedFiles` for such tasks, 
and `Executor.updateDependencies` fetches them into this directory. Python 
searches PYTHONPATH before the standard library and site-packages, and it lists 
the directory again when it changes. As a result:
   
   - With `--py-files helpers.py --files token.py`, no Python worker of an 
isolated session starts. An interpreter check with this PYTHONPATH order 
(Spark's Python paths, then a directory holding `token.py`) showed `python3 -m 
pyspark.daemon` failing while importing `pyspark`: `pyspark/util.py:29` imports 
`traceback`, which reaches `tokenize` and raises `ImportError: cannot import 
name 'EXACT_TOKEN_TYPES' from 'token'`. Without that directory, the import 
succeeds. On the base branch, the daemon runs in `<root>/<uuid>` and never sees 
this directory.
   - With `--files settings.py`, `import settings` in a UDF loads that file 
instead of an installed `settings` package.
   - Once a task without an artifact state has run on an executor, session B's 
`import helpers2` there can resolve to session A's `pyfiles/helpers2.py`.
   
   The PR description says files given with `--files` are not changed, and 
`spark.sql.artifact.isolation.enabled` keeps a session's artifacts away from 
other sessions. Neither holds for isolated sessions anymore. Sessions without 
isolation see this directory by design, because they share artifacts, so they 
are no precedent for isolated sessions.
   
   **Recommended change:** Change `globalPythonFilesPath` in 
PythonWorkerFactory.scala (lines 161-176) so that isolated sessions' workers 
get the application's `.py` files through a directory that holds only those 
files, the way YARN uses `__pyfiles__`. It should no longer append the whole 
default files directory, as line 174 does now. When the factory computes its 
path, create that directory outside the files root and outside every session 
folder, for example under Spark's local directory. Copy into it each 
`spark.submit.pyFiles` `.py` file that the factory finds by name in the files 
root. Append the directory after the application's archives, which are still 
added by their own path. Do all of this before the idle-worker monitor thread 
starts. Update the method's Scaladoc and the doc of 
`spark.python.isolatedSession.globalPyFiles.enabled` (Python.scala lines 
100-105) to say that only the application's Python files are added. Add Python 
worker tests for a files root that holds other 
 modules.
   
   **Why this works:** Python can import a `.py` module only from a directory 
on its path, so the change exposed the directory that holds the copies, and 
with it everything else that lands there. A directory with only copies of the 
application's `.py` files gives the same import result for those files, in the 
same position: after Spark's paths and any user PYTHONPATH, and before the 
standard library and site-packages. Nothing else written to the files root then 
reaches isolated sessions. The session's own folder and includes still come 
first, because the worker inserts them ahead of PYTHONPATH.
   
   **Compatibility:** Sessions without artifact isolation keep the base-branch 
PYTHONPATH, which includes the whole default files directory. Isolated sessions 
keep the precedence that the change gives the application's Python files.
   
   **Risks:** Isolated sessions will no longer import modules from `--files`, 
from unpacked archives, or from files added by other sessions. Those imports 
worked only with this unreleased change, and only when some `.py` file was 
among the application's Python files, so no released behavior is lost. Each 
worker factory of an isolated session now writes a small directory of file 
copies (or each JVM does, if the directory is shared). The directory must be 
removed together with Spark's local directories when the application ends. 
Setting `spark.python.isolatedSession.globalPyFiles.enabled` to `false` still 
adds nothing, so the change can be rolled back the same way as before.
   
   **Constraints:** Keep the order the change chose: the session's own files 
first, then Spark's paths and any user PYTHONPATH, then the application's 
archives and the new directory, then the standard library and site-packages. 
Take the copies from the files in the default files directory, never from the 
submit-side paths, so the change keeps working on executors that run on other 
hosts. Create the directory and its copies before the factory starts its 
idle-worker monitor thread. If creating them fails, the factory should fail 
with that error rather than silently leave the files unimportable. Add nothing 
when the setting is off or for the workers of sessions without isolation, and 
keep the docs' statement about YARN limited to YARN's application master and 
executors.
   
   **Exclusions:**
   - Sessions without isolation keep the whole default files directory on their 
path, as on the base branch.
   - Tasks without an artifact state still fetch every session's added files 
into an executor's files directory. The repair only stops isolated sessions 
from importing them.
   - The Python workers of a YARN client-mode driver still cannot import the 
application's Python files, a gap that predates this change.
   
   **Verification:**
   - **Regression:** Take an application whose `spark.files` holds two `.py` 
modules, only one of which is in `spark.submit.pyFiles`. An isolated session 
imports the listed module and gets ModuleNotFoundError for the other, both in a 
driver-side worker such as a UDTF's `analyze` and in an executor-side worker.
   - **Regression:** A `.py` file that is only in `spark.files` and is named 
like a standard-library module that the Python worker imports at startup, for 
example `token.py`, does not stop an isolated session's Python UDF from running 
when a `.py` file is also among the application's Python files.
   - **Regression:** An isolated session's UDF cannot import a `.py` file that 
was added to the default files directory after the session's worker factory 
exists, for example with `SparkContext.addFile` from a session without 
isolation.
   - **Compatibility:** In an isolated session, the application's `.py` module 
and zipped package remain importable on the driver and on executors, and a 
session's own file still wins a name clash. With 
`spark.python.isolatedSession.globalPyFiles.enabled` set to `false`, the import 
fails as on the base branch.



##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -147,7 +148,32 @@ private[spark] class PythonWorkerFactory(
   private val pythonPath = PythonUtils.mergePythonPaths(
     PythonUtils.sparkPythonPath,
     envVars.getOrElse("PYTHONPATH", ""),
-    sys.env.getOrElse("PYTHONPATH", ""))
+    sys.env.getOrElse("PYTHONPATH", ""),
+    globalPythonFilesPath)
+
+  /**
+   * 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. Only the files in the default files directory are used: 
spark-submit and
+   * `SparkContext` put them there, except on YARN, which puts them on 
PYTHONPATH instead.

Review Comment:
   **Nit (P3):** YARN puts the application's Python files on the PYTHONPATH 
only of the containers it launches, the application master and the executors 
(`resource-managers/yarn/src/main/scala/org/apache/spark/deploy/yarn/Client.scala:984-1009`).
 And spark-submit does not add `--py-files` to `spark.files` on YARN 
(`core/src/main/scala/org/apache/spark/deploy/SparkSubmit.scala:581-583`). Take 
a JVM driver in YARN client mode, such as a Spark Connect server started with 
`--master yarn --deploy-mode client --py-files deps.py`. Its driver-side 
workers, such as a UDTF's `analyze` or Python data source planning, find 
`deps.py` neither on PYTHONPATH nor in the files directory, with the setting on 
or off. That gap is older than this PR, but this sentence and the setting's doc 
in `Python.scala` (lines 103-105) say YARN covers these workers. Wording such 
as "except on YARN, which puts them on the PYTHONPATH of its application master 
and executors instead, but not of a client-mode driver" would
  be accurate. Avoid saying that the files are absent from the files directory 
on YARN: YARN links the archives into each container's working directory, which 
is an executor's files directory.
   
   **Verification:**
   - **Inspection:** Both the Scaladoc of the method that computes isolated 
sessions' extra Python path and the doc of 
`spark.python.isolatedSession.globalPyFiles.enabled` describe YARN's PYTHONPATH 
handling as covering only its application master and executors, not every 
worker, and neither says that YARN keeps the application's Python files out of 
the default files directory.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/PythonGlobalPyFilesSuite.scala:
##########
@@ -0,0 +1,132 @@
+/*
+ * 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 {
+
+  // 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 = Utils.createTempDir()
+    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)
+  }
+
+  // As spark-submit does with --py-files outside YARN.
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set("spark.files", globalPyFiles.mkString(","))
+    .set("spark.submit.pyFiles", globalPyFiles.mkString(","))

Review Comment:
   **Nit (P3):** Both settings name the same readable originals, on the one 
host where the driver and executors run. So these tests cannot tell whether the 
factory reads the copies in the default files directory, which is what works on 
executors on other hosts, or the submit-side paths. A factory that put the 
submit-side paths on PYTHONPATH would still pass every case here, including the 
precedence and flag-off cases. To make the suite depend on the copies, point 
`spark.submit.pyFiles` at the same file names under a directory that does not 
exist, and keep the real paths in `spark.files`. A short comment would explain 
why the fixture differs from what spark-submit sets.
   
   **Verification:**
   - **Regression:** When the application's Python files are reachable only as 
the copies in the default files directory, because the submit-side paths do not 
exist, an isolated session still imports the module and the zipped package in a 
UDTF's `analyze` and `eval`. A factory that used the submit-side paths would 
fail this case.



##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala:
##########
@@ -147,7 +148,32 @@ private[spark] class PythonWorkerFactory(
   private val pythonPath = PythonUtils.mergePythonPaths(
     PythonUtils.sparkPythonPath,
     envVars.getOrElse("PYTHONPATH", ""),
-    sys.env.getOrElse("PYTHONPATH", ""))
+    sys.env.getOrElse("PYTHONPATH", ""),
+    globalPythonFilesPath)

Review Comment:
   **Nit (P3):** This initializer runs after `new MonitorThread().start()` at 
line 143, and `globalPythonFilesPath` can now throw. With `--conf 
spark.python.isolatedSession.globalPyFiles.enabled=0`, `conf.get` at line 164 
fails with a config type-mismatch error. The constructor then aborts after the 
thread has started, and that thread loops forever holding the factory. 
`SparkEnv.createPythonWorker` builds the factory inside `getOrElseUpdate`, so 
nothing is cached, and every later request of an isolated session builds 
another factory and leaks another thread. Making the monitor thread's start the 
constructor's last statement, after every initializer, avoids the leak.
   
   **Verification:**
   - **Regression:** Creating an isolated session's Python worker factory with 
`spark.python.isolatedSession.globalPyFiles.enabled` set to `0` fails with the 
setting's type-mismatch error, and repeated attempts leave the number of 
running idle-worker monitor threads unchanged.
   - **Behavior:** Constructing a Python worker factory successfully starts 
exactly one idle-worker monitor thread for it.



-- 
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]

Reply via email to