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 (#64459)

Tom Owersda62cb100cb8
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 3b5d247a1b78..6554b3731740 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -920,24 +920,41 @@ 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 on
- # connect — "server closed the connection unexpectedly" / an SSL EOF from a pooler, firewall,
- # or SSH-tunnel hiccup — is transient and recovers on a retry, exactly like the drops the
- # import read path already retries via `_connect_with_dropped_retry`. Without an in-process
- # retry here that 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.
- connection = _connect_with_dropped_retry(
- lambda: _connect_to_postgres(
- host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl
- ),
- structlog.get_logger(),
- )
- try:
- return _schemas_from_conn(connection, schema, names)
- finally:
- connection.close()
+ # Schema discovery opens a fresh connection on its own periodic cadence. A momentary 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,
+ )
+ 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()
def get_primary_keys_for_schemas(
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 29cfe3adee50..d44946c4b409 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -1410,6 +1410,77 @@ class TestPostgresSchemaDiscovery:
assert set(schemas.keys()) == {"public.users"}
connection.close.assert_called_once()
+ def _drop_on_execute_connection(self, error):
+ cursor = mock.MagicMock()
+ cursor.execute.side_effect = error
+
+ cursor_context = mock.MagicMock()
+ cursor_context.__enter__.return_value = cursor
+ cursor_context.__exit__.return_value = None
+
+ connection = mock.MagicMock()
+ connection.cursor.return_value = cursor_context
+ return connection
+
+ def test_get_schemas_retries_pooler_drop_during_discovery_query(self):
+ # The connect can succeed and the pooler then drop the upstream backend on the first
+ # discovery query — Supavisor surfaces this as "(EDBHANDLEREXITED) connection to database
+ # closed" (XX000 InternalError_). The retry must span the discovery queries, not just the
+ # connect, so a fresh connection reruns discovery instead of escaping as captured error noise.
+ drop = psycopg.errors.InternalError_(
+ "(EDBHANDLEREXITED) connection to database closed. Check logs for more information"
+ )
+ dropped_connection = self._drop_on_execute_connection(drop)
+ 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=[dropped_connection, 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="",
+ )
+
+ # Drop on the first query reconnected and reran discovery — before the fix the retry only
+ # wrapped the connect, so the query-time drop escaped on the first attempt (call_count == 1).
+ assert connect_mock.call_count == 2
+ assert set(schemas.keys()) == {"public.users"}
+ dropped_connection.close.assert_called_once()
+ good_connection.close.assert_called_once()
+
+ def test_get_schemas_does_not_retry_non_drop_error_during_discovery_query(self):
+ # A genuine XX000 internal error that isn't the pooler drop must propagate on the first
+ # discovery attempt — the discovery retry is scoped strictly to transient drops.
+ err = psycopg.errors.InternalError_("XX000: internal error: something went wrong")
+ dropped_connection = self._drop_on_execute_connection(err)
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect",
+ side_effect=[dropped_connection],
+ ) 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 == 1
+ dropped_connection.close.assert_called_once()
+
def test_get_schemas_does_not_retry_permanent_connect_error(self):
# A permanent connect failure (bad password) must propagate on the first attempt — the
# dropped-connection retry is scoped strictly to transient drops.