cpython/Lib/importlib
Miss Islington (bot) 7d074702eb
[3.14] gh-143650: Fix importlib race condition on import failure (GH-143651) (#144662)
gh-143650: Fix importlib race condition on import failure (GH-143651)

Fix a race condition where a thread could receive a partially-initialized
module when another thread's import fails. The race occurs when:

1. Thread 1 starts importing, adds module to sys.modules
2. Thread 2 sees the module in sys.modules via the fast path
3. Thread 1's import fails, removes module from sys.modules
4. Thread 2 returns a stale module reference not in sys.modules

The fix adds verification after the "skip lock" optimization in both Python
and C code paths to check if the module is still in sys.modules. If the
module was removed (due to import failure), we retry the import so the
caller receives the actual exception from the import failure rather than
a stale module reference.
(cherry picked from commit ac8b5b6890)

Co-authored-by: Gregory P. Smith <68491+gpshead@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-11 06:06:51 +00:00
..
metadata gh-120910: Fix issue resolving relative paths outside site-packages. (#120911) 2024-06-23 13:06:07 -04:00
resources gh-123987: Fix NotADirectoryError in NamespaceReader when sentinel present (#124018) 2025-01-26 16:23:54 +00:00
__init__.py gh-125519: Improve traceback if importlib.reload() is called with a non-module object (#125520) 2024-10-21 07:53:21 +01:00
_abc.py gh-102515: Remove unused imports in the Lib/ directory (#102516) 2023-03-08 11:45:38 +00:00
_bootstrap.py [3.14] gh-143650: Fix importlib race condition on import failure (GH-143651) (#144662) 2026-02-11 06:06:51 +00:00
_bootstrap_external.py [3.14] gh-141930: Use the regular IO stack to write .pyc files for a better error message on failure (GH-141931) (#142021) 2025-12-01 18:43:50 +02:00
abc.py [3.14] GH-137426: Remove code deprecation of importlib.abc.ResourceLoader (GH-137567) (#137654) 2025-08-12 15:47:28 +03:00
machinery.py gh-121604: Make sure all deprecated items in importlib raise DeprecationWarning (#128007) 2025-01-14 16:48:46 -08:00
readers.py bpo-46118: Move importlib.resources to its own package. (#30176) 2021-12-30 21:00:48 -05:00
simple.py bpo-46118: Move importlib.resources to its own package. (#30176) 2021-12-30 21:00:48 -05:00
util.py gh-122188: Move magic number to its own file (#122243) 2024-07-30 15:31:05 -04:00