[SPARK-60893][PYTHON] Keep the import caches of Spark's own zip archives when Python workers invalidate import caches #60108
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
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)
python/pyspark/worker_util.py:90 — see inline.Nit (P3)
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"} -->
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:
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:
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).
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.
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.
pyspark and py4j were loaded from, found through their module specs. On pip installs neither comes from a zip, so nothing is kept.PYTHONPATH and YARN-localized --py-files, is refreshed as before.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.
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.
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.
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:
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:
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
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)
python/pyspark/worker_util.py:100 — see inline.Nit (P3)
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
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.
_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._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"} -->
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"} -->
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.
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.
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:
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.
Approved these changes.
Merge Summary:
Posted by merge_spark_pr.py
HyukjinKwon
gaogaotiantian
What changes were proposed in this pull request?
worker_util.setup_spark_filesnow calls a new_invalidate_import_caches()instead ofimportlib.invalidate_caches(). The new function keeps thezipimporters of Spark's own zip archives, and invalidates everything else exactly as before:1. When
worker_utilis imported, it records the zip archives that this worker'spysparkandpy4jwere loaded from (_SPARK_ARCHIVES), using their module specs. With a Spark distribution or pip-installed PySpark, which ships the same zips underpyspark/python/lib, these arepyspark.zipand the py4j zip underSPARK_HOME. When neither package is loaded from a zip, the set is empty andimportlib.invalidate_caches()is called directly.2. When invalidating, it temporarily removes from
sys.path_importer_cachethezipimporterentries whosearchiveis one of those, callsimportlib.invalidate_caches(), and puts them back. It scans alist(...)snapshot of the cache, asimportlibdoes, so an import on another thread can't change the dict during the scan. Only absolute-path entries are kept aside, becauseimportlib.invalidate_caches()deliberately drops relative-path entries in case the working directory changed.Why are the changes needed?
setup_spark_filesaddsspark_files_dirand thepython_includestosys.pathand then invalidates the import caches. That happens on the first task of every new worker process, and on every task whenspark.python.worker.reuseis disabled.importlib.invalidate_caches()callsinvalidate_caches()on every finder insys.path_importer_cache, and every package imported from a zip archive has its ownzipimporterthere. Afterimport pyspark.worker,pyspark.ziphas 15 of them (pyspark.zip,pyspark.zip/pyspark,pyspark.zip/pyspark/sql, ...). The cost depends on the Python version:zipimporter.invalidate_caches()re-reads the archive's whole central directory right away, sopyspark.zipis re-read 15 times.PathFinder.invalidate_caches()importsimportlib.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.zipand the py4j zip, fromSPARK_HOMEor 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'spysparkorpy4j, for example one placed before Spark's archives on YARN throughspark.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:
PYTHONPATH, for example fromspark.executorEnv.PYTHONPATHor 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.python_includes(addPyFile,--py-files, Spark Connect artifacts) are still invalidated. A zip that is newly added tosys.pathhas no cached finder yet, so Python reads its current contents on the first lookup either way.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_filestime afterimport pyspark.worker, withpyspark.zipbuilt 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
PYTHONPATHand from zips added throughaddPyFile,--py-filesor Spark Connect artifacts are still found as before.How was this patch tested?
SetupSparkFilesImportCacheTeststopyspark/tests/test_worker.py. Both tests callsetup_spark_filesand 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; underpython/run-tests, py4j is.-
test_user_archive_changes_are_picked_up: after a module is added to a user zip onsys.path, the module can be imported oncesetup_spark_filesruns.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.spark-submitwith worker reuse. Job 1 added a zip withaddPyFileand 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.