[Bug] Deadlock interruption can leak CPython's import lock and freeze the worker (still on Python 3.13/3.14)

Abierto
#2,115 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@tconley1428 ya está trabajando en esto.

Desde el 12/11/2026.

  • #2118 de @tconley1428 — cerrado sin fusionar

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
25/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python
Área
backend

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

sdk-python
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 cb inside it. GC can invoke cb at 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_interruption replaced 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_interruption still injects unconditionally on main at 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.

Lenguaje dominante
Python
Estrellas
1.3k
Forks
305
Merge medio
3 d 23 h
PR fusionados (30 d)
44

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de temporalio/sdk-python

Todos los issues de temporalio/sdk-python

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.