: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): absorb transient slot-active during CDC WAL read (#68548)
Tom Owers866ff812dc24
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.pyindex 6865ea411e3a..347ba60dfffe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py@@ -37,6 +37,12 @@ logger = structlog.get_logger(__name__)_SLOT_ACTIVE_MARKER = "is active for pid"_SLOT_ADVANCE_MAX_ATTEMPTS = 3+# The first fetch of pg_logical_slot_peek_binary_changes acquires the replication slot, which+# Postgres rejects with SQLSTATE 55006 (ObjectInUse, "... is active for PID ...") while a prior+# run's connection is still releasing it. The slot frees on its own, so a short in-process retry+# absorbs the handoff instead of failing — and replaying — the whole extraction attempt.+_SLOT_READ_MAX_ATTEMPTS = 4+@dataclass(frozen=True, slots=True)class PgCDCConnectionParams:@@ -140,6 +146,7 @@ class PgCDCStreamReader:"""if self._conn is None:raise RuntimeError("Not connected. Call connect() first.")+ conn = self._connself._last_rows_consumed = 0upto = sql.Literal(upto_nchanges) if upto_nchanges is not None else sql.SQL("NULL")@@ -155,20 +162,37 @@ class PgCDCStreamReader:pub_name=sql.Literal(self._params.publication_name),)- with self._conn.cursor(name="cdc_stream") as cur:- cur.itersize = 1000- cur.execute(query)+ # The named cursor runs the peek lazily, so the slot is acquired on the first fetch — that+ # is where "... is active for PID ..." surfaces, before any event is yielded. Retry that+ # handoff in-process so a prior run's still-releasing connection can't fail the whole+ # attempt. Once a row lands the slot is ours, so never retry past that point; if it stays+ # held the error propagates to the retryable SLOT_IN_USE path.+ for attempt in range(_SLOT_READ_MAX_ATTEMPTS):+ slot_acquired = False+ try:+ with conn.cursor(name="cdc_stream") as cur:+ cur.itersize = 1000+ cur.execute(query)- for row in cur:- self._last_rows_consumed += 1- if on_row is not None:- on_row()+ for row in cur:+ slot_acquired = True+ self._last_rows_consumed += 1+ if on_row is not None:+ on_row()- lsn_str: str = row[0]- data: bytes = row[2]+ lsn_str: str = row[0]+ data: bytes = row[2]- events = self._decoder.decode_message(data, lsn_str)- yield from events+ events = self._decoder.decode_message(data, lsn_str)+ yield from events+ return+ except psycopg.errors.ObjectInUse as e:+ conn.rollback()+ if slot_acquired or _SLOT_ACTIVE_MARKER not in str(e).lower() or attempt == _SLOT_READ_MAX_ATTEMPTS - 1:+ raise+ self._last_rows_consumed = 0+ logger.warning("slot_read_busy_retry", slot_name=self._params.slot_name, attempt=attempt + 1)+ time.sleep(0.5 * 2**attempt)def confirm_position(self, position: str) -> None:"""Advance the replication slot to the given LSN.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.pyindex 2dac0e5f1030..ab0f3dcd5f79 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.py@@ -5,6 +5,7 @@ from unittest.mock import patchimport psycopgfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader import (+ _SLOT_READ_MAX_ATTEMPTS,PgCDCConnectionParams,PgCDCStreamReader,)@@ -166,6 +167,74 @@ class TestPgCDCStreamReaderReadChanges:assert reader.last_rows_consumed == len(rows)+class TestPgCDCStreamReaderReadChangesSlotInUse:+ def _reader_reading(self, params, iter_side_effect):+ reader = PgCDCStreamReader(params)+ fake_cursor = mock.MagicMock()+ fake_cursor.__iter__.side_effect = iter_side_effect+ reader._conn = mock.MagicMock()+ reader._conn.cursor.return_value.__enter__.return_value = fake_cursor+ # Isolate the read mechanics (retry + row count) from pgoutput decoding.+ reader._decoder = mock.MagicMock()+ reader._decoder.decode_message.return_value = []+ return reader, fake_cursor++ def test_read_changes_retries_slot_in_use_then_succeeds(self, params):+ # A prior run's connection is still releasing the slot on the first fetch; the next+ # attempt self-heals instead of failing the whole extraction.+ rows = [("0/1", 1, b"a"), ("0/2", 1, b"b")]+ reader, fake_cursor = self._reader_reading(+ params,+ [+ psycopg.errors.ObjectInUse('replication slot "posthog_slot" is active for PID 2999'),+ iter(rows),+ ],+ )+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader.time.sleep"+ ) as sleep:+ list(reader.read_changes(upto_nchanges=10))++ assert fake_cursor.__iter__.call_count == 2+ assert reader.last_rows_consumed == len(rows)+ # First backoff is 0.5 * 2**0 — asserting the value locks the multiplier.+ sleep.assert_called_once_with(0.5)+ reader._conn.rollback.assert_called_once()++ def test_read_changes_reraises_when_slot_stays_in_use(self, params):+ # A slot that never frees exhausts the in-process retries and re-raises, so the run still+ # surfaces as the retryable SLOT_IN_USE classification rather than looping or silently+ # returning no changes.+ reader, fake_cursor = self._reader_reading(+ params,+ psycopg.errors.ObjectInUse('replication slot "posthog_slot" is active for PID 2999'),+ )+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader.time.sleep"+ ) as sleep:+ with pytest.raises(psycopg.errors.ObjectInUse):+ list(reader.read_changes(upto_nchanges=10))++ assert fake_cursor.__iter__.call_count == _SLOT_READ_MAX_ATTEMPTS+ assert sleep.call_count == _SLOT_READ_MAX_ATTEMPTS - 1++ def test_read_changes_does_not_retry_unrelated_object_in_use(self, params):+ # A different SQLSTATE 55006 (not the transient slot handoff) is re-raised immediately,+ # never retried, so an unrelated failure isn't silently delayed.+ reader, fake_cursor = self._reader_reading(+ params,+ psycopg.errors.ObjectInUse("database is being accessed by other users"),+ )+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader.time.sleep"+ ) as sleep:+ with pytest.raises(psycopg.errors.ObjectInUse):+ list(reader.read_changes(upto_nchanges=10))++ assert fake_cursor.__iter__.call_count == 1+ sleep.assert_not_called()++class TestPgCDCStreamReaderConfirmPosition:def test_confirm_position_retries_transient_dropped_connection(self, params):good_conn = mock.MagicMock()