:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(temporal): stop a worker from losing its shutdown signal (#109060)
Tom Owers57780db930a8
diff --git a/bin/temporal-django-worker b/bin/temporal-django-workerindex 820e36205b55..f2195c06d235 100755--- a/bin/temporal-django-worker+++ b/bin/temporal-django-worker@@ -2,11 +2,28 @@set -e+# The worker can lose a SIGTERM (for example when its asyncio signal pipe is full), and then it+# keeps polling for new work until the pod is killed. The worker handles a repeated SIGTERM as a+# no-op, so this sends it again until the worker exits.+SIGTERM_RESEND_INTERVAL_SECONDS="${TEMPORAL_WORKER_SIGTERM_RESEND_INTERVAL_SECONDS:-30}"+resender_pid=""++resend_sigterm_until_exit() {+ while kill -0 "$worker_pid" >/dev/null 2>&1; do+ sleep "$SIGTERM_RESEND_INTERVAL_SECONDS"+ kill -SIGTERM "$worker_pid" >/dev/null 2>&1 || true+ done+}+cleanup() {if kill -0 "$worker_pid" >/dev/null 2>&1; thenecho "Signaling worker to initialize graceful shutdown"kill -SIGTERM "$worker_pid"echo "Worker signaled for graceful shutdown"+ if [ -z "$resender_pid" ]; then+ resend_sigterm_until_exit &+ resender_pid=$!+ fielseecho "Could not initiate graceful shutdown as worker process is not running"fidiff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex caedc7aa57a1..d272f4374cd9 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -4,7 +4,6 @@ import signalimport typingimport asyncioimport datetime as dt-import functoolsimport threadingimport faulthandlerimport collections.abc@@ -51,6 +50,7 @@ from posthog.temporal.common.health_server import HealthCheckServerfrom posthog.temporal.common.interceptor import is_task_queue_supportedfrom posthog.temporal.common.liveness_tracker import LivenessInterceptor, get_liveness_trackerfrom posthog.temporal.common.logger import configure_logger, get_logger+from posthog.temporal.common.shutdown import ShutdownSignalListenerfrom posthog.temporal.common.worker import ManagedWorker, create_workerfrom posthog.temporal.data_modeling import (ACTIVITIES as DATA_MODELING_ACTIVITIES,@@ -941,13 +941,21 @@ class Command(BaseCommand):f"No healthcheck server due to health_port={health_port} and health_max_idle_seconds={health_max_idle_seconds}")- for sig in (signal.SIGTERM, signal.SIGINT):- loop.add_signal_handler(- sig,- functools.partial(shutdown_on_signal, worker=worker, health_srv=health_server, sig=sig, loop=loop),- )+ signal_listener = ShutdownSignalListener()+ signal_listener.install()++ async def run_until_worker_stops() -> None:+ async def shut_down_on_first_signal() -> None:+ sig = await signal_listener.wait()+ shutdown_on_signal(worker=worker, health_srv=health_server, sig=sig, loop=loop)++ signal_watcher = asyncio.create_task(shut_down_on_first_signal())+ try:+ await worker.run()+ finally:+ _ = signal_watcher.cancel()- runner.run(worker.run())+ runner.run(run_until_worker_stops())if shutdown_task:logger.info("Waiting on shutdown_task")diff --git a/posthog/temporal/common/shutdown.py b/posthog/temporal/common/shutdown.pyindex e169faafbc6b..bad0a5ffb5d5 100644--- a/posthog/temporal/common/shutdown.py+++ b/posthog/temporal/common/shutdown.py@@ -1,3 +1,4 @@+import signalimport typingimport asyncioimport threading@@ -208,3 +209,49 @@ class ShutdownMonitor:if self.is_worker_shutdown():self.logger.debug("Worker is shutting down.")raise WorkerShuttingDownError.from_activity_context()+++class ShutdownSignalListener:+ """Record SIGTERM and SIGINT for a worker to act on, without depending on asyncio's self-pipe.++ `loop.add_signal_handler` delivers a signal through a wakeup byte that the C signal handler+ writes to the loop's self-pipe. When that pipe is full, the write fails with `BlockingIOError`+ ("Exception ignored when trying to write to the signal wakeup fd"), the byte is lost, and the+ worker never starts to shut down. It then keeps polling for new work until the pod is killed.++ A Python-level handler from `signal.signal` runs in the main thread whether or not the byte+ reaches the pipe, so this listener records the signal there and `wait` polls for it.+ """++ def __init__(+ self,+ signals: tuple[signal.Signals, ...] = (signal.SIGTERM, signal.SIGINT),+ poll_interval_seconds: float = 1.0,+ ):+ self._signals = signals+ self._poll_interval_seconds = poll_interval_seconds+ self._received: signal.Signals | None = None+ self._received_event = threading.Event()++ def install(self) -> None:+ """Replace the handlers for the listened signals. Call it from the main thread."""+ for sig in self._signals:+ signal.signal(sig, self._handle)++ def _handle(self, signum: int, frame: object) -> None:+ # A later signal (for example the SIGTERM that the worker wrapper script sends again) keeps+ # the first one, so a shutdown starts only once.+ if self._received is None:+ self._received = signal.Signals(signum)+ self._received_event.set()++ @property+ def received(self) -> signal.Signals | None:+ return self._received++ async def wait(self) -> signal.Signals:+ """Return the first signal received, polling so that no wakeup byte is needed."""+ while not self._received_event.is_set():+ await asyncio.sleep(self._poll_interval_seconds)+ assert self._received is not None+ return self._receiveddiff --git a/posthog/temporal/tests/test_shutdown.py b/posthog/temporal/tests/test_shutdown.pyindex eac5a1758ebb..baaccbe79301 100644--- a/posthog/temporal/tests/test_shutdown.py+++ b/posthog/temporal/tests/test_shutdown.py@@ -1,5 +1,9 @@+import osimport uuid+import signal+import socketimport asyncio+import contextlibfrom concurrent.futures import ThreadPoolExecutorimport pytest@@ -10,6 +14,7 @@ from temporalio.common import RetryPolicyfrom temporalio.exceptions import ActivityError, ApplicationErrorfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker+from posthog.temporal.common.shutdown import ShutdownSignalListenerfrom posthog.temporal.tests.utils.workflow import Waiter, WaitInputs, WaitMode, WaitWorkflow@@ -171,3 +176,34 @@ async def test_shutdown_monitor_sync(temporal_client: Client, task_queue: str, werr.__cause__.__cause__.type == "WorkerShuttingDownError"or err.__cause__.__cause__.type == "WorkerShutdown")++[email protected]("wakeup_fd_full", [False, True])+async def test_shutdown_signal_listener_keeps_the_first_signal(wakeup_fd_full: bool):+ previous_handlers = {sig: signal.getsignal(sig) for sig in (signal.SIGTERM, signal.SIGINT)}+ read_sock, write_sock = socket.socketpair()+ write_sock.setblocking(False)+ previous_wakeup_fd = signal.set_wakeup_fd(write_sock.fileno()) if wakeup_fd_full else None+ try:+ if wakeup_fd_full:+ with contextlib.suppress(BlockingIOError):+ while True:+ write_sock.send(b"\0" * 4096)++ listener = ShutdownSignalListener(poll_interval_seconds=0.01)+ listener.install()++ os.kill(os.getpid(), signal.SIGTERM)+ assert await asyncio.wait_for(listener.wait(), timeout=5) == signal.SIGTERM++ os.kill(os.getpid(), signal.SIGINT)+ await asyncio.sleep(0.05)+ assert listener.received == signal.SIGTERM+ finally:+ if previous_wakeup_fd is not None:+ signal.set_wakeup_fd(previous_wakeup_fd)+ for sig, handler in previous_handlers.items():+ signal.signal(sig, handler)+ read_sock.close()+ write_sock.close()