: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(warehouse-sources): advance the CDC slot when a run reads no changes (#91635)
Daniel RC42e3b9851fed
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex 1e9677d2b3d9..015301ac84c7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -234,6 +234,11 @@ class CDCExtractActivity:# past transactions that are completely yielded — see _read_wal_loop.self.current_txn_lsn: str | None = Noneself.last_complete_txn_end_lsn: str | None = None+ # End of WAL before this run peeked, and whether the peek reached the end of the backlog.+ # Together they let a run that decoded nothing still release the WAL it examined — see+ # _handle_no_changes.+ self._pre_read_position: str | None = None+ self._backlog_drained: bool = Falseself.event_count: int = 0self.all_table_names: set[str] = set()# Wall-clock start, set in run(); drives cdc_extraction_duration_seconds.@@ -864,6 +869,9 @@ class CDCExtractActivity:try:self._require_configured_slot()self.reader.connect()+ # Taken before the peek, so anything committed after it stays above this position and+ # is decoded by a later run.+ self._pre_read_position = self.reader.current_position()self._load_pk_columns()self._read_wal_loop()@@ -1316,6 +1324,7 @@ class CDCExtractActivity:# Drained: the peek returned less than a full page, so the backlog is exhausted.# Leave any buffered tail for run()'s _final_flush (is_final=True) + advance.if rows_consumed < limit:+ self._backlog_drained = Truereturnif (time.monotonic() - self._run_started_at) >= CDC_READ_SOFT_DEADLINE_SECONDS:@@ -1451,11 +1460,32 @@ class CDCExtractActivity:def _handle_no_changes(self, truncated_tables: list[str]) -> None:"""Early-return path: no DML events were read."""+ # A mid-run page advance already released the WAL it committed, so the slot moved this run.+ advanced = self.last_confirmed_lsn is not Noneif truncated_tables:truncate_end_lsn = self.reader.last_commit_end_lsnif truncate_end_lsn is not None:self._confirm_position(truncate_end_lsn)self.log.info("slot_advanced_past_truncate", position=truncate_end_lsn)+ advanced = True++ # Logical decoding reads every WAL record, but the peek only returns the ones the+ # publication covers, so a source whose publication is quiet while the rest of the database+ # writes yields nothing to advance on. The slot then pins the WAL from its last confirmed+ # position and the source retains it until the lag safety net drops the slot. The peek+ # examined every record up to the pre-read position and kept none of them, so releasing that+ # much is safe. Two conditions bound it. The backlog must have drained, because a run+ # stopped by the read deadline left records below that position unread. Nothing else may+ # have advanced the slot this run, because the pre-read position can sit behind where those+ # advances left it, and the next quiet run releases the remainder anyway.+ if not advanced and self._backlog_drained and self._pre_read_position is not None:+ try:+ self._confirm_position(self._pre_read_position)+ self.log.info("slot_advanced_no_changes", position=self._pre_read_position)+ except Exception:+ # Retention hygiene, not the run's work. Failing here would mark every schema failed+ # and email the customer about a run that read nothing and lost nothing.+ self.log.warning("slot_advance_no_changes_failed", exc_info=True)now = dt.datetime.now(tz=dt.UTC)for schema in self.cdc_schemas:diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.pyindex 2f87f3c0d2ae..b7440b3da5d9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py@@ -997,6 +997,7 @@ class TestCDCExtractActivity:mock_reader.read_changes.return_value = iter([])mock_reader.truncated_tables = []mock_reader.last_rows_consumed = 0+ mock_reader.current_position.return_value = "0/900"mock_adapter = MagicMock()mock_adapter.create_reader.return_value = mock_readermock_get_adapter.return_value = mock_adapter@@ -1004,8 +1005,10 @@ class TestCDCExtractActivity:inputs = CDCExtractInput(team_id=1, source_id=source.id)cdc_extract_activity(inputs)- # No slot advance and reader still cleaned up- mock_reader.confirm_position.assert_not_called()+ # The peek examined everything up to the pre-read position and found nothing to sync, so the+ # slot must still move. Leaving it pinned makes a busy source retain WAL on every quiet run+ # until the lag safety net drops the slot.+ mock_reader.confirm_position.assert_called_once_with("0/900")mock_reader.close.assert_called_once()# Schema marked completed even with no changes@@ -3099,10 +3102,14 @@ class _ScriptedReader:self.confirmed_positions: list[str] = []self.on_row_calls = 0self.upto_nchanges_calls: list[int | None] = []+ self.pre_read_position = "0/900"def connect(self):pass+ def current_position(self):+ return self.pre_read_position+def get_primary_key_columns(self, schema, tables):return {}@@ -3135,6 +3142,47 @@ class _ScriptedReader:pass+class TestQuietRunSlotAdvance:+ """A run that decodes nothing releases the WAL it examined, so a quiet publication on a busy+ source stops retaining WAL until the lag safety net drops the slot. The peek must have reached+ the end of the backlog first: a short read leaves records below that position unexamined."""++ @pytest.mark.parametrize(+ "drained,pre_read,already_confirmed,expected_advances",+ [+ (True, "0/900", None, ["0/900"]),+ (False, "0/900", None, []),+ (True, None, None, []),+ (True, "0/900", "0/500", []),+ ],+ )+ def test_quiet_run_advance_conditions(self, drained, pre_read, already_confirmed, expected_advances):+ source = _make_source()+ act = _make_extract_activity(source)+ act.cdc_schemas = [_make_schema("users", source=source)]+ act.reader = MagicMock(last_commit_end_lsn=None)+ act._pre_read_position = pre_read+ act._backlog_drained = drained+ act.last_confirmed_lsn = already_confirmed++ act._handle_no_changes([])++ assert [c.args[0] for c in act.reader.confirm_position.call_args_list] == expected_advances++ def test_a_failed_quiet_advance_does_not_fail_the_run(self):+ source = _make_source()+ act = _make_extract_activity(source)+ act.cdc_schemas = [_make_schema("users", source=source)]+ act.reader = MagicMock(last_commit_end_lsn=None)+ act.reader.confirm_position.side_effect = RuntimeError("slot is active for PID 42")+ act._pre_read_position = "0/900"+ act._backlog_drained = True++ act._handle_no_changes([])++ assert act.cdc_schemas[0].status == ExternalDataSchema.Status.COMPLETED++class TestSuccessRepaintGuards:"""A run finishing after the sweeper marked the source broken must not repaint the schemahealthy — that hides the breakage from the UI and from the failure digest email."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.pyindex 6fa799181e21..7d399ccc6a61 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py@@ -89,6 +89,8 @@ class CDCStreamReader(Protocol):def confirm_position(self, position: str) -> None: ...+ def current_position(self) -> str | None: ...+def get_primary_key_columns(self, schema_name: str, table_names: list[str]) -> dict[str, list[str]]: ...def get_decoder_key_columns(self, table_name: str) -> list[str]: ...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 2610224207df..3f931b19e27c 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@@ -9,7 +9,7 @@ from __future__ import annotationsimport timefrom collections.abc import Callable, Iterator-from contextlib import AbstractContextManager+from contextlib import AbstractContextManager, suppressfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING@@ -236,6 +236,35 @@ class PgCDCStreamReader:time.sleep(0.5 * 2**attempt)self._conn = conn = self._open_streaming_connection()+ def current_position(self) -> str | None:+ """Read the source's flushed end-of-WAL LSN.++ The caller takes this before it peeks, so a run that decodes nothing can still release the+ WAL it examined. It must be the flush pointer, not pg_current_wal_lsn(): logical decoding+ reads only flushed WAL, so the write pointer can name records a later peek never examines.+ With synchronous_commit=off a commit can sit in that gap, and advancing the slot past it+ would drop the change. The flush pointer read here is always at or below every later peek's+ end of WAL, which makes the caller's "everything below this was examined" claim exact.++ Returns None when the position cannot be read, which includes a source in recovery, where+ pg_current_wal_flush_lsn() is not callable. The caller then leaves the slot where it is, so+ a failure here costs retention rather than data.+ """+ if self._conn is None:+ return None+ try:+ with self._conn.cursor() as cur:+ cur.execute("SELECT pg_current_wal_flush_lsn()::text")+ row = cur.fetchone()+ self._conn.commit()+ except Exception:+ # The rollback reaches the same connection that just failed, so it can fail too.+ with suppress(Exception):+ self._conn.rollback()+ logger.warning("current_wal_lsn_read_failed", slot_name=self._params.slot_name, exc_info=True)+ return None+ return row[0] if row else None+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 1c02c73a7377..25d1b3542af9 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@@ -490,3 +490,29 @@ class TestPgCDCStreamReaderConfirmPosition:reader.confirm_position("B4/C7327D08")conn.close.assert_called_once()+++class TestPgCDCStreamReaderCurrentPosition:+ def test_current_position_returns_the_end_of_wal(self, params):+ reader = PgCDCStreamReader(params)+ fake_conn = mock.MagicMock()+ fake_conn.cursor.return_value.__enter__.return_value.fetchone.return_value = ("B4/C7327D08",)+ reader._conn = fake_conn++ assert reader.current_position() == "B4/C7327D08"++ def test_current_position_returns_none_without_a_connection(self, params):+ assert PgCDCStreamReader(params).current_position() is None++ def test_current_position_returns_none_instead_of_failing_the_run(self, params):+ # A source in recovery cannot run pg_current_wal_flush_lsn(). The caller only loses the+ # quiet-run slot advance, so this must never propagate.+ reader = PgCDCStreamReader(params)+ fake_conn = mock.MagicMock()+ fake_conn.cursor.return_value.__enter__.return_value.execute.side_effect = (+ psycopg.errors.ObjectNotInPrerequisiteState("recovery is in progress")+ )+ fake_conn.rollback.side_effect = psycopg.OperationalError("the connection is closed")+ reader._conn = fake_conn++ assert reader.current_position() is None