HeartSaVioR commented on code in PR #60674:
URL: https://github.com/apache/spark/pull/60674#discussion_r4623627870


##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks, confirmed: with a listed `token.py`, every Python worker of an 
isolated session failed to start. Rather than document it, I've changed the 
design in 5ccf9516a28, as the alternative you named:
   
   - `PythonWorkerFactory` no longer puts these files on the `PYTHONPATH` that 
the workers start with. It passes them in `SPARK_GLOBAL_PYTHON_PATH`, a 
`SPARK_` name, so a session can't set it.
   - `worker_util.setup_spark_files` adds them when the worker sets up the 
files of a task, after its start-up imports. This is how the workers of a 
session without isolation add the default files directory and its archives.
   - The session's own files still come first: the worker starts in the 
session's folder, which Python puts first on `sys.path`, and the session's 
archives are added in front of these files.
   - Once a worker has started, a listed module still comes before the standard 
library, as the default files directory does without isolation. The migration 
note and the description now say so.
   
   Tests in `PythonGlobalPyFilesSuite`:
   - `spark.submit.pyFiles` now lists a `token.py` and a zip that bundles a 
`signal` package, both of which raise when imported. The workers still start.
   - Both `analyze` and `eval` check that the start-time `PYTHONPATH` holds 
none of these files.
   - If they go back on the start-time path, the suite fails with the 
`token.py` error.
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks. With the change in 5ccf9516a28, the daemon no longer reads these 
archives when it starts, because they are no longer on its start-time path. 
Each worker reads a listed archive's index when an import first passes it, as 
the workers of a session without isolation do with the archives that PySpark 
adds for them.
   
   The factory now adds only the `.zip`, `.egg` and `.jar` archives, the same 
kinds PySpark adds without isolation. So it no longer adds other kinds of 
listed files.
   
   Jars stay, because PySpark adds them for a session without isolation too, 
and that is how `--packages` jars reach those workers today. The description 
now states this cost.
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks, fixed in 5ccf9516a28. The config doc, the factory's Scaladoc, the 
migration note and the description now describe the boundary the way the code 
decides it:
   - the workers that run in an isolated session's folder can import the listed 
files that have a copy in the default files directory;
   - spark-submit makes these copies in client mode outside YARN, and PySpark 
makes them when it starts the driver;
   - a JVM driver on YARN in client mode and an application in standalone 
cluster deploy mode get no copies;
   - workers started without the session's artifact state, such as the Spark 
Connect `foreachBatch` and streaming listener workers, keep their previous path.
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks, fixed in 5ccf9516a28 with your wording: a new session gets a new 
Python worker factory, which reads the config when it is created.
   



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