: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(postgres): skip foreign-key discovery gracefully on failure (#63148)
Tom Owers0e9bec22a09a
diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.pyindex 4c352fe6ca0b..81f87854bba3 100644--- a/posthog/temporal/data_imports/sources/postgres/source.py+++ b/posthog/temporal/data_imports/sources/postgres/source.py@@ -281,15 +281,24 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaschema=config.schema,names=names,)- db_foreign_keys = get_postgres_foreign_keys(- host=host,- port=port,- user=config.user,- password=config.password,- database=config.database,- schema=config.schema,- names=names,- )+ # Foreign keys are advisory metadata (they pre-populate relationship hints in the+ # table picker). The discovery query joins three `information_schema` views, which+ # can be expensive enough to OOM the source database on schemas with many+ # constraints. Degrade gracefully on any failure — like PK and index discovery+ # below — so optional metadata never breaks schema listing or the import.+ try:+ db_foreign_keys = get_postgres_foreign_keys(+ host=host,+ port=port,+ user=config.user,+ password=config.password,+ database=config.database,+ schema=config.schema,+ names=names,+ )+ except Exception as e:+ structlog.get_logger().warning("Failed to detect foreign keys for Postgres schemas", exc_info=e)+ db_foreign_keys = {}if with_counts:row_counts = get_postgres_row_count(diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex 9137a92b3787..09be09e1968b 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -39,6 +39,7 @@ from posthog.temporal.data_imports.sources.postgres.partitioned_tables import (from posthog.temporal.data_imports.sources.postgres.postgres import (SSL_REQUIRED_AFTER_DATE,JsonAsStringLoader,+ PostgresDiscoveredSchema,PostgresImplementation,PostgreSQLColumn,RangeAsStringLoader,@@ -767,6 +768,64 @@ class TestPostgresSchemaDiscovery:patch_connect_to_postgres.assert_not_called()+class TestPostgresSourceGetSchemasDegradesGracefully:+ @pytest.fixture+ def source(self):+ return PostgresSource()++ def _config(self):+ return mock.MagicMock(user="u", password="p", database="db", schema="", ssh_tunnel=None)++ @pytest.mark.parametrize(+ "exc",+ [+ psycopg.errors.OutOfMemory(+ 'out of memory\nDETAIL: Failed on request of size 2048 in memory context "ExecutorState".'+ ),+ psycopg.OperationalError("connection refused"),+ Exception("unexpected error"),+ ],+ )+ def test_foreign_key_discovery_failure_does_not_break_schema_listing(self, source, exc):+ # A failing foreign-key lookup (e.g. the source DB OOMs on the information_schema join)+ # must degrade to empty foreign keys, not take down the whole schema listing.+ discovered = {+ "public.users": PostgresDiscoveredSchema(+ source_catalog=None,+ source_schema="public",+ source_table_name="users",+ columns=[("id", "integer", False)],+ )+ }++ tunnel_cm = mock.MagicMock()+ tunnel_cm.__enter__.return_value = ("localhost", 5432)+ tunnel_cm.__exit__.return_value = None++ with (+ mock.patch.object(source, "with_ssh_tunnel", return_value=tunnel_cm),+ mock.patch(+ "posthog.temporal.data_imports.sources.postgres.source.get_postgres_schemas",+ return_value=discovered,+ ),+ mock.patch(+ "posthog.temporal.data_imports.sources.postgres.source.get_postgres_foreign_keys",+ side_effect=exc,+ ),+ # PK/index discovery opens its own connection; let it fail so the test needs no real DB.+ # That path is already guarded and defaults gracefully.+ mock.patch(+ "posthog.temporal.data_imports.sources.postgres.source.pg_connection",+ side_effect=psycopg.OperationalError("no db in test"),+ ),+ ):+ schemas = source.get_schemas(self._config(), team_id=1)++ assert len(schemas) == 1+ assert schemas[0].name == "public.users"+ assert schemas[0].foreign_keys == []++class TestGetSslmode:@pytest.mark.parametrize("require_ssl,expected",