: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
feat(data-warehouse): exit a draining worker when only zombie activities remain (#112663)
Tom Owers2b5f974ed602
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex cdc489f547c4..fbdb6fc2dc32 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -52,6 +52,7 @@ from posthog.temporal.common.liveness_tracker import LivenessInterceptor, get_lifrom posthog.temporal.common.logger import configure_logger, get_loggerfrom posthog.temporal.common.shutdown import ShutdownSignalListenerfrom posthog.temporal.common.worker import ManagedWorker, create_worker+from posthog.temporal.common.zombie_exit import ZombieActivityExitfrom posthog.temporal.data_modeling import (ACTIVITIES as DATA_MODELING_ACTIVITIES,SEMANTIC_ENRICHMENT_ACTIVITIES,@@ -845,8 +846,21 @@ class Command(BaseCommand):if health_srv:await health_srv.stop()+ zombie_exit: ZombieActivityExit | None = None+ if settings.TEMPORAL_WORKER_ZOMBIE_EXIT_ENABLED:+ zombie_exit = ZombieActivityExit(+ tracker=get_liveness_tracker(),+ grace_seconds=settings.TEMPORAL_WORKER_ZOMBIE_EXIT_GRACE_SECONDS,+ task_queue=task_queue,+ )+ zombie_exit.start()+# Then shutdown the worker- await worker.shutdown()+ try:+ await worker.shutdown()+ finally:+ if zombie_exit is not None:+ zombie_exit.stop()def shutdown_on_signal(worker: ManagedWorker,@@ -879,6 +893,8 @@ class Command(BaseCommand):health_port=health_port,health_max_idle_seconds=health_max_idle_seconds,combined_metrics_server_enabled=not disable_combined_metrics_server,+ zombie_exit_enabled=settings.TEMPORAL_WORKER_ZOMBIE_EXIT_ENABLED,+ zombie_exit_grace_seconds=settings.TEMPORAL_WORKER_ZOMBIE_EXIT_GRACE_SECONDS,)logger.info("Starting Temporal Worker")diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex bc03f6a2ffce..fdff492a7ab8 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -23,6 +23,15 @@ TEMPORAL_FALLBACK_SECRET_KEYS: list[str] = get_list(os.getenv("TEMPORAL_FALLBACKGRACEFUL_SHUTDOWN_TIMEOUT_SECONDS: int | None = get_from_env("GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS", None, optional=True, type_cast=int)+# After SIGTERM plus the grace, the worker exits when every activity that still runs is one the+# Temporal server already closed (timed out, and retried on another worker if attempts remain).+# Off by default: without it, such an activity holds the worker for the full graceful shutdown timeout.+TEMPORAL_WORKER_ZOMBIE_EXIT_ENABLED: bool = get_from_env(+ "TEMPORAL_WORKER_ZOMBIE_EXIT_ENABLED", False, type_cast=str_to_bool+)+TEMPORAL_WORKER_ZOMBIE_EXIT_GRACE_SECONDS: float = get_from_env(+ "TEMPORAL_WORKER_ZOMBIE_EXIT_GRACE_SECONDS", 180.0, type_cast=float+)MAX_CONCURRENT_WORKFLOW_TASKS: int | None = get_from_env("MAX_CONCURRENT_WORKFLOW_TASKS", None, optional=True, type_cast=int)diff --git a/posthog/temporal/common/liveness_tracker.py b/posthog/temporal/common/liveness_tracker.pyindex f33f5ef0f942..ecf804812cda 100644--- a/posthog/temporal/common/liveness_tracker.py+++ b/posthog/temporal/common/liveness_tracker.py@@ -1,10 +1,15 @@import time+import datetime as dtimport threading+import contextvars+import dataclasses+from collections.abc import Callablefrom typing import Anyfrom temporalio import activityfrom temporalio.worker import (ActivityInboundInterceptor,+ ActivityOutboundInterceptor,ExecuteActivityInput,ExecuteWorkflowInput,Interceptor,@@ -23,6 +28,19 @@ class RunningActivity:workflow_id: str | Noneattempt: intstarted_at: float+ is_local: bool = False+ # Server clock, as Unix seconds. The server measures `start_to_close_timeout` from+ # `server_started_at` and `schedule_to_close_timeout` from `scheduled_at`.+ server_started_at: float | None = None+ scheduled_at: float | None = None+ start_to_close_timeout: float | None = None+ schedule_to_close_timeout: float | None = None+ heartbeat_timeout: float | None = None+ last_heartbeat_at: float | None = None+ # The longest time this attempt went without a heartbeat. It stays set when heartbeats start+ # again, because the server does not reopen an attempt that it timed out.+ max_heartbeat_gap: float = 0.0+ cancellation_details: Callable[[], activity.ActivityCancellationDetails | None] | None = Noneclass LivenessTracker:@@ -37,6 +55,7 @@ class LivenessTracker:self._last_workflow_time: float = time.time()self._running_activities: dict[int, RunningActivity] = {}self._next_activity_key = 0+ self._last_activity_end_time: float | None = Noneself._lock = threading.Lock()def record_activity_start(self, activity: RunningActivity) -> int:@@ -51,6 +70,26 @@ class LivenessTracker:def record_activity_end(self, key: int) -> None:with self._lock:self._running_activities.pop(key, None)+ self._last_activity_end_time = time.time()++ def record_activity_heartbeat(self, key: int) -> None:+ now = time.time()+ with self._lock:+ running = self._running_activities.get(key)+ if running is None:+ return+ gap = now - (running.last_heartbeat_at or running.started_at)+ self._running_activities[key] = dataclasses.replace(+ running,+ last_heartbeat_at=now,+ max_heartbeat_gap=max(running.max_heartbeat_gap, gap),+ )++ def get_last_activity_end_time(self) -> float | None:+ """Return when an activity last handed its result to the SDK, or `None` if none did."""++ with self._lock:+ return self._last_activity_end_timedef get_running_activities(self) -> list[RunningActivity]:with self._lock:@@ -112,15 +151,37 @@ def get_liveness_tracker() -> LivenessTracker:return _tracker+def _total_seconds(timeout: dt.timedelta | None) -> float | None:+ return timeout.total_seconds() if timeout is not None else None+++class _LivenessActivityOutboundInterceptor(ActivityOutboundInterceptor):+ def __init__(self, next: ActivityOutboundInterceptor, on_heartbeat: Callable[[], None]):+ super().__init__(next)+ self._on_heartbeat = on_heartbeat++ def heartbeat(self, *details: Any) -> None:+ super().heartbeat(*details)+ self._on_heartbeat()++class _LivenessActivityInboundInterceptor(ActivityInboundInterceptor):_tracker: LivenessTrackerdef __init__(self, next: ActivityInboundInterceptor):super().__init__(next)self._tracker = get_liveness_tracker()+ self._key: int | None = None++ def init(self, outbound: ActivityOutboundInterceptor) -> None:+ super().init(_LivenessActivityOutboundInterceptor(outbound, self._record_heartbeat))++ def _record_heartbeat(self) -> None:+ if self._key is not None:+ self._tracker.record_activity_heartbeat(self._key)async def execute_activity(self, input: ExecuteActivityInput) -> Any:- key = self._record_start() if activity.in_activity() else None+ key = self._key = self._record_start() if activity.in_activity() else Nonetry:result = await super().execute_activity(input)self._tracker.record_activity_execution()@@ -135,6 +196,9 @@ class _LivenessActivityInboundInterceptor(ActivityInboundInterceptor):def _record_start(self) -> int:info = activity.info()+ # The shutdown path reads the cancellation details from a thread that has no activity+ # context, so it needs a copy of this context to run `activity.cancellation_details` in.+ context = contextvars.copy_context()return self._tracker.record_activity_start(RunningActivity(activity_type=info.activity_type,@@ -142,6 +206,13 @@ class _LivenessActivityInboundInterceptor(ActivityInboundInterceptor):workflow_id=info.workflow_id,attempt=info.attempt,started_at=time.time(),+ is_local=info.is_local,+ server_started_at=info.started_time.timestamp(),+ scheduled_at=info.scheduled_time.timestamp(),+ start_to_close_timeout=_total_seconds(info.start_to_close_timeout),+ schedule_to_close_timeout=_total_seconds(info.schedule_to_close_timeout),+ heartbeat_timeout=_total_seconds(info.heartbeat_timeout),+ cancellation_details=lambda: context.run(activity.cancellation_details),))diff --git a/posthog/temporal/common/zombie_exit.py b/posthog/temporal/common/zombie_exit.pynew file mode 100644index 000000000000..a63713502342--- /dev/null+++ b/posthog/temporal/common/zombie_exit.py@@ -0,0 +1,193 @@+import os+import sys+import time+import threading+from collections.abc import Callable++from prometheus_client import Counter++from posthog.dataclasses import frozen+from posthog.temporal.common.liveness_tracker import LivenessTracker, RunningActivity+from posthog.temporal.common.logger import get_logger++LOGGER = get_logger(__name__)++# Added to each server deadline before the worker treats it as passed. It covers the clock+# difference between the worker and the server, the delay of the server timeout timer, and the+# time the SDK holds a heartbeat back before it sends it (`max_heartbeat_throttle_interval`).+DEADLINE_MARGIN_SECONDS = 60.0++# An activity that returned still has its result on the way to the server. The worker does not+# exit until this long after the last activity returned, so that result is not lost.+RESULT_FLUSH_SECONDS = 30.0++POLL_INTERVAL_SECONDS = 5.0++# Prometheus pulls the counter, so the process stays up for a short time to give a scrape a+# chance. The log lines are the complete record if no scrape comes in time.+METRICS_SCRAPE_WAIT_SECONDS = 15.0++ABANDONED_ACTIVITIES_COUNTER = Counter(+ "temporal_worker_shutdown_abandoned_activities_total",+ "Activities a worker abandoned at shutdown because the Temporal server had already closed them.",+ labelnames=["task_queue", "activity_type", "reason"],+)+++@frozen+class ZombieActivity:+ activity: RunningActivity+ reason: str+ timeout_seconds: float | None+ seconds_past_deadline: float | None+++def classify_zombie(+ running: RunningActivity, now: float, margin: float = DEADLINE_MARGIN_SECONDS+) -> ZombieActivity | None:+ """Return why the server no longer accepts a result from this activity, or `None` if it can."""++ # The server does not track a local activity, so the worker has no deadline to compare.+ if running.is_local:+ return None++ details = running.cancellation_details() if running.cancellation_details is not None else None+ if details is not None and (details.not_found or details.timed_out):+ return ZombieActivity(+ activity=running,+ reason="timed_out" if details.timed_out else "not_found",+ timeout_seconds=None,+ seconds_past_deadline=None,+ )++ if running.start_to_close_timeout is not None and running.server_started_at is not None:+ past = now - (running.server_started_at + running.start_to_close_timeout)+ if past > margin:+ return ZombieActivity(+ activity=running,+ reason="start_to_close_timeout",+ timeout_seconds=running.start_to_close_timeout,+ seconds_past_deadline=past,+ )++ if running.schedule_to_close_timeout is not None and running.scheduled_at is not None:+ past = now - (running.scheduled_at + running.schedule_to_close_timeout)+ if past > margin:+ return ZombieActivity(+ activity=running,+ reason="schedule_to_close_timeout",+ timeout_seconds=running.schedule_to_close_timeout,+ seconds_past_deadline=past,+ )++ if running.heartbeat_timeout is not None:+ current_gap = now - (running.last_heartbeat_at or running.started_at)+ past = max(current_gap, running.max_heartbeat_gap) - running.heartbeat_timeout+ if past > margin:+ return ZombieActivity(+ activity=running,+ reason="heartbeat_timeout",+ timeout_seconds=running.heartbeat_timeout,+ seconds_past_deadline=past,+ )++ return None+++class ZombieActivityExit:+ """Exits a worker that is shutting down when only zombie activities hold it.++ A zombie activity is one the Temporal server already closed: it timed the attempt out, and it+ retries the attempt on another worker if attempts remain. The thread of such an activity can+ stay blocked in a call that never returns, and `Worker.shutdown()` waits for it until the+ graceful shutdown timeout ends. That thread can no longer report a result, so the wait has no+ use.++ The check runs on its own thread, so it also works when the event loop is blocked.+ """++ def __init__(+ self,+ tracker: LivenessTracker,+ grace_seconds: float,+ task_queue: str,+ exit_process: Callable[[int], None] = os._exit,+ clock: Callable[[], float] = time.time,+ wait: Callable[[float], bool] | None = None,+ ) -> None:+ self._tracker = tracker+ self._grace_seconds = grace_seconds+ self._task_queue = task_queue+ self._exit_process = exit_process+ self._clock = clock+ self._stopped = threading.Event()+ self._wait = wait if wait is not None else self._stopped.wait+ self._logger = LOGGER.bind(task_queue=task_queue)++ def start(self) -> None:+ thread = threading.Thread(target=self.run, name="zombie-activity-exit", daemon=True)+ thread.start()++ def stop(self) -> None:+ self._stopped.set()++ def find_zombies_if_only_zombies_remain(self) -> list[ZombieActivity] | None:+ """Return the zombie activities when the worker can exit now, else `None`."""++ now = self._clock()+ running = self._tracker.get_running_activities()+ # With no activity left, `Worker.shutdown()` returns without help.+ if not running:+ return None++ last_end = self._tracker.get_last_activity_end_time()+ if last_end is not None and now - last_end < RESULT_FLUSH_SECONDS:+ return None++ zombies: list[ZombieActivity] = []+ for activity in running:+ zombie = classify_zombie(activity, now)+ if zombie is None:+ return None+ zombies.append(zombie)+ return zombies++ def run(self) -> None:+ if self._wait(self._grace_seconds):+ return++ while True:+ zombies = self.find_zombies_if_only_zombies_remain()+ if zombies is not None:+ self._abandon(zombies)+ return+ if self._wait(POLL_INTERVAL_SECONDS):+ return++ def _abandon(self, zombies: list[ZombieActivity]) -> None:+ now = self._clock()+ self._logger.warning("Exiting worker because only zombie activities remain", count=len(zombies))+ for zombie in zombies:+ running = zombie.activity+ self._logger.warning(+ "Zombie activity abandoned at shutdown",+ activity_type=running.activity_type,+ workflow_type=running.workflow_type,+ workflow_id=running.workflow_id,+ attempt=running.attempt,+ running_seconds=round(now - running.started_at),+ reason=zombie.reason,+ timeout_seconds=zombie.timeout_seconds,+ seconds_past_deadline=(+ round(zombie.seconds_past_deadline) if zombie.seconds_past_deadline is not None else None+ ),+ )+ ABANDONED_ACTIVITIES_COUNTER.labels(+ task_queue=self._task_queue, activity_type=running.activity_type, reason=zombie.reason+ ).inc()++ if self._wait(METRICS_SCRAPE_WAIT_SECONDS):+ return+ sys.stdout.flush()+ sys.stderr.flush()+ self._exit_process(0)diff --git a/posthog/temporal/tests/common/test_liveness_tracker.py b/posthog/temporal/tests/common/test_liveness_tracker.pyindex 4144594da7c3..49c4508f0bef 100644--- a/posthog/temporal/tests/common/test_liveness_tracker.py+++ b/posthog/temporal/tests/common/test_liveness_tracker.py@@ -1,6 +1,8 @@import time+import datetime as dtimport pytest+import time_machinefrom unittest.mock import AsyncMock, MagicMock, patchfrom django.conf import settings@@ -262,6 +264,36 @@ class TestLivenessActivityInboundInterceptor:)assert tracker.get_running_activities() == []+ async def test_records_each_heartbeat_of_the_running_activity(self):+ tracker = LivenessTracker()+ heartbeats_seen: list[tuple[float | None, float]] = []+ outbound = MagicMock()+ next_interceptor = AsyncMock()+ next_interceptor.init = MagicMock(side_effect=lambda wrapped: setattr(next_interceptor, "outbound", wrapped))++ async def execute(_input):+ with time_machine.travel(dt.datetime(2026, 1, 1, 0, 5, tzinfo=dt.UTC), tick=False):+ next_interceptor.outbound.heartbeat("details")+ [running] = tracker.get_running_activities()+ heartbeats_seen.append((running.last_heartbeat_at, running.max_heartbeat_gap))++ next_interceptor.execute_activity.side_effect = execute+ interceptor = _LivenessActivityInboundInterceptor(next_interceptor)+ interceptor._tracker = tracker+ interceptor.init(outbound)++ info = MagicMock(activity_type="cdc_extract_activity", workflow_type="cdc-extraction", is_local=False)+ info.heartbeat_timeout = dt.timedelta(minutes=10)+ with (+ time_machine.travel(dt.datetime(2026, 1, 1, tzinfo=dt.UTC), tick=False),+ patch("posthog.temporal.common.liveness_tracker.activity.in_activity", return_value=True),+ patch("posthog.temporal.common.liveness_tracker.activity.info", return_value=info),+ ):+ await interceptor.execute_activity(MagicMock(spec=ExecuteActivityInput))++ outbound.heartbeat.assert_called_once_with("details")+ assert heartbeats_seen == [(dt.datetime(2026, 1, 1, 0, 5, tzinfo=dt.UTC).timestamp(), 300.0)]+@pytest.mark.asyncioclass TestLivenessWorkflowInterceptor:diff --git a/posthog/temporal/tests/common/test_zombie_exit.py b/posthog/temporal/tests/common/test_zombie_exit.pynew file mode 100644index 000000000000..27b67cc4ea33--- /dev/null+++ b/posthog/temporal/tests/common/test_zombie_exit.py@@ -0,0 +1,177 @@+import pytest++from temporalio.activity import ActivityCancellationDetails++from posthog.temporal.common.liveness_tracker import LivenessTracker, RunningActivity+from posthog.temporal.common.zombie_exit import (+ DEADLINE_MARGIN_SECONDS,+ RESULT_FLUSH_SECONDS,+ ZombieActivityExit,+ classify_zombie,+)++NOW = 1_000_000.0+GRACE = 180.0+++def _activity(activity_type: str = "sync_new_schemas_activity", age: float = 3600.0, **overrides) -> RunningActivity:+ fields: dict = {+ "activity_type": activity_type,+ "workflow_type": "some-workflow",+ "workflow_id": "wf-1",+ "attempt": 1,+ "started_at": NOW - age,+ "server_started_at": NOW - age,+ "scheduled_at": NOW - age,+ }+ return RunningActivity(**(fields | overrides))+++def _past_start_to_close(**overrides) -> RunningActivity:+ return _activity(start_to_close_timeout=600.0, **overrides)+++def _live(**overrides) -> RunningActivity:+ fields: dict = {+ "activity_type": "import_data_activity_sync",+ "start_to_close_timeout": 86_400.0,+ "heartbeat_timeout": 120.0,+ "last_heartbeat_at": NOW - 4.0,+ "max_heartbeat_gap": 5.0,+ }+ return _activity(**(fields | overrides))+++ "running,expected_reason",+ [+ (_past_start_to_close(), "start_to_close_timeout"),+ (_activity(start_to_close_timeout=3600.0 - DEADLINE_MARGIN_SECONDS + 1), None),+ (+ _activity(age=600.0, start_to_close_timeout=3600.0, schedule_to_close_timeout=300.0),+ "schedule_to_close_timeout",+ ),+ (_activity(start_to_close_timeout=86_400.0, heartbeat_timeout=120.0), "heartbeat_timeout"),+ (+ _activity(start_to_close_timeout=86_400.0, heartbeat_timeout=120.0, last_heartbeat_at=NOW - 500.0),+ "heartbeat_timeout",+ ),+ (+ _activity(+ start_to_close_timeout=86_400.0,+ heartbeat_timeout=120.0,+ last_heartbeat_at=NOW - 120.0 - DEADLINE_MARGIN_SECONDS + 1,+ ),+ None,+ ),+ # Heartbeats that start again do not reopen an attempt the server timed out.+ (+ _activity(+ start_to_close_timeout=86_400.0,+ heartbeat_timeout=120.0,+ last_heartbeat_at=NOW - 1.0,+ max_heartbeat_gap=900.0,+ ),+ "heartbeat_timeout",+ ),+ (_live(), None),+ (_activity(), None),+ (_past_start_to_close(is_local=True), None),+ (_live(cancellation_details=lambda: ActivityCancellationDetails(not_found=True)), "not_found"),+ (_live(cancellation_details=lambda: ActivityCancellationDetails(timed_out=True)), "timed_out"),+ (_live(cancellation_details=lambda: ActivityCancellationDetails(cancel_requested=True)), None),+ (_live(cancellation_details=lambda: ActivityCancellationDetails(worker_shutdown=True)), None),+ (_live(cancellation_details=lambda: None), None),+ ],+)+def test_classify_zombie(running: RunningActivity, expected_reason: str | None) -> None:+ zombie = classify_zombie(running, NOW)++ assert (zombie.reason if zombie else None) == expected_reason+++class _FakeTime:+ def __init__(self, max_waits: int = 50) -> None:+ self.now = NOW+ self.max_waits = max_waits+ self.waits: list[float] = []++ def clock(self) -> float:+ return self.now++ def wait(self, seconds: float) -> bool:+ self.waits.append(seconds)+ self.now += seconds+ return len(self.waits) >= self.max_waits+++def _run(tracker: LivenessTracker, fake_time: _FakeTime) -> list[int]:+ exit_codes: list[int] = []+ ZombieActivityExit(+ tracker=tracker,+ grace_seconds=GRACE,+ task_queue="test-task-queue",+ exit_process=exit_codes.append,+ clock=fake_time.clock,+ wait=fake_time.wait,+ ).run()+ return exit_codes+++ "running,expected_exit_codes",+ [+ ([_past_start_to_close()], [0]),+ ([_past_start_to_close(), _activity(start_to_close_timeout=86_400.0, heartbeat_timeout=120.0)], [0]),+ ([_live(start_to_close_timeout=10 * 86_400.0, heartbeat_timeout=None)], []),+ ([_past_start_to_close(), _live(start_to_close_timeout=10 * 86_400.0, heartbeat_timeout=None)], []),+ ([], []),+ ],+ ids=["zombie_only", "zombies_of_two_kinds", "live_only", "zombie_and_live", "nothing_running"],+)+def test_exits_only_when_every_running_activity_is_a_zombie(+ running: list[RunningActivity], expected_exit_codes: list[int]+) -> None:+ tracker = LivenessTracker()+ for activity in running:+ tracker.record_activity_start(activity)+ fake_time = _FakeTime()++ assert _run(tracker, fake_time) == expected_exit_codes+ assert fake_time.waits[0] == GRACE+++def test_exits_once_the_last_live_activity_returns_and_its_result_had_time_to_flush() -> None:+ tracker = LivenessTracker()+ tracker.record_activity_start(_past_start_to_close())+ live_key = tracker.record_activity_start(_live(start_to_close_timeout=10 * 86_400.0, heartbeat_timeout=None))+ fake_time = _FakeTime()+ exit_times: list[float] = []+ live_ended_at: list[float] = []++ def wait(seconds: float) -> bool:+ stop = fake_time.wait(seconds)+ if len(fake_time.waits) == 4:+ tracker.record_activity_end(live_key)+ tracker._last_activity_end_time = fake_time.now+ live_ended_at.append(fake_time.now)+ return stop++ ZombieActivityExit(+ tracker=tracker,+ grace_seconds=GRACE,+ task_queue="test-task-queue",+ exit_process=lambda _code: exit_times.append(fake_time.now),+ clock=fake_time.clock,+ wait=wait,+ ).run()++ assert len(exit_times) == 1+ assert exit_times[0] - live_ended_at[0] >= RESULT_FLUSH_SECONDS+++def test_does_not_exit_when_the_worker_stops_during_the_grace() -> None:+ tracker = LivenessTracker()+ tracker.record_activity_start(_past_start_to_close())++ assert _run(tracker, _FakeTime(max_waits=1)) == []