: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): scope statement_timeout for schema discovery query (#64291)
Tom Owers631232258598
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.pyindex 74f2b421ecc2..6adc99c98d01 100644--- a/posthog/temporal/data_imports/sources/postgres/postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py@@ -78,6 +78,15 @@ SYSTEM_POSTGRES_SCHEMAS = ["information_schema", "pg_catalog", "pg_toast"]# default statement_timeout on the source role.SYNC_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins+# Statement timeout scoped to the schema-discovery metadata query in `_get_table`.+# `information_schema.columns` computes `numeric_precision`/`numeric_scale` via the per-column+# `_pg_numeric_*` SQL functions, which can be slow on large catalogs. The setup connection has no+# statement_timeout we control until `postgres_source` sets one *after* `_get_table` returns, so+# the query would otherwise inherit whatever (possibly very short) default the source role/server+# imposes and get cancelled mid-discovery. Scope a generous-but-bounded budget so a too-short+# default can't kill it.+METADATA_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins+# How many times the metadata-gathering phase reconnects and retries when a hot-standby# recovery conflict terminates the setup connection. Past this the conflict is treated as# sustained and surfaced as the non-retryable "successive SerializationFailure errors" abort.@@ -1880,10 +1889,25 @@ def _get_table(_explain_query(cursor, query, logger)logger.debug(f"Running query: {query.as_string()}")- cursor.execute(query)+ # Scope a generous statement_timeout to the schema-discovery query. On regular tables it reads+ # `information_schema.columns`, whose `numeric_precision`/`numeric_scale` columns invoke the+ # per-column `_pg_numeric_*` SQL functions — slow enough on large catalogs that a short+ # role/server default `statement_timeout` (some hosted/pooled Postgres set one) cancels the+ # query with QueryCanceled before discovery finishes. The outer 10-minute setup timeout isn't+ # set until `postgres_source` continues after `_get_table` returns, so without this the query+ # inherits that short default. Own transaction so the `SET LOCAL` scopes to this query and+ # auto-resets (the connection is autocommit, so this is a self-contained BEGIN/COMMIT) without+ # leaking onto the numeric probe below, which deliberately bounds itself tighter.+ with cursor.connection.transaction():+ cursor.execute(+ sql.SQL("SET LOCAL statement_timeout = {timeout}").format(+ timeout=sql.Literal(METADATA_STATEMENT_TIMEOUT_MS)+ )+ )+ cursor.execute(query)+ metadata_rows = cursor.fetchall()numeric_data_types = {"numeric", "decimal"}- metadata_rows = cursor.fetchall()# For unconstrained numeric columns (declared as `numeric` with no precision/scale),# postgres returns NULL for numeric_precision/numeric_scale in information_schema. Fallingdiff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex 09826685e923..5a9e441dba37 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -42,6 +42,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (_MAX_SETUP_CONNECTION_DROPPED_RETRIES,_MAX_SETUP_RECOVERY_CONFLICT_RETRIES,FORCE_UTF8_CLIENT_ENCODING,+ METADATA_STATEMENT_TIMEOUT_MS,SSL_REQUIRED_AFTER_DATE,JsonAsStringLoader,PostgresDiscoveredSchema,@@ -2823,7 +2824,55 @@ class TestIsReadReplica:assert result is False+class _RecordingCursor:+ """Wraps a real cursor, recording executed SQL as text while delegating everything else."""++ def __init__(self, inner: Any):+ self._inner = inner+ self.executed: list[str] = []++ def execute(self, query: Any, *args: Any, **kwargs: Any) -> Any:+ try:+ self.executed.append(query.as_string())+ except Exception:+ self.executed.append(str(query))+ return self._inner.execute(query, *args, **kwargs)++ def __getattr__(self, name: str) -> Any:+ return getattr(self._inner, name)++class TestGetTable:+ @pytest.mark.django_db+ def test_schema_discovery_query_runs_under_scoped_statement_timeout(self):+ """The `information_schema.columns` metadata query is wrapped in its own transaction that+ first issues a `SET LOCAL statement_timeout`, so a short role/server default can't cancel+ it mid-discovery — the QueryCanceled on `_pg_numeric_scale` we observed against pooled+ Postgres. Pin that the timeout is scoped immediately before the query it protects."""+ logger = structlog.get_logger()++ with django_connection.cursor() as dj_cursor:+ dj_cursor.execute(+ "CREATE TABLE test_get_table_timeout_scope (id INTEGER PRIMARY KEY, amount NUMERIC(10, 2))"+ )+ spy = _RecordingCursor(dj_cursor)+ table = _get_table(cast(Any, spy), "public", "test_get_table_timeout_scope", logger)++ # Real execution still succeeds and returns the expected columns.+ assert {c.name for c in table.columns} >= {"id", "amount"}++ set_local_idx = next(+ i+ for i, q in enumerate(spy.executed)+ if "SET LOCAL" in q and "statement_timeout" in q and str(METADATA_STATEMENT_TIMEOUT_MS) in q+ )+ # The metadata SELECT (not the best-effort EXPLAIN that precedes it) must run directly+ # after the SET LOCAL, inside the same transaction.+ info_schema_idx = next(+ i for i, q in enumerate(spy.executed) if "information_schema.columns" in q and "EXPLAIN" not in q+ )+ assert info_schema_idx == set_local_idx + 1+@pytest.mark.django_dbdef test_regular_table(self):logger = structlog.get_logger()