[Bug] Deadlock interruption can leak CPython's import lock and freeze the worker (still on Python 3.13/3.14)
I maintainer di solito rispondono entro 1 giorno
Valutazione
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Idoneità per principianti
- 25/100
Direzione di ricerca
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.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
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.
- Lingua principale
- Python
- Stelle
- 1.3k
- Fork
- 305
- Merge medio
- 3g 23h
- PR unite (30g)
- 44
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Nessun modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di temporalio/sdk-python
-
[Bug] Catching the ValueError from upsert_search_attributes (naive datetime) still leaves a workflow stuck retrying its taskForse già presa @VegetarianOrc l’ha presa oggi. Apertasdk-python
temporalio/sdk-python#2200 · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
-
[Bug] Python: replayed Local Activity timeout causes NDE (TimeoutError not wrapped in ActivityError)Forse già presa @mjameswh l’ha presa 1 giorno fa. Apertabug sdk-python
temporalio/sdk-python#2183 · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
-
[Bug] workflow_streams: subscribe() raises RPCError when a publish signal lands during the continue-as-new workflow taskForse già presa @feiiiiii5 l’ha presa 5 giorni fa. Aperta
Difficoltà 3/5 1-2 giorni Idoneità per principianti 52/100
temporalio/sdk-python#2170 ·
I maintainer di solito rispondono entro 1 giorno
-
Support custom peer identity verification while retaining standard TLS authenticationForse già presa @dzsquared l’ha presa 23 giorni fa. Aperta
Difficoltà 5/5 Più di una settimana Idoneità per principianti 35/100
temporalio/sdk-python#2106 · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
-
Cloud CI Skips Nexus TestsForse di nuovo libera @tconley1428 l’ha presa 114 giorni fa e non c’è nessuna pull request aperta. Aperta
temporalio/sdk-python#1704 · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di temporalio/sdk-python
Issue simili
-
area:print-dispatch
Difficoltà 2/5 1-3 ore Idoneità per principianti 92/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
area/geometry good first issue help wanted kind/doc-mismatch severity/4-minor
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
Apich-Organization/rssn#295 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 88/100
-
chore claimed
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
schuyler/corvidae#1424 · 2 commenti ·
I maintainer di solito rispondono entro 1 giorno