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): retry transient drops when reconnecting in offset chunking (#63054)

Tom Owers139920686325
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 468e08f024e0..9b509e9787f9 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -145,6 +145,36 @@ def _is_connection_dropped_error(error: BaseException) -> bool:
return False
+def _connect_with_dropped_retry(
+ connect: Callable[[], psycopg.Connection],
+ logger: FilteringBoundLogger,
+ *,
+ max_attempts: int = 5,
+) -> psycopg.Connection:
+ """Open a connection via `connect`, retrying transient connection-dropped errors.
+
+ The streaming recovery path (offset chunking) is reached precisely because the
+ source just dropped our connection (idle cull, failover, mid-stream SSL EOF), so
+ the very reconnect that bootstraps the recovery can itself hit a still-recovering
+ source and fail with another connection-dropped error. Without this, that
+ transient failure escapes the recovery loop and fails the whole sync. Retry with
+ bounded backoff; permanent errors (auth failures, SSL-required) are re-raised
+ immediately because `_is_connection_dropped_error` only matches transient drops.
+ """
+ attempt = 0
+ while True:
+ try:
+ return connect()
+ except (psycopg.errors.ProtocolViolation, psycopg.OperationalError) as e:
+ if not _is_connection_dropped_error(e):
+ raise
+ attempt += 1
+ if attempt >= max_attempts:
+ raise
+ logger.debug(f"Connection attempt failed ({e}). Retrying (attempt {attempt}/{max_attempts})")
+ time.sleep(min(2 * attempt, 30))
+
+
@dataclasses.dataclass(frozen=True)
class PostgresDiscoveredSchema:
source_catalog: str | None
@@ -2019,7 +2049,7 @@ def postgres_source(
successive_errors = 0
successive_conn_errors = 0
- connection = get_connection()
+ connection = _connect_with_dropped_retry(get_connection, logger)
# Autocommit so each LIMIT/OFFSET query runs as its own statement
# and no transaction stays open across the slow delta-merge that
# happens between yields. A held transaction is what gets the
@@ -2095,7 +2125,7 @@ def postgres_source(
f"(attempt {successive_conn_errors})"
)
time.sleep(min(2 * successive_conn_errors, 30))
- connection = get_connection()
+ connection = _connect_with_dropped_retry(get_connection, logger)
connection.autocommit = True
except Exception:
_safe_close_connection(connection)
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index bbb4ac136628..9137a92b3787 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -45,6 +45,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (
SafeDateLoader,
_build_count_query,
_build_query,
+ _connect_with_dropped_retry,
_get_estimated_row_count_for_partitioned_table,
_get_partition_settings,
_get_partition_settings_for_partitioned_table,
@@ -235,6 +236,54 @@ class TestIsConnectionDroppedError:
assert _is_connection_dropped_error(error) is False
+class TestConnectWithDroppedRetry:
+ @pytest.fixture
+ def logger(self):
+ return structlog.get_logger()
+
+ def test_retries_dropped_connection_then_succeeds(self, logger):
+ good_conn = mock.MagicMock()
+ connect = mock.MagicMock(
+ side_effect=[
+ # The exact error surfaced in production: a mid-stream SSL EOF on
+ # the reconnect that bootstraps offset-chunking recovery.
+ psycopg.OperationalError("consuming input failed: SSL SYSCALL error: EOF detected"),
+ psycopg.OperationalError("server closed the connection unexpectedly"),
+ good_conn,
+ ]
+ )
+
+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"):
+ result = _connect_with_dropped_retry(connect, logger, max_attempts=5)
+
+ assert result is good_conn
+ assert connect.call_count == 3
+
+ def test_permanent_error_is_not_retried(self, logger):
+ connect = mock.MagicMock(
+ side_effect=psycopg.OperationalError(
+ 'connection to server at "10.0.0.1" failed: FATAL: password authentication failed'
+ )
+ )
+
+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"):
+ with pytest.raises(psycopg.OperationalError):
+ _connect_with_dropped_retry(connect, logger, max_attempts=5)
+
+ assert connect.call_count == 1
+
+ def test_gives_up_after_max_attempts(self, logger):
+ connect = mock.MagicMock(
+ side_effect=psycopg.OperationalError("consuming input failed: SSL SYSCALL error: EOF detected")
+ )
+
+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"):
+ with pytest.raises(psycopg.OperationalError):
+ _connect_with_dropped_retry(connect, logger, max_attempts=3)
+
+ assert connect.call_count == 3
+
+
class TestPostgresSourceForPipelineSchemaResolution:
@pytest.fixture
def source(self):