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): recover from Supavisor pooler DbHandler drop during setup (#64071)

Tom Owers02c882dac63a
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index d08677881166..f95a1e4a8ebc 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -83,6 +83,11 @@ SYNC_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins
# sustained and surfaced as the non-retryable "successive SerializationFailure errors" abort.
_MAX_SETUP_RECOVERY_CONFLICT_RETRIES = 10
+# Bounded in-process retries for a transient connection drop hit *during* the setup metadata
+# probes (not just the initial connect). Mirrors `_connect_with_dropped_retry`'s default; past
+# this the drop is treated as sustained and re-raised for Temporal to retry the whole activity.
+_MAX_SETUP_CONNECTION_DROPPED_RETRIES = 5
+
def source_requires_ssl(source: ExternalDataSource, source_config: Any = None) -> bool:
"""Return whether this source must connect over SSL/TLS.
@@ -134,17 +139,30 @@ _CONNECTION_DROPPED_ERROR_SUBSTRINGS = (
"terminating connection due to",
)
+# Supavisor (Supabase's connection pooler) doesn't surface a dropped upstream connection with a
+# libpq/PgBouncer signature — it raises its own pooler-internal error as a generic psycopg
+# InternalError_ (SQLSTATE XX000) with the message "(EDBHANDLEREXITED) DbHandler exited. Check
+# logs for more information". The pooler's per-session DbHandler process exits when its backend
+# connection dies (idle cull, backend restart, failover), so it's the same transient class as the
+# libpq drops above and recovers on reconnect. Matched narrowly by the stable "DbHandler exited"
+# text — the surrounding "(EDBHANDLEREXITED)" code and trailing "Check logs..." vary and are
+# excluded — so genuine XX000 internal errors (data corruption, etc.) stay non-recoverable.
+_POOLER_CONNECTION_DROPPED_ERROR_SUBSTRINGS = ("dbhandler exited",)
+
# Exception types that can carry a connection-dropped error. ProtocolViolation is
# PgBouncer's synthetic error packet; OperationalError is libpq detecting the dead
# socket. IdleInTransactionSessionTimeout (SQLSTATE 25P03) is what Postgres raises
# when the source's idle_in_transaction_session_timeout culls our backend while a
# server-side cursor holds a transaction open across the slow delta-merge between
# yields — psycopg maps it to InternalError, not OperationalError, so it must be
-# named explicitly or the type-based catch below would miss it.
+# named explicitly or the type-based catch below would miss it. InternalError_ is the
+# generic XX000 class Supavisor's "DbHandler exited" pooler drop arrives as; it's only
+# treated as a drop when its message matches the narrow pooler signature above.
_CONNECTION_DROPPED_ERROR_TYPES = (
psycopg.errors.ProtocolViolation,
psycopg.OperationalError,
psycopg.errors.IdleInTransactionSessionTimeout,
+ psycopg.errors.InternalError_,
)
@@ -180,6 +198,11 @@ def _is_connection_dropped_error(error: BaseException) -> bool:
if isinstance(error, psycopg.errors.ProtocolViolation | psycopg.OperationalError):
message = " ".join(str(arg) for arg in error.args).lower()
return any(substring in message for substring in _CONNECTION_DROPPED_ERROR_SUBSTRINGS)
+ # Supavisor's pooler drop arrives as a generic XX000 InternalError_, not the libpq/PgBouncer
+ # types above, so match it on its own narrow signature (see _POOLER_CONNECTION_DROPPED_*).
+ if isinstance(error, psycopg.errors.InternalError_):
+ message = " ".join(str(arg) for arg in error.args).lower()
+ return any(substring in message for substring in _POOLER_CONNECTION_DROPPED_ERROR_SUBSTRINGS)
return False
@@ -2081,6 +2104,7 @@ def postgres_source(
# "successive SerializationFailure errors" abort the read path already uses, rather than
# letting Temporal re-run setup straight back into the same wall.
setup_recovery_conflicts = 0
+ setup_connection_dropped_errors = 0
while True:
# Opening the setup connection can itself hit a transient drop ("server closed the
# connection unexpectedly", idle cull, failover) — the same class of error the read
@@ -2300,6 +2324,26 @@ def postgres_source(
f"(attempt {setup_recovery_conflicts}/{_MAX_SETUP_RECOVERY_CONFLICT_RETRIES})"
)
time.sleep(min(2 * setup_recovery_conflicts, 30))
+ except _CONNECTION_DROPPED_ERROR_TYPES as e:
+ # A transient drop *during* the metadata probes (e.g. a Supavisor pooler "DbHandler
+ # exited" or a libpq "server closed the connection unexpectedly" while running
+ # `_get_table`) leaves the connection dead. `_connect_with_dropped_retry` only guards
+ # the initial connect, so without this the probe-time drop escapes and fails the
+ # whole activity. Reconnect and retry the probes in-process with bounded backoff,
+ # mirroring the recovery-conflict handler above and the read path's offset-chunking
+ # recovery. Permanent errors (auth failures, SSL-required, genuine XX000 internal
+ # errors) aren't connection drops, so they re-raise immediately.
+ if not _is_connection_dropped_error(e):
+ raise
+ _safe_close_connection(connection)
+ setup_connection_dropped_errors += 1
+ if setup_connection_dropped_errors >= _MAX_SETUP_CONNECTION_DROPPED_RETRIES:
+ raise
+ logger.debug(
+ f"Connection dropped during table setup ({e}). Reconnecting and retrying "
+ f"(attempt {setup_connection_dropped_errors}/{_MAX_SETUP_CONNECTION_DROPPED_RETRIES})"
+ )
+ time.sleep(min(2 * setup_connection_dropped_errors, 30))
def get_rows(chunk_size: int) -> Iterator[Any]:
arrow_schema = table.to_arrow_schema()
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 21b85cbc07cc..5989a08505e4 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -39,6 +39,7 @@ from posthog.temporal.data_imports.sources.postgres.partitioned_tables import (
should_preserve_asc_sort,
)
from posthog.temporal.data_imports.sources.postgres.postgres import (
+ _MAX_SETUP_CONNECTION_DROPPED_RETRIES,
_MAX_SETUP_RECOVERY_CONFLICT_RETRIES,
FORCE_UTF8_CLIENT_ENCODING,
SSL_REQUIRED_AFTER_DATE,
@@ -559,6 +560,41 @@ class TestPostgresSourceSetupRecoveryConflictRetry:
assert connect_mock.call_count == 1
+ def test_sustained_connection_drop_during_setup_probes_is_retried_then_reraised(self):
+ # A transient drop hit *during* the metadata probes — here Supavisor's pooler "DbHandler
+ # exited" (XX000 InternalError_) raised by `_get_table` — must reconnect and retry the
+ # probes in-process, not escape on the first failure. Once the drop is sustained the
+ # original error re-raises (Temporal then retries the whole activity).
+ err = psycopg.errors.InternalError_("(EDBHANDLEREXITED) DbHandler exited. Check logs for more information")
+ connection = self._make_failing_connection(err)
+
+ with patch(
+ "posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect",
+ return_value=connection,
+ ) as connect_mock:
+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"):
+ with pytest.raises(psycopg.errors.InternalError_):
+ self._call_postgres_source()
+
+ # Each retry reconnects, so connect is called once per attempt before giving up.
+ assert connect_mock.call_count == _MAX_SETUP_CONNECTION_DROPPED_RETRIES
+
+ def test_non_dropped_internal_error_during_setup_probes_is_not_retried(self):
+ # A genuine XX000 internal error that isn't the pooler drop is not a connection drop, so it
+ # must propagate on the first probe instead of being retried by the dropped-connection handler.
+ err = psycopg.errors.InternalError_("XX000: internal error: something went wrong")
+ connection = self._make_failing_connection(err)
+
+ with patch(
+ "posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect",
+ return_value=connection,
+ ) as connect_mock:
+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"):
+ with pytest.raises(psycopg.errors.InternalError_):
+ self._call_postgres_source()
+
+ assert connect_mock.call_count == 1
+
class TestIsConnectionDroppedError:
@pytest.mark.parametrize(
@@ -576,6 +612,11 @@ class TestIsConnectionDroppedError:
# so it's detected by type alone — even with no message to match on.
psycopg.errors.IdleInTransactionSessionTimeout("terminating connection due to idle-in-transaction timeout"),
psycopg.errors.IdleInTransactionSessionTimeout(),
+ # Supavisor (Supabase's connection pooler) tears down a session whose backend connection
+ # died and surfaces it as a generic XX000 InternalError_ — a transient drop, not a libpq
+ # signature, so it's matched on the pooler's own "DbHandler exited" text.
+ psycopg.errors.InternalError_("(EDBHANDLEREXITED) DbHandler exited. Check logs for more information"),
+ psycopg.errors.InternalError_("(EDBHANDLEREXITED) DBHANDLER EXITED. Check logs for more information"),
],
)
def test_connection_dropped_errors_are_detected(self, error):
@@ -595,6 +636,9 @@ class TestIsConnectionDroppedError:
psycopg.errors.UniqueViolation("duplicate key value violates unique constraint"),
ValueError("server conn crashed?"),
Exception("server conn crashed?"),
+ # A genuine XX000 internal error that isn't the Supavisor pooler drop must stay
+ # non-recoverable — the InternalError_ match is scoped to the "DbHandler exited" text.
+ psycopg.errors.InternalError_("XX000: internal error: something went wrong"),
],
)
def test_unrelated_errors_are_not_detected(self, error):