: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 slot advance (#68544)
Tom Owers5822882807f5
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 826bb60dbca6..6865ea411e3a 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@@ -7,6 +7,7 @@ approach — batch reads on a schedule.from __future__ import annotations+import timefrom collections.abc import Callable, Iteratorfrom contextlib import AbstractContextManagerfrom dataclasses import dataclass@@ -14,6 +15,7 @@ from typing import TYPE_CHECKINGimport psycopgimport structlog+import psycopg.errorsfrom psycopg import sqlfrom products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent@@ -29,6 +31,12 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)+# pg_replication_slot_advance rejects the advance with SQLSTATE 55006 (ObjectInUse) while the slot+# is still acquired by another backend. The advance runs on its own short-lived connection while the+# streaming peek releases the slot, so the two can momentarily overlap; the slot frees on its own.+_SLOT_ACTIVE_MARKER = "is active for pid"+_SLOT_ADVANCE_MAX_ATTEMPTS = 3+@dataclass(frozen=True, slots=True)class PgCDCConnectionParams:@@ -192,14 +200,34 @@ class PgCDCStreamReader:logger,)try:- with advance_conn.cursor() as cur:- cur.execute(query)- advance_conn.commit()+ self._advance_slot(advance_conn, query)finally:advance_conn.close()logger.info("advanced_slot", slot_name=self._params.slot_name, position=position)+ def _advance_slot(self, conn: psycopg.Connection, query: sql.Composed) -> None:+ """Run the slot-advance query, retrying the brief window where the slot is still+ held by another backend ("... is active for PID ...").++ Advancing is idempotent (re-advancing past a confirmed LSN is a no-op), and the slot+ frees on its own, so a short in-process retry absorbs a sub-second handoff instead of+ failing — and replaying — the whole extraction. Exhausting the retries re-raises, so a+ slot that stays held still surfaces as the retryable SLOT_IN_USE classification.+ """+ for attempt in range(_SLOT_ADVANCE_MAX_ATTEMPTS):+ try:+ with conn.cursor() as cur:+ cur.execute(query)+ conn.commit()+ return+ except psycopg.errors.ObjectInUse as e:+ conn.rollback()+ if _SLOT_ACTIVE_MARKER not in str(e).lower() or attempt == _SLOT_ADVANCE_MAX_ATTEMPTS - 1:+ raise+ logger.warning("slot_advance_busy_retry", slot_name=self._params.slot_name, attempt=attempt + 1)+ time.sleep(0.5 * 2**attempt)+def get_primary_key_columns(self, schema_name: str, table_names: list[str]) -> dict[str, list[str]]:"""Query information_schema for PK columns of the given tables.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 4ed470b6ff2e..2dac0e5f1030 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@@ -212,3 +212,59 @@ class TestPgCDCStreamReaderConfirmPosition:reader.confirm_position("0/1234ABCD")assert connect.call_count == 1++ def _reader_advancing(self, params, execute_side_effect):+ conn = mock.MagicMock()+ cur = conn.cursor.return_value.__enter__.return_value+ cur.execute.side_effect = execute_side_effect+ connect = mock.MagicMock(return_value=conn)+ reader = PgCDCStreamReader(params)+ return reader, conn, cur, connect++ def test_confirm_position_retries_while_slot_active(self, params):+ # The slot is momentarily held while the streaming peek releases it; the advance+ # self-heals on the next attempt instead of failing the whole extraction.+ reader, conn, cur, connect = self._reader_advancing(+ params,+ [psycopg.errors.ObjectInUse('replication slot "posthog_slot" is active for PID 2999'), None],+ )+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader._connect_to_postgres",+ connect,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader.time.sleep"+ ),+ ):+ reader.confirm_position("0/1234ABCD")++ assert cur.execute.call_count == 2+ # The failed advance aborts the transaction, so the retry must reset it first or real+ # psycopg raises InFailedSqlTransaction.+ conn.rollback.assert_called_once()+ conn.commit.assert_called_once()+ conn.close.assert_called_once()++ def test_confirm_position_raises_when_slot_stays_active(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 forever.+ reader, conn, cur, connect = self._reader_advancing(+ 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._connect_to_postgres",+ connect,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader.time.sleep"+ ),+ ):+ with pytest.raises(psycopg.errors.ObjectInUse):+ reader.confirm_position("0/1234ABCD")++ assert cur.execute.call_count == 3+ conn.commit.assert_not_called()+ conn.close.assert_called_once()