FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

GH-83065: Fix import deadlock by implementing hierarchical module locking by gpshead · Pull Request #137196 · python/cpython · GitHub

Repository navigation

Prev Previous commit
Next Next commit
_HierarchicalLockManager: release locks on __enter__ failure; accept …
…partial parent on cycle

If lock.acquire() raises (e.g. _DeadlockError or KeyboardInterrupt) after
some chain locks are already held, __exit__ is never called and the held
locks leak permanently. Wrap the loop so any exception releases what was
acquired before re-raising.

When acquiring a parent's lock would deadlock with another thread that is
loading that parent, skip the parent and proceed - the same accept-a-
partial-parent policy that _lock_unlock_module() applies. Without this,
concurrent cross-package circular imports that previously succeeded via
that path now raise _DeadlockError to user code. The leaf's lock is still
required; a deadlock there propagates as before.

Also lift _get_module_chain to a module-level function as it does not use
self.
  • Loading branch information
gpshead committed Apr 28, 2026
commit 478402345c8342b9aad7b6dce26c8bc4917ef62f
55 changes: 38 additions & 17 deletions Lib/importlib/_bootstrap.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,15 @@ def __exit__(self, *args, **kwargs):
self._lock.release()


def _get_module_chain(name):
"""Return the chain of dotted-name prefixes from root to leaf.

For example: 'a.b.c' -> ['a', 'a.b', 'a.b.c']
"""
parts = name.split('.')
return ['.'.join(parts[:i+1]) for i in range(len(parts))]


class _HierarchicalLockManager:
"""Manages acquisition of multiple module locks in hierarchical order.

Expand All @@ -433,27 +442,39 @@ class _HierarchicalLockManager:

def __init__(self, name):
self._name = name
self._module_chain = self._get_module_chain(name)
self._module_chain = _get_module_chain(name)
self._locks = []

def _get_module_chain(self, name):
"""Get all modules in the hierarchy from root to leaf.

For example: 'a.b.c' -> ['a', 'a.b', 'a.b.c']
"""
parts = name.split('.')
return ['.'.join(parts[:i+1]) for i in range(len(parts))]

def __enter__(self):
# Acquire locks for all modules in hierarchy order (parent to child)
for module_name in self._module_chain:
# Only acquire lock if module is not already fully loaded
module = sys.modules.get(module_name)
if (module is None or
getattr(getattr(module, "__spec__", None), "_initializing", False)):
lock = _get_module_lock(module_name)
lock.acquire()
self._locks.append((module_name, lock))
try:
for module_name in self._module_chain:
# Only acquire lock if module is not already fully loaded
module = sys.modules.get(module_name)
if (module is None or
getattr(getattr(module, "__spec__", None),
"_initializing", False)):
lock = _get_module_lock(module_name)
try:
lock.acquire()
except _DeadlockError:
if module_name == self._name:
raise
# The parent is being initialised by a thread that
# is (transitively) waiting on a lock we hold.
# Apply the same policy as _lock_unlock_module():
# accept a partially-initialised parent for circular
# imports rather than failing the whole chain.
continue
self._locks.append((module_name, lock))
except:
# __exit__ is not called when __enter__ raises (e.g. _DeadlockError
# on the leaf lock, or KeyboardInterrupt), so release whatever we
# already hold to avoid permanently leaking held module locks.
for module_name, lock in reversed(self._locks):
lock.release()
self._locks.clear()
raise
return self

def __exit__(self, *args, **kwargs):
Expand Down

Back | FazBrowse Home | New Git URL