: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(ws): decouple loader liveness heartbeat from batch processing (#60916)
estefania291472fccd6a
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex b2116b1b7e6e..0469f95d61bc 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -44,6 +44,7 @@ POLL_INTERVAL_SECONDS = 2.0RECOVERY_INTERVAL_SECONDS = 30.0RETRY_BACKOFF_BASE_SECONDS = 15+HEARTBEAT_INTERVAL_SECONDS = 5.0@dataclass@@ -57,6 +58,7 @@ class ConsumerConfig:poll_limit: int = 50health_port: int = 8080health_timeout_seconds: float = 60.0+ heartbeat_interval_seconds: float = HEARTBEAT_INTERVAL_SECONDSrecovery_interval_seconds: float = RECOVERY_INTERVAL_SECONDSretry_backoff_base_seconds: int = RETRY_BACKOFF_BASE_SECONDSrecovery_grace_seconds: int | None = None@@ -88,6 +90,7 @@ class BatchConsumer:self._conn: psycopg.AsyncConnection[Any] | None = Noneself._recovery_conn: psycopg.AsyncConnection[Any] | None = Noneself._recovery_task: asyncio.Task[None] | None = None+ self._heartbeat_task: asyncio.Task[None] | None = Noneasync def run(self) -> None:"""Main loop: poll → group → process → unlock → repeat."""@@ -112,6 +115,7 @@ class BatchConsumer:try:await self._recovery_sweep()self._recovery_task = asyncio.create_task(self._recovery_loop())+ self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())while not self._shutdown.is_set():if self._health_reporter:@@ -372,6 +376,19 @@ class BatchConsumer:except Exception:logger.exception("recovery_sweep_error")+ async def _heartbeat_loop(self) -> None:+ """Report liveness on a fixed cadence, independent of batch processing."""+ while not self._shutdown.is_set():+ if self._health_reporter:+ self._health_reporter()+ try:+ await asyncio.wait_for(+ self._shutdown.wait(),+ timeout=self._config.heartbeat_interval_seconds,+ )+ except TimeoutError:+ pass+async def _recovery_sweep(self) -> None:"""Recover batches left in 'executing' by a crashed pod."""conn = self._recovery_conn or self._conn@@ -443,13 +460,14 @@ class BatchConsumer:loop.add_signal_handler(sig, self._shutdown.set)async def _close(self) -> None:- """Cancel the recovery task, release all advisory locks, and close both connections."""- if self._recovery_task is not None:- self._recovery_task.cancel()- try:- await self._recovery_task- except asyncio.CancelledError:- pass+ """Cancel the recovery and heartbeat tasks, release all advisory locks, and close both connections."""+ for task in (self._recovery_task, self._heartbeat_task):+ if task is not None:+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ passif self._recovery_conn is not None and not self._recovery_conn.closed:await self._recovery_conn.close()diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex b11e4ed4d78b..a04f107a9a1b 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -1,3 +1,4 @@+import asynciofrom typing import Anyimport pytest@@ -5,6 +6,7 @@ from unittest.mock import AsyncMock, patchimport structlog+from posthog.temporal.data_imports.pipelines.pipeline_v3.load.health import HealthStatefrom posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (BatchConsumer,ConsumerConfig,@@ -399,3 +401,43 @@ class TestLogContextBinding:assert "batch_id" not in structlog.contextvars.get_contextvars()assert "workflow_run_id" not in structlog.contextvars.get_contextvars()+++class TestHeartbeatLoop:+ @pytest.mark.asyncio+ async def test_reports_until_shutdown(self):+ consumer = _make_consumer(heartbeat_interval_seconds=0.01)+ calls = 0++ def reporter():+ nonlocal calls+ calls += 1++ consumer._health_reporter = reporter++ task = asyncio.create_task(consumer._heartbeat_loop())+ await asyncio.sleep(0.05)+ consumer._shutdown.set()+ await asyncio.wait_for(task, timeout=1.0)++ assert calls >= 2++ @pytest.mark.asyncio+ async def test_keeps_liveness_healthy_through_long_batch(self):+ # A poll cycle (large final-batch compaction) can run far longer than the+ # health timeout; the dedicated heartbeat must keep liveness green so+ # kubelet doesn't SIGTERM the pod mid-batch.+ health = HealthState(timeout_seconds=0.1)+ consumer = _make_consumer(heartbeat_interval_seconds=0.02)+ consumer._health_reporter = health.report_healthy++ task = asyncio.create_task(consumer._heartbeat_loop())+ await asyncio.sleep(0.3) # simulate a batch ~3x the health timeout+ assert health.is_healthy() is True++ consumer._shutdown.set()+ await asyncio.wait_for(task, timeout=1.0)++ # Once the heartbeat stops, liveness correctly goes stale again.+ await asyncio.sleep(0.2)+ assert health.is_healthy() is False