Skip to content

: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.

feat(data-warehouse): log what holds a worker at shutdown (#109009)

Tom Owers7796dc8ca312
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 79c907fc3aa0..caedc7aa57a1 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -1,4 +1,5 @@
import os
+import time
import signal
import typing
import asyncio
@@ -815,6 +816,21 @@ class Command(BaseCommand):
logger.info("Initiating shutdown")
+ # Each activity that runs now holds this pod until it returns or the graceful shutdown
+ # timeout ends, so this list shows what a slow shutdown waits on.
+ running_activities = get_liveness_tracker().get_running_activities()
+ now = time.time()
+ logger.info("Activities running at shutdown", count=len(running_activities))
+ for running in running_activities:
+ logger.info(
+ "Activity running 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),
+ )
+
# Shutdown health server first so k8s stops sending traffic
if health_srv:
await health_srv.stop()
diff --git a/posthog/temporal/common/liveness_tracker.py b/posthog/temporal/common/liveness_tracker.py
index ece94fdfd82c..f33f5ef0f942 100644
--- a/posthog/temporal/common/liveness_tracker.py
+++ b/posthog/temporal/common/liveness_tracker.py
@@ -2,6 +2,7 @@ import time
import threading
from typing import Any
+from temporalio import activity
from temporalio.worker import (
ActivityInboundInterceptor,
ExecuteActivityInput,
@@ -11,9 +12,19 @@ from temporalio.worker import (
WorkflowInterceptorClassInput,
)
+from posthog.dataclasses import frozen
from posthog.temporal.common.interceptor import ALL_TASK_QUEUES
+@frozen
+class RunningActivity:
+ activity_type: str
+ workflow_type: str | None
+ workflow_id: str | None
+ attempt: int
+ started_at: float
+
+
class LivenessTracker:
"""Tracks the last time the worker successfully executed a workflow or activity.
@@ -24,8 +35,27 @@ class LivenessTracker:
def __init__(self):
self._last_activity_time: float = time.time()
self._last_workflow_time: float = time.time()
+ self._running_activities: dict[int, RunningActivity] = {}
+ self._next_activity_key = 0
self._lock = threading.Lock()
+ def record_activity_start(self, activity: RunningActivity) -> int:
+ """Register a running activity and return the key that `record_activity_end` takes."""
+
+ with self._lock:
+ key = self._next_activity_key
+ self._next_activity_key += 1
+ self._running_activities[key] = activity
+ return key
+
+ def record_activity_end(self, key: int) -> None:
+ with self._lock:
+ self._running_activities.pop(key, None)
+
+ def get_running_activities(self) -> list[RunningActivity]:
+ with self._lock:
+ return list(self._running_activities.values())
+
def record_activity_execution(self) -> None:
"""Record that an activity was executed."""
@@ -90,6 +120,7 @@ class _LivenessActivityInboundInterceptor(ActivityInboundInterceptor):
self._tracker = get_liveness_tracker()
async def execute_activity(self, input: ExecuteActivityInput) -> Any:
+ key = self._record_start() if activity.in_activity() else None
try:
result = await super().execute_activity(input)
self._tracker.record_activity_execution()
@@ -98,6 +129,21 @@ class _LivenessActivityInboundInterceptor(ActivityInboundInterceptor):
except Exception:
self._tracker.record_activity_execution()
raise
+ finally:
+ if key is not None:
+ self._tracker.record_activity_end(key)
+
+ def _record_start(self) -> int:
+ info = activity.info()
+ return self._tracker.record_activity_start(
+ RunningActivity(
+ activity_type=info.activity_type,
+ workflow_type=info.workflow_type,
+ workflow_id=info.workflow_id,
+ attempt=info.attempt,
+ started_at=time.time(),
+ )
+ )
class _LivenessWorkflowInterceptor(WorkflowInboundInterceptor):
diff --git a/posthog/temporal/common/shutdown.py b/posthog/temporal/common/shutdown.py
index 8b22636ea8f6..e169faafbc6b 100644
--- a/posthog/temporal/common/shutdown.py
+++ b/posthog/temporal/common/shutdown.py
@@ -2,6 +2,7 @@ import typing
import asyncio
import threading
import contextvars
+from collections.abc import Callable
from structlog import get_logger
from temporalio import activity
@@ -61,6 +62,7 @@ class ShutdownMonitor:
def __init__(self):
self._monitor_shutdown_task: asyncio.Task[None] | None = None
self._monitor_shutdown_thread: threading.Thread | None = None
+ self._on_shutdown_callbacks: list[tuple[contextvars.Context, Callable[[], None]]] = []
self._is_shutdown_event = asyncio.Event()
self._is_shutdown_event_sync = threading.Event()
self._stop_event_sync = threading.Event()
@@ -105,10 +107,27 @@ class ShutdownMonitor:
# Not running in an activity context.
return
+ self.logger.info("Shutdown detected.")
+ # Run the callbacks before the event is set: a caller that sees the event can raise and
+ # leave the monitor at once, and a callback that ran after that would never run at all.
+ for context, callback in self._on_shutdown_callbacks:
+ try:
+ context.run(callback)
+ except Exception:
+ self.logger.exception("A shutdown callback failed.")
self._is_shutdown_event.set()
self._monitor_shutdown_task = asyncio.create_task(monitor())
+ def run_on_shutdown(self, callback: Callable[[], None]) -> None:
+ """Call `callback` once when the worker starts to shut down.
+
+ `callback` runs with a copy of the caller's contextvars, taken now, so it sees the structlog
+ context the caller has bound (for example the job context an activity binds after it enters
+ the monitor). Only the async monitor calls it, so register it inside `async with ShutdownMonitor()`.
+ """
+ self._on_shutdown_callbacks.append((contextvars.copy_context(), callback))
+
def start_sync(self):
"""Start a `threading.Thread` to monitor for worker shutdown.
diff --git a/posthog/temporal/tests/common/test_liveness_tracker.py b/posthog/temporal/tests/common/test_liveness_tracker.py
index 3d492d2cbe55..4144594da7c3 100644
--- a/posthog/temporal/tests/common/test_liveness_tracker.py
+++ b/posthog/temporal/tests/common/test_liveness_tracker.py
@@ -1,7 +1,7 @@
import time
import pytest
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, patch
from django.conf import settings
@@ -11,6 +11,7 @@ from posthog.temporal.common.interceptor import is_task_queue_supported
from posthog.temporal.common.liveness_tracker import (
LivenessInterceptor,
LivenessTracker,
+ RunningActivity,
_LivenessActivityInboundInterceptor,
_LivenessWorkflowInterceptor,
get_liveness_tracker,
@@ -223,6 +224,44 @@ class TestLivenessActivityInboundInterceptor:
# Should still have recorded execution
assert tracker.get_idle_time() < 1.0
+ @pytest.mark.parametrize("fails", [False, True])
+ async def test_lists_activity_only_while_it_runs(self, fails):
+ tracker = LivenessTracker()
+ seen_while_running: list[list[RunningActivity]] = []
+
+ async def execute(_input):
+ seen_while_running.append(tracker.get_running_activities())
+ if fails:
+ raise ValueError("test error")
+ return "result"
+
+ next_interceptor = AsyncMock()
+ next_interceptor.execute_activity.side_effect = execute
+ interceptor = _LivenessActivityInboundInterceptor(next_interceptor)
+ interceptor._tracker = tracker
+
+ info = MagicMock(activity_type="import_data_activity_sync", workflow_type="external-data-job")
+ info.workflow_id = "wf-1"
+ info.attempt = 3
+ with (
+ patch("posthog.temporal.common.liveness_tracker.activity.in_activity", return_value=True),
+ patch("posthog.temporal.common.liveness_tracker.activity.info", return_value=info),
+ ):
+ if fails:
+ with pytest.raises(ValueError):
+ await interceptor.execute_activity(MagicMock(spec=ExecuteActivityInput))
+ else:
+ await interceptor.execute_activity(MagicMock(spec=ExecuteActivityInput))
+
+ [running] = seen_while_running[0]
+ assert (running.activity_type, running.workflow_type, running.workflow_id, running.attempt) == (
+ "import_data_activity_sync",
+ "external-data-job",
+ "wf-1",
+ 3,
+ )
+ assert tracker.get_running_activities() == []
+
@pytest.mark.asyncio
class TestLivenessWorkflowInterceptor:
diff --git a/posthog/temporal/tests/test_shutdown.py b/posthog/temporal/tests/test_shutdown.py
index cfa2f2f3a3cc..eac5a1758ebb 100644
--- a/posthog/temporal/tests/test_shutdown.py
+++ b/posthog/temporal/tests/test_shutdown.py
@@ -57,6 +57,7 @@ async def test_shutdown_monitor_async(temporal_client: Client):
# longer than a few seconds on loaded CI runners.
_ = await asyncio.wait([wait_for_shutdown_task], timeout=15)
assert waiter.shutdown_monitor.is_worker_shutdown()
+ assert waiter.shutdown_callback_ran.is_set()
_ = await asyncio.wait([shutdown_task, worker_run_task], timeout=5)
# Need to start a new worker to pick-up the workflow again and set the failure.
diff --git a/posthog/temporal/tests/utils/workflow.py b/posthog/temporal/tests/utils/workflow.py
index 2c67c1722bb8..d4c348e531eb 100644
--- a/posthog/temporal/tests/utils/workflow.py
+++ b/posthog/temporal/tests/utils/workflow.py
@@ -43,6 +43,10 @@ class Waiter:
self.heartbeater: Heartbeater | None = None
self.heartbeater_sync: HeartbeaterSync | None = None
self.shutdown_monitor: ShutdownMonitor | None = None
+ self.shutdown_callback_ran = threading.Event()
+
+ def _on_shutdown(self) -> None:
+ self.shutdown_callback_ran.set()
@activity.defn
async def wait_for_activity(self, inputs: WaitInputsActivity) -> None:
@@ -57,6 +61,7 @@ class Waiter:
await asyncio.sleep(0)
async with self.heartbeater, self.shutdown_monitor:
+ self.shutdown_monitor.run_on_shutdown(self._on_shutdown)
while True:
elapsed = loop.time() - start
diff --git a/products/warehouse_sources/backend/temporal/data_imports/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
index 2c98048b8cb0..6e32e725036b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
@@ -2,7 +2,7 @@ import logging
import datetime as dt
from typing import TYPE_CHECKING
-from temporalio import workflow
+from temporalio import activity, workflow
from temporalio.common import MetricCounter
from posthog.kafka_client.routing import get_producer
@@ -74,6 +74,19 @@ def get_version_check_skipped_metric() -> MetricCounter:
)
+def get_worker_shutdown_handoff_metric(source_type: str | None) -> MetricCounter:
+ # Counts imports that gave up a shutting-down worker so another pod can continue them. An
+ # import that never hands off keeps its pod alive for the whole graceful shutdown timeout.
+ return (
+ activity.metric_meter()
+ .with_additional_attributes({"source_type": source_type or "unknown"})
+ .create_counter(
+ "warehouse_worker_shutdown_handoff_total",
+ "Imports that raised WorkerShuttingDownError so another worker could continue them.",
+ )
+ )
+
+
def emit_data_import_app_metrics(job: "ExternalDataJob") -> None:
"""Emit app_metrics2 rows for a data import job that just reached terminal state.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index 57553f49c067..cb589326d6e3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -2,6 +2,7 @@ import uuid
import socket
import asyncio
import datetime as dt
+import functools
import dataclasses
from typing import TYPE_CHECKING, Any, NoReturn, Optional
@@ -25,7 +26,7 @@ from posthog.temporal.common.activity_context import current_activity_attempt
from posthog.temporal.common.errors import NonReportableError
from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
from posthog.temporal.common.logger import get_logger
-from posthog.temporal.common.shutdown import ShutdownMonitor
+from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownError
from posthog.temporal.common.utils import is_stale_connection_read_only_error
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
@@ -37,7 +38,10 @@ from products.warehouse_sources.backend.models.external_data_schema import (
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
-from products.warehouse_sources.backend.temporal.data_imports.metrics import TERMINAL_JOB_STATUSES
+from products.warehouse_sources.backend.temporal.data_imports.metrics import (
+ TERMINAL_JOB_STATUSES,
+ get_worker_shutdown_handoff_metric,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
handle_non_retryable_error,
report_heartbeat_timeout,
@@ -421,6 +425,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
sync_type=model.schema.sync_type if model.schema is not None else None,
pipeline_version=model.pipeline_version,
)
+ shutdown_monitor.run_on_shutdown(functools.partial(_log_worker_shutdown_during_import, logger))
job_inputs = PipelineInputs(
source_id=inputs.source_id,
@@ -706,6 +711,18 @@ POSTHOG_DATABASE_UNAVAILABLE_MESSAGE = (
)
+def _log_worker_shutdown_during_import(logger: FilteringBoundLogger) -> None:
+ # One line per import still running when the worker got SIGTERM. A matching hand-off line from
+ # _handle_import_error means the import moved to another pod; without one, the import held
+ # this pod until it finished or the graceful shutdown timeout ran out.
+ info = activity.info()
+ logger.info(
+ "Worker shutdown detected while import is running",
+ attempt=info.attempt,
+ attempt_elapsed_seconds=round((dt.datetime.now(dt.UTC) - info.started_time).total_seconds()),
+ )
+
+
async def _handle_import_error(
job_inputs: PipelineInputs,
logger: FilteringBoundLogger,
@@ -732,6 +749,13 @@ async def _handle_import_error(
Everything else is logged as an exception and re-raised so Temporal retries it as usual.
"""
+ if isinstance(error, WorkerShuttingDownError):
+ # An expected hand-off, not a failure: Temporal retries the activity on another worker.
+ if activity.in_activity():
+ get_worker_shutdown_handoff_metric(str(job_inputs.job_type)).add(1)
+ await logger.ainfo("Handing the import off to another worker because this worker is shutting down")
+ raise error
+
source_cls = SourceRegistry.get_source(job_inputs.job_type)
error_msg = str(error)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index 77b9e7499c49..5ed4f047fd73 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -22,6 +22,7 @@ from posthog.integration_secrets.errors import (
SecretMissingError,
)
from posthog.temporal.common.errors import NonReportableError
+from posthog.temporal.common.shutdown import WorkerShuttingDownError
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
@@ -67,6 +68,9 @@ class _FakeAsyncCM:
async def __aexit__(self, *args):
return False
+ def run_on_shutdown(self, callback):
+ pass
+
def _passthrough(fn):
"""Stand-in for database_sync_to_async_pool that just calls the wrapped fn."""
@@ -365,6 +369,28 @@ async def test_source_classified_retryable_error_logged_as_warning_not_exception
logger.aexception.assert_not_awaited()
+async def test_worker_shutdown_is_reraised_unwrapped_as_a_handoff_not_an_exception():
+ error = WorkerShuttingDownError("5", "import_data_activity_sync", "data-warehouse-task-queue", 2, "wf", "wt")
+ source = mock.MagicMock(spec=SimpleSource)
+ source.get_non_retryable_errors.return_value = {}
+ source.get_retryable_errors.return_value = {"worker that is shutting down"}
+
+ logger = mock.MagicMock()
+ logger.ainfo = mock.AsyncMock()
+ logger.awarning = mock.AsyncMock()
+ logger.aexception = mock.AsyncMock()
+ logger.adebug = mock.AsyncMock()
+
+ with mock.patch.object(module.SourceRegistry, "get_source", return_value=source):
+ with pytest.raises(WorkerShuttingDownError) as exc_info:
+ await module._handle_import_error(mock.MagicMock(), logger, error)
+
+ assert exc_info.value is error
+ logger.ainfo.assert_awaited_once()
+ logger.aexception.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_unknown_resource_error_reraised_as_non_reportable():
# The web pods and the data-import workers deploy separately, so for about an hour after a new