[Bug] Deadlock interruption can leak CPython's import lock and freeze the worker (still on Python 3.13/3.14)
Maintainer antworten meist innerhalb von 1 Tag
@tconley1428 arbeitet bereits daran.
Seit 12.11.2026.
- #2118 von @tconley1428 — ohne Merge geschlossen
Bewertung
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Anfängerfreundlichkeit
- 25/100
Rechercherichtung
Start by reading _RunningWorkflow.attempt_deadlock_interruption and Runtime._raise_in_thread, then inspect the import-lock behavior described in the reproduction and related issues #2095 and #2067. The issue suggests making deadlock interruption opt-out or opt-in; deciding a safe policy and its effects on workflow failure and eviction requires design work. Done means a slow activation reports TMPRL1101 without leaving the worker's import lock wedged.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Beschreibung
What are you really trying to do?
Run a Python worker with sandboxed workflows under real load. Under CPU pressure, some activations exceed the 2 s deadlock timeout (TMPRL1101).
Describe the bug
When an activation exceeds the deadlock timeout, _RunningWorkflow.attempt_deadlock_interruption calls Runtime._raise_in_thread(thread_id, _InterruptDeadlockError), which uses PyThreadState_SetAsyncExc.
If the activation thread is inside an import, the asynchronous exception can be delivered right after _imp.acquire_lock() returns, and before importlib's try/finally starts. CPython's global import lock is then never released.
There are two places this happens:
importlib._bootstrap._get_module_lock;- the module-lock weakref callback
cbinside it. GC can invokecbat any time, with no import frame on the stack.
Every thread that imports afterwards blocks forever. That includes the worker's event-loop thread, which imports through the sandbox when it creates a workflow instance. The process sits at 0% CPU with no output, while Core keeps polling.
The sandbox imports during activations, because each run gets a fresh sys.modules. A slow activation is therefore often inside importlib when the timer fires.
This is the same mechanism as #2095, which was closed as not planned on the basis that Python 3.13 fixed the logging case. importlib was not fixed. As of 3.14.7, _get_module_lock and cb still do _imp.acquire_lock() followed by try:. The repro below wedges on 3.12, 3.13 and 3.14. So this does not go away by upgrading Python, and it is not limited to user code that happens to log.
Related: #2067 is another async-exception-injection failure on the same path.
Minimal Reproduction
Pure CPython, without Temporal: two threads re-import modules while a third thread fires PyThreadState_SetAsyncExc at them, which is what Runtime._raise_in_thread does. Afterwards, a fresh import from another thread should complete.
import ctypes, faulthandler, importlib, os, random, sys, tempfile, threading, time
faulthandler.dump_traceback_later(float(sys.argv[2]) + 20, exit=True)
N, SECS = int(sys.argv[1]), float(sys.argv[2])
d = tempfile.mkdtemp(prefix="lockleak")
for i in range(N):
with open(os.path.join(d, f"m{i}.py"), "w") as f:
f.write("X = sum(range(50))\n")
sys.path.insert(0, d)
importlib.invalidate_caches()
class Interrupt(BaseException):
pass
stop = threading.Event()
stats = {"imports": 0, "interrupts_caught": 0, "fired": 0}
def worker():
i = 0
while not stop.is_set():
name = f"m{i % N}"
i += 1
try:
sys.modules.pop(name, None)
importlib.import_module(name)
stats["imports"] += 1
except Interrupt:
stats["interrupts_caught"] += 1
except Exception:
pass
try:
time.sleep(0.01)
except Interrupt:
pass
workers = [threading.Thread(target=worker, daemon=True) for _ in range(2)]
for w in workers:
w.start()
set_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
set_exc.argtypes = [ctypes.c_ulong, ctypes.py_object]
t_end = time.monotonic() + SECS
while time.monotonic() < t_end:
w = random.choice(workers)
set_exc(w.ident, Interrupt)
stats["fired"] += 1
time.sleep(random.uniform(0, 0.0005))
print("phase: interrupter done", stats, flush=True)
stop.set()
for w in workers:
try:
w.join(5)
except Interrupt:
pass
print("phase: workers joined", [w.is_alive() for w in workers], flush=True)
import gc; gc.collect()
progress = {"done": 0}
def checker():
for i in range(N):
sys.modules.pop(f"m{i}", None)
importlib.import_module(f"m{i}")
progress["done"] += 1
c = threading.Thread(target=checker, daemon=True)
c.start(); c.join(10)
hung = c.is_alive()
print(sys.version.split()[0], stats, "checker_done=%d/%d" % (progress["done"], N),
"HANG at m%d" % progress["done"] if hung else "no hang", flush=True)
os._exit(0)
Run it as python probe.py 400 8. These results are from macOS on arm64:
| CPython | result |
|---|---|
| 3.11.12 | wedged 3/3 |
| 3.12.1 | wedged 3/3 |
3.12.16 (python:3.12-slim, Linux) |
wedged 3/3 |
| 3.13.2 | wedged 3/3 |
| 3.14.7 | wedged 3/3 |
"Wedged" means the faulthandler watchdog fired, because even the main thread's import gc never returned.
3.14.7: the interrupt lands in cb while it holds the import lock, and the thread dies holding it:
Exception ignored while calling weakref callback <function _get_module_lock.<locals>.cb at 0x109ecc7d0>:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 449, in cb
Interrupt:
...
phase: interrupter done {'imports': 662, 'interrupts_caught': 23, 'fired': 10961}
phase: workers joined [False, True]
Timeout (0:00:28)!
Thread 0x000000016e5f3000 [Thread-2 (worker)] (most recent call first):
File "<frozen importlib._bootstrap>", line 435 in _get_module_lock
File "<frozen importlib._bootstrap>", line 420 in __enter__
File "<frozen importlib._bootstrap>", line 1368 in _find_and_load
...
Thread 0x00000001f4526180 (most recent call first):
File "<frozen importlib._bootstrap>", line 435 in _get_module_lock
File "<frozen importlib._bootstrap>", line 420 in __enter__
File "<frozen importlib._bootstrap>", line 1368 in _find_and_load
File "probe.py", line 59 in <module> # import gc
With a real worker. We also reproduced this through the real SDK path on temporalio 1.30.0, Python 3.12.1, with a start_local server, the default sandbox and the stock 2 s deadlock timeout:
- Workflow that re-imports ~24k trivial modules on every activation: wedged 2/2 before the first round finished. The main thread was in
_get_module_lock, and 10 of 11 threads were waiting on the import lock. - Same import load on the first activation only (a load spike): wedged 1/1.
- The same spike with
attempt_deadlock_interruptionreplaced by a no-op that only logs: 2/2 clean runs, 3/3 rounds each. Eviction retried and then succeeded once the slow activation finished.
Happy to share the worker script if useful.
Environment/Versions
- temporalio 1.30.0 (reproduced end to end).
attempt_deadlock_interruptionstill injects unconditionally onmainat 4733537c4. - CPython 3.11.12, 3.12.1, 3.12.16, 3.13.2, 3.14.7 on macOS (arm64) and Linux.
Additional context
A frame check before raising can't make this safe. cb runs from GC or a refcount drop with no importlib frame on the stack, so there is nothing to detect beforehand. In general, PyThreadState_SetAsyncExc can't be made safe from outside the target thread while that thread may be holding any acquire(); try: lock.
A suggestion, in line with the request in #2095: make the deadlock interrupt opt-out, or opt-in. The worker would report TMPRL1101 and fail the task without injecting into the thread, and let eviction wait, as it already does for a workflow that never yields. Today the only switch is debug_mode, which drops deadlock detection entirely.
- Vorherrschende Sprache
- Python
- Sterne
- 1.3k
- Forks
- 305
- Ø Merge
- 3 T. 23 Std.
- Gemergte PRs (30 T.)
- 44
Entwicklungsumgebung
- Kein Dockerfile und keine Docker-Compose-Datei
- Keine Pull-Request-Vorlage
- Beitragsleitfaden lesen
Erste Schritte
- Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
- Forken Sie das Repository und arbeiten Sie in einem Branch.
- Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.
Mehr aus temporalio/sdk-python
-
[Bug] Catching the ValueError from upsert_search_attributes (naive datetime) still leaves a workflow stuck retrying its taskEvtl. vergeben @VegetarianOrc hat das heute übernommen. Offensdk-python
temporalio/sdk-python#2200 · 1 zugewiesene Person ·
Maintainer antworten meist innerhalb von 1 Tag
-
[Bug] Python: replayed Local Activity timeout causes NDE (TimeoutError not wrapped in ActivityError)Evtl. vergeben @mjameswh hat das vor 1 Tag übernommen. Offenbug sdk-python
temporalio/sdk-python#2183 · 1 zugewiesene Person ·
Maintainer antworten meist innerhalb von 1 Tag
-
[Bug] workflow_streams: subscribe() raises RPCError when a publish signal lands during the continue-as-new workflow taskEvtl. vergeben @feiiiiii5 hat das vor 5 Tagen übernommen. Offen
Schwierigkeit 3/5 1-2 Tage Anfängerfreundlichkeit 52/100
temporalio/sdk-python#2170 ·
Maintainer antworten meist innerhalb von 1 Tag
-
Support custom peer identity verification while retaining standard TLS authenticationEvtl. vergeben @dzsquared hat das vor 23 Tagen übernommen. Offen
Schwierigkeit 5/5 Über eine Woche Anfängerfreundlichkeit 35/100
temporalio/sdk-python#2106 · 1 zugewiesene Person ·
Maintainer antworten meist innerhalb von 1 Tag
-
Cloud CI Skips Nexus TestsEvtl. wieder frei @tconley1428 hat das vor 114 Tagen übernommen, und es ist kein Pull Request offen. Offen
temporalio/sdk-python#1704 · 1 zugewiesene Person ·
Maintainer antworten meist innerhalb von 1 Tag
Alle Issues in temporalio/sdk-python
Ähnliche Issues
-
area:print-dispatch
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 92/100
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
Maintainer antworten meist innerhalb von 1 Tag
-
area/geometry good first issue help wanted kind/doc-mismatch severity/4-minor
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 68/100
Apich-Organization/rssn#295 ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 88/100
-
chore claimed
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 72/100
schuyler/corvidae#1424 · 2 Kommentare ·
Maintainer antworten meist innerhalb von 1 Tag