: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(data-warehouse): isolate postgres schema-discovery probes with autocommit (#63630)
Daniel RC0a59d23212b8
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.pyindex 0dcf58efc5be..225b7440d7ab 100644--- a/posthog/temporal/data_imports/sources/postgres/postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py@@ -1132,12 +1132,11 @@ def _explain_query(cursor: psycopg.Cursor, query: sql.Composed, logger: Filterinlogger.debug(f"Running EXPLAIN on {query.as_string()}")try:- # Debug-only and best-effort: a query may use syntax the source DB rejects (e.g.- # TABLESAMPLE on CockroachDB). Savepoint so a failure doesn't poison the transaction.- with cursor.connection.transaction(savepoint_name="explain_query"):- query_with_explain = sql.SQL("EXPLAIN {}").format(query)- cursor.execute(query_with_explain)- rows = cursor.fetchall()+ # Debug-only, best-effort: EXPLAIN may use syntax the source rejects (e.g. TABLESAMPLE+ # on CockroachDB), so swallow failures.+ query_with_explain = sql.SQL("EXPLAIN {}").format(query)+ cursor.execute(query_with_explain)+ rows = cursor.fetchall()explain_result: str = ""# Build up a single string of the EXPLAIN outputfor row in rows:@@ -1283,13 +1282,11 @@ def _get_table_chunk_size(cursor: psycopg.Cursor, inner_query: sql.Composed, log) as subquery""").format(inner_query)- # Best-effort: the sampled query can fail (e.g. TABLESAMPLE on CockroachDB). Savepoint- # so a failure falls back to DEFAULT_CHUNK_SIZE without poisoning the transaction.- with cursor.connection.transaction(savepoint_name="table_chunk_size"):- _explain_query(cursor, query, logger)- logger.debug(f"Running query: {query.as_string()}")- cursor.execute(query)- row = cursor.fetchone()+ # Best-effort: the sampled query can fail (e.g. TABLESAMPLE on CockroachDB); fall back.+ _explain_query(cursor, query, logger)+ logger.debug(f"Running query: {query.as_string()}")+ cursor.execute(query)+ row = cursor.fetchone()if row is None:logger.debug(f"_get_table_chunk_size: No results returned. Using DEFAULT_CHUNK_SIZE={DEFAULT_CHUNK_SIZE}")@@ -1366,13 +1363,21 @@ def _get_rows_to_sync(cursor: psycopg.Cursor, count_query: sql.Composed, logger:def _get_partition_settings(- cursor: psycopg.Cursor, schema: str, table_name: str, logger: FilteringBoundLogger+ cursor: psycopg.Cursor,+ schema: str,+ table_name: str,+ logger: FilteringBoundLogger,+ *,+ is_partitioned: bool | None = None,) -> PartitionSettings | None:# For partitioned tables, a plain COUNT(*) and pg_table_size on the# parent would scan every child partition / return 0. Use catalog# estimates instead.try:- if _is_partitioned_table(cursor, schema, table_name):+ # Reuse the caller's partition flag when given; saves a redundant catalog round trip.+ if is_partitioned is None:+ is_partitioned = _is_partitioned_table(cursor, schema, table_name)+ if is_partitioned:return _get_partition_settings_for_partitioned_table(cursor, schema, table_name, logger)except Exception as e:logger.debug(f"_get_partition_settings: partition detection failed, falling back: {e}")@@ -1617,13 +1622,9 @@ def _get_table(# already materialized on disk and behave like tables here.if unconstrained_numeric_columns and probe_unconstrained_numeric_scale and not is_view:try:- # Isolate the probe in a savepoint so that any failure (permission denied, bad- # type, statement_timeout, network blip) rolls back cleanly without poisoning the- # enclosing metadata transaction. Without this, a probe error leaves the- # transaction in `INERROR` state and every subsequent query in `postgres_source`- # (SET LOCAL statement_timeout, _is_read_replica, _get_primary_keys, _get_rows_to_sync,- # ...) fails with `InFailedSqlTransaction: current transaction is aborted`.- with cursor.connection.transaction(savepoint_name="probe_numeric_scale"):+ # Own transaction so the 30s `SET LOCAL statement_timeout` below scopes to this+ # 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@@ -1804,6 +1805,11 @@ def postgres_source() from eraise+ # Autocommit so each best-effort probe is its own transaction: one that fails — a+ # read-replica recovery conflict on a slow COUNT(*), or syntax the source rejects like+ # TABLESAMPLE on CockroachDB — can't poison the rest. Replaces the per-probe savepoints.+ connection.autocommit = True+with connection:with connection.cursor() as cursor:logger.debug("Getting table types...")@@ -1822,8 +1828,9 @@ def postgres_source(probe_unconstrained_numeric_scale=fresh_schema_being_created,)+ # Session, not LOCAL: under autocommit a LOCAL timeout has no transaction to bind to.cursor.execute(- sql.SQL("SET LOCAL statement_timeout = {timeout}").format(+ sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(1000 * 60 * 10) # 10 mins))@@ -1934,7 +1941,7 @@ def postgres_source(logger.debug("Getting partition settings...")partition_settings = (- _get_partition_settings(cursor, schema, table_name, logger)+ _get_partition_settings(cursor, schema, table_name, logger, is_partitioned=is_partitioned)if should_use_incremental_fieldelse None)diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex fb4ff76823a7..e05ef64e751c 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -1326,41 +1326,73 @@ class TestIsPartitionedTable:assert _is_partitioned_table(cast(Any, dj_cursor), "public", table_name) is expected+def autocommit_pg_connection():+ # Raw autocommit connection to the test DB — mirrors how discovery connects in production+ # (no shared transaction). The default django_db cursor runs inside a transaction and can't+ # exercise the isolation path.+ sd = django_connection.settings_dict+ conn = psycopg.connect(+ host=sd["HOST"] or None,+ port=sd["PORT"] or None,+ dbname=sd["NAME"],+ user=sd["USER"] or None,+ password=sd["PASSWORD"] or None,+ autocommit=True,+ )+ try:+ yield conn+ finally:+ conn.close()++class TestGetTableChunkSize:@pytest.mark.django_db- def test_failing_probe_falls_back_without_poisoning_transaction(self):+ def test_failing_probe_isolated_by_autocommit(self, autocommit_pg_connection):+ # A failing probe falls back to DEFAULT_CHUNK_SIZE and, under autocommit, doesn't poison+ # the connection for later probes.logger = structlog.get_logger()-- with django_connection.cursor() as dj_cursor:+ with autocommit_pg_connection.cursor() as cursor:inner_query = sql.SQL("SELECT * FROM does_not_exist_chunk_probe").format()- chunk_size = _get_table_chunk_size(cast(Any, dj_cursor), inner_query, logger)+ chunk_size = _get_table_chunk_size(cast(Any, cursor), inner_query, logger)assert chunk_size == DEFAULT_CHUNK_SIZE- dj_cursor.execute("SELECT 1")- assert dj_cursor.fetchone()[0] == 1+ cursor.execute("SELECT 1")+ assert cursor.fetchone()[0] == 1class TestGetRowsToSync:+ # Mirrors a misconfigured incremental field: COUNT(*) over a column that doesn't exist.+ _FAILING_COUNT_QUERY = sql.SQL("SELECT COUNT(*) FROM {table} WHERE {col} > 0").format(+ table=sql.Identifier("information_schema", "tables"),+ col=sql.Identifier("does_not_exist_count_col"),+ )+@pytest.mark.django_dbdef test_failing_count_query_falls_back_to_zero_without_capturing(self):logger = structlog.get_logger()- # Count query references a column that doesn't exist — mirrors a misconfigured- # incremental field (e.g. djstripe_updated on a table that lacks it).- count_query = sql.SQL("SELECT COUNT(*) FROM {table} WHERE {col} > 0").format(- table=sql.Identifier("information_schema", "tables"),- col=sql.Identifier("does_not_exist_count_col"),- )-with django_connection.cursor() as dj_cursor:with patch("posthog.temporal.data_imports.sources.postgres.postgres.capture_exception") as mock_capture:- rows = _get_rows_to_sync(cast(Any, dj_cursor), count_query, logger)+ rows = _get_rows_to_sync(cast(Any, dj_cursor), self._FAILING_COUNT_QUERY, logger)# Best-effort estimate falls back to 0 and never reports the handled failure.assert rows == 0mock_capture.assert_not_called()+ @pytest.mark.django_db+ def test_failing_count_isolated_by_autocommit(self, autocommit_pg_connection):+ # Regression for the reported incident: a read-replica recovery conflict cancels the+ # rows-to-sync COUNT(*). Under autocommit the failure stays contained — returns 0 and+ # leaves the connection usable — instead of poisoning a shared transaction.+ logger = structlog.get_logger()+ with autocommit_pg_connection.cursor() as cursor:+ assert _get_rows_to_sync(cast(Any, cursor), self._FAILING_COUNT_QUERY, logger) == 0++ cursor.execute("SELECT 1")+ assert cursor.fetchone()[0] == 1+def test_temp_file_limit_error_still_raises(self):logger = structlog.get_logger()@@ -1627,6 +1659,25 @@ class TestGetPartitionSettings:assert result is not Noneassert result.partition_size > 0+ def test_reuses_passed_is_partitioned_flag(self):+ # When the caller already knows the table is partitioned, skip re-detecting it.+ logger = structlog.get_logger()+ cursor = mock.MagicMock()+ sentinel = object()++ with (+ patch("posthog.temporal.data_imports.sources.postgres.postgres._is_partitioned_table") as mock_detect,+ patch(+ "posthog.temporal.data_imports.sources.postgres.postgres._get_partition_settings_for_partitioned_table",+ return_value=sentinel,+ ) as mock_partitioned,+ ):+ result = _get_partition_settings(cast(Any, cursor), "public", "t", logger, is_partitioned=True)++ mock_detect.assert_not_called()+ mock_partitioned.assert_called_once()+ assert result is sentinel+class TestPostgreSQLColumnToArrowField:@pytest.mark.parametrize(