: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): recover from mid-window connection drops in-process (#66934)
Tom Owersfd1e13b46fa3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.pyindex f2b43990b568..bca6793a10dd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py@@ -37,6 +37,10 @@ from products.warehouse_sources.backend.types import IncrementalFieldType, Parti# how to handle it (e.g. retry the whole sync at a higher level).WINDOW_MAX_QUERY_CANCELED_RETRIES = 3WINDOW_MAX_SERIALIZATION_RETRIES = 5+# Mirrors the server-cursor read path's successive-connection-error abort: a transient+# mid-stream drop is retried in-process (reconnect + replay the window) up to this many+# times before giving up and re-raising so the activity can restart from scratch.+WINDOW_MAX_CONNECTION_DROP_RETRIES = 10_RANGE_BOUND_RE = re.compile(r"FOR VALUES FROM \((.*)\) TO \((.*)\)", re.DOTALL)@@ -368,6 +372,7 @@ def iterate_date_windows(max_window_multiplier: int = 30,min_window_divisor: int = 10,using_read_replica: bool = False,+ is_connection_dropped: Callable[[BaseException], bool] = lambda _e: False,clock: Callable[[], float] = time.monotonic,sleeper: Callable[[float], None] = time.sleep,) -> Iterator[pa.Table]:@@ -413,6 +418,7 @@ def iterate_date_windows(empty_streak = 0qc_retries = 0sf_retries = 0+ cd_retries = 0windows_run = 0start = clock()@@ -466,12 +472,31 @@ def iterate_date_windows()sleeper(2 * sf_retries)continue+ except psycopg.Error as e:+ # A mid-stream connection drop (idle cull, failover, pooler/SSL EOF) surfaces here as a+ # ProtocolViolation/OperationalError ("server conn crashed?"). It's transient and recovers+ # on a fresh connection — the same class the server-cursor read path resumes in-process —+ # so reconnect and replay the window instead of letting it escape and fail the whole+ # activity. Only safe before any chunk of this window has been yielded; once a chunk is out,+ # replaying the window would duplicate it, so re-raise and let the sync restart.+ if not is_connection_dropped(e) or rows_this_window > 0:+ raise+ cd_retries += 1+ if cd_retries > WINDOW_MAX_CONNECTION_DROP_RETRIES:+ logger.exception(f"iterate_date_windows: exhausted connection-drop retries at lo={lo} hi={hi}")+ raise+ logger.warning(+ f"iterate_date_windows: connection dropped at lo={lo} hi={hi} (retry {cd_retries}), reconnecting"+ )+ sleeper(min(2 * cd_retries, 30))+ continueelapsed = clock() - w_starttotal_rows += rows_this_windowwindows_run += 1qc_retries = 0sf_retries = 0+ cd_retries = 0logger.info(f"iterate_date_windows: window {lo}..{hi} done: {rows_this_window} rows in {elapsed:.1f}s (window={window})")@@ -662,6 +687,7 @@ def is_supported_incremental_type_for_window(field_type: Optional[IncrementalFie__all__ = [+ "WINDOW_MAX_CONNECTION_DROP_RETRIES","WINDOW_MAX_QUERY_CANCELED_RETRIES","WINDOW_MAX_SERIALIZATION_RETRIES","ChildPartition",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex 4f54a2c2e7f6..ffad50eb00fb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -3208,6 +3208,7 @@ def postgres_source(arrow_schema=arrow_schema,logger=logger,using_read_replica=using_read_replica,+ is_connection_dropped=_is_connection_dropped_error,)returndiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.pyindex 65f3251405d9..b74b773b6c9c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.eXminUnsupportedError,)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.partitioned_tables import (+ WINDOW_MAX_CONNECTION_DROP_RETRIES,WINDOW_MAX_QUERY_CANCELED_RETRIES,WINDOW_MAX_SERIALIZATION_RETRIES,ChildPartition,@@ -5266,6 +5267,9 @@ class _FakeCursor:Each invocation of iterate_date_windows opens a fresh cursor; `script` is alist of per-cursor behaviors. A behavior is one of:- list[tuple] → rows returned from fetchmany, then []+ - list whose last element is an Exception → those rows are returned from+ fetchmany, then the exception is raised on the next fetch (models a drop+ mid-stream, after some chunks have already been yielded)- Exception instance → raised from execute()"""@@ -5276,19 +5280,25 @@ class _FakeCursor:self.description[0].name = "id"self.description[1].name = "val"self._rows_remaining: list = []+ self._fetch_error: Exception | None = Noneself._executed = Falsedef execute(self, query):self.owner.executed_queries.append(query)if isinstance(self.behaviour, Exception):raise self.behaviour- self._rows_remaining = list(self.behaviour)+ rows = list(self.behaviour)+ if rows and isinstance(rows[-1], Exception):+ self._fetch_error = rows.pop()+ self._rows_remaining = rowsself._executed = Truedef fetchmany(self, n: int):if not self._executed:return []batch, self._rows_remaining = self._rows_remaining[:n], self._rows_remaining[n:]+ if not batch and self._fetch_error is not None:+ raise self._fetch_errorreturn batchdef __enter__(self):@@ -5518,6 +5528,57 @@ class TestIterateDateWindowsFake:))+ def test_reconnects_and_retries_window_on_connection_drop_before_rows(self):+ # A mid-stream drop on the windowed read path used to escape uncaught and fail the whole+ # activity (ProtocolViolation "server conn crashed?"). When it fires before any chunk of the+ # window is yielded, replaying the window is safe, so the walker reconnects and resumes.+ child = ChildPartition(+ oid=1,+ schema="public",+ name="p",+ partbound="FOR VALUES FROM ('2026-01-01') TO ('2026-01-02')",+ )+ script = [psycopg.errors.ProtocolViolation("server conn crashed?"), [(1, 10)], [], []]+ tables, factory = _run_windows(+ script=script,+ child_partitions=[child],+ is_connection_dropped=_is_connection_dropped_error,+ )+ assert factory.connections_opened >= 2+ assert sum(t.num_rows for t in tables) == 1++ def test_reraises_connection_drop_after_rows_yielded(self):+ # Once a chunk of the window is out, replaying it would duplicate rows — so a drop mid-window+ # must propagate rather than retry.+ child = ChildPartition(+ oid=1,+ schema="public",+ name="p",+ partbound="FOR VALUES FROM ('2026-01-01') TO ('2026-01-02')",+ )+ script = [[(1, 10), psycopg.errors.ProtocolViolation("server conn crashed?")]]+ with pytest.raises(psycopg.errors.ProtocolViolation):+ _run_windows(+ script=script,+ child_partitions=[child],+ is_connection_dropped=_is_connection_dropped_error,+ )++ def test_raises_after_max_connection_drop_retries(self):+ child = ChildPartition(+ oid=1,+ schema="public",+ name="p",+ partbound="FOR VALUES FROM ('2026-01-01') TO ('2026-01-02')",+ )+ script = [psycopg.errors.ProtocolViolation("server conn crashed?")] * (WINDOW_MAX_CONNECTION_DROP_RETRIES + 2)+ with pytest.raises(psycopg.errors.ProtocolViolation):+ _run_windows(+ script=script,+ child_partitions=[child],+ is_connection_dropped=_is_connection_dropped_error,+ )+def test_does_not_set_per_window_statement_timeout(self):"""Critical: this is the user's explicit requirement — no tightened timeout."""child = ChildPartition(