: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): stop retrying a schema discovery catalog scan that hits statement timeout (#80287)
Tom Owers02ba0fd50774
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex 32e453b6825d..f402abd3d702 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -626,6 +626,25 @@ def _raised_while_closing_generator(error: BaseException) -> bool:return False+def _schema_discovery_timeout_error() -> QueryTimeoutException:+ """Build the timeout error for the schema discovery catalog scan in `_schemas_from_conn`.++ That function already raises `statement_timeout` to `METADATA_STATEMENT_TIMEOUT_MS` before this+ query, so hitting it here means the catalog has enough tables/columns in scope that enumerating+ them can't finish even under the generous timeout — a fixed cost of the schema's size, not+ something a retry against the same schema fixes. Narrowing the source's `schema` field, or the+ tables selected for sync, is the customer's lever. Distinct wording from+ `_statement_timeout_as_non_retryable`'s incremental-field message, which doesn't apply here —+ this query scans every table in scope, not one column.+ """+ return QueryTimeoutException(+ "Timed out listing table columns while discovering the database schema. There are enough "+ "tables in scope that PostHog could not enumerate their columns within the timeout. Narrow "+ "the schema selected for this source, or reduce the number of tables synced, then re-enable "+ "the sync."+ )++def _pk_uniqueness_probe_timeout_error() -> QueryTimeoutException:"""Build the timeout error for the fallback `id` primary-key uniqueness probe.@@ -1400,39 +1419,49 @@ def _schemas_from_conn()schema_placeholders, schema_params = _build_named_value_placeholders("schema", source_schemas)- cursor.execute(- f"""- SELECT * FROM (- SELECT- table_schema,- table_name,- column_name,- data_type,- is_nullable,- ordinal_position- FROM information_schema.columns- WHERE table_schema IN ({schema_placeholders})- UNION ALL- SELECT- n.nspname AS table_schema,- c.relname AS table_name,- a.attname AS column_name,- pg_catalog.format_type(a.atttypid, a.atttypmod) AS data_type,- CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable,- a.attnum AS ordinal_position- FROM pg_class c- JOIN pg_namespace n ON c.relnamespace = n.oid- JOIN pg_attribute a ON a.attrelid = c.oid- WHERE c.relkind = 'm'- AND n.nspname IN ({schema_placeholders})- AND a.attnum > 0- AND NOT a.attisdropped- ) t- ORDER BY table_schema ASC, table_name ASC, ordinal_position ASC- """,- schema_params,- )- result = cursor.fetchall()+ try:+ cursor.execute(+ f"""+ SELECT * FROM (+ SELECT+ table_schema,+ table_name,+ column_name,+ data_type,+ is_nullable,+ ordinal_position+ FROM information_schema.columns+ WHERE table_schema IN ({schema_placeholders})+ UNION ALL+ SELECT+ n.nspname AS table_schema,+ c.relname AS table_name,+ a.attname AS column_name,+ pg_catalog.format_type(a.atttypid, a.atttypmod) AS data_type,+ CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable,+ a.attnum AS ordinal_position+ FROM pg_class c+ JOIN pg_namespace n ON c.relnamespace = n.oid+ JOIN pg_attribute a ON a.attrelid = c.oid+ WHERE c.relkind = 'm'+ AND n.nspname IN ({schema_placeholders})+ AND a.attnum > 0+ AND NOT a.attisdropped+ ) t+ ORDER BY table_schema ASC, table_name ASC, ordinal_position ASC+ """,+ schema_params,+ )+ result = cursor.fetchall()+ except psycopg.errors.QueryCanceled as e:+ # QueryCanceled also covers a hot-standby recovery conflict mid-scan ("conflict with+ # recovery"), which `get_schemas`'s outer `_retry_on_connection_dropped` already retries+ # via `_is_recovery_conflict_error` — that one is transient and must keep propagating+ # unconverted. Only a genuine statement_timeout means the catalog is too big to enumerate+ # in time, where retrying re-runs the same futile scan against the same schema.+ if "statement timeout" not in " ".join(str(arg) for arg in e.args).lower():+ raise+ raise _schema_discovery_timeout_error() from ecolumns_by_table: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)discovered_pairs_by_schema_and_table = {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex d8c9da2fc109..9e2cac3c4cba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -453,6 +453,11 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa# retry budget re-running the same futile statement-timeout query before the workflow gives# up. Match the index-guidance fragment every postgres statement-timeout message shares."has an appropriate index": None,+ # Activity-layer twin for `_schema_discovery_timeout_error` (schema discovery's own+ # statement-timeout classification, distinct from the incremental-field message above).+ # Same reasoning: match the raw `str(e)` fragment so the activity-level check recognises+ # it too, instead of burning the retry budget re-scanning the same oversized catalog.+ "listing table columns while discovering the database schema": None,"TemporaryFileSizeExceedsLimitException": None,"Name or service not known": None,# Sibling getaddrinfo failure to "Name or service not known" (EAI_NONAME): EAI_NODATAdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.pyindex 938e4b6a2790..ebf08cf37888 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py@@ -108,6 +108,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p_rls_active_from_conn,_role_subject_to_rls,_safe_close_connection,+ _schema_discovery_timeout_error,_schemas_from_conn,_statement_timeout_as_non_retryable,_tunnel_with_handshake_translation,@@ -879,6 +880,22 @@ class TestPostgresSourceNonRetryableErrors:is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())assert is_non_retryable, f"Read-replica timeout error should be non-retryable: {error_msg}"+ @pytest.mark.parametrize(+ "error_msg",+ [+ # Raw activity-level message (what `sync_new_schemas_activity` sees via str(e)) — no+ # class name. Raised by `_schemas_from_conn` when the column-listing catalog scan+ # itself exhausts the raised METADATA_STATEMENT_TIMEOUT_MS.+ str(_schema_discovery_timeout_error()),+ # Temporal-wrapped message (what the workflow-level check sees) — carries the class name.+ f"QueryTimeoutException: {_schema_discovery_timeout_error()}",+ ],+ )+ def test_schema_discovery_catalog_timeout_is_non_retryable(self, source, error_msg):+ non_retryable = source.get_non_retryable_errors()+ is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())+ assert is_non_retryable, f"Schema discovery catalog timeout should be non-retryable: {error_msg}"+@pytest.mark.parametrize("error_msg",[@@ -6090,6 +6107,49 @@ class TestGetTable:column_query_idx = next(i for i, q in enumerate(conn.executed) if "information_schema.columns" in q)assert set_timeout_idx < column_query_idx+ @pytest.mark.django_db+ def test_schemas_from_conn_catalog_scan_timeout_is_non_retryable(self):+ # A catalog wide enough that the column-listing query itself exhausts the raised+ # METADATA_STATEMENT_TIMEOUT_MS: retrying re-runs the same futile scan, so it must be+ # converted to the non-retryable QueryTimeoutException instead of the raw, retried QueryCanceled.+ cursor = MagicMock()+ cursor.execute.side_effect = [+ None, # SET statement_timeout+ psycopg.errors.QueryCanceled("canceling statement due to statement timeout"), # catalog scan+ ]+ connection = MagicMock()+ connection.cursor.return_value.__enter__.return_value = cursor++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres._get_discovered_tables",+ return_value=({"big_table": (None, "public", "big_table")}, False),+ ):+ with pytest.raises(QueryTimeoutException) as exc_info:+ _schemas_from_conn(cast(Any, connection), "public", None)++ assert str(exc_info.value) == str(_schema_discovery_timeout_error())++ @pytest.mark.django_db+ def test_schemas_from_conn_recovery_conflict_stays_retryable(self):+ # A hot-standby recovery conflict during the catalog scan is also a QueryCanceled, but it's+ # transient and already retried by `get_schemas`'s outer `_retry_on_connection_dropped` (via+ # `_is_recovery_conflict_error`). It must propagate unconverted, not get mapped to the+ # non-retryable timeout error meant for a genuinely oversized catalog.+ cursor = MagicMock()+ cursor.execute.side_effect = [+ None, # SET statement_timeout+ psycopg.errors.QueryCanceled("canceling statement due to conflict with recovery"),+ ]+ connection = MagicMock()+ connection.cursor.return_value.__enter__.return_value = cursor++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres._get_discovered_tables",+ return_value=({"big_table": (None, "public", "big_table")}, False),+ ):+ with pytest.raises(psycopg.errors.QueryCanceled, match="conflict with recovery"):+ _schemas_from_conn(cast(Any, connection), "public", None)+@pytest.mark.django_dbdef test_regular_table(self):logger = structlog.get_logger()