This is an automated email from the ASF dual-hosted git repository.

gaogaotiantian pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 82286b2c9700 [SPARK-60893][PYTHON] Keep the import caches of Spark's 
own zip archives when Python workers invalidate import caches
82286b2c9700 is described below

commit 82286b2c97005a572ccaead1146108fb5453808a
Author: Tian Gao <[email protected]>
AuthorDate: Tue Nov 10 16:05:25 2026 -0800

    [SPARK-60893][PYTHON] Keep the import caches of Spark's own zip archives 
when Python workers invalidate import caches
    
    ### What changes were proposed in this pull request?
    
    `worker_util.setup_spark_files` now calls a new 
`_invalidate_import_caches()` instead of `importlib.invalidate_caches()`. The 
new function keeps the `zipimporter`s of Spark's own zip archives, and 
invalidates everything else exactly as before:
    
    1. When `worker_util` is imported, it records the zip archives that this 
worker's `pyspark` and `py4j` were loaded from (`_SPARK_ARCHIVES`), using their 
module specs. With a Spark distribution or pip-installed PySpark, which ships 
the same zips under `pyspark/python/lib`, these are `pyspark.zip` and the py4j 
zip under `SPARK_HOME`. When neither package is loaded from a zip, the set is 
empty and `importlib.invalidate_caches()` is called directly.
    2. When invalidating, it temporarily removes from `sys.path_importer_cache` 
the `zipimporter` entries whose `archive` is one of those, calls 
`importlib.invalidate_caches()`, and puts them back. It scans a `list(...)` 
snapshot of the cache, as `importlib` does, so an import on another thread 
can't change the dict during the scan. Only absolute-path entries are kept 
aside, because `importlib.invalidate_caches()` deliberately drops relative-path 
entries in case the working directory changed.
    
    ### Why are the changes needed?
    
    `setup_spark_files` adds `spark_files_dir` and the `python_includes` to 
`sys.path` and then invalidates the import caches. That happens on the first 
task of every new worker process, and on every task when 
`spark.python.worker.reuse` is disabled.
    
    `importlib.invalidate_caches()` calls `invalidate_caches()` on every finder 
in `sys.path_importer_cache`, and every package imported from a zip archive has 
its own `zipimporter` there. After `import pyspark.worker`, `pyspark.zip` has 
15 of them (`pyspark.zip`, `pyspark.zip/pyspark`, `pyspark.zip/pyspark/sql`, 
...). The cost depends on the Python version:
    
    - Up to Python 3.12, `zipimporter.invalidate_caches()` re-reads the 
archive's whole central directory right away, so `pyspark.zip` is re-read 15 
times.
    - On Python 3.13+, it drops the cached listing, which is shared per 
archive, and the listing is re-read on the next lookup. That lookup happens 
right away, because `PathFinder.invalidate_caches()` imports 
`importlib.metadata`.
    
    For Spark's own archives those re-reads are wasted. A zipimporter's cache 
only goes stale when its archive is rewritten in place, and `pyspark.zip` and 
the py4j zip, from `SPARK_HOME` or the copies Spark ships to YARN containers, 
are not replaced while an application runs. That also holds in daemon mode, 
where forked workers inherit listings cached when the daemon started. A user 
zip that supplies the worker's `pyspark` or `py4j`, for example one placed 
before Spark's archives on YARN [...]
    
    All other archives keep today's behavior:
    
    - User archives on the worker's `PYTHONPATH`, for example from 
`spark.executorEnv.PYTHONPATH` or YARN-localized `--py-files`, may be rebuilt 
while an application runs. The daemon may have cached their listings before the 
first task, so they are still refreshed.
    - Zips sent through `python_includes` (`addPyFile`, `--py-files`, Spark 
Connect artifacts) are still invalidated. A zip that is newly added to 
`sys.path` has no cached finder yet, so Python reads its current contents on 
the first lookup either way.
    - User code that calls `importlib.invalidate_caches()` itself is not 
affected, since only Spark's own call changes.
    
    Nearly all of the cost comes from `pyspark.zip`, so limiting the kept set 
to Spark's archives keeps almost the whole speedup.
    
    Measured `setup_spark_files` time after `import pyspark.worker`, with 
`pyspark.zip` built from master or from this branch and the py4j zip on the 
path, as with #60071 (SPARK-60855), which removes the spark-core JAR from the 
path (median of 21 fresh processes, macOS arm64):
    
    | Python | master | this PR |
    |---|---|---|
    | 3.11 | 42.3 ms | 5.2 ms |
    | 3.12 | 39.8 ms | 5.3 ms |
    | 3.13 | 5.0 ms | 2.4 ms |
    | 3.14 | 4.9 ms | 2.3 ms |
    
    Until #60071 is merged, the spark-core JAR is still on the worker path. It 
is not one of Spark's archives as defined here, so it is still re-read on each 
new worker, about 7-8 ms on top of these numbers.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No, other than faster Python worker startup. Modules from user archives on 
`PYTHONPATH` and from zips added through `addPyFile`, `--py-files` or Spark 
Connect artifacts are still found as before.
    
    ### How was this patch tested?
    
    - Added `SetupSparkFilesImportCacheTests` to 
`pyspark/tests/test_worker.py`. Both tests call `setup_spark_files` and check 
its effect:
      - `test_spark_archives_are_not_invalidated`: the archives that pyspark 
and py4j were loaded from are not invalidated. It skips when neither was loaded 
from a zip; under `python/run-tests`, py4j is.
      - `test_user_archive_changes_are_picked_up`: after a module is added to a 
user zip on `sys.path`, the module can be imported once `setup_spark_files` 
runs.
    
      Both pass on Python 3.11, 3.12, 3.13 and 3.14. Each of these wrong 
implementations fails one of them: invalidating everything as before, keeping 
every zipimporter, an empty set of Spark archives, and no invalidation at all.
    - `python/run-tests --testnames 
'pyspark.tests.test_worker,pyspark.sql.tests.test_python_worker_env,pyspark.sql.tests.test_udf'`
 passed on Python 3.12.
    - Manually ran `spark-submit` with worker reuse. Job 1 added a zip with 
`addPyFile` and imported from it; job 2 added a second zip, and the same worker 
process imported from both.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Isaac
    
    This pull request and its description were written by Isaac.
    
    
    
    Closes #60108 from gaogaotiantian/skip-startup-zip-invalidation.
    
    Authored-by: Tian Gao <[email protected]>
    Signed-off-by: Tian Gao <[email protected]>
    
    
    skip-checks: true
---
 python/pyspark/tests/test_worker.py | 52 ++++++++++++++++++++++++++++++++++++
 python/pyspark/worker_util.py       | 53 ++++++++++++++++++++++++++++++++++++-
 2 files changed, 104 insertions(+), 1 deletion(-)

diff --git a/python/pyspark/tests/test_worker.py 
b/python/pyspark/tests/test_worker.py
index 5d1ace34c44f..ea62bbf55c63 100644
--- a/python/pyspark/tests/test_worker.py
+++ b/python/pyspark/tests/test_worker.py
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+import importlib
 import io
 import json
 import os
@@ -23,6 +24,8 @@ import tempfile
 import threading
 import time
 import unittest
+import zipfile
+import zipimport
 from typing import Any, Optional
 from unittest.mock import patch
 
@@ -32,8 +35,10 @@ try:
 except ImportError:
     has_resource_module = False
 
+import py4j
 from py4j.protocol import Py4JJavaError
 
+import pyspark
 from pyspark import SparkConf, SparkContext
 from pyspark.accumulators import _accumulatorRegistry
 from pyspark.core.files import SparkFiles
@@ -53,6 +58,7 @@ from pyspark.util import PythonEvalType
 from pyspark.worker_metrics import WorkerMetrics
 
 with patch.dict(os.environ, {"SPARK_PYTHON_RUNTIME": "PYTHON_WORKER"}):
+    from pyspark import worker_util
     from pyspark.worker import main as worker_main
 
 
@@ -413,6 +419,52 @@ class WorkerInitResponseTests(unittest.TestCase):
         self.assertIn("data error", 
outfile.read(read_int(outfile)).decode("utf-8"))
 
 
+class SetupSparkFilesImportCacheTests(unittest.TestCase):
+    def setUp(self):
+        temp_dir = tempfile.TemporaryDirectory()
+        self.addCleanup(temp_dir.cleanup)
+        self.temp_dir = temp_dir.name
+        # setup_spark_files changes these, so restore them for later tests.
+        self.addCleanup(sys.path.__setitem__, slice(None), list(sys.path))
+        self.addCleanup(setattr, SparkFiles, "_root_directory", 
SparkFiles._root_directory)
+        self.addCleanup(
+            setattr, SparkFiles, "_is_running_on_worker", 
SparkFiles._is_running_on_worker
+        )
+
+    def test_spark_archives_are_not_invalidated(self):
+        archives = {
+            module.__loader__.archive
+            for module in (pyspark, py4j)
+            if isinstance(module.__loader__, zipimport.zipimporter)
+        }
+        if not archives:
+            self.skipTest("neither pyspark nor py4j was loaded from a zip 
archive")
+
+        with patch.object(zipimport.zipimporter, "invalidate_caches", 
autospec=True) as invalidate:
+            worker_util.setup_spark_files(self.temp_dir, [])
+
+        invalidated = {call.args[0].archive for call in 
invalidate.call_args_list}
+        self.assertTrue(archives.isdisjoint(invalidated))
+
+    def test_user_archive_changes_are_picked_up(self):
+        user_zip = os.path.join(self.temp_dir, "user.zip")
+        with zipfile.ZipFile(user_zip, "w") as zf:
+            zf.writestr("_spark_user_a.py", "")
+        sys.path.insert(0, user_zip)
+        self.addCleanup(sys.path_importer_cache.pop, user_zip, None)
+        self.addCleanup(sys.modules.pop, "_spark_user_a", None)
+        self.addCleanup(sys.modules.pop, "_spark_user_b", None)
+        importlib.import_module("_spark_user_a")
+
+        with zipfile.ZipFile(user_zip, "a") as zf:
+            zf.writestr("_spark_user_b.py", "")
+        worker_util.setup_spark_files(self.temp_dir, [])
+
+        # This is the check: it raises ModuleNotFoundError if 
setup_spark_files did not refresh
+        # the user archive's cached directory listing.
+        importlib.import_module("_spark_user_b")
+
+
 class WorkerTests(ReusedPySparkTestCase):
     def test_cancel_task(self):
         temp = tempfile.NamedTemporaryFile(delete=True)
diff --git a/python/pyspark/worker_util.py b/python/pyspark/worker_util.py
index 8b5bb153f634..416f58c73087 100644
--- a/python/pyspark/worker_util.py
+++ b/python/pyspark/worker_util.py
@@ -20,10 +20,12 @@ Util functions for workers.
 """
 
 import importlib
+import importlib.util
 import json
 import os
 import sys
 import warnings
+import zipimport
 from contextlib import contextmanager
 from inspect import currentframe, getframeinfo
 from typing import IO, Any, Generator, Optional, Union, overload
@@ -68,6 +70,55 @@ def add_path(path: str) -> bool:
     return False
 
 
+def _zip_archive_of(module_name: str) -> Optional[str]:
+    spec = importlib.util.find_spec(module_name)
+    loader = spec.loader if spec is not None else None
+    return loader.archive if isinstance(loader, zipimport.zipimporter) else 
None
+
+
+# The zip archives this worker's pyspark and py4j were loaded from, such as
+# $SPARK_HOME/python/lib/pyspark.zip or the copy that Spark ships to YARN 
containers. They are
+# not replaced while an application runs, so _invalidate_import_caches keeps 
their cached
+# directory listings. A user zip that supplies the worker's pyspark or py4j 
counts as one of
+# these archives and must not be replaced while the application runs either: 
the worker already
+# runs modules from it, so a replaced copy could not be used safely anyway. 
Other archives,
+# including user archives on PYTHONPATH, may be replaced and are not kept.
+_SPARK_ARCHIVES = frozenset(
+    archive for archive in map(_zip_archive_of, ("pyspark", "py4j")) if 
archive is not None
+)
+
+
+def _invalidate_import_caches() -> None:
+    """
+    Like importlib.invalidate_caches(), but keeps the zipimporters of Spark's 
own archives
+    (_SPARK_ARCHIVES).
+
+    Up to Python 3.12, invalidating a zipimporter re-reads the archive's whole 
directory, and an
+    archive has one zipimporter per package imported from it, so pyspark.zip 
is re-read once for
+    every package the worker imported from it. Python 3.13+ re-reads each 
archive once on its
+    next lookup. All other archives, such as user archives on PYTHONPATH and 
the ones in
+    python_includes, are still invalidated.
+    """
+    if not _SPARK_ARCHIVES:
+        importlib.invalidate_caches()
+        return
+    kept = {
+        path: finder
+        for path, finder in list(sys.path_importer_cache.items())
+        # importlib.invalidate_caches() drops relative paths because the 
working directory may
+        # have changed, so only keep absolute ones.
+        if isinstance(finder, zipimport.zipimporter)
+        and finder.archive in _SPARK_ARCHIVES
+        and os.path.isabs(path)
+    }
+    for path in kept:
+        del sys.path_importer_cache[path]
+    try:
+        importlib.invalidate_caches()
+    finally:
+        sys.path_importer_cache.update(kept)
+
+
 def read_command(serializer: FramedSerializer, file: Union[IO, bytes, 
memoryview]) -> Any:
     if not is_remote_only():
         from pyspark.core.broadcast import Broadcast
@@ -172,7 +223,7 @@ def setup_spark_files(
         path_changed = add_path(os.path.join(spark_files_dir, filename)) or 
path_changed
 
     if path_changed:
-        importlib.invalidate_caches()
+        _invalidate_import_caches()
 
 
 @overload


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to