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


##########
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:
   > [!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. This is covered by the new `PythonWorkerFactorySuite` test, the same 
one as the copy-directory lifetime comment. Without `cachedPaths == paths` or 
without `dir.isDirectory`, that test fails.
   



##########
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:
   > [!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, added in 779c3d152d9. `GlobalPyFilesPrecedenceTestsMixin` has a new 
test where a new session adds, as a Python file, a zip holding 
`global_py_files_clash.py`. It runs with Spark Connect locally and on the local 
cluster.
   
   A UDF imports the session's version. If the worker adds the application's 
files after all of the session's entries, the test fails.
   
   As you noted, the order relative to the session's folder alone can't be 
observed. The folder is the worker's working directory and so is `sys.path[0]`.
   



##########
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:
   > [!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, added in 779c3d152d9. A new suite case turns 
`spark.python.use.daemon` off for a new isolated session. A Python UDTF then 
imports the application's module and packages in `analyze` and `eval`, and 
checks that the workers' start-time `PYTHONPATH` holds none of these files. 
Without the simple-worker launch's `SPARK_GLOBAL_PYTHON_PATH`, the case fails.
   



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