classification
Title: Import deadlock detection causes deadlock
Type: behavior Stage: patch review
Components: Library (Lib) Versions: Python 3.9, Python 3.8, Python 3.7, Python 3.6
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Ronan.Lamy, brett.cannon, eric.snow, pconnell, pitrou
Priority: normal Keywords: patch

Created on 2019-09-10 13:26 by Ronan.Lamy, last changed 2019-12-09 10:27 by arigo.

Pull Requests
URL Status Linked Edit
PR 17518 open arigo, 2019-12-09 10:27
Messages (1)
msg351647 - (view) Author: Ronan Lamy (Ronan.Lamy) * Date: 2019-09-10 13:26
There seems to be a race condition in importlib._bootstrap._ModuleLock that can cause a deadlock. The sequence of operations is as follows:

* Thread 1 calls lock.acquire()
* Thread 1 sets itself as lock.owner and begins importing the module
* Thread 2 calls lock.acquire() and waits for lock.lock
* Thread 2 gets lock.lock
* Thread 1 calls lock.acquire() again, due to a nested import
* Thread 1 sets itself as blocking on lock: _blocking_on[tid1] = lock
* Thread 2 enters lock.has_deadlock()
* Thread 2 busy-waits forever in has_deadlock() because lock.owner == tid1 and _blocking_on[tid1] == lock
* Thread 1 waits forever for lock.lock since thread 2 owns it

The issue was found in pypy3 but it also affects all the recent CPython versions I tried.
I can reliably reproduce the issue by adding an artificial delay to _ModuleLock.has_deadlock(), e.g. with this patch:

diff --git a/Lib/test/test_import/__init__.py b/Lib/test/test_import/__init__.py
index f167c84..7f7188e 100644
--- a/Lib/test/test_import/__init__.py
+++ b/Lib/test/test_import/__init__.py
@@ -435,10 +435,15 @@ class ImportTests(unittest.TestCase):
                 os.does_not_exist
 
     def test_concurrency(self):
+        def delay_has_deadlock(frame, event, arg):
+            if event == 'call' and frame.f_code.co_name == 'has_deadlock':
+                time.sleep(0.2)
+
         sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'data'))
         try:
             exc = None
             def run():
+                sys.settrace(delay_has_deadlock)
                 event.wait()
                 try:
                     import package
History
Date User Action Args
2019-12-09 10:27:17arigosetkeywords: + patch
stage: patch review
pull_requests: + pull_request16996
2019-10-28 20:47:46pconnellsetnosy: + pconnell
2019-09-11 14:04:05eric.snowsetnosy: + brett.cannon, eric.snow
2019-09-11 13:10:14eric.snowsetnosy: + pitrou
2019-09-10 13:26:40Ronan.Lamycreate