: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-imports): retry a poisoned lease-release connection with a fresh one (#84121)
Tom Owersd237f49fd713
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 310cc046b07c..e1801a70ee5c 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@@ -695,13 +695,46 @@ class BatchConsumer:returntry:await self._adapter.unlock(group_conn, batches=batches, owner_token=self._owner_token)+ return+ except psycopg.OperationalError as e:+ if not self._adapter.per_group_connections:+ # Advisory-lock adapters release on the session that acquired the lock;+ # a fresh connection wouldn't hold it, so there's nothing to retry with.+ self._log_unlock_failure(e, team_id=team_id, schema_id=schema_id)+ returnexcept Exception as e:- logger.exception(- self._event("unlock_for_batches_failed"),- team_id=team_id,- external_data_schema_id=schema_id,- )- capture_exception(e)+ self._log_unlock_failure(e, team_id=team_id, schema_id=schema_id)+ return++ # The batch heartbeat shares this per-group connection with the batch loop and+ # can be cancelled mid-query when the group task itself is cancelled (e.g. shutdown+ # draining a batch stuck deep in the sink write) — a psycopg command cancelled+ # mid-flight leaves the connection unable to accept another ("another command is+ # already in progress"), the same class of issue _drop_conn guards against for the+ # poll/recovery connections. The lease release isn't session-scoped, so retrying once+ # on a fresh connection is safe, and cheap since this runs once per group, not per batch.+ try:+ retry_conn = await self._connect()+ except Exception as e:+ self._log_unlock_failure(e, team_id=team_id, schema_id=schema_id)+ return+ try:+ await self._adapter.unlock(retry_conn, batches=batches, owner_token=self._owner_token)+ except Exception as e:+ self._log_unlock_failure(e, team_id=team_id, schema_id=schema_id)+ finally:+ try:+ await retry_conn.close()+ except Exception:+ pass++ def _log_unlock_failure(self, error: Exception, *, team_id: int, schema_id: str) -> None:+ logger.exception(+ self._event("unlock_for_batches_failed"),+ team_id=team_id,+ external_data_schema_id=schema_id,+ )+ capture_exception(error)async def _get_status_conn(self, lock_conn: psycopg.AsyncConnection[Any] | None) -> psycopg.AsyncConnection[Any]:"""Return the connection to use for status writes, preferring the lock session."""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 e4cc69302f1d..42579bd5c15e 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@@ -2044,6 +2044,97 @@ class TestPerGroupConnectionIsolation:group_conn.close.assert_awaited_once()+class TestUnlockGroup:+ @pytest.mark.asyncio+ async def test_retries_on_fresh_connection_when_group_conn_is_poisoned(self):+ # A heartbeat query cancelled mid-flight can leave the per-group psycopg+ # connection unable to accept another command ("another command is already+ # in progress"). This must retry on a fresh connection instead of just+ # capturing the error and leaving the group's lease dangling until its TTL+ # expires.+ consumer = _make_consumer()+ poisoned_conn = _make_healthy_conn()+ fresh_conn = _make_healthy_conn()+ batches = [_make_batch()]++ mock_unlock = AsyncMock(side_effect=[psycopg.OperationalError("another command is already in progress"), None])++ with (+ patch.object(consumer._adapter, "unlock", mock_unlock),+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=fresh_conn) as mock_connect,+ patch.object(batch_consumer_module, "capture_exception") as mock_capture,+ ):+ await consumer._unlock_group(poisoned_conn, batches, team_id=1, schema_id="schema-1")++ mock_connect.assert_awaited_once()+ assert [call.args[0] for call in mock_unlock.await_args_list] == [poisoned_conn, fresh_conn]+ fresh_conn.close.assert_awaited_once()+ mock_capture.assert_not_called()++ @pytest.mark.asyncio+ async def test_gives_up_and_reports_when_retry_also_fails(self):+ consumer = _make_consumer()+ poisoned_conn = _make_healthy_conn()+ fresh_conn = _make_healthy_conn()+ batches = [_make_batch()]++ retry_error = psycopg.OperationalError("connection refused")+ mock_unlock = AsyncMock(+ side_effect=[psycopg.OperationalError("another command is already in progress"), retry_error]+ )++ with (+ patch.object(consumer._adapter, "unlock", mock_unlock),+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=fresh_conn),+ patch.object(batch_consumer_module, "capture_exception") as mock_capture,+ ):+ await consumer._unlock_group(poisoned_conn, batches, team_id=1, schema_id="schema-1")++ mock_capture.assert_called_once_with(retry_error)+ fresh_conn.close.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_advisory_lock_adapter_does_not_retry_with_a_fresh_connection(self):+ # Advisory locks are session-scoped: releasing on a different connection+ # wouldn't hold the lock, so retrying there would silently leak it.+ consumer = _make_consumer()+ poisoned_conn = _make_healthy_conn()+ batches = [_make_batch()]++ mock_unlock = AsyncMock(side_effect=psycopg.OperationalError("another command is already in progress"))++ with (+ patch.object(consumer._adapter, "unlock", mock_unlock),+ patch.object(consumer._adapter, "per_group_connections", False),+ patch.object(consumer, "_connect", new_callable=AsyncMock) as mock_connect,+ patch.object(batch_consumer_module, "capture_exception") as mock_capture,+ ):+ await consumer._unlock_group(poisoned_conn, batches, team_id=1, schema_id="schema-1")++ mock_connect.assert_not_called()+ mock_unlock.assert_awaited_once()+ mock_capture.assert_called_once()++ @pytest.mark.asyncio+ async def test_reports_original_error_when_reconnecting_for_retry_fails(self):+ consumer = _make_consumer()+ poisoned_conn = _make_healthy_conn()+ batches = [_make_batch()]++ connect_error = OSError("connection refused")+ mock_unlock = AsyncMock(side_effect=psycopg.OperationalError("another command is already in progress"))++ with (+ patch.object(consumer._adapter, "unlock", mock_unlock),+ patch.object(consumer, "_connect", new_callable=AsyncMock, side_effect=connect_error),+ patch.object(batch_consumer_module, "capture_exception") as mock_capture,+ ):+ await consumer._unlock_group(poisoned_conn, batches, team_id=1, schema_id="schema-1")++ mock_unlock.assert_awaited_once()+ mock_capture.assert_called_once_with(connect_error)++class TestGroupByKey:def test_groups_by_team_and_schema(self):batches = [