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

未關閉
#2,115 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

@tconley1428 已經在處理了。

開始於 2026年11月12日。

  • #2118 來自 @tconley1428 —— 已關閉,未合併

評估

難度
5/5
預估耗時
一週以上
新手友好度
25/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
python
領域
backend

研究方向

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.

由索引模型根據 Issue 內容生成。

描述

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.

主要語言
Python
星號
1.3k
分支
305
平均合併
3 天 23 小時
30 天內合併 PR
44

環境準備

  • 沒有 Dockerfile 或 Docker Compose 檔案
  • 沒有 Pull Request 範本
  • 閱讀貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

temporalio/sdk-python 的其他 Issue

查看 temporalio/sdk-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。