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 a dropped connection during batch consumer shutdown (#107012)

Tom Owers835d9549c1f0
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 7b6d79a8ce4d..bea8617d35ad 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
@@ -122,6 +122,17 @@ def _is_schema_lag_error(error: BaseException) -> bool:
return isinstance(error, psycopg.errors.UndefinedColumn | psycopg.errors.UndefinedTable)
+def _is_transient_connection_error(error: BaseException, conn: psycopg.AsyncConnection[Any]) -> bool:
+ """Whether ``error`` is ``conn`` dying mid-query rather than a real bug.
+
+ Mirrors ``_is_transient_queue_connection_drop`` in postgres_queue/consumer.py: a network
+ blip, server-side cull, pgbouncer bounce, or (for a call made from ``_close``) the pod's
+ own network path tearing down concurrently with its graceful shutdown all leave ``conn``
+ closed or broken — the connection is gone, not the query wrong.
+ """
+ return isinstance(error, psycopg.OperationalError) and (conn.closed or conn.broken)
+
+
class OwnershipLostError(Exception):
"""Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""
@@ -1409,6 +1420,11 @@ class BatchConsumer:
if _is_admin_shutdown_error(e):
# Admin-initiated disconnect during teardown is expected; the lease just expires.
logger.warning(self._event("release_all_owned_admin_shutdown"), error=str(e))
+ elif _is_transient_connection_error(e, self._poll_conn):
+ # The connection died mid-teardown rather than release_all_owned itself
+ # being wrong — nothing to retry with here, so the lease just expires
+ # per the comment above.
+ logger.warning(self._event("release_all_owned_connection_dropped"), error=str(e))
else:
logger.exception(self._event("release_all_owned_failed_on_shutdown"))
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 02f4c5a70710..a522a4f0c1d5 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
@@ -962,19 +962,35 @@ class TestAdminShutdownErrorClassification:
mock_capture.assert_not_called()
@pytest.mark.asyncio
- async def test_close_does_not_report_admin_shutdown_error(self):
- # Queue DB terminates the poll connection via an administrator command (failover,
- # maintenance restart) while _close() tries the best-effort lease release.
- # _close() already notes this path is best-effort; the error must not reach
+ @pytest.mark.parametrize(
+ "error,drops_connection",
+ [
+ (psycopg.errors.AdminShutdown("terminating connection due to administrator command"), False),
+ (
+ psycopg.OperationalError("consuming input failed: server closed the connection unexpectedly"),
+ True,
+ ),
+ ],
+ )
+ async def test_close_does_not_report_expected_lease_release_errors(
+ self, error: BaseException, drops_connection: bool
+ ) -> None:
+ # Queue DB drops the poll connection while _close() tries the best-effort lease
+ # release — via an administrator command, or a generic connection drop (e.g. the
+ # pod's own network path tearing down concurrently with its graceful shutdown).
+ # _close() already notes this path is best-effort; neither shape must reach
# error tracking.
consumer = _make_consumer()
+
+ async def raise_error(*args: Any, **kwargs: Any) -> None:
+ if drops_connection:
+ # `closed` is a read-only property on the real AsyncConnection; swap in a
+ # fresh mock with it set, rather than assigning the attribute in place.
+ consumer._poll_conn = _make_healthy_conn(closed=True)
+ raise error
+
with (
- patch.object(
- consumer._adapter,
- "release_all_owned",
- new_callable=AsyncMock,
- side_effect=psycopg.errors.AdminShutdown("terminating connection due to administrator command"),
- ),
+ patch.object(consumer._adapter, "release_all_owned", new_callable=AsyncMock, side_effect=raise_error),
patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
):
await consumer._close()