: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(data-warehouse): survive transient errors in the batch heartbeat (#69105)
Eric Duongf20ba64b98e1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex 95d22b63ff2f..4c35802b07b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -638,8 +638,33 @@ class BatchConsumer:owner_token=self._owner_token,lease_ttl_seconds=self._lease_ttl_seconds,)- if not renewed:- raise OwnershipLostError(f"group lease lost for ({batch.team_id}, {batch.schema_id})")+ except Exception as e:+ # A transient blip (pgbouncer bounce, network hiccup) must not+ # end the heartbeat for the rest of a long batch: with renewals+ # stopped, the lease expires and the executing row ages past+ # grace while the owner is still healthily applying — inviting+ # a concurrent re-claim of a batch that is mid-write. Log and+ # try again next tick; a genuinely dead connection keeps+ # failing and the lease-expiry backstop still applies.+ logger.warning(+ self._event("batch_heartbeat_renewal_failed"),+ batch_id=batch.id,+ team_id=batch.team_id,+ external_data_schema_id=batch.schema_id,+ error=str(e),+ )+ continue+ if not renewed:+ # Another pod reclaimed the group: stop heartbeating so the+ # in-flight apply is fenced by the per-batch ownership checks.+ logger.warning(+ self._event("batch_heartbeat_lease_lost"),+ batch_id=batch.id,+ team_id=batch.team_id,+ external_data_schema_id=batch.schema_id,+ )+ return+ try:await self._adapter.update_status(lock_conn,batch_id=batch.id,@@ -647,8 +672,14 @@ class BatchConsumer:attempt=attempt,batch_created_at=batch.created_at,)- except Exception:- return+ except Exception as e:+ logger.warning(+ self._event("batch_heartbeat_status_refresh_failed"),+ batch_id=batch.id,+ team_id=batch.team_id,+ external_data_schema_id=batch.schema_id,+ error=str(e),+ )async def _process_single(self, batch: PendingBatch, lock_conn: psycopg.AsyncConnection[Any] | None = None) -> bool:"""Bind per-batch log context, then process. Returns True only on success.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex 5c583e14fe0d..b145ecf85da7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -7,6 +7,9 @@ from unittest.mock import AsyncMock, patchimport psycopgimport structlog+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import (+ batch_consumer as batch_consumer_module,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (OwnershipLostError,)@@ -1557,3 +1560,35 @@ class TestDispatchGroups:task.cancel()with pytest.raises(asyncio.CancelledError):await task+++class TestBatchHeartbeat:+ @pytest.mark.asyncio+ async def test_transient_renewal_failure_does_not_end_heartbeat(self):+ # A single pgbouncer/network blip previously killed the heartbeat+ # silently for the rest of the batch: renewals stopped, the lease+ # expired under a healthy owner, and another pod could re-claim the+ # batch mid-apply. The loop must survive transient errors and only+ # stop when the lease is genuinely lost.+ consumer = _make_consumer()+ renew = AsyncMock(side_effect=[ConnectionError("blip"), True, False])+ refresh = AsyncMock()++ sleep_count = 0++ async def fast_sleep(_seconds):+ nonlocal sleep_count+ sleep_count += 1+ if sleep_count > 10:+ raise AssertionError("heartbeat loop did not exit after lease loss")++ with (+ patch.object(consumer._adapter, "renew_lease", renew),+ patch.object(consumer._adapter, "update_status", refresh),+ patch.object(batch_consumer_module.asyncio, "sleep", fast_sleep),+ ):+ await consumer._batch_heartbeat(AsyncMock(), _make_batch(), attempt=1)++ # blip -> continue; renewed -> status refresh; lease lost -> stop+ assert renew.await_count == 3+ refresh.assert_awaited_once()