Skip to content

Instantly share code, notes, and snippets.

@bojanz
Created August 18, 2026 21:51
Show Gist options
  • Select an option

  • Save bojanz/b014eba60c42561969c1ccb6d80b2126 to your computer and use it in GitHub Desktop.

Select an option

Save bojanz/b014eba60c42561969c1ccb6d80b2126 to your computer and use it in GitHub Desktop.
"""An exception in _WorkerGreenlet._before_run_task strands the caller forever.
ThreadPool worker threads run a task like this (gevent/threadpool.py)::
def __run_task(self, func, args, kwargs, thread_result):
self._before_run_task(func, args, kwargs, thread_result)
try:
thread_result.set(func(*args, **kwargs))
except:
thread_result.handle_error((self, func), self._exc_info())
finally:
self._after_run_task(func, args, kwargs, thread_result)
`_before_run_task` runs *outside* the try that resolves `thread_result`. It
calls `sys.setprofile()` and `sys.settrace()`, and those can raise: any PEP 578
audit hook that raises on the "sys.setprofile" event makes `sys.setprofile()`
raise, on every Python version. When that happens, `run()` logs "Failed to run
worker thread", marks the task done and exits -- with the ThreadResult never
set. Whoever called `apply()`/`spawn().get()` waits forever, and the pool
semaphore slot that `spawn()` acquired is never released (`semaphore.release`
is the ThreadResult's `_call_when_ready`). The semaphore has `maxsize + 1`
slots; once that many tasks have been stranded, `spawn()` itself blocks
forever for every caller, even after the trigger is gone.
This script injects the failure with exactly such an audit hook; no gevent
internals are replaced. Three demos:
1. bug: one task strands its caller (a 2s Timeout is wrapped around
`apply()` purely so the script terminates).
2. slot leak: strand `maxsize + 1` tasks, remove the trigger -- the idle
pool still hangs every subsequent `apply()`.
3. fix: with `__run_task` patched to resolve the ThreadResult when
`_before_run_task` raises, the caller gets the RuntimeError
and the pool stays usable.
The "Failed to run worker thread" tracebacks on stderr are expected: today
they are the only visible symptom.
"""
import sys
import gevent
from gevent.threadpool import ThreadPool, _WorkerGreenlet
FAIL = [False]
def audit_hook(event, args):
if event == "sys.setprofile" and FAIL[0]:
raise RuntimeError("sys.setprofile rejected by audit hook")
def try_apply(pool, seconds=2):
try:
with gevent.Timeout(seconds):
return "returned %r" % (pool.apply(len, ("x",)),)
except gevent.Timeout:
return "HUNG - %r" % (pool,)
except RuntimeError as exc:
return "raised at the call site: %s" % (exc,)
def fixed_run_task(self, func, args, kwargs, thread_result):
"""The suggested fix: always resolve the ThreadResult."""
try:
self._before_run_task(func, args, kwargs, thread_result)
except BaseException:
thread_result.handle_error((self, func), self._exc_info())
raise
try:
thread_result.set(func(*args, **kwargs))
except: # pylint:disable=bare-except
thread_result.handle_error((self, func), self._exc_info())
finally:
self._after_run_task(func, args, kwargs, thread_result)
del func, args, kwargs, thread_result
def main():
print("gevent", gevent.__version__, "on python", sys.version.split()[0])
sys.addaudithook(audit_hook)
# 1. The bug: a failing _before_run_task strands the caller.
pool = ThreadPool(10)
print("baseline:", try_apply(pool))
FAIL[0] = True
print("bug:", try_apply(pool))
FAIL[0] = False
# 2. The slot leak: strand maxsize + 1 tasks, then remove the trigger.
# The pool is idle, but every slot is gone: apply() hangs forever.
pool = ThreadPool(2)
FAIL[0] = True
for _ in range(3):
pool.spawn(len, ("x",))
while pool.task_queue.unfinished_tasks:
# Each failure kills its worker; keep respawning until every
# queued task has been taken and stranded.
pool.adjust()
gevent.sleep(0.01)
FAIL[0] = False
print("slot leak, trigger removed:", try_apply(pool))
# 3. The fix, applied from outside.
_WorkerGreenlet._WorkerGreenlet__run_task = fixed_run_task
pool = ThreadPool(10)
FAIL[0] = True
print("fixed:", try_apply(pool))
FAIL[0] = False
print("fixed pool still works:", try_apply(pool))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment