spark-test commented on code in PR #60108:
URL: https://github.com/apache/spark/pull/60108#discussion_r4505184756
##########
python/pyspark/worker_util.py:
##########
@@ -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 = {
Review Comment:
**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:
```python
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.
##########
python/pyspark/tests/test_worker.py:
##########
@@ -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)
Review Comment:
**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](https://github.com/apache/spark/pull/60108#issuecomment-6645437446).
**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.
##########
python/pyspark/worker_util.py:
##########
@@ -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()
Review Comment:
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"}
-->
--
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]