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.

fix(data-imports): stop reporting admin-shutdown queue DB disconnects to error tracking (#82715)

Tom Owers16f607d2d166
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.py
index 46ddb6f922a5..01c455977490 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
@@ -103,6 +103,15 @@ def _is_connect_timeout_error(error: BaseException) -> bool:
return isinstance(error, psycopg.errors.ConnectionTimeout)
+# SQLSTATE 57P01: the queue DB itself terminated the connection via an administrator
+# command — a managed-Postgres failover, a maintenance restart, or an explicit
+# pg_terminate_backend(). Same self-healing shape as the guards above: the connection
+# is simply gone, _ensure_poll_conn/_ensure_recovery_conn redial on the next cycle, and
+# the caller's existing retry/backoff already covers the gap.
+def _is_admin_shutdown_error(error: BaseException) -> bool:
+ return isinstance(error, psycopg.errors.AdminShutdown)
+
+
class OwnershipLostError(Exception):
"""Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""
@@ -489,6 +498,8 @@ class BatchConsumer:
logger.warning(self._event("poll_failed_queue_db_starting_up"), error=str(e))
elif _is_connect_timeout_error(e):
logger.warning(self._event("poll_failed_queue_db_connect_timeout"), error=str(e))
+ elif _is_admin_shutdown_error(e):
+ logger.warning(self._event("poll_failed_queue_db_admin_shutdown"), error=str(e))
else:
logger.exception(self._event("poll_failed_queue_db_unreachable"))
capture_exception(e)
@@ -1088,6 +1099,8 @@ class BatchConsumer:
logger.warning(self._event("recovery_sweep_db_starting_up"), error=str(e))
elif _is_connect_timeout_error(e):
logger.warning(self._event("recovery_sweep_connect_timeout"), error=str(e))
+ elif _is_admin_shutdown_error(e):
+ logger.warning(self._event("recovery_sweep_admin_shutdown"), error=str(e))
else:
logger.exception(self._event("recovery_sweep_error"))
capture_exception(e)
@@ -1114,6 +1127,8 @@ class BatchConsumer:
logger.warning(self._event("reconcile_sweep_db_starting_up"), error=str(e))
elif _is_connect_timeout_error(e):
logger.warning(self._event("reconcile_sweep_connect_timeout"), error=str(e))
+ elif _is_admin_shutdown_error(e):
+ logger.warning(self._event("reconcile_sweep_admin_shutdown"), error=str(e))
else:
logger.exception(self._event("reconcile_sweep_error"))
capture_exception(e)
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.py
index fd477bb5f41f..9268569db916 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
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
OwnershipLostError,
+ _is_admin_shutdown_error,
_is_connect_timeout_error,
_is_dns_resolution_transient_error,
_is_server_not_ready_error,
@@ -756,6 +757,135 @@ class TestConnectTimeoutErrorClassification:
mock_capture.assert_not_called()
+class TestAdminShutdownErrorClassification:
+ def test_classifies_admin_shutdown(self) -> None:
+ assert (
+ _is_admin_shutdown_error(
+ psycopg.errors.AdminShutdown("terminating connection due to administrator command")
+ )
+ is True
+ )
+
+ def test_ignores_other_operational_errors(self) -> None:
+ # A generic OperationalError carrying similar wording is not the same as psycopg's
+ # dedicated AdminShutdown class (SQLSTATE 57P01) and must not be misclassified.
+ assert (
+ _is_admin_shutdown_error(psycopg.OperationalError("terminating connection due to administrator command"))
+ is False
+ )
+
+ @pytest.mark.asyncio
+ async def test_recovery_loop_does_not_report_admin_shutdown_error(self):
+ # Reproduces the reported issue: the queue DB terminates the recovery connection
+ # via an administrator command (failover, maintenance restart) while the periodic
+ # reconcile sweep is running. The sweep already retries every interval, so this
+ # self-healing disconnect must not be sent to error tracking.
+ config = ConsumerConfig(
+ database_url="postgres://unused:unused@localhost/unused",
+ recovery_interval_seconds=0.01,
+ reconcile_interval_seconds=0,
+ )
+ consumer = BatchConsumer(config=config, process_batch=AsyncMock())
+ consumer._recovery_conn = _make_healthy_conn()
+
+ second_reconcile_started = asyncio.Event()
+ call_count = 0
+
+ async def flaky_reconcile() -> None:
+ nonlocal call_count
+ call_count += 1
+ if call_count == 1:
+ raise psycopg.errors.AdminShutdown("terminating connection due to administrator command")
+ second_reconcile_started.set()
+
+ with (
+ patch.object(consumer, "_recovery_sweep_with_timeout", new_callable=AsyncMock),
+ patch.object(consumer, "_reconcile_failed_runs", side_effect=flaky_reconcile),
+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ loop_task = asyncio.create_task(consumer._recovery_loop())
+ await asyncio.wait_for(second_reconcile_started.wait(), timeout=2.0)
+ consumer._shutdown.set()
+ await asyncio.wait_for(loop_task, timeout=5.0)
+
+ mock_capture.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_poll_failure_does_not_report_admin_shutdown_error(self):
+ # Same self-healing admin-initiated disconnect as above, but hit directly by the
+ # main poll loop's own OperationalError branch — reproduces the reported issue's
+ # exact stack (get_unprocessed_and_lock raising mid-query).
+ config = ConsumerConfig(
+ database_url="postgres://unused:unused@localhost/unused",
+ poll_interval_seconds=0.01,
+ )
+ consumer = BatchConsumer(config=config, process_batch=AsyncMock())
+
+ second_poll_started = asyncio.Event()
+ fetch_calls = 0
+
+ async def flaky_fetch(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ nonlocal fetch_calls
+ fetch_calls += 1
+ if fetch_calls == 1:
+ raise psycopg.errors.AdminShutdown("terminating connection due to administrator command")
+ second_poll_started.set()
+ return []
+
+ with (
+ patch.object(
+ consumer, "_connect", new_callable=AsyncMock, side_effect=lambda **kwargs: _make_healthy_conn()
+ ),
+ patch.object(consumer, "_install_signal_handlers"),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ new_callable=AsyncMock,
+ return_value=[],
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_unprocessed_and_lock",
+ side_effect=flaky_fetch,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.release_all_owned_leases",
+ new_callable=AsyncMock,
+ ),
+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ run_task = asyncio.create_task(consumer.run())
+ await asyncio.wait_for(second_poll_started.wait(), timeout=2.0)
+ consumer._shutdown.set()
+ await asyncio.wait_for(run_task, timeout=5.0)
+
+ mock_capture.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_recovery_sweep_does_not_report_admin_shutdown_error(self):
+ # Same self-healing admin-initiated disconnect, but hit by the periodic recovery
+ # sweep's own OperationalError branch rather than the reconcile sweep.
+ consumer = _make_consumer(recovery_interval_seconds=0.01)
+ swept = asyncio.Event()
+
+ async def raise_admin_shutdown(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ swept.set()
+ raise psycopg.errors.AdminShutdown("terminating connection due to administrator command")
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ side_effect=raise_admin_shutdown,
+ ),
+ patch.object(consumer, "_reconcile_failed_runs", new_callable=AsyncMock),
+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ loop_task = asyncio.create_task(consumer._recovery_loop())
+ await asyncio.wait_for(swept.wait(), timeout=2.0)
+ consumer._shutdown.set()
+ await asyncio.wait_for(loop_task, timeout=5.0)
+
+ mock_capture.assert_not_called()
+
+
class TestStartupLiveness:
@pytest.mark.asyncio
async def test_heartbeat_reports_liveness_while_startup_sweep_runs(self):