Skip to content

: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.

fix(postgres): surface dropped connection during metadata discovery instead of masked commit error (#63810)

Tom Owersf50c30cf5523
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 8756d24cfce3..d08677881166 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -183,6 +183,26 @@ def _is_connection_dropped_error(error: BaseException) -> bool:
return False
+def _raise_if_setup_connection_broken(connection: psycopg.Connection) -> None:
+ """Surface a connection dropped during metadata discovery as a retryable error.
+
+ The best-effort probes run during `postgres_source` setup (`_explain_query`,
+ `_get_table_chunk_size`, and the numeric-scale probe in `_get_table`) isolate their
+ queries in `connection.transaction(savepoint_name=...)`. When the upstream
+ connection drops mid-probe, psycopg's `Transaction.__exit__` skips its savepoint
+ teardown — it early-returns whenever the connection is no longer OK — leaving the
+ connection's transaction-nesting counter incremented. The surrounding helpers then
+ swallow the follow-up "connection closed" errors, so discovery finishes "successfully"
+ and the implicit commit in the enclosing `with connection:` raises a misleading
+ `ProgrammingError: Explicit commit() forbidden within a Transaction context`, burying
+ the real cause. Detect the broken connection first and raise the actual
+ dropped-connection error (transient, so it stays retryable) — the activity then retries
+ on a fresh connection instead of failing on a self-inflicted commit error.
+ """
+ if connection.broken:
+ raise psycopg.OperationalError("connection to server was lost during table metadata discovery")
+
+
def _connect_with_dropped_retry(
connect: Callable[[], psycopg.Connection],
logger: FilteringBoundLogger,
@@ -2256,6 +2276,14 @@ def postgres_source(
raise
except Exception:
raise
+
+ # If a transient drop killed the connection during one of the best-effort
+ # savepoint probes above, the implicit commit on `with connection:` exit would
+ # otherwise raise a misleading "Explicit commit() forbidden within a Transaction
+ # context" (psycopg leaves the transaction-nesting counter incremented when it
+ # tears a savepoint down on a no-longer-OK connection). Surface the real,
+ # retryable dropped-connection error instead.
+ _raise_if_setup_connection_broken(connection)
break
except psycopg.errors.SerializationFailure as e:
if "conflict with recovery" not in "".join(e.args):
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 6d6a4126bd73..c28ae28ccbd6 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -72,6 +72,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (
_is_read_replica,
_is_unsupported_function_error,
_normalize_function_names,
+ _raise_if_setup_connection_broken,
_rls_active_from_conn,
_role_subject_to_rls,
_statement_timeout_as_non_retryable,
@@ -569,6 +570,33 @@ class TestIsConnectionDroppedError:
assert _is_connection_dropped_error(error) is False
+class TestRaiseIfSetupConnectionBroken:
+ """A connection dropped mid-discovery must surface as a retryable error, not the masked
+ `ProgrammingError: Explicit commit() forbidden within a Transaction context` that psycopg's
+ implicit `with connection:` exit-commit raises when a savepoint teardown leaks the
+ transaction-nesting counter on a no-longer-OK connection."""
+
+ def test_broken_connection_raises_retryable_dropped_error(self):
+ connection = mock.MagicMock()
+ connection.broken = True
+
+ with pytest.raises(psycopg.OperationalError) as exc_info:
+ _raise_if_setup_connection_broken(cast(Any, connection))
+
+ # Classified as a transient drop, so the activity keeps retrying...
+ assert _is_connection_dropped_error(exc_info.value) is True
+ # ...and the message is not matched by any NonRetryableErrors substring.
+ message = str(exc_info.value)
+ assert not any(key in message for key in PostgresSource().get_non_retryable_errors())
+
+ def test_healthy_connection_is_a_noop(self):
+ connection = mock.MagicMock()
+ connection.broken = False
+
+ # A healthy connection must not raise.
+ _raise_if_setup_connection_broken(cast(Any, connection))
+
+
class TestConnectWithDroppedRetry:
@pytest.fixture
def logger(self):