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(postgres): retry transient pooler drop during schema discovery (#64458)

Tom Owersd62588fcf6f1
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index e33c6d423eb7..08af8059658e 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -14,7 +14,7 @@ from datetime import (
time as datetime_time,
timezone,
)
-from typing import TYPE_CHECKING, Any, Literal, LiteralString, Optional, cast
+from typing import TYPE_CHECKING, Any, Literal, LiteralString, Optional, TypeVar, cast
if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -245,6 +245,34 @@ def _raise_if_setup_connection_broken(connection: psycopg.Connection) -> None:
raise psycopg.OperationalError("connection to server was lost during table metadata discovery")
+_T = TypeVar("_T")
+
+
+def _retry_on_connection_dropped(
+ operation: Callable[[], _T],
+ logger: FilteringBoundLogger,
+ *,
+ max_attempts: int = 5,
+) -> _T:
+ """Run `operation`, retrying transient connection-dropped errors with bounded backoff.
+
+ Permanent errors (auth failures, SSL-required) are re-raised immediately because
+ `_is_connection_dropped_error` only matches transient drops.
+ """
+ attempt = 0
+ while True:
+ try:
+ return operation()
+ except _CONNECTION_DROPPED_ERROR_TYPES as e:
+ if not _is_connection_dropped_error(e):
+ raise
+ attempt += 1
+ if attempt >= max_attempts:
+ raise
+ logger.debug(f"Connection dropped ({e}). Retrying (attempt {attempt}/{max_attempts})")
+ time.sleep(min(2 * attempt, 30))
+
+
def _connect_with_dropped_retry(
connect: Callable[[], psycopg.Connection],
logger: FilteringBoundLogger,
@@ -261,18 +289,7 @@ def _connect_with_dropped_retry(
bounded backoff; permanent errors (auth failures, SSL-required) are re-raised
immediately because `_is_connection_dropped_error` only matches transient drops.
"""
- attempt = 0
- while True:
- try:
- return connect()
- except _CONNECTION_DROPPED_ERROR_TYPES as e:
- if not _is_connection_dropped_error(e):
- raise
- attempt += 1
- if attempt >= max_attempts:
- raise
- logger.debug(f"Connection attempt failed ({e}). Retrying (attempt {attempt}/{max_attempts})")
- time.sleep(min(2 * attempt, 30))
+ return _retry_on_connection_dropped(connect, logger, max_attempts=max_attempts)
def _next_recovery_conflict_chunk_size(chunk_size: int, successive_errors: int) -> int:
@@ -929,42 +946,32 @@ def get_schemas(
names: list[str] | None = None,
) -> dict[str, PostgresDiscoveredSchema]:
"""Get all tables from PostgreSQL source schemas to sync."""
- # Schema discovery opens a fresh connection on its own periodic cadence. A momentary drop —
+
+ # Schema discovery opens a fresh connection on its own periodic cadence. A transient drop —
# "server closed the connection unexpectedly" / an SSL EOF from a pooler, firewall, or
- # SSH-tunnel hiccup, or a Supavisor "(EDBHANDLEREXITED)" pooler drop — is transient and recovers
- # on a retry, exactly like the drops the import read path already retries via
- # `_connect_with_dropped_retry`. Transaction-mode poolers (Supabase's Supavisor, PgBouncer)
- # routinely accept the client connection and only drop the upstream backend once the first
- # query runs, so the drop lands on the discovery query (`_is_duckdb_connection`'s
- # `SELECT version()`), not the connect — the retry must span both or the blip fails the whole
- # discovery activity and surfaces as captured error-tracking noise even though the next attempt
- # would succeed. Permanent errors (auth failures, SSL-required) re-raise immediately because
- # `_is_connection_dropped_error` only matches transient drops.
- logger = structlog.get_logger()
- attempt = 0
- while True:
- connection = _connect_with_dropped_retry(
- lambda: _connect_to_postgres(
- host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl
- ),
- logger,
+ # SSH-tunnel hiccup, or a Supavisor "DbHandler exited" (EDBHANDLEREXITED) mid-query — is the
+ # same class the import read path already retries via `_connect_with_dropped_retry`.
+ # Transaction-mode poolers (Supabase's Supavisor, PgBouncer) routinely accept the client
+ # connection and only drop the upstream backend once the first query runs, so the drop can land
+ # either on connect or on the first discovery query (e.g. `SELECT version()` in
+ # `_is_duckdb_connection`). Retry the whole connect-and-discover cycle on a fresh connection so
+ # the retry spans both — otherwise the blip fails the discovery activity and surfaces as
+ # captured error-tracking noise even though the next attempt would succeed. Permanent errors
+ # (auth failures, SSL-required) re-raise immediately because `_is_connection_dropped_error` only
+ # matches transient drops.
+ def _connect_and_discover() -> dict[str, PostgresDiscoveredSchema]:
+ connection = _connect_to_postgres(
+ host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl
)
try:
return _schemas_from_conn(connection, schema, names)
- except _CONNECTION_DROPPED_ERROR_TYPES as e:
- if not _is_connection_dropped_error(e):
- raise
- attempt += 1
- if attempt >= _MAX_SETUP_CONNECTION_DROPPED_RETRIES:
- raise
- logger.debug(
- f"Schema discovery query failed ({e}). "
- f"Retrying (attempt {attempt}/{_MAX_SETUP_CONNECTION_DROPPED_RETRIES})"
- )
- time.sleep(min(2 * attempt, 30))
finally:
connection.close()
+ return _retry_on_connection_dropped(
+ _connect_and_discover, structlog.get_logger(), max_attempts=_MAX_SETUP_CONNECTION_DROPPED_RETRIES
+ )
+
def get_primary_keys_for_schemas(
host: str,
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 71543cbe88ff..082689a062fd 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -1437,6 +1437,75 @@ class TestPostgresSchemaDiscovery:
connection.cursor.return_value = cursor_context
return connection
+ @pytest.mark.parametrize("n_drops", [1, 2, 3])
+ def test_get_schemas_retries_repeated_pooler_drops_during_discovery_query(self, n_drops: int):
+ # `n_drops` successive Supavisor pooler drops on the first discovery query
+ # ("(EDBHANDLEREXITED) DbHandler exited", XX000 InternalError_), then a healthy connection.
+ # Each drop must reconnect and rerun the whole connect-and-discover cycle on a fresh
+ # connection, recovering once the pooler stops dropping the upstream backend — so connect is
+ # called once per dropped attempt plus once for the successful one.
+ dropping_connections = [
+ self._drop_on_execute_connection(
+ psycopg.errors.InternalError_("(EDBHANDLEREXITED) DbHandler exited. Check logs for more information")
+ )
+ for _ in range(n_drops)
+ ]
+ good_connection = self._mock_connection(
+ [("public", "users")],
+ [("public", "users", "id", "integer", "NO", 1)],
+ )
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect",
+ side_effect=[*dropping_connections, good_connection],
+ ) as connect_mock:
+ with mock.patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"):
+ schemas = get_schemas(
+ host="localhost",
+ port=5432,
+ database="postgres",
+ user="postgres",
+ password="postgres",
+ schema="",
+ )
+
+ assert connect_mock.call_count == n_drops + 1
+ assert set(schemas.keys()) == {"public.users"}
+ for dropped in dropping_connections:
+ dropped.close.assert_called_once()
+ good_connection.close.assert_called_once()
+
+ def test_get_schemas_reraises_after_exhausting_retries_on_sustained_discovery_drop(self):
+ # When every attempt hits the pooler drop on the discovery query, discovery exhausts its
+ # bounded in-process retries and re-raises the original error for Temporal to retry the whole
+ # activity — it does not loop forever. With _MAX_SETUP_CONNECTION_DROPPED_RETRIES attempts,
+ # connect is called once per attempt and each connection is closed before the next reconnect.
+ dropping_connections = [
+ self._drop_on_execute_connection(
+ psycopg.errors.InternalError_("(EDBHANDLEREXITED) DbHandler exited. Check logs for more information")
+ )
+ for _ in range(_MAX_SETUP_CONNECTION_DROPPED_RETRIES)
+ ]
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect",
+ side_effect=dropping_connections,
+ ) as connect_mock:
+ with mock.patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"):
+ with pytest.raises(psycopg.errors.InternalError_):
+ get_schemas(
+ host="localhost",
+ port=5432,
+ database="postgres",
+ user="postgres",
+ password="postgres",
+ schema="",
+ )
+
+ assert connect_mock.call_count == _MAX_SETUP_CONNECTION_DROPPED_RETRIES
+ for dropped in dropping_connections:
+ dropped.close.assert_called_once()
+
def test_get_schemas_retries_transient_connection_drop_on_connect(self):
# A transient drop on the discovery connect ("server closed the connection unexpectedly")
# is the same class of error the import read path already recovers from. Discovery must