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): CDC improvements — advance slot only past fully-flushed transactions (#64719)

Daniel RC9f78caf45110
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.py
index f484f4d185f6..33263287e12d 100644
--- a/posthog/temporal/data_imports/cdc/activities.py
+++ b/posthog/temporal/data_imports/cdc/activities.py
@@ -128,6 +128,12 @@ class CDCExtractActivity:
self.batcher: ChangeEventBatcher | None = None
self.last_end_lsn: str | None = None
self.last_confirmed_lsn: str | None = None
+ # Transaction-boundary tracking for safe mid-run slot advances. All events of
+ # one transaction share the same commit end LSN (position_serialized), so an LSN
+ # change marks a fully-yielded transaction. We only ever micro-advance the slot
+ # past transactions that are completely yielded — see _read_wal_loop.
+ self.current_txn_lsn: str | None = None
+ self.last_complete_txn_end_lsn: str | None = None
self.event_count: int = 0
self.all_table_names: set[str] = set()
@@ -678,6 +684,14 @@ class CDCExtractActivity:
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
@@ -685,13 +699,24 @@ class CDCExtractActivity:
tables = self.batcher.flush()
self.all_table_names.update(tables.keys())
self._process_flush(tables, is_final=False)
- # Advance the slot after each successful flush. At this point every
- # batch in this micro-flush is either in Kafka (streaming) or persisted
- # in sync_type_config["cdc_deferred_runs"] (snapshot), so it's safe to
- # release the WAL up to this LSN.
- if self.last_end_lsn is not None and self.last_end_lsn != self.last_confirmed_lsn:
- self.reader.confirm_position(self.last_end_lsn)
- self.last_confirmed_lsn = self.last_end_lsn
+ # 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.reader.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,
diff --git a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
index a0bce70d97a8..865bfcd6f096 100644
--- a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -1,4 +1,5 @@
import uuid
+from contextlib import nullcontext
from datetime import UTC, datetime
from typing import Literal
@@ -1254,6 +1255,95 @@ class TestCDCExtractActivity:
assert any("status" in call.kwargs.get("update_fields", []) for call in mock_job.save.call_args_list)
+class TestSlotAdvanceTransactionSafety:
+ """The slot must only advance past FULLY-yielded transactions.
+
+ A micro-flush can fire mid-transaction (the batcher threshold is per-event).
+ Since every event of a transaction shares its commit end LSN, advancing to that
+ LSN while the transaction's tail is still un-yielded would lose the tail on crash.
+ """
+
+ @pytest.mark.parametrize(
+ "event_positions,max_events,crashes,expected_advances",
+ [
+ # Mid-transaction flush: txn-1 (0/100) ×2 then txn-2 (0/200) ×3, flush after
+ # 4 events lands mid txn-2. The micro-flush advances only to txn-1's end LSN;
+ # the final flush advances to txn-2's.
+ (["0/100", "0/100", "0/200", "0/200", "0/200"], 4, False, ["0/100", "0/200"]),
+ # Single transaction (one commit LSN): a threshold of 2 forces a mid-transaction
+ # micro-flush, but the transaction never completes during the loop, so no
+ # micro-advance may happen — only the final flush advances, once.
+ (["0/100", "0/100", "0/100"], 2, False, ["0/100"]),
+ # Crash mid txn-2 (after the micro-flush at 4 events, before txn-2 finishes):
+ # the slot stays at txn-1's end and must never reach txn-2's LSN.
+ (["0/100", "0/100", "0/200", "0/200"], 4, True, ["0/100"]),
+ ],
+ )
+ @patch("posthog.temporal.data_imports.cdc.activities.ChangeEventBatcher")
+ @patch("posthog.temporal.data_imports.cdc.activities.activity")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
+ @patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch.object(CDCExtractActivity, "_get_cdc_schemas")
+ @patch("posthog.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("posthog.temporal.data_imports.cdc.activities.ExternalDataJob")
+ @patch("posthog.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_slot_advances_only_past_completed_transactions(
+ self,
+ mock_close_conns,
+ MockJob,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ MockS3Writer,
+ MockProducer,
+ mock_activity,
+ MockBatcher,
+ event_positions,
+ max_events,
+ crashes,
+ expected_advances,
+ ):
+ from posthog.temporal.data_imports.cdc.batcher import ChangeEventBatcher as RealBatcher
+
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ events = [
+ _make_event(op="I", table="users", position=pos, columns={"id": i}) for i, pos in enumerate(event_positions)
+ ]
+
+ mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
+ mock_activity,
+ MockProducer,
+ MockS3Writer,
+ mock_get_adapter,
+ mock_get_schemas,
+ MockSourceModel,
+ MockJob,
+ mock_close_conns,
+ source,
+ [schema],
+ events,
+ )
+
+ if crashes:
+ # The source dies after yielding the listed events but before txn-2 finishes.
+ def _dying_changes():
+ yield from events
+ raise RuntimeError("pod killed mid-transaction")
+
+ mock_reader.read_changes.return_value = _dying_changes()
+
+ MockBatcher.return_value = RealBatcher(max_events=max_events)
+
+ run_ctx = pytest.raises(RuntimeError, match="pod killed mid-transaction") if crashes else nullcontext()
+ with run_ctx:
+ cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
+
+ advanced_positions = [c.args[0] for c in mock_reader.confirm_position.call_args_list]
+ assert advanced_positions == expected_advances
+
+
class TestSlotInvalidationRecovery:
"""When the replication slot is invalidated/dropped on the source DB, the activity
must recreate it and reset all CDC schemas to snapshot mode instead of failing forever."""