← Back to Pull requests

[SPARK-60893][PYTHON] Keep the import caches of Spark's own zip archives when Python workers invalidate import caches #60108

Closed
gaogaotiantian closed this pull request without merging on Nov 11, 2026 00:05 UTC
View on GitHub
gaogaotiantian gaogaotiantian commented on Nov 04, 2026 20:53 UTC
Author

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 zipimporters 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 through spark.executorEnv.PYTHONPATH, is treated the same way: the worker already runs modules from it, so it can't be replaced safely while the application runs anyway.

    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.

    Diff: 105 lines (+104 / -1) across 2 files Reviewer: HyukjinKwon Review duration: 8831m
    All Vouch review confidence checks passed
    Residual risk 0.05 = Change Risk (0.32) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.32 · 105 lines diff across 2 files
    0.32
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.77 · 5 substantive comment(s)
    0.77
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.279
    Real PR Conversation Timeline
    18 items
    spark-test spark-test commented on Nov 04, 2026 22:45 UTC
    Reviewer

    Review summary

    The new helper keeps the zipimporters of archives that were on sys.path when the worker started, and it still refreshes archives added later through python_includes, as the description says. Two problems remain in the new code. The filter that picks the importers to keep iterates the live sys.path_importer_cache, so an import on another thread during the scan can make setup_spark_files fail with RuntimeError: dictionary changed size during iteration. Iterating a list(...) snapshot, as the standard library does, avoids this. The new tests call the helper directly, one of them with a substitute snapshot, so they would still pass if setup_spark_files went back to importlib.invalidate_caches() and the startup re-reads returned. One question for the author follows.

    Cross-cutting observations

  • Whichever startup archives you decide to keep, the code that selects them still scans sys.path_importer_cache. The snapshot-based scan therefore applies equally to the current filter and to any filter that replaces it.
  • The iteration fix can land now, independently of how you answer the question about startup archives replaced while the Python daemon runs.

    Findings

    2 total: 0 P0, 0 P1, 1 P2, 1 P3.

    Non-blocking (P2)

  • Startup-archive filter iterates the live sys.path_importer_cache — python/pyspark/worker_util.py:90 — see inline.
  • Nit (P3)

  • New tests never exercise setup_spark_files or the real startup snapshot — python/pyspark/tests/test_worker.py:468 — see inline.
  • Decision challenges

    Kept startup-zip listings now date from Python daemon start, not worker start

    Keeping the zipimporters of startup archives saves the re-reads your table measures. In daemon mode, the default outside Windows, it also changes how long their listings live. Forked workers inherit the zipimporters and directory listings that the daemon's own imports created for every zip on the startup PYTHONPATH. On the base branch, each new worker's first setup_spark_files refreshed them: spark_files_dir is never on the daemon's sys.path, so that call always ran the invalidation. With this change the listings are kept for as long as the daemon lives, which is normally until the executor stops. The comment above _startup_sys_path only says that the archives do not change while the worker runs.

    What this review verified: daemon.py imports the worker module after fork. A new worker is forked whenever no idle one is available, idle workers are killed after a minute in which no worker is released, and every task gets a new worker when spark.python.worker.reuse is false. User zips can reach the startup path through spark.executorEnv.PYTHONPATH or the executor's own PYTHONPATH. In a daemon-shaped repro on CPython 3.12 with this PR's setup_spark_files, a user zip was rebuilt in place after the daemon started, and workers forked afterwards imported from it. A module added to the zip raised ModuleNotFoundError. A module that grew was read truncated and failed with SyntaxError. A module that moved behind a new entry imported without error, but with that entry's bytes. With the base branch's worker_util.py, workers forked the same way loaded the new contents. With the zip unchanged, both versions behaved the same, and a fresh process started after the rebuild was fine with both. As the description says, Spark's own startup archives (pyspark.zip, the py4j zip, the spark-core JAR and YARN-localized files) are not replaced during an application, and zips from python_includes and Spark Connect artifacts are still refreshed, so only user-managed archives are affected. The base-branch refresh was also only partial, because reused workers skipped it on tasks that brought no new includes.

    What it could not verify, and the question for you: is replacing a user-managed zip on the worker's startup PYTHONPATH while the application runs out of scope? If it is, could the comment and docstring say that kept listings date from daemon start, and that such archives must not be replaced while the application runs? If it is not, the kept set could be limited to the archives Spark itself puts on the worker path: pyspark.zip, the py4j zip and the spark-core JAR. The pyspark and py4j zips can be found from where those packages were loaded, and the JVM could pass the full list, including the JAR. By your table the JAR accounts for most of the saving on Python 3.13+, so it should stay in that set. User archives would then keep the refresh they get today.

    Generated by Omnigent on Databricks
    <!-- SPARK_OSS_REVIEW_REQUEST 35177416621 -->

    <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"79324e2c197d4f073f7d","id":"pass-a:live-importer-cache-iteration"},{"delivery":"inline","fingerprint":"e42526e1dd45a3fe55bd","id":"pass-b:tests-bypass-setup-spark-files"}],"head_sha":"5fe0d9a37632c539bb7456926b2eecb4fa233fbc","verdict_sha256":"8892d2f9a744c686e5509c08bd55026b25c864bf926dd4fbca8fecb93cacdd43"} -->

    spark-test spark-test commented on code on Nov 04, 2026 22:45 UTC
    Code Review
    python/pyspark/worker_util.py:1
    @@ -68,6 +74,34 @@ def add_path(path: str) -> bool:
         return False
     
     
    +def _invalidate_import_caches() -> None:
    +    """
    +    Like importlib.invalidate_caches(), but keeps the zipimporters of archives that were on
    +    sys.path when the worker started.
    +
    +    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. Archives added after startup, such as the ones in python_includes, are still
    +    invalidated.
    +    """
    +    kept = {
    +        path: finder
    +        for path, finder in sys.path_importer_cache.items()

    Non-blocking (P2): This comprehension iterates the live sys.path_importer_cache and runs Python code for each entry, so the GIL can pass to another thread in the middle of the scan. If that thread imports a module that is not loaded yet, PathFinder inserts finders for the entries that setup_spark_files just added, and the scan raises RuntimeError: dictionary changed size during iteration. The error escapes setup_spark_files during worker initialization, so the task attempt fails with an error unrelated to the user's code. Reused workers that get new includes while a thread from an earlier task is still running are the main case. importlib.invalidate_caches(), which setup_spark_files called before this change, walks a list(...) snapshot of the same dict and cannot fail this way. On CPython 3.12, a background thread doing imports made this helper raise in 30 of 20,000 calls at a 10 microsecond switch interval, and a version that iterates a snapshot never raised. Iterating a snapshot keeps the result the same:

            for path, finder in list(sys.path_importer_cache.items())
    

    Verification:

  • Regression: Inserting an entry into sys.path_importer_cache while the helper is collecting the importers to keep does not make it raise, and the helper still keeps the startup archive's importers and invalidates the later-added archive.

  • Behavior: The existing checks still hold: a startup archive's importers are neither invalidated nor replaced, a later-added archive is invalidated, and an added archive rewritten in place exposes its new module after invalidation.
  • spark-test spark-test commented on code on Nov 04, 2026 22:45 UTC
    Code Review
    python/pyspark/tests/test_worker.py:1
    @@ -413,6 +417,72 @@ def fail(_, it):
             self.assertIn("data error", outfile.read(read_int(outfile)).decode("utf-8"))
     
     
    +class InvalidateImportCachesTests(unittest.TestCase):
    +    def setUp(self):
    +        temp_dir = tempfile.TemporaryDirectory()
    +        self.addCleanup(temp_dir.cleanup)
    +        self.temp_dir = temp_dir.name
    +
    +    def _write_zip(self, path, modules):
    +        with zipfile.ZipFile(path, "w") as zf:
    +            for name, source in modules.items():
    +                zf.writestr(name, source)
    +
    +    def _add_zip(self, archive_name, modules):
    +        path = os.path.join(self.temp_dir, archive_name)
    +        self._write_zip(path, modules)
    +        sys.path.insert(0, path)
    +
    +        def cleanup():
    +            sys.path.remove(path)
    +            for key in [k for k in sys.path_importer_cache if k.startswith(path)]:
    +                del sys.path_importer_cache[key]
    +            zipimport._zip_directory_cache.pop(path, None)
    +
    +        self.addCleanup(cleanup)
    +        return path
    +
    +    def _import(self, name):
    +        self.addCleanup(sys.modules.pop, name, None)
    +        return importlib.import_module(name)
    +
    +    def test_startup_archives_are_not_invalidated(self):
    +        startup = self._add_zip(
    +            "startup.zip",
    +            {"_spark_startup_pkg/__init__.py": "", "_spark_startup_pkg/mod.py": "x = 1"},
    +        )
    +        added = self._add_zip("added.zip", {"_spark_added_mod.py": "x = 1"})
    +        self.addCleanup(sys.modules.pop, "_spark_startup_pkg", None)
    +        self._import("_spark_startup_pkg.mod")
    +        self._import("_spark_added_mod")
    +        startup_finders = {
    +            k: v for k, v in sys.path_importer_cache.items() if k.startswith(startup)
    +        }
    +        # The archive itself and the package inside it each have a zipimporter.
    +        self.assertEqual(len(startup_finders), 2)
    +
    +        with (
    +            patch.object(worker_util, "_startup_sys_path", frozenset([startup])),
    +            patch.object(zipimport.zipimporter, "invalidate_caches", autospec=True) as invalidate,
    +        ):
    +            worker_util._invalidate_import_caches()

    Nit (P3): Both new tests call _invalidate_import_caches() directly, and this one also replaces _startup_sys_path with its own snapshot. Nothing exercises setup_spark_files or the snapshot taken when worker_util is imported. If setup_spark_files went back to calling importlib.invalidate_caches(), or the snapshot stopped containing the real startup archives, both tests would still pass while the startup re-reads this PR removes came back. A test that runs setup_spark_files with a new directory and checks an archive from the real snapshot, such as the py4j zip that bin/pyspark puts on PYTHONPATH, would close the gap; it can skip that check when py4j was not loaded from a zip.

    Verification:

  • Regression: Driving invalidation through setup_spark_files with a newly added path keeps the importers of the py4j archive that was on sys.path when worker_util was imported, while a later-added archive is still invalidated. The check fails when setup_spark_files calls importlib.invalidate_caches() directly instead.

  • Behavior: After the new check runs, sys.path, the finder-cache entries it created, and the SparkFiles root directory and worker flag are back to their previous values, so later tests in the same process are unaffected.
  • gaogaotiantian gaogaotiantian commented on code on Nov 04, 2026 23:49 UTC
    Code Review
    python/pyspark/worker_util.py:1
    @@ -68,6 +74,34 @@ def add_path(path: str) -> bool:
         return False
     
     
    +def _invalidate_import_caches() -> None:
    +    """
    +    Like importlib.invalidate_caches(), but keeps the zipimporters of archives that were on
    +    sys.path when the worker started.
    +
    +    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. Archives added after startup, such as the ones in python_includes, are still
    +    invalidated.
    +    """
    +    kept = {
    +        path: finder
    +        for path, finder in sys.path_importer_cache.items()

    Good catch, thanks. Done in a9da1a07586: the scan now iterates list(sys.path_importer_cache.items()), as importlib.invalidate_caches() does.

    I didn't add a regression test for this one. A real thread race isn't deterministic, and forcing it would mean patching the helper's internals, which the reworked tests deliberately avoid (see the other thread).

    gaogaotiantian gaogaotiantian commented on code on Nov 04, 2026 23:49 UTC
    Code Review
    python/pyspark/tests/test_worker.py:1
    @@ -413,6 +417,72 @@ def fail(_, it):
             self.assertIn("data error", outfile.read(read_int(outfile)).decode("utf-8"))
     
     
    +class InvalidateImportCachesTests(unittest.TestCase):
    +    def setUp(self):
    +        temp_dir = tempfile.TemporaryDirectory()
    +        self.addCleanup(temp_dir.cleanup)
    +        self.temp_dir = temp_dir.name
    +
    +    def _write_zip(self, path, modules):
    +        with zipfile.ZipFile(path, "w") as zf:
    +            for name, source in modules.items():
    +                zf.writestr(name, source)
    +
    +    def _add_zip(self, archive_name, modules):
    +        path = os.path.join(self.temp_dir, archive_name)
    +        self._write_zip(path, modules)
    +        sys.path.insert(0, path)
    +
    +        def cleanup():
    +            sys.path.remove(path)
    +            for key in [k for k in sys.path_importer_cache if k.startswith(path)]:
    +                del sys.path_importer_cache[key]
    +            zipimport._zip_directory_cache.pop(path, None)
    +
    +        self.addCleanup(cleanup)
    +        return path
    +
    +    def _import(self, name):
    +        self.addCleanup(sys.modules.pop, name, None)
    +        return importlib.import_module(name)
    +
    +    def test_startup_archives_are_not_invalidated(self):
    +        startup = self._add_zip(
    +            "startup.zip",
    +            {"_spark_startup_pkg/__init__.py": "", "_spark_startup_pkg/mod.py": "x = 1"},
    +        )
    +        added = self._add_zip("added.zip", {"_spark_added_mod.py": "x = 1"})
    +        self.addCleanup(sys.modules.pop, "_spark_startup_pkg", None)
    +        self._import("_spark_startup_pkg.mod")
    +        self._import("_spark_added_mod")
    +        startup_finders = {
    +            k: v for k, v in sys.path_importer_cache.items() if k.startswith(startup)
    +        }
    +        # The archive itself and the package inside it each have a zipimporter.
    +        self.assertEqual(len(startup_finders), 2)
    +
    +        with (
    +            patch.object(worker_util, "_startup_sys_path", frozenset([startup])),
    +            patch.object(zipimport.zipimporter, "invalidate_caches", autospec=True) as invalidate,
    +        ):
    +            worker_util._invalidate_import_caches()

    Agreed, thanks. In a9da1a07586 I replaced both tests with SetupSparkFilesImportCacheTests, which only calls setup_spark_files and uses the real module state. Nothing patches or calls the helper.

  • test_startup_archive_import_caches_are_kept: the zipimporters of the py4j zip that the test process loaded py4j from are not invalidated and stay the same objects. It skips when py4j was not loaded from a zip; under python/run-tests it runs.

  • test_include_import_caches_are_refreshed: an include rewritten in place exposes its new module after a later setup_spark_files call adds another include.

  • test_user_archive_on_startup_path_import_caches_are_refreshed: covers the daemon question in the review summary.
  • setUp restores sys.path, the finder-cache entries it created, and SparkFiles._root_directory / _is_running_on_worker. I checked that setup_spark_files calling importlib.invalidate_caches() directly, or an empty set of kept archives, fails the first test.

    gaogaotiantian gaogaotiantian commented on Nov 04, 2026 23:49 UTC
    Author

    Thanks for the thorough review. On the decision challenge (kept startup-zip listings date from daemon start): you're right. I had only considered when sys.path is captured, not that forked workers inherit the listings the daemon cached. Replacing a user zip on the startup PYTHONPATH isn't something we want to put out of scope, so a9da1a07586 takes the second option.

  • The kept set is now only Spark's own archives: the zips this worker's pyspark and py4j were loaded from, found through their module specs. On pip installs neither comes from a zip, so nothing is kept.

  • Every other zip, including user archives on PYTHONPATH and YARN-localized --py-files, is refreshed as before.

  • The spark-core JAR isn't included. #60071 (approved) removes it from the worker path, so after that there is nothing to keep. The table in the description is now measured without it: 42.3 → 5.2 ms on 3.11, 39.8 → 5.3 ms on 3.12, 5.0 → 2.4 ms on 3.13 and 4.9 → 2.3 ms on 3.14. That's the same as keeping every startup zip, since pyspark.zip accounts for nearly all of the cost.
  • The new test_user_archive_on_startup_path_import_caches_are_refreshed reproduces your scenario through setup_spark_files. It starts a Python process with a user zip on PYTHONPATH, imports from it, rebuilds the zip, and imports a module that was added. It fails with ModuleNotFoundError when every startup zip is kept, and passes now.

    The other two findings are answered inline, and the description and title are updated to match.

    gaogaotiantian gaogaotiantian commented on code on Nov 04, 2026 23:53 UTC
    Code Review
    python/pyspark/tests/test_worker.py:1
    @@ -413,6 +417,72 @@ def fail(_, it):
             self.assertIn("data error", outfile.read(read_int(outfile)).decode("utf-8"))
     
     
    +class InvalidateImportCachesTests(unittest.TestCase):
    +    def setUp(self):
    +        temp_dir = tempfile.TemporaryDirectory()
    +        self.addCleanup(temp_dir.cleanup)
    +        self.temp_dir = temp_dir.name
    +
    +    def _write_zip(self, path, modules):
    +        with zipfile.ZipFile(path, "w") as zf:
    +            for name, source in modules.items():
    +                zf.writestr(name, source)
    +
    +    def _add_zip(self, archive_name, modules):
    +        path = os.path.join(self.temp_dir, archive_name)
    +        self._write_zip(path, modules)
    +        sys.path.insert(0, path)
    +
    +        def cleanup():
    +            sys.path.remove(path)
    +            for key in [k for k in sys.path_importer_cache if k.startswith(path)]:
    +                del sys.path_importer_cache[key]
    +            zipimport._zip_directory_cache.pop(path, None)
    +
    +        self.addCleanup(cleanup)
    +        return path
    +
    +    def _import(self, name):
    +        self.addCleanup(sys.modules.pop, name, None)
    +        return importlib.import_module(name)
    +
    +    def test_startup_archives_are_not_invalidated(self):
    +        startup = self._add_zip(
    +            "startup.zip",
    +            {"_spark_startup_pkg/__init__.py": "", "_spark_startup_pkg/mod.py": "x = 1"},
    +        )
    +        added = self._add_zip("added.zip", {"_spark_added_mod.py": "x = 1"})
    +        self.addCleanup(sys.modules.pop, "_spark_startup_pkg", None)
    +        self._import("_spark_startup_pkg.mod")
    +        self._import("_spark_added_mod")
    +        startup_finders = {
    +            k: v for k, v in sys.path_importer_cache.items() if k.startswith(startup)
    +        }
    +        # The archive itself and the package inside it each have a zipimporter.
    +        self.assertEqual(len(startup_finders), 2)
    +
    +        with (
    +            patch.object(worker_util, "_startup_sys_path", frozenset([startup])),
    +            patch.object(zipimport.zipimporter, "invalidate_caches", autospec=True) as invalidate,
    +        ):
    +            worker_util._invalidate_import_caches()

    Follow-up: in c624fc324f7 I renamed test_startup_archive_import_caches_are_kept to test_spark_archive_import_caches_are_kept. With the kept set now limited to Spark's own archives, py4j's zip is kept because it's the archive py4j was loaded from, not because it was on the startup path. The test itself is unchanged. I also fixed the _spark_archives comment to cover the copies Spark ships to YARN containers.

    gaogaotiantian gaogaotiantian commented on code on Nov 05, 2026 00:00 UTC
    Code Review
    python/pyspark/tests/test_worker.py:1
    @@ -413,6 +417,72 @@ def fail(_, it):
             self.assertIn("data error", outfile.read(read_int(outfile)).decode("utf-8"))
     
     
    +class InvalidateImportCachesTests(unittest.TestCase):
    +    def setUp(self):
    +        temp_dir = tempfile.TemporaryDirectory()
    +        self.addCleanup(temp_dir.cleanup)
    +        self.temp_dir = temp_dir.name
    +
    +    def _write_zip(self, path, modules):
    +        with zipfile.ZipFile(path, "w") as zf:
    +            for name, source in modules.items():
    +                zf.writestr(name, source)
    +
    +    def _add_zip(self, archive_name, modules):
    +        path = os.path.join(self.temp_dir, archive_name)
    +        self._write_zip(path, modules)
    +        sys.path.insert(0, path)
    +
    +        def cleanup():
    +            sys.path.remove(path)
    +            for key in [k for k in sys.path_importer_cache if k.startswith(path)]:
    +                del sys.path_importer_cache[key]
    +            zipimport._zip_directory_cache.pop(path, None)
    +
    +        self.addCleanup(cleanup)
    +        return path
    +
    +    def _import(self, name):
    +        self.addCleanup(sys.modules.pop, name, None)
    +        return importlib.import_module(name)
    +
    +    def test_startup_archives_are_not_invalidated(self):
    +        startup = self._add_zip(
    +            "startup.zip",
    +            {"_spark_startup_pkg/__init__.py": "", "_spark_startup_pkg/mod.py": "x = 1"},
    +        )
    +        added = self._add_zip("added.zip", {"_spark_added_mod.py": "x = 1"})
    +        self.addCleanup(sys.modules.pop, "_spark_startup_pkg", None)
    +        self._import("_spark_startup_pkg.mod")
    +        self._import("_spark_added_mod")
    +        startup_finders = {
    +            k: v for k, v in sys.path_importer_cache.items() if k.startswith(startup)
    +        }
    +        # The archive itself and the package inside it each have a zipimporter.
    +        self.assertEqual(len(startup_finders), 2)
    +
    +        with (
    +            patch.object(worker_util, "_startup_sys_path", frozenset([startup])),
    +            patch.object(zipimport.zipimporter, "invalidate_caches", autospec=True) as invalidate,
    +        ):
    +            worker_util._invalidate_import_caches()

    Another follow-up: in b722e43aaf8 I simplified the tests to check what setup_spark_files is for, not how it does it. SetupSparkFilesImportCacheTests now has two tests:

  • test_spark_archives_are_not_invalidated: the archives that pyspark and py4j were loaded from are not invalidated.

  • 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.
  • They replace the three tests from my earlier replies, including the subprocess one. Both still go only through setup_spark_files, and they fail with the old importlib.invalidate_caches() call, with an empty set of kept archives, and with no invalidation.

    spark-test spark-test commented on code on Nov 08, 2026 05:40 UTC
    Code Review
    python/pyspark/tests/test_worker.py:1
    @@ -413,6 +419,52 @@ def fail(_, it):
             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)

    Nit (P3): user.zip joins sys.path here, after worker_util has already computed _SPARK_ARCHIVES, so this test only covers a zip added after startup. With the previous round's rule, which kept every archive on sys.path when worker_util was imported, this test and test_spark_archives_are_not_invalidated both still pass, while a user zip already on the startup PYTHONPATH stays stale. That is the daemon-start case this PR now deliberately refreshes, and the subprocess test that covered it was removed in b722e43aaf8. A test that starts a child process with a user zip first on PYTHONPATH, rewrites the zip in place, calls setup_spark_files with a new directory, and then imports the added module would restore that signal.

    This extends an existing discussion.

    Verification:

  • Regression: With the kept set computed from every archive on sys.path when worker_util is imported, the new check fails because the module added to the startup-path user zip cannot be imported. With the current rule, the check passes.

  • Behavior: The existing checks still hold: the archives pyspark and py4j were loaded from are not invalidated, and a user zip added to sys.path after import still exposes a module appended to it.
  • spark-test spark-test commented on code on Nov 08, 2026 05:40 UTC
    Code Review
    python/pyspark/worker_util.py:1
    @@ -68,6 +70,50 @@ 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. 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.
    +    """
    +    kept = {

    Non-blocking (P2): When _SPARK_ARCHIVES is empty, nothing can be kept, but this still snapshots and type-checks every sys.path_importer_cache entry before making the same importlib.invalidate_caches() call as before. That adds work to each invalidation that grows with the cache, about 3 us at 50 entries on CPython 3.12. The set is empty only when a worker loads neither pyspark nor py4j from a zip. An example is a YARN application with a JVM main class, such as the Spark Connect server: it gets no shipped pyspark archives, so its workers import PySpark installed on the executor hosts. Pip-installed PySpark is not such a case, because the package ships pyspark.zip and the py4j zip under pyspark/python/lib and Spark puts them first on the worker PYTHONPATH. Returning early when the set is empty gives the same result:

        if not _SPARK_ARCHIVES:
            importlib.invalidate_caches()
            return
    

    Verification:

  • Inspection: When the set of Spark archives is empty, the helper returns right after calling importlib.invalidate_caches(), before building any snapshot of sys.path_importer_cache.

  • Behavior: With no Spark archive loaded from a zip, invalidation through setup_spark_files still refreshes a user zip on sys.path and still drops relative-path cache entries, exactly as importlib.invalidate_caches() does.

  • Compatibility: With pyspark or py4j loaded from a zip, the zipimporters of those archives are still neither invalidated nor replaced, and other zips on sys.path are still refreshed.
  • spark-test spark-test commented on Nov 08, 2026 05:40 UTC
    Reviewer

    Review summary

    Since the last review, the scan of sys.path_importer_cache iterates a list(...) snapshot, and the tests go through setup_spark_files with the real set of Spark archives, so both earlier findings are addressed. In answer to the earlier question, only the archives that pyspark and py4j were loaded from now keep their import caches. A repro on CPython 3.12 confirmed that an ordinary user zip on the startup PYTHONPATH is refreshed again.

    Two problems remain. The simplified tests no longer cover a user zip that is already on the worker path at startup, so a regression to keeping every startup zip would still pass the suite. And when no Spark archive was loaded from a zip, _invalidate_import_caches still scans the whole cache although it can keep nothing. That affects fewer workers than the description implies, because pip-installed PySpark workers load both packages from zips. One question for the author follows.

    Cross-cutting observations

  • Both the missing startup-path test and the question about zips that bundle py4j or pyspark concern the same promise in the description: user zips that are already on the worker path when it starts keep being refreshed.
  • The startup-path test can be added now and will pass under either answer to the question, which only decides how a zip that also supplies py4j or pyspark should be treated.

    Findings

    2 total: 0 P0, 0 P1, 1 P2, 1 P3.

    Non-blocking (P2)

  • Cache scan runs even when no Spark archive can be kept — python/pyspark/worker_util.py:100 — see inline.
  • Nit (P3)

  • Tests no longer cover a user zip already on the startup path — python/pyspark/tests/test_worker.py:453 — see inline.
  • Re-review status

    Prior AI findings: 2 no longer raised, 0 still raised; additional unresolved findings in this review: 2.

    New attribution: 1 newly introduced, 1 late catch, 0 previously raised, 0 unattributed.

    PR description suggestions

  • The description says the set of Spark archives is empty "as with pip-installed PySpark". Python workers of a pip install do load both packages from zips: the package ships pyspark.zip and the py4j zip under pyspark/python/lib, and Spark puts them first on the worker PYTHONPATH. So pip-installed workers keep those archives and get the speedup too, and the set is empty only when a worker imports both packages from directories.
  • Decision challenges

    Should a user zip that bundles py4j or pyspark keep its refresh?

    _SPARK_ARCHIVES is computed from where pyspark and py4j were loaded, so it can include a user zip, not only the archives Spark ships. On YARN, spark.executorEnv.PYTHONPATH and the submitting client's PYTHONPATH come before the localized pyspark.zip and py4j zip (Client.scala:1004-1009). Executors get no SPARK_HOME, so Spark prepends only the spark-core JAR to that path (PythonWorkerFactory.scala:147-150). A user dependency zip there that bundles py4j or pyspark, for example one built from requirements that pull in pyspark, then supplies those packages and is treated as a Spark archive.

    What this review verified: in a repro on CPython 3.12 with this PR's worker_util, sys.path started with a user zip holding a copy of py4j and a user module, followed by Spark's py4j zip and the pyspark sources. The user zip entered _SPARK_ARCHIVES. After a module was appended to it in place, importing that module after setup_spark_files raised ModuleNotFoundError. With the base branch's worker_util.py, the same layout imported it, and with a user zip that does not bundle py4j, this PR imported it too. In daemon mode, if such a zip is rebuilt while the application runs, workers forked afterwards still use the listing the daemon cached at startup when they import user modules from it, such as ones a UDF needs. Added modules are then not found, and moved entries are read from stale offsets. On the base branch, each new worker's first setup_spark_files refreshed that listing.

    What it could not verify, and the question for you: should a user-managed zip that supplies py4j or pyspark keep the refresh the description promises for user archives? This review could not determine whether such layouts are supported, or how often such a zip is rebuilt in place while an application runs.

  • If yes, _SPARK_ARCHIVES could be limited to archives Spark itself puts on the worker path, for example by intersecting it with entries the JVM passes to the worker.

  • If no, the comment above _SPARK_ARCHIVES could say that a zip supplying pyspark or py4j counts as Spark's archive and must not be replaced while the application runs.
  • This follows up on an existing discussion.

    Generated by Omnigent on Databricks
    <!-- SPARK_OSS_REVIEW_REQUEST 35466698309 -->

    <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"a8f99d01e46c05973489","id":"pass-a:startup-path-user-zip-refresh-untested"},{"delivery":"inline","fingerprint":"9b6cfec5caa76711dc32","id":"pass-b:empty-kept-set-still-scans-cache"}],"head_sha":"35cf8c5ae062188196880b5d813550ce75425c4b","verdict_sha256":"28183e0b235c92a8bb37900e7eeaec22e6f459f49d0bc8c113c8dec2ef4ea74f"} -->

    spark-test spark-test commented on code on Nov 08, 2026 05:40 UTC
    Code Review
    python/pyspark/worker_util.py:1
    @@ -68,6 +74,34 @@ def add_path(path: str) -> bool:
         return False
     
     
    +def _invalidate_import_caches() -> None:
    +    """
    +    Like importlib.invalidate_caches(), but keeps the zipimporters of archives that were on
    +    sys.path when the worker started.
    +
    +    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. Archives added after startup, such as the ones in python_includes, are still
    +    invalidated.
    +    """
    +    kept = {
    +        path: finder
    +        for path, finder in sys.path_importer_cache.items()

    Thanks, I checked the current head. The scan now iterates a list(...) snapshot of sys.path_importer_cache, the same way importlib.invalidate_caches() does, so an import on another thread can no longer break it. No regression test is needed for this fix: a deterministic one would have to plant a finder that changes the cache in the middle of the scan, which is more machinery than a one-line change needs.

    <!-- SPARK_DEV_REVIEW_REPLY {"feedback_id":"inline:4474292425","thread_id":"inline:4474292425","verdict_sha256":"28183e0b235c92a8bb37900e7eeaec22e6f459f49d0bc8c113c8dec2ef4ea74f"} -->

    gaogaotiantian gaogaotiantian commented on code on Nov 09, 2026 23:44 UTC
    Code Review
    python/pyspark/worker_util.py:1
    @@ -68,6 +70,50 @@ 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. 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.
    +    """
    +    kept = {

    Done in fa217e33b9c: _invalidate_import_caches now calls importlib.invalidate_caches() and returns right away when _SPARK_ARCHIVES is empty. I checked that path by running the tests with py4j unpacked into a directory: the set is empty, and a user zip on sys.path is still refreshed.

    Thanks also for the correction about pip installs, answered in the PR comment.

    gaogaotiantian gaogaotiantian commented on code on Nov 09, 2026 23:44 UTC
    Code Review
    python/pyspark/tests/test_worker.py:1
    @@ -413,6 +419,52 @@ def fail(_, it):
             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)

    Thanks. That's right: neither test catches a return to keeping every zip on the startup path. I'd still like to leave this out. We simplified the tests to check what setup_spark_files is for, and the only way to put a zip on the path at process start is a child process, which is the extra machinery we removed on purpose. The rule itself is now spelled out in the _SPARK_ARCHIVES comment and the description: archives other than the ones pyspark and py4j were loaded from, including user zips on PYTHONPATH, are refreshed. A change back to keeping every startup zip would have to contradict that comment, which review should catch.

    gaogaotiantian gaogaotiantian commented on Nov 09, 2026 23:44 UTC
    Author

    Thanks for the re-review.

    Pip installs: you're right, and my earlier reply here was wrong. The wheel ships pyspark/python/lib/pyspark.zip and the py4j zip, and sparkPythonPath puts them first on the worker path. I checked with the 4.1.0 wheel in a fresh venv: a worker loads pyspark from .../pyspark/python/lib/pyspark.zip/pyspark/__init__.py and py4j from .../py4j-0.10.9.9-src.zip/py4j/__init__.py. So pip-installed workers keep those archives and get the speedup. The description now says so.

    A user zip that bundles pyspark or py4j: I went with the second option. In fa217e33b9c, the _SPARK_ARCHIVES comment says that a zip which supplies the worker's pyspark or py4j counts as Spark's archive and must not be replaced while the application runs. The description says the same. Two reasons:

  • Such a zip can't be replaced safely mid-application, even on master. The daemon and its workers already run pyspark (or py4j) modules from it, and pyspark imports many of its submodules lazily, so after a refresh the later imports would come from the new copy while the modules already loaded come from the old one. The refresh on master changes how that layout fails, but doesn't make it work.

  • Limiting the set to entries the JVM passes would drop YARN. Executors there have no SPARK_HOME, so the localized pyspark.zip reaches the worker through the PYTHONPATH that Client builds, not through sparkPythonPath. A list from PythonWorkerFactory wouldn't include it, so YARN workers would lose the speedup unless the archive list were plumbed from the client as well.
  • The two inline findings are answered in their threads.

    HyukjinKwon HyukjinKwon approved these changes on Nov 09, 2026 23:47 UTC
    Approved Reviewer

    Approved these changes.

    gaogaotiantian gaogaotiantian commented on Nov 11, 2026 00:05 UTC
    Author
    Reviewers
    Assignees
    gaogaotiantian gaogaotiantian
    Labels
    risk: low confidence: 85.4% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 32.4% (LOW) · Higher = larger blast radius
    32.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.4% · Lower = rushed or shallow review
    85.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.7% · Safe to merge
    4.7%
    Repository