holoviz/panel · #9073
fix: Keep pn.serve(threaded=True) working after the main thread finishes
panel/io/threads.py40 + / 0 −
@@ -1,7 +1,11 @@ import asyncio+# Imported for its side effect: the exit hook that disables thread pools must+# be registered before ours so that ours runs first+import concurrent.futures.thread # noqa: F401 import logging import threading import typing as t+import weakref from tornado.ioloop import IOLoop @@ -12,6 +16,37 @@ _SHUTDOWN_TIMEOUT = 5 +_exit_hook_registered = False+_started_threads: weakref.WeakSet['StoppableThread'] = weakref.WeakSet()+++def _join_threads_at_exit() -> None:+ while threads := [thread for thread in list(_started_threads) if thread.is_alive()]:+ for thread in threads:+ thread.join()+++def _register_exit_hook() -> None:+ """+ Keep thread pools usable for as long as a StoppableThread is serving.++ When the main thread finishes, Python first disables all thread pools+ and only then waits for the remaining threads, so a server that keeps+ running in a thread could no longer hand off any work. Waiting for the+ server threads in a hook that runs before the pools are disabled avoids+ that. Such hooks run in reverse order of registration.+ """+ global _exit_hook_registered+ if _exit_hook_registered:+ return+ try:+ threading._register_atexit(_join_threads_at_exit) # type: ignore[attr-defined]+ except (AttributeError, RuntimeError):+ # No such hook, or the interpreter is already shutting down+ return+ _exit_hook_registered = True++ class StoppableThread(threading.Thread): """Thread class with a stop() method.""" @@ -25,6 +60,11 @@ def __init__(self, io_loop, owns_loop: bool = False, **kwargs): self.server_id = kwargs.get('kwargs', {}).get('server_id') self._shutdown_task: t.Any | None = None + def start(self) -> None:+ _register_exit_hook()+ _started_threads.add(self)+ super().start()+ def run(self) -> None: if hasattr(self, '_target'): target, args, kwargs = self._target, self._args, self._kwargs # type: ignorepanel/tests/test_server.py33 + / 1 −
@@ -13,12 +13,14 @@ import time import weakref +from concurrent.futures import ThreadPoolExecutor from functools import partial import param import pytest import requests +from bokeh.client import pull_session from bokeh.events import ButtonClick from packaging.version import Version from tornado.ioloop import IOLoop@@ -43,7 +45,7 @@ from panel.tests import util as test_util from panel.tests.util import ( get_open_ports, reverse_proxy as reverse_proxy_ctx, serve_and_request,- serve_and_wait, unix_only, wait_until,+ serve_and_wait, unix_only, wait_for_server, wait_until, ) from panel.widgets import ( Button, Tabulator, Terminal, TextInput,@@ -2247,3 +2249,33 @@ def test_serve_show_opens_single_tab(num_procs): [sys.executable, "-c", script], capture_output=True, text=True, timeout=60 ).stdout assert out.count('SHOW') == 1+++def test_serve_threaded_after_main_thread_finishes():+ # https://github.com/holoviz/panel/issues/9044+ port = get_open_ports()[0]+ script = (+ "import panel as pn\n"+ f"pn.serve(lambda: pn.panel('x'), port={port}, show=False, threaded=True,\n"+ " liveness=True)\n"+ )+ process = subprocess.Popen([sys.executable, "-c", script])+ try:+ # The script's main thread finishes before the server responds+ wait_for_server(port, timeout=60)+ response = requests.get(f"http://127.0.0.1:{port}/", timeout=10)+ # Session replies are handed to a separate thread pool; a broken+ # pool leaves the client waiting forever, hence the timeout+ def pull_roots():+ with pull_session(url=f"http://127.0.0.1:{port}/") as session:+ return session.document.roots+ executor = ThreadPoolExecutor(max_workers=1)+ try:+ roots = executor.submit(pull_roots).result(timeout=30)+ finally:+ executor.shutdown(wait=False)+ finally:+ process.kill()+ process.wait()+ assert response.status_code == 200+ assert roots