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 connection drops during schema discovery (#64068)

Tom Owersc7e3f67434c6
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 077927bef6bc..0a8cb46c0309 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -908,10 +908,24 @@ def get_schemas(
names: list[str] | None = None,
) -> dict[str, PostgresDiscoveredSchema]:
"""Get all tables from PostgreSQL source schemas to sync."""
- with pg_connection(
- host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl
- ) as connection:
+ # 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()
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 f0e5a80b1e22..5612d5520ac0 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -1340,6 +1340,64 @@ class TestPostgresSchemaDiscovery:
connection.cursor.return_value = cursor_context
return connection
+ 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
+ # retry the connect in-process and recover instead of failing the whole run — and surfacing
+ # as captured error-tracking noise — on the first blip.
+ drop = psycopg.OperationalError(
+ 'connection failed: connection to server at "66.33.22.246", port 11212 failed: '
+ "server closed the connection unexpectedly"
+ )
+ 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=[drop, 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="",
+ )
+
+ # First connect dropped, second succeeded — before the fix the drop escaped on the first
+ # connect (call_count == 1) and failed the discovery activity.
+ assert connect_mock.call_count == 2
+ assert set(schemas.keys()) == {"public.users"}
+ 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.
+ err = psycopg.OperationalError(
+ 'connection to server at "10.0.0.1" failed: FATAL: password authentication failed for user "postgres"'
+ )
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect",
+ side_effect=err,
+ ) as connect_mock:
+ with mock.patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"):
+ with pytest.raises(psycopg.OperationalError):
+ get_schemas(
+ host="localhost",
+ port=5432,
+ database="postgres",
+ user="postgres",
+ password="postgres",
+ schema="",
+ )
+
+ assert connect_mock.call_count == 1
+
def test_get_schemas_qualifies_table_names_when_schema_is_blank(self):
connection = self._mock_connection(
[("public", "users"), ("analytics", "events")],