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(data-warehouse): bound CDC WAL reads, cap decoder tx buffer (#65908)

Daniel RC29fbb5631390
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index 713a8122f600..f76f5a84942b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -83,6 +83,22 @@ RETENTION_CAP_SAFETY_FACTOR = 0.8
# attempt a failure won't be retried, so it's the last chance to record a visible failed-run row.
CDC_MAX_EXTRACTION_ATTEMPTS = 3
+# Per-peek bound on WAL changes. A large backlog is drained over several passes (and, if needed,
+# several scheduled runs) instead of one unbounded read that risks the 2h activity timeout and
+# re-decodes from the slot start on every retry. The slot advances after each pass, so the next
+# peek resumes where this one stopped.
+CDC_MAX_CHANGES_PER_READ = 100_000
+# Ceiling for the adaptive growth below. The decoder's MAX_TX_BUFFER_EVENTS (500k) is the real
+# bound on an oversized single transaction — it trips before the window doubles far past it — so
+# this only needs a little headroom above that guard.
+CDC_MAX_CHANGES_LIMIT_CAP = 800_000
+# Stop starting new peeks past this wall-clock so the final flush + slot advance fit inside the
+# activity's 2h start-to-close timeout (see CDCExtractionWorkflow). The remainder is picked up on
+# the next scheduled run.
+CDC_READ_SOFT_DEADLINE_SECONDS = 90 * 60
+# Heartbeat at most this often while fetching WAL rows (the activity heartbeat timeout is 10m).
+CDC_READ_HEARTBEAT_INTERVAL_SECONDS = 30.0
+
@dataclasses.dataclass
class CDCExtractInput:
@@ -831,73 +847,151 @@ class CDCExtractActivity:
# ------------------------------------------------------------------
# WAL read loop with periodic micro-batch flushes
# ------------------------------------------------------------------
+ def _make_read_heartbeat(self) -> Callable[[], None]:
+ """Throttled ``activity.heartbeat`` for ``read_changes``' per-row callback.
+
+ The decoder yields nothing until a COMMIT, so a single large transaction would
+ otherwise starve the 10m heartbeat timeout while it is being fetched. Throttled by
+ wall-clock to avoid a heartbeat call on every WAL row.
+ """
+ last_heartbeat = 0.0
+
+ def heartbeat() -> None:
+ nonlocal last_heartbeat
+ now = time.monotonic()
+ if now - last_heartbeat >= CDC_READ_HEARTBEAT_INTERVAL_SECONDS:
+ activity.heartbeat()
+ last_heartbeat = now
+
+ return heartbeat
+
def _read_wal_loop(self) -> None:
- """Read WAL events with periodic micro-batch flushes.
+ """Read WAL events with periodic micro-batch flushes, bounded per peek.
+
+ Each pass peeks at most ``CDC_MAX_CHANGES_PER_READ`` changes so a large backlog can't
+ push the activity past its 2h timeout. When a pass returns a full page, the slot is
+ advanced past everything it committed and another pass runs, until the backlog drains,
+ the soft deadline hits, or (defensively) the limit cap is reached.
- Streaming schemas get Kafka messages immediately after each S3 write.
- The slot is advanced after each successful flush so that long-running
- extractions that hit the activity timeout don't have to replay events
- on the next run.
+ Streaming schemas get Kafka messages immediately after each S3 write. The slot is
+ advanced after each successful flush so a long extraction never replays committed
+ events on the next run.
"""
+ assert self._run_started_at is not None
event_name_to_schema_name = self._build_event_name_map()
self.batcher = ChangeEventBatcher()
+ on_row = self._make_read_heartbeat()
+
+ limit = CDC_MAX_CHANGES_PER_READ
+ while True:
+ for event in self.reader.read_changes(upto_nchanges=limit, on_row=on_row):
+ activity.heartbeat()
+
+ # Resolve to the schema's stored `name` so downstream keying lines up. Log
+ # unmatched drops: a silent drop here is how a name mismatch starves a table.
+ canonical_name = event_name_to_schema_name.get(event.table_name)
+ if canonical_name is None:
+ self.log.debug("cdc_event_dropped_unmatched_table", table=event.table_name)
+ continue
+ if canonical_name != event.table_name:
+ event = dataclasses.replace(event, table_name=canonical_name)
+
+ event = self._project_event_columns(event)
+ self.batcher.add(event)
+
+ # A change in position_serialized proves the previous transaction fully
+ # yielded — all of its events are now buffered or flushed. Record its end LSN
+ # as the high-water mark we may safely release the WAL up to.
+ if event.position_serialized != self.current_txn_lsn:
+ self.last_complete_txn_end_lsn = self.current_txn_lsn
+ self.current_txn_lsn = event.position_serialized
+
+ self.last_end_lsn = event.position_serialized
+ self.event_count += 1
+
+ if self.batcher.should_flush:
+ tables = self.batcher.flush()
+ self.all_table_names.update(tables.keys())
+ self._process_flush(tables, is_final=False)
+ metrics.get_micro_batches_flushed_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
+ # Advance only to the end of the last FULLY-yielded transaction, never to
+ # last_end_lsn: a micro-flush can fire mid-transaction (the batcher
+ # threshold is checked per event), and every event of the in-flight
+ # transaction shares its commit end LSN. Confirming that LSN while the
+ # transaction's tail is still un-yielded in the generator would release
+ # the WAL past un-flushed events — a crash before the next flush then
+ # loses them permanently. Consequences of this conservative bound:
+ # (a) a single giant transaction gets no micro-advance until it
+ # completes (a retry re-decodes it — safe, slow);
+ # (b) on crash-replay the already-flushed prefix of the in-flight
+ # transaction is re-delivered — incremental_merge dedups by PK,
+ # scd2_append may create duplicate history rows. Accepted vs. loss.
+ if (
+ self.last_complete_txn_end_lsn is not None
+ and self.last_complete_txn_end_lsn != self.last_confirmed_lsn
+ ):
+ self._confirm_position(self.last_complete_txn_end_lsn)
+ self.last_confirmed_lsn = self.last_complete_txn_end_lsn
+ self.log.info(
+ "cdc_micro_batch_flushed",
+ events_so_far=self.event_count,
+ trackers=len(self.write_trackers),
+ )
- for event in self.reader.read_changes():
- activity.heartbeat()
+ # Capture remaining table names before deciding on the next pass / final flush.
+ self.all_table_names.update(self.batcher.table_names)
- # Resolve to the schema's stored `name` so downstream keying lines up. Log
- # unmatched drops: a silent drop here is how a name mismatch starves a table.
- canonical_name = event_name_to_schema_name.get(event.table_name)
- if canonical_name is None:
- self.log.debug("cdc_event_dropped_unmatched_table", table=event.table_name)
- continue
- if canonical_name != event.table_name:
- event = dataclasses.replace(event, table_name=canonical_name)
-
- event = self._project_event_columns(event)
- self.batcher.add(event)
-
- # A change in position_serialized proves the previous transaction fully
- # yielded — all of its events are now buffered or flushed. Record its end LSN
- # as the high-water mark we may safely release the WAL up to.
- if event.position_serialized != self.current_txn_lsn:
- self.last_complete_txn_end_lsn = self.current_txn_lsn
- self.current_txn_lsn = event.position_serialized
-
- self.last_end_lsn = event.position_serialized
- self.event_count += 1
-
- if self.batcher.should_flush:
- tables = self.batcher.flush()
- self.all_table_names.update(tables.keys())
- self._process_flush(tables, is_final=False)
- metrics.get_micro_batches_flushed_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
- # Advance only to the end of the last FULLY-yielded transaction, never to
- # last_end_lsn: a micro-flush can fire mid-transaction (the batcher
- # threshold is checked per event), and every event of the in-flight
- # transaction shares its commit end LSN. Confirming that LSN while the
- # transaction's tail is still un-yielded in the generator would release
- # the WAL past un-flushed events — a crash before the next flush then
- # loses them permanently. Consequences of this conservative bound:
- # (a) a single giant transaction gets no micro-advance until it
- # completes (a retry re-decodes it — safe, slow);
- # (b) on crash-replay the already-flushed prefix of the in-flight
- # transaction is re-delivered — incremental_merge dedups by PK,
- # scd2_append may create duplicate history rows. Accepted vs. loss.
- if (
- self.last_complete_txn_end_lsn is not None
- and self.last_complete_txn_end_lsn != self.last_confirmed_lsn
- ):
- self._confirm_position(self.last_complete_txn_end_lsn)
- self.last_confirmed_lsn = self.last_complete_txn_end_lsn
- self.log.info(
- "cdc_micro_batch_flushed",
+ rows_consumed = self.reader.last_rows_consumed
+ # 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:
+ return
+
+ if (time.monotonic() - self._run_started_at) >= CDC_READ_SOFT_DEADLINE_SECONDS:
+ self.log.warning(
+ "cdc_read_soft_deadline_reached",
events_so_far=self.event_count,
- trackers=len(self.write_trackers),
+ rows_consumed=rows_consumed,
)
+ return
- # Capture remaining table names before final flush
- self.all_table_names.update(self.batcher.table_names)
+ # Full page: drain the buffered (committed) events and advance the slot past every
+ # transaction this pass committed so the next peek resumes cleanly.
+ #
+ # A full page that advanced nothing is a defensive guard, not a live path:
+ # pg_logical_slot_peek_binary_changes only returns fully-committed transactions, so a
+ # page that returns rows always commits something and advances. Were that ever to not
+ # hold, grow the window so an oversized single transaction can complete in one peek (or
+ # trip the decoder's MAX_TX_BUFFER_EVENTS guard) instead of re-peeking the same page.
+ if not self._drain_and_advance_page():
+ limit = min(limit * 2, CDC_MAX_CHANGES_LIMIT_CAP)
+
+ def _drain_and_advance_page(self) -> bool:
+ """Between peeks: flush buffered events and advance the slot past every committed
+ transaction. Returns whether the slot advanced.
+
+ Safe to advance to the decoder's last commit end LSN here (not only to
+ last_complete_txn_end_lsn as the mid-loop micro-flush does): the peek has stopped at a
+ transaction boundary, so every event yielded this pass belongs to a committed
+ transaction and is now flushed. Unmatched-table commits carry the slot forward too —
+ their WAL is intentionally dropped. Re-reading instead would re-add already-flushed
+ events and duplicate SCD2 history rows.
+ """
+ assert self.batcher is not None
+ if self.batcher.event_count > 0:
+ tables = self.batcher.flush()
+ self.all_table_names.update(tables.keys())
+ self._process_flush(tables, is_final=False)
+ metrics.get_micro_batches_flushed_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
+
+ commit_lsn = self.reader.last_commit_end_lsn
+ if commit_lsn is not None and commit_lsn != self.last_confirmed_lsn:
+ self._confirm_position(commit_lsn)
+ self.last_confirmed_lsn = commit_lsn
+ self.last_end_lsn = commit_lsn
+ activity.heartbeat()
+ return True
+ return False
# ------------------------------------------------------------------
# Post-WAL handling
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.py
index 5d90e50392f5..89a70ed0f4a5 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
@@ -11,6 +11,7 @@ import psycopg.errors
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.cdc.activities import (
+ CDC_MAX_CHANGES_PER_READ,
SLOT_INVALIDATION_RECOVERY_MESSAGE,
CDCExtractActivity,
CDCExtractInput,
@@ -162,6 +163,8 @@ def _setup_mocks(
mock_reader = MagicMock()
mock_reader.read_changes.return_value = iter(events)
mock_reader.truncated_tables = []
+ # Below CDC_MAX_CHANGES_PER_READ so the bounded read loop treats this as a single drained pass.
+ mock_reader.last_rows_consumed = len(events)
mock_reader.get_decoder_key_columns.return_value = []
mock_adapter = MagicMock()
mock_adapter.create_reader.return_value = mock_reader
@@ -696,6 +699,7 @@ class TestCDCExtractActivity:
mock_reader = MagicMock()
mock_reader.read_changes.return_value = iter([])
mock_reader.truncated_tables = []
+ mock_reader.last_rows_consumed = 0
mock_adapter = MagicMock()
mock_adapter.create_reader.return_value = mock_reader
mock_get_adapter.return_value = mock_adapter
@@ -1007,6 +1011,7 @@ class TestCDCExtractActivity:
mock_reader = MagicMock()
mock_reader.read_changes.return_value = iter([]) # no DML events
mock_reader.truncated_tables = ["users"]
+ mock_reader.last_rows_consumed = 0
mock_reader.last_commit_end_lsn = "0/500"
mock_reader.get_decoder_key_columns.return_value = []
mock_adapter = MagicMock()
@@ -2304,3 +2309,226 @@ class TestFailureVisibilityJobs:
assert MockJob.objects.create.call_count == 2
created_for = {call.kwargs["schema"] for call in MockJob.objects.create.call_args_list}
assert created_for == {schema_a, schema_b}
+
+
+class _ScriptedReader:
+ """Reader stub that serves preconfigured WAL pages to the bounded read loop.
+
+ Each page is (events, rows_consumed, commit_end_lsn). read_changes() exposes that page's
+ rows_consumed / last_commit_end_lsn exactly as the real reader does after a peek, so the
+ multi-pass loop sees a full page (rows_consumed >= cap) followed by a drained one (< cap).
+ """
+
+ def __init__(self, pages):
+ self._pages = list(pages)
+ self._idx = 0
+ self.last_rows_consumed = 0
+ self.last_commit_end_lsn = None
+ self.truncated_tables: list[str] = []
+ self.confirmed_positions: list[str] = []
+ self.on_row_calls = 0
+ self.upto_nchanges_calls: list[int | None] = []
+
+ def connect(self):
+ pass
+
+ def get_primary_key_columns(self, schema, tables):
+ return {}
+
+ def get_decoder_key_columns(self, table):
+ return []
+
+ def clear_truncated_tables(self):
+ self.truncated_tables = []
+
+ def read_changes(self, upto_nchanges=None, on_row=None):
+ self.upto_nchanges_calls.append(upto_nchanges)
+ events, rows_consumed, commit_end_lsn = self._pages[self._idx]
+ self._idx += 1
+ self.last_rows_consumed = rows_consumed
+ self.last_commit_end_lsn = commit_end_lsn
+
+ def gen():
+ for ev in events:
+ if on_row is not None:
+ on_row()
+ self.on_row_calls += 1
+ yield ev
+
+ return gen()
+
+ def confirm_position(self, lsn):
+ self.confirmed_positions.append(lsn)
+
+ def close(self):
+ pass
+
+
+class TestCDCBoundedReadLoop:
+ """The read loop peeks at most CDC_MAX_CHANGES_PER_READ changes per pass, advancing the slot
+ between passes so a large backlog drains over several passes (and, if needed, runs)."""
+
+ def _run_with_reader(
+ self,
+ mock_activity,
+ MockProducer,
+ MockS3Writer,
+ mock_get_adapter,
+ mock_get_schemas,
+ MockSourceModel,
+ MockJob,
+ mock_close_conns,
+ reader,
+ ):
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ schema.sync_type_config["primary_key_columns"] = ["id"]
+ _setup_mocks(
+ mock_activity,
+ MockProducer,
+ MockS3Writer,
+ mock_get_adapter,
+ mock_get_schemas,
+ MockSourceModel,
+ MockJob,
+ mock_close_conns,
+ source,
+ [schema],
+ [],
+ )
+ # Replace the default MagicMock reader with the scripted multi-pass reader.
+ mock_get_adapter.return_value.create_reader.return_value = reader
+
+ cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
+ return schema
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch.object(CDCExtractActivity, "_get_cdc_schemas")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_full_page_then_drained_advances_slot_between_passes(
+ self,
+ mock_close_conns,
+ MockJob,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ MockS3Writer,
+ MockProducer,
+ mock_activity,
+ ):
+ reader = _ScriptedReader(
+ [
+ ([_make_event(op="I", table="users", position="0/100")], CDC_MAX_CHANGES_PER_READ, "0/100"),
+ ([_make_event(op="I", table="users", position="0/200")], 5, "0/200"),
+ ]
+ )
+
+ self._run_with_reader(
+ mock_activity,
+ MockProducer,
+ MockS3Writer,
+ mock_get_adapter,
+ mock_get_schemas,
+ MockSourceModel,
+ MockJob,
+ mock_close_conns,
+ reader,
+ )
+
+ # Two peeks: a full page, then a drained one. The first pass advances the slot to its last
+ # commit before re-peeking; the final flush advances to the second pass's last event.
+ assert len(reader.upto_nchanges_calls) == 2
+ assert reader.confirmed_positions == ["0/100", "0/200"]
+ # The per-row heartbeat callback was wired through read_changes and fired during the reads.
+ assert reader.on_row_calls == 2
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch.object(CDCExtractActivity, "_get_cdc_schemas")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_soft_deadline_stops_starting_new_passes(
+ self,
+ mock_close_conns,
+ MockJob,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ MockS3Writer,
+ MockProducer,
+ mock_activity,
+ monkeypatch,
+ ):
+ # Deadline already elapsed: a full first page must not start a second pass.
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDC_READ_SOFT_DEADLINE_SECONDS", 0
+ )
+ reader = _ScriptedReader(
+ [([_make_event(op="I", table="users", position="0/100")], CDC_MAX_CHANGES_PER_READ, "0/100")]
+ )
+
+ schema = self._run_with_reader(
+ mock_activity,
+ MockProducer,
+ MockS3Writer,
+ mock_get_adapter,
+ mock_get_schemas,
+ MockSourceModel,
+ MockJob,
+ mock_close_conns,
+ reader,
+ )
+
+ assert len(reader.upto_nchanges_calls) == 1 # no second peek despite a full page
+ assert schema.status == "Completed" # the run still finalizes what it read
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch.object(CDCExtractActivity, "_get_cdc_schemas")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_full_page_with_no_committed_progress_doubles_the_limit(
+ self,
+ mock_close_conns,
+ MockJob,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ MockS3Writer,
+ MockProducer,
+ mock_activity,
+ ):
+ # Defensive backstop: a full page that commits nothing (so the slot can't advance) grows
+ # the window instead of re-peeking the identical page forever.
+ reader = _ScriptedReader(
+ [
+ ([], CDC_MAX_CHANGES_PER_READ, None),
+ ([_make_event(op="I", table="users", position="0/300")], 5, "0/300"),
+ ]
+ )
+
+ self._run_with_reader(
+ mock_activity,
+ MockProducer,
+ MockS3Writer,
+ mock_get_adapter,
+ mock_get_schemas,
+ MockSourceModel,
+ MockJob,
+ mock_close_conns,
+ reader,
+ )
+
+ assert reader.upto_nchanges_calls == [CDC_MAX_CHANGES_PER_READ, CDC_MAX_CHANGES_PER_READ * 2]
+ assert reader.confirmed_positions == ["0/300"] # nothing to advance on pass 1; pass 2 drains
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
index 1ad677c1e046..d5869703dbda 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
@@ -116,6 +116,8 @@ def _extract_patches(source, schemas, events):
reader = MagicMock()
reader.read_changes.return_value = iter(events)
reader.truncated_tables = []
+ # Below CDC_MAX_CHANGES_PER_READ so the bounded read loop treats this as a single drained pass.
+ reader.last_rows_consumed = len(events)
reader.get_decoder_key_columns.return_value = []
adapter = MagicMock()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
index 13ac424f07b4..c9b514681769 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
@@ -32,11 +32,18 @@ from typing import Any
import pyarrow as pa
+from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCTransactionTooLargeError
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.position import PgLSN
logger = logging.getLogger(__name__)
+# A transaction is buffered entirely in memory until its COMMIT, when every event is yielded
+# at once. Cap the buffer so a single pathologically large transaction can't OOM the worker;
+# the orchestration layer classifies CDCTransactionTooLargeError as a non-retryable failure.
+# Spill-to-disk is out of scope.
+MAX_TX_BUFFER_EVENTS = 500_000
+
# PostgreSQL epoch: 2000-01-01 00:00:00 UTC
# Timestamps in pgoutput are microseconds since this epoch
PG_EPOCH = datetime(2000, 1, 1, tzinfo=UTC)
@@ -241,7 +248,7 @@ class PgOutputDecoder:
columns = _decode_tuple(tuple_data, relation)
- self._tx_buffer.append(
+ self._buffer_event(
ChangeEvent(
operation="I",
table_name=relation.qualified_name,
@@ -279,7 +286,7 @@ class PgOutputDecoder:
columns = _decode_tuple(payload[offset:], relation)
- self._tx_buffer.append(
+ self._buffer_event(
ChangeEvent(
operation="U",
table_name=relation.qualified_name,
@@ -310,7 +317,7 @@ class PgOutputDecoder:
columns = _decode_tuple(payload[offset:], relation)
- self._tx_buffer.append(
+ self._buffer_event(
ChangeEvent(
operation="D",
table_name=relation.qualified_name,
@@ -354,6 +361,14 @@ class PgOutputDecoder:
logger.warning("Received event for unknown relation_id %d — missing R message?", relation_id)
return relation
+ def _buffer_event(self, event: ChangeEvent) -> None:
+ """Buffer a decoded change until COMMIT, guarding against an unbounded transaction."""
+ self._tx_buffer.append(event)
+ if len(self._tx_buffer) > MAX_TX_BUFFER_EVENTS:
+ raise CDCTransactionTooLargeError(
+ f"Transaction buffered more than {MAX_TX_BUFFER_EVENTS} changes before COMMIT"
+ )
+
def _read_cstring(data: bytes, offset: int) -> tuple[str, int]:
"""Read a null-terminated C string from data starting at offset."""
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.py
index cf6c61416dc4..3c10fd92e994 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,7 +7,7 @@ approach — batch reads on a schedule.
from __future__ import annotations
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from contextlib import AbstractContextManager
from dataclasses import dataclass
from typing import TYPE_CHECKING
@@ -63,6 +63,7 @@ class PgCDCStreamReader:
self._tunnel_cm: AbstractContextManager[tuple[str, int]] | None = None
self._effective_host: str = params.host
self._effective_port: int = params.port
+ self._last_rows_consumed: int = 0
def connect(self) -> None:
# If a source is provided, enter the SSH tunnel context (no-op if SSH is disabled).
@@ -91,30 +92,54 @@ class PgCDCStreamReader:
user=self._params.user,
password=self._params.password,
require_ssl=self._params.require_ssl,
+ # Server-side ceiling (30m) so a stalled WAL decode can't hang the streaming
+ # connection indefinitely. Bounds a single peek; the caller's soft deadline
+ # bounds the whole run. Dropped if the source sits behind a pooler that rejects
+ # the libpq `options` parameter (CDC sources never do).
+ options="-c statement_timeout=1800000",
),
logger,
)
- def read_changes(self) -> Iterator[ChangeEvent]:
- """Read all pending WAL changes from the replication slot.
+ def read_changes(
+ self,
+ upto_nchanges: int | None = None,
+ on_row: Callable[[], None] | None = None,
+ ) -> Iterator[ChangeEvent]:
+ """Read pending WAL changes from the replication slot.
Uses peek (non-consuming) so the slot position is not advanced.
Call confirm_position() after successful processing.
+ ``upto_nchanges`` bounds one peek: ``pg_logical_slot_peek_binary_changes`` stops once a
+ transaction's COMMIT pushes the decoded-change count past it. It never splits a
+ transaction, so a single large transaction is still returned in full (the decoder's own
+ buffer guard bounds that case). ``None`` reads the whole backlog.
+
+ ``on_row`` is invoked once per fetched WAL row so the caller can heartbeat during a long
+ decode — the decoder yields nothing until a COMMIT, so a big transaction would otherwise
+ produce no events to drive a heartbeat off.
+
+ After iteration, ``last_rows_consumed`` holds the raw row count for this call so the
+ caller can detect a full page (rows reached the cap) and peek again.
+
Uses a named server-side cursor to stream rows in chunks rather than
buffering the entire WAL backlog in client memory.
"""
if self._conn is None:
raise RuntimeError("Not connected. Call connect() first.")
+ self._last_rows_consumed = 0
+ upto = sql.Literal(upto_nchanges) if upto_nchanges is not None else sql.SQL("NULL")
query = sql.SQL(
"SELECT lsn, xid, data FROM pg_logical_slot_peek_binary_changes("
- "{slot_name}, NULL, NULL, "
+ "{slot_name}, NULL, {upto_nchanges}, "
"'proto_version', '1', "
"'publication_names', {pub_name}"
")"
).format(
slot_name=sql.Literal(self._params.slot_name),
+ upto_nchanges=upto,
pub_name=sql.Literal(self._params.publication_name),
)
@@ -123,6 +148,10 @@ class PgCDCStreamReader:
cur.execute(query)
for row in cur:
+ self._last_rows_consumed += 1
+ if on_row is not None:
+ on_row()
+
lsn_str: str = row[0]
data: bytes = row[2]
@@ -197,6 +226,15 @@ class PgCDCStreamReader:
"""
return self._decoder.last_commit_end_lsn
+ @property
+ def last_rows_consumed(self) -> int:
+ """Raw WAL rows fetched during the most recent ``read_changes()`` call.
+
+ Reaches the ``upto_nchanges`` cap (or slightly above it, since a transaction is never
+ split) while the slot still has a backlog; stays below it once the backlog is drained.
+ """
+ return self._last_rows_consumed
+
def close(self) -> None:
if self._conn is not None:
self._conn.close()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
index 3a8eacbc92ba..1ba5757c4a91 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
@@ -1,9 +1,12 @@
import struct
from datetime import UTC, datetime
+import pytest
+
import pyarrow as pa
from parameterized import parameterized
+from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCTransactionTooLargeError
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.decoder import (
_OID_BOOL,
_OID_FLOAT8,
@@ -16,6 +19,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.c
_pg_timestamp_to_datetime,
)
+_DECODER_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.decoder"
+
def _make_cstring(s: str) -> bytes:
return s.encode("utf-8") + b"\x00"
@@ -495,3 +500,38 @@ class TestPgTimestamp:
def test_pg_epoch(self):
result = _pg_timestamp_to_datetime(0)
assert result == datetime(2000, 1, 1, tzinfo=UTC)
+
+
+class TestTransactionBufferGuard:
+ """A single transaction is buffered fully in memory until COMMIT; the decoder caps it so one
+ pathological transaction can't OOM the worker."""
+
+ def _decoder_with_relation(self) -> PgOutputDecoder:
+ decoder = PgOutputDecoder()
+ decoder.decode_message(_make_relation(1, "public", "users", [("id", _OID_INT4, -1)]), "0/1")
+ return decoder
+
+ def test_raises_when_transaction_exceeds_buffer_cap(self, monkeypatch):
+ monkeypatch.setattr(f"{_DECODER_MODULE}.MAX_TX_BUFFER_EVENTS", 3)
+ decoder = self._decoder_with_relation()
+ decoder.decode_message(_make_begin(), "0/1")
+
+ # Up to the cap buffers without yielding (events flush only on COMMIT).
+ for i in range(3):
+ assert decoder.decode_message(_make_insert(1, [("t", str(i))]), "0/1") == []
+
+ # The change past the cap aborts decoding instead of growing the buffer unbounded.
+ with pytest.raises(CDCTransactionTooLargeError):
+ decoder.decode_message(_make_insert(1, [("t", "99")]), "0/1")
+
+ def test_cap_is_per_transaction(self, monkeypatch):
+ # The buffer clears at each COMMIT, so a long stream of small transactions never trips the cap.
+ monkeypatch.setattr(f"{_DECODER_MODULE}.MAX_TX_BUFFER_EVENTS", 2)
+ decoder = self._decoder_with_relation()
+
+ for _ in range(3):
+ decoder.decode_message(_make_begin(), "0/1")
+ decoder.decode_message(_make_insert(1, [("t", "1")]), "0/1")
+ decoder.decode_message(_make_insert(1, [("t", "2")]), "0/1")
+ events = decoder.decode_message(_make_commit(), "0/1")
+ assert len(events) == 2
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.py
index ba7f7e8a1175..71908b16a044 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
@@ -108,6 +108,60 @@ class TestPgCDCStreamReaderConnect:
assert connect.call_count == 1
+class TestPgCDCStreamReaderConnectOptions:
+ def test_connect_sets_statement_timeout(self, params):
+ connect = mock.MagicMock(return_value=mock.MagicMock())
+ reader = PgCDCStreamReader(params)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader._connect_to_postgres",
+ connect,
+ ):
+ reader.connect()
+
+ # A stalled server-side WAL decode can't hang the streaming connection indefinitely.
+ assert "statement_timeout=1800000" in connect.call_args.kwargs["options"]
+
+
+class TestPgCDCStreamReaderReadChanges:
+ def _reader_serving(self, params, rows):
+ reader = PgCDCStreamReader(params)
+ fake_cursor = mock.MagicMock()
+ fake_cursor.__iter__.return_value = iter(rows)
+ reader._conn = mock.MagicMock()
+ reader._conn.cursor.return_value.__enter__.return_value = fake_cursor
+ # Isolate the read mechanics (row count + callback) from pgoutput decoding.
+ reader._decoder = mock.MagicMock()
+ reader._decoder.decode_message.return_value = []
+ return reader, fake_cursor
+
+ def test_read_changes_bounds_peek_with_upto_nchanges(self, params):
+ reader, fake_cursor = self._reader_serving(params, [])
+ list(reader.read_changes(upto_nchanges=100_000))
+ rendered = fake_cursor.execute.call_args.args[0].as_string(None)
+ # Third positional arg of pg_logical_slot_peek_binary_changes is the change cap.
+ assert ", NULL, 100000, " in rendered
+
+ def test_read_changes_passes_null_when_unbounded(self, params):
+ reader, fake_cursor = self._reader_serving(params, [])
+ list(reader.read_changes())
+ rendered = fake_cursor.execute.call_args.args[0].as_string(None)
+ assert ", NULL, NULL, " in rendered
+
+ def test_read_changes_invokes_on_row_per_row_and_counts(self, params):
+ rows = [("0/1", 1, b"a"), ("0/2", 1, b"b"), ("0/3", 1, b"c")]
+ reader, _ = self._reader_serving(params, rows)
+ on_row_calls = 0
+
+ def on_row() -> None:
+ nonlocal on_row_calls
+ on_row_calls += 1
+
+ list(reader.read_changes(upto_nchanges=10, on_row=on_row))
+
+ assert on_row_calls == len(rows)
+ assert reader.last_rows_consumed == len(rows)
+
+
class TestPgCDCStreamReaderConfirmPosition:
def test_confirm_position_retries_transient_dropped_connection(self, params):
good_conn = mock.MagicMock()