: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): raise statement_timeout before schema discovery probes (#65658)
Tom Owers1ec559279ba1
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.pyindex 2ef8cd73847b..2ec1f7bd5a16 100644--- a/posthog/temporal/data_imports/sources/postgres/postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py@@ -2149,6 +2149,23 @@ def _get_table(column already exists and the probed value is discarded, so the caller should gateprobing on "is a fresh schema being created" (see the equivalent gating on`_get_estimated_row_count_for_partitioned_table` in `postgres_source`)."""+ # Raise a generous statement_timeout for the whole discovery phase before issuing any query.+ # The outer 10-minute setup timeout isn't set until `postgres_source` continues after+ # `_get_table` returns, so without this every probe here — the `pg_matviews`/`pg_views` lookups,+ # the metadata SELECT (whose `information_schema.columns` `numeric_*` columns invoke the slow+ # per-column `_pg_numeric_*` functions), and even the `BEGIN` opening a scoping transaction —+ # inherits a short role/server default that some hosted/pooled Postgres set, which cancels the+ # statement with QueryCanceled mid-discovery. Session, not LOCAL: the connection is autocommit,+ # so a LOCAL timeout has nothing to bind to and a scoping transaction's own `BEGIN` would itself+ # run under the short default. Best-effort: engines without statement_timeout (e.g. DuckDB)+ # reject the SET, so clear any aborted transaction and fall back to the default.+ try:+ cursor.execute(+ sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(METADATA_STATEMENT_TIMEOUT_MS))+ )+ except psycopg.Error:+ cursor.connection.rollback()+is_mat_view_query = sql.SQL("select {table} in (select matviewname from pg_matviews where schemaname = {schema}) as res").format(schema=sql.Literal(schema), table=sql.Literal(table_name))@@ -2209,23 +2226,8 @@ def _get_table(_explain_query(cursor, query, logger)logger.debug(f"Running query: {query.as_string()}")- # 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()+ cursor.execute(query)+ metadata_rows = cursor.fetchall()numeric_data_types = {"numeric", "decimal"}@@ -2258,10 +2260,9 @@ def _get_table(# aggregation and auto-resets (a self-contained BEGIN/COMMIT under autocommit).with cursor.connection.transaction():# Scope a short statement_timeout to the probe so a pathologically large table- # or slow aggregation can't hang schema discovery. The outer 10-minute- # statement_timeout isn't set until `postgres_source` continues after- # `_get_table` returns, so without this the probe inherits whatever role-level- # default postgres has — which might be "no limit" on some hosted instances.+ # or slow aggregation can't hang schema discovery. Without this the probe would+ # inherit the generous discovery-phase timeout set at the top of `_get_table`,+ # which is deliberately too loose for a full-table aggregation.cursor.execute(sql.SQL("SET LOCAL statement_timeout = {timeout}").format(timeout=sql.Literal(30 * 1000) # 30 secondsdiff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex b4bd27ce66af..820621d61487 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -4173,12 +4173,23 @@ class _RecordingConnection:class TestGetTable:+ def teardown_method(self):+ # `_get_table` and `_schemas_from_conn` raise a session-level `statement_timeout` on the+ # connection (production opens and closes its own, so the GUC is discarded with it). Here+ # they run against the shared `django_connection`, which Postgres does not reset on+ # transaction rollback — reset it after every test so a raised timeout can't leak onto+ # later tests reusing the connection.+ with django_connection.cursor() as dj_cursor:+ dj_cursor.execute("RESET statement_timeout")+@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."""+ def test_schema_discovery_raises_statement_timeout_before_any_probe(self):+ """`_get_table` raises a generous session-level `statement_timeout` before issuing any+ discovery query, so a short role/server default can't cancel discovery with QueryCanceled.+ The protection must precede every probe — the `pg_matviews`/`pg_views` lookups and the+ transaction `BEGIN` that scopes the metadata query both ran under the inherited short+ default before, which canceled the statement against pooled Postgres. Pin that the timeout+ is the first statement issued, ahead of the metadata SELECT it ultimately protects."""logger = structlog.get_logger()with django_connection.cursor() as dj_cursor:@@ -4191,17 +4202,19 @@ class TestGetTable:# Real execution still succeeds and returns the expected columns.assert {c.name for c in table.columns} >= {"id", "amount"}- set_local_idx = next(+ set_timeout_idx = next(ifor i, q in enumerate(spy.executed)- if "SET LOCAL" in q and "statement_timeout" in q and str(METADATA_STATEMENT_TIMEOUT_MS) in q+ if "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.+ # The protective timeout must come before the first discovery probe (the+ # `pg_matviews` lookup) and the metadata SELECT — not midway through, where a+ # short default would already have canceled an earlier statement.+ first_probe_idx = next(i for i, q in enumerate(spy.executed) if "pg_matviews" in q)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+ assert set_timeout_idx < first_probe_idx < info_schema_idx@pytest.mark.django_dbdef test_schemas_from_conn_runs_under_scoped_statement_timeout(self):@@ -4213,15 +4226,7 @@ class TestGetTable:dj_cursor.execute("CREATE TABLE test_schemas_from_conn_timeout (id INTEGER PRIMARY KEY, name TEXT)")conn = _RecordingConnection(django_connection)- try:- discovered = _schemas_from_conn(cast(Any, conn), "public", ["test_schemas_from_conn_timeout"])- finally:- # `_schemas_from_conn` issues a session-level `SET statement_timeout` (production opens and- # closes its own connection, so the GUC is discarded with it). Here it runs against the shared- # `django_connection`, which Postgres does not reset on transaction rollback — clear it so the- # raised timeout can't leak onto subsequent tests reusing the connection.- with django_connection.cursor() as dj_cursor:- dj_cursor.execute("RESET statement_timeout")+ discovered = _schemas_from_conn(cast(Any, conn), "public", ["test_schemas_from_conn_timeout"])assert "test_schemas_from_conn_timeout" in discoveredassert {col[0] for col in discovered["test_schemas_from_conn_timeout"].columns} >= {"id", "name"}