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

オープン
#2,115 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

@tconley1428 がすでに取り組んでいます。

2026年11月12日 から。

  • #2118 @tconley1428 による — マージされずにクローズ

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
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時間
マージ済み PR(30日)
44

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

temporalio/sdk-python のほかの issue

temporalio/sdk-python の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。