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): auto-recover CDC when replication slot is invalidated (#63133)

Daniel RC7b33f2b06976
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.py
index 54d4cf402356..07a87ffb37c0 100644
--- a/posthog/temporal/data_imports/cdc/activities.py
+++ b/posthog/temporal/data_imports/cdc/activities.py
@@ -43,6 +43,18 @@ from products.warehouse_sources.backend.models.external_data_source import Exter
logger = structlog.get_logger(__name__)
+# Shown as latest_error on schemas reset by slot-invalidation recovery.
+SLOT_INVALIDATION_RECOVERY_MESSAGE = (
+ "The source database invalidated this source's replication slot (its WAL retention limit was "
+ "exceeded), so changes since the last successful sync could not be read. PostHog recreated the "
+ "slot and scheduled a full re-sync of this table; change data capture resumes automatically "
+ "once the re-sync completes."
+)
+
+# The sweeper's auto-drop must fire below the engine's own retention cap, otherwise the
+# engine invalidates the slot first and we lose the chance to act cleanly.
+RETENTION_CAP_SAFETY_FACTOR = 0.8
+
@dataclasses.dataclass
class CDCExtractInput:
@@ -496,6 +508,14 @@ class CDCExtractActivity:
self._update_log_positions()
except Exception as exc:
+ if self.adapter is not None and self.adapter.is_slot_invalidation_error(exc):
+ try:
+ self._recover_from_slot_invalidation(exc)
+ return
+ except Exception as recovery_exc:
+ self.log.exception("cdc_slot_recovery_failed")
+ self._handle_failure(recovery_exc)
+ raise
self._handle_failure(exc)
raise
finally:
@@ -685,21 +705,32 @@ class CDCExtractActivity:
trunc_schema = self.schema_by_name.get(table_name)
if trunc_schema is None:
continue
- trunc_log = self._schema_log(trunc_schema)
- trunc_log.warning("truncate_detected", table=table_name, schema_id=str(trunc_schema.id))
- trunc_schema.sync_type_config["cdc_mode"] = "snapshot"
- trunc_schema.sync_type_config.pop("cdc_last_log_position", None)
- trunc_schema.initial_sync_complete = False
- trunc_schema.save(update_fields=["sync_type_config", "initial_sync_complete", "updated_at"])
- try:
- from products.data_warehouse.backend.data_load.service import unpause_external_data_schedule
-
- unpause_external_data_schedule(str(trunc_schema.id))
- trunc_log.info("unpaused_schema_schedule_for_resnapshot", schema_id=str(trunc_schema.id))
- except Exception:
- trunc_log.warning("failed_to_unpause_schema_schedule", schema_id=str(trunc_schema.id))
+ self._schema_log(trunc_schema).warning(
+ "truncate_detected", table=table_name, schema_id=str(trunc_schema.id)
+ )
+ self._reset_schema_to_snapshot(trunc_schema)
+ self._unpause_schema_schedule(trunc_schema)
return truncated_tables
+ def _reset_schema_to_snapshot(self, schema: ExternalDataSchema, *, clear_deferred_runs: bool = False) -> None:
+ """Put a schema back into snapshot mode so its own schedule re-syncs it from scratch."""
+ schema.sync_type_config["cdc_mode"] = "snapshot"
+ schema.sync_type_config.pop("cdc_last_log_position", None)
+ if clear_deferred_runs:
+ schema.sync_type_config.pop("cdc_deferred_runs", None)
+ schema.initial_sync_complete = False
+ schema.save(update_fields=["sync_type_config", "initial_sync_complete", "updated_at"])
+
+ def _unpause_schema_schedule(self, schema: ExternalDataSchema) -> None:
+ schema_log = self._schema_log(schema)
+ try:
+ from products.data_warehouse.backend.data_load.service import unpause_external_data_schedule
+
+ unpause_external_data_schedule(str(schema.id))
+ schema_log.info("unpaused_schema_schedule_for_resnapshot", schema_id=str(schema.id))
+ except Exception:
+ schema_log.warning("failed_to_unpause_schema_schedule", schema_id=str(schema.id), exc_info=True)
+
def _handle_no_changes(self, truncated_tables: list[str]) -> None:
"""Early-return path: no DML events were read."""
if truncated_tables:
@@ -805,15 +836,56 @@ class CDCExtractActivity:
# ------------------------------------------------------------------
# Failure / success finalization
# ------------------------------------------------------------------
- def _handle_failure(self, exc: Exception) -> None:
- self.log.exception("cdc_extract_failed")
+ def _fail_created_jobs(self, error: str) -> None:
for job in self.created_jobs:
if job.status == ExternalDataJob.Status.RUNNING:
job.status = ExternalDataJob.Status.FAILED
# NOTE: may need to truncate if stack traces grow unwieldy
- job.latest_error = str(exc)
+ job.latest_error = error
job.finished_at = dt.datetime.now(tz=dt.UTC)
job.save(update_fields=["status", "latest_error", "finished_at", "updated_at"])
+
+ def _recover_from_slot_invalidation(self, exc: Exception) -> None:
+ """The slot can't be resumed (invalidated or dropped on the source DB): recreate it
+ and reset every CDC schema to snapshot mode so it re-syncs from current table state.
+
+ WAL between the slot's last confirmed position and the new slot's consistent point is
+ gone — the re-snapshot covers current rows, but intermediate changes in that gap
+ (including their _cdc history rows) cannot be recovered.
+ """
+ assert self.source is not None
+ assert self.adapter is not None
+ self.log.warning("cdc_slot_unrecoverable_recreating", error=str(exc))
+
+ self._fail_created_jobs(SLOT_INVALIDATION_RECOVERY_MESSAGE)
+
+ # Reset schemas before touching the slot (schedules stay paused): if recreation
+ # fails below, the next run hits the invalidation again and recovery reruns
+ # idempotently — no schema keeps streaming across the gap unnoticed. Deferred
+ # runs are dropped: they reference WAL from the dead slot, the re-snapshot
+ # supersedes them, and flushing them later would merge stale rows over fresh ones.
+ for schema in self.cdc_schemas:
+ self._reset_schema_to_snapshot(schema, clear_deferred_runs=True)
+ schema.status = ExternalDataSchema.Status.FAILED
+ schema.latest_error = SLOT_INVALIDATION_RECOVERY_MESSAGE
+ schema.save(update_fields=["status", "latest_error", "updated_at"])
+ self._schema_log(schema).warning("cdc_schema_reset_for_slot_recovery", schema_id=str(schema.id))
+
+ resource_fields = self.adapter.recreate_slot(self.source, tables=[s.name for s in self.cdc_schemas])
+
+ self.source.job_inputs = {**(self.source.job_inputs or {}), **resource_fields}
+ self.source.save(update_fields=["job_inputs", "updated_at"])
+
+ # Unpause only after the new slot exists, so no snapshot can run before change
+ # capture has a consistent point to resume from.
+ for schema in self.cdc_schemas:
+ self._unpause_schema_schedule(schema)
+
+ self.log.info("cdc_slot_recovery_complete", schemas_reset=len(self.cdc_schemas))
+
+ def _handle_failure(self, exc: Exception) -> None:
+ self.log.exception("cdc_extract_failed")
+ self._fail_created_jobs(str(exc))
for schema in self.cdc_schemas:
schema.status = ExternalDataSchema.Status.FAILED
# NOTE: may need to truncate if stack traces grow unwieldy
@@ -930,6 +1002,7 @@ def cleanup_orphan_slots_activity() -> None:
try:
with adapter.management_connection(source, connect_timeout=10) as conn:
lag_bytes = adapter.get_lag_bytes(conn, cdc_config.slot_name)
+ retention_cap_mb = adapter.get_retention_cap_mb(conn)
except Exception:
source_log.exception("failed_to_check_slot_lag")
continue
@@ -940,11 +1013,16 @@ def cleanup_orphan_slots_activity() -> None:
lag_mb = lag_bytes / (1024 * 1024)
- if lag_mb >= cdc_config.lag_critical_threshold_mb:
+ critical_threshold_mb = cdc_config.lag_critical_threshold_mb
+ if retention_cap_mb is not None:
+ critical_threshold_mb = min(critical_threshold_mb, int(retention_cap_mb * RETENTION_CAP_SAFETY_FACTOR))
+
+ if lag_mb >= critical_threshold_mb:
source_log.error(
"slot_lag_critical",
lag_mb=round(lag_mb, 1),
- threshold_mb=cdc_config.lag_critical_threshold_mb,
+ threshold_mb=critical_threshold_mb,
+ retention_cap_mb=retention_cap_mb,
)
if cdc_config.management_mode == "posthog" and cdc_config.auto_drop_slot:
diff --git a/posthog/temporal/data_imports/cdc/adapters.py b/posthog/temporal/data_imports/cdc/adapters.py
index d83e8289e4e3..0f7614eace89 100644
--- a/posthog/temporal/data_imports/cdc/adapters.py
+++ b/posthog/temporal/data_imports/cdc/adapters.py
@@ -74,6 +74,27 @@ class CDCSourceAdapter(Protocol[CDCConfigT_co]):
def get_lag_bytes(self, conn: Any, slot_name: str) -> int | None: ...
+ def get_retention_cap_mb(self, conn: Any) -> int | None:
+ """Engine-enforced cap on retained change-stream backlog in MB (PG:
+ max_slot_wal_keep_size). None when unlimited or unknown. Once the backlog
+ crosses this cap the engine invalidates the slot itself, so safety nets
+ must act below it."""
+ ...
+
+ def is_slot_invalidation_error(self, exc: BaseException) -> bool:
+ """Whether the exception means the engine invalidated or dropped the
+ change-stream resource (PG: replication slot lost to max_slot_wal_keep_size)
+ such that it cannot be resumed and must be recreated."""
+ ...
+
+ def recreate_slot(self, source: ExternalDataSource, tables: list[str]) -> dict[str, Any]:
+ """Drop and recreate the change-stream resource after invalidation, against the
+ existing capture definition (recreating it when PostHog owns it). ``tables`` is
+ the capture set used if the definition must be recreated. Returns ``cdc_*``
+ job_inputs updates (e.g. the new consistent point). Raises when recreation isn't
+ possible (e.g. a customer-owned publication is missing)."""
+ ...
+
def parse_cdc_config(self, source: ExternalDataSource) -> CDCConfigT_co: ...
def setup_resources(
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 a5317dc0b256..cf57fae34e83 100644
--- a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -5,7 +5,15 @@ from typing import Literal
import pytest
from unittest.mock import MagicMock, patch
-from posthog.temporal.data_imports.cdc.activities import CDCExtractActivity, CDCExtractInput, cdc_extract_activity
+import psycopg.errors
+
+from posthog.temporal.data_imports.cdc.activities import (
+ SLOT_INVALIDATION_RECOVERY_MESSAGE,
+ CDCExtractActivity,
+ CDCExtractInput,
+ cdc_extract_activity,
+ cleanup_orphan_slots_activity,
+)
from posthog.temporal.data_imports.cdc.types import ChangeEvent
@@ -99,6 +107,7 @@ def _setup_mocks(
mock_reader.get_decoder_key_columns.return_value = []
mock_adapter = MagicMock()
mock_adapter.create_reader.return_value = mock_reader
+ mock_adapter.is_slot_invalidation_error.return_value = False
mock_get_adapter.return_value = mock_adapter
mock_s3 = MagicMock()
@@ -557,6 +566,7 @@ class TestCDCExtractActivity:
mock_reader.truncated_tables = []
mock_adapter = MagicMock()
mock_adapter.create_reader.return_value = mock_reader
+ mock_adapter.is_slot_invalidation_error.return_value = False
mock_get_adapter.return_value = mock_adapter
inputs = CDCExtractInput(team_id=1, source_id=source.id)
@@ -1103,3 +1113,178 @@ class TestCDCExtractActivity:
# Job should be marked COMPLETED by the activity (no Kafka consumer will do it)
assert any("status" in call.kwargs.get("update_fields", []) for call in mock_job.save.call_args_list)
+
+
+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."""
+
+ def _setup(self, mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity):
+ source = _make_source()
+ MockSourceModel.objects.get.return_value = source
+
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ schema.sync_type_config["cdc_last_log_position"] = "0/OLD"
+ schema.sync_type_config["cdc_deferred_runs"] = [{"run_uuid": "stale"}]
+ mock_get_schemas.return_value = [schema]
+
+ invalidation_error = psycopg.errors.ObjectNotInPrerequisiteState(
+ 'can no longer get changes from replication slot "posthog_slot"\n'
+ "DETAIL: This slot has been invalidated because it exceeded the maximum reserved size."
+ )
+ mock_reader = MagicMock()
+ mock_reader.read_changes.side_effect = invalidation_error
+ mock_reader.truncated_tables = []
+
+ mock_adapter = MagicMock()
+ mock_adapter.create_reader.return_value = mock_reader
+ mock_adapter.is_slot_invalidation_error.return_value = True
+ mock_get_adapter.return_value = mock_adapter
+
+ mock_activity.heartbeat = MagicMock()
+ mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1")
+
+ return source, schema, mock_reader, mock_adapter
+
+ @patch("posthog.temporal.data_imports.cdc.activities.activity")
+ @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.close_old_connections")
+ def test_invalidated_slot_is_recreated_and_schemas_reset_to_snapshot(
+ self,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ mock_activity,
+ ):
+ source, schema, mock_reader, mock_adapter = self._setup(
+ mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity
+ )
+
+ def _recreate_slot(source_arg, tables):
+ # Schemas must already be reset when the slot is recreated — if recreation
+ # fails, no schema may keep streaming across the gap on the next run.
+ assert schema.sync_type_config["cdc_mode"] == "snapshot"
+ return {"cdc_consistent_point": "0/AA"}
+
+ mock_adapter.recreate_slot.side_effect = _recreate_slot
+
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
+ # Recovery handles the error — the activity must not raise (no pointless Temporal retries).
+ cdc_extract_activity(inputs)
+
+ mock_adapter.recreate_slot.assert_called_once_with(source, tables=["users"])
+ assert source.job_inputs["cdc_consistent_point"] == "0/AA"
+ source.save.assert_called()
+
+ assert schema.sync_type_config["cdc_mode"] == "snapshot"
+ assert "cdc_last_log_position" not in schema.sync_type_config
+ assert "cdc_deferred_runs" not in schema.sync_type_config
+ assert schema.initial_sync_complete is False
+ assert schema.status == "Failed"
+ assert schema.latest_error == SLOT_INVALIDATION_RECOVERY_MESSAGE
+
+ mock_reader.close.assert_called_once()
+
+ @patch("posthog.temporal.data_imports.cdc.activities.activity")
+ @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.close_old_connections")
+ def test_recovery_failure_marks_schemas_failed_and_raises(
+ self,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ mock_activity,
+ ):
+ source, schema, mock_reader, mock_adapter = self._setup(
+ mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity
+ )
+ mock_adapter.recreate_slot.side_effect = RuntimeError("cannot recreate slot")
+
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
+ with pytest.raises(RuntimeError, match="cannot recreate slot"):
+ cdc_extract_activity(inputs)
+
+ assert schema.status == "Failed"
+ assert "cannot recreate slot" in schema.latest_error
+ mock_reader.close.assert_called_once()
+
+ @patch("posthog.temporal.data_imports.cdc.activities.activity")
+ @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.close_old_connections")
+ def test_non_invalidation_errors_do_not_trigger_recovery(
+ self,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ mock_activity,
+ ):
+ source, schema, mock_reader, mock_adapter = self._setup(
+ mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity
+ )
+ mock_reader.read_changes.side_effect = RuntimeError("connection lost")
+ mock_adapter.is_slot_invalidation_error.return_value = False
+
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
+ with pytest.raises(RuntimeError, match="connection lost"):
+ cdc_extract_activity(inputs)
+
+ mock_adapter.recreate_slot.assert_not_called()
+ assert schema.sync_type_config["cdc_mode"] == "streaming"
+
+
+class TestCleanupOrphanSlotsRetentionCap:
+ """The sweeper's auto-drop must fire below the engine's own retention cap
+ (max_slot_wal_keep_size), otherwise the engine invalidates the slot first."""
+
+ def _setup(self, mock_get_adapter, MockSourceModel, lag_mb, cap_mb):
+ source = _make_source()
+ qs = MockSourceModel.objects.filter.return_value
+ qs.exclude.return_value.exclude.return_value.exclude.return_value.exclude.return_value = [source]
+
+ cdc_config = MagicMock()
+ cdc_config.slot_name = "posthog_slot"
+ cdc_config.publication_name = "posthog_pub"
+ cdc_config.management_mode = "posthog"
+ cdc_config.auto_drop_slot = True
+ cdc_config.lag_warning_threshold_mb = 1024
+ cdc_config.lag_critical_threshold_mb = 10240
+
+ mock_adapter = MagicMock()
+ mock_adapter.parse_cdc_config.return_value = cdc_config
+ mock_adapter.get_lag_bytes.return_value = lag_mb * 1024 * 1024
+ mock_adapter.get_retention_cap_mb.return_value = cap_mb
+ mock_get_adapter.return_value = mock_adapter
+ return source, mock_adapter
+
+ @patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch("posthog.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("posthog.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_retention_cap_lowers_critical_threshold(self, mock_close_conns, MockSourceModel, mock_get_adapter):
+ # Configured critical is 10240 MB, but the engine caps retention at 1000 MB:
+ # at 900 MB of lag (>= 80% of the cap) the sweeper must already act.
+ source, mock_adapter = self._setup(mock_get_adapter, MockSourceModel, lag_mb=900, cap_mb=1000)
+
+ cleanup_orphan_slots_activity()
+
+ mock_adapter.drop_resources.assert_called_once()
+ assert source.status is MockSourceModel.Status.ERROR
+ source.save.assert_called()
+
+ @patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch("posthog.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("posthog.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_unlimited_retention_keeps_configured_threshold(self, mock_close_conns, MockSourceModel, mock_get_adapter):
+ source, mock_adapter = self._setup(mock_get_adapter, MockSourceModel, lag_mb=900, cap_mb=None)
+
+ cleanup_orphan_slots_activity()
+
+ mock_adapter.drop_resources.assert_not_called()
diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py b/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py
index 6e0ca7c38e7c..e6cc6000de3a 100644
--- a/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py
@@ -15,7 +15,9 @@ from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import (
create_slot_and_publication,
drop_slot,
drop_slot_and_publication,
+ get_max_slot_wal_keep_size_mb,
get_slot_lag_bytes,
+ is_slot_invalidation_error,
publication_exists,
remove_table_from_publication,
slot_exists,
@@ -85,6 +87,39 @@ class PostgresCDCAdapter:
def get_lag_bytes(self, conn: Any, slot_name: str) -> int | None:
return get_slot_lag_bytes(conn, slot_name)
+ def get_retention_cap_mb(self, conn: Any) -> int | None:
+ return get_max_slot_wal_keep_size_mb(conn)
+
+ def is_slot_invalidation_error(self, exc: BaseException) -> bool:
+ return is_slot_invalidation_error(exc)
+
+ def recreate_slot(self, source: ExternalDataSource, tables: list[str]) -> dict[str, Any]:
+ """Drop the dead replication slot and create a fresh one against the existing
+ publication, recreating the publication first when PostHog owns it and it's gone.
+ Returns the job_inputs updates (new consistent point). Raises when recreation
+ isn't possible (no slot configured, customer-owned publication missing).
+ """
+ cdc_config = self.parse_cdc_config(source)
+ if not cdc_config.slot_name:
+ raise RuntimeError("Cannot recreate CDC replication slot: no slot name configured for this source")
+
+ schema = self._resolve_schema(source)
+ with cdc_pg_connection(source) as conn:
+ drop_slot(conn, cdc_config.slot_name)
+ if cdc_config.publication_name and not publication_exists(conn, cdc_config.publication_name):
+ if cdc_config.management_mode != "posthog":
+ raise RuntimeError(
+ f"Publication '{cdc_config.publication_name}' does not exist on the source database. "
+ "Recreate it (see the CDC setup instructions), then resync the source."
+ )
+ consistent_point = create_slot_and_publication(
+ conn, cdc_config.slot_name, cdc_config.publication_name, schema, tables=tables
+ )
+ else:
+ consistent_point = create_slot(conn, cdc_config.slot_name)
+
+ return {"cdc_consistent_point": consistent_point}
+
def setup_resources(
self,
source: ExternalDataSource,
diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/config.py b/posthog/temporal/data_imports/sources/postgres/cdc/config.py
index 1a18e2ce9d21..e542406b0add 100644
--- a/posthog/temporal/data_imports/sources/postgres/cdc/config.py
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/config.py
@@ -16,8 +16,8 @@ from posthog.temporal.data_imports.cdc.adapters import CDCConfig, ManagementMode
if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
-DEFAULT_LAG_WARNING_THRESHOLD_MB = 1024
-DEFAULT_LAG_CRITICAL_THRESHOLD_MB = 10240
+DEFAULT_LAG_WARNING_THRESHOLD_MB = 512
+DEFAULT_LAG_CRITICAL_THRESHOLD_MB = 2048
@dataclasses.dataclass(frozen=True, kw_only=True)
diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.py b/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.py
index ea8b4aaeaf00..413aa97f4956 100644
--- a/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.py
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.py
@@ -199,6 +199,49 @@ def remove_table_from_publication(
logger.info("Removed table %s.%s from publication '%s'", schema, table, pub_name)
+# Substrings of the errors Postgres raises when reading from / advancing a slot that it
+# invalidated (max_slot_wal_keep_size exceeded). Wordings differ across PG 13–17.
+_SLOT_INVALIDATION_MESSAGE_MARKERS = (
+ "can no longer get changes from replication slot",
+ "slot has been invalidated",
+ "cannot advance replication slot that has not previously reserved WAL",
+)
+
+
+def is_slot_invalidation_error(exc: BaseException) -> bool:
+ """Whether the exception (or anything in its chain) means the replication slot is
+ unusable and must be recreated: invalidated by Postgres or dropped entirely.
+ """
+ seen: set[int] = set()
+ current: BaseException | None = exc
+ while current is not None and id(current) not in seen:
+ seen.add(id(current))
+ message = str(current)
+ if isinstance(current, psycopg.errors.ObjectNotInPrerequisiteState) and any(
+ marker in message for marker in _SLOT_INVALIDATION_MESSAGE_MARKERS
+ ):
+ return True
+ if (
+ isinstance(current, psycopg.errors.UndefinedObject)
+ and "replication slot" in message
+ and "does not exist" in message
+ ):
+ return True
+ current = current.__cause__ or current.__context__
+ return False
+
+
+def get_max_slot_wal_keep_size_mb(conn: psycopg.Connection) -> int | None:
+ """The server's max_slot_wal_keep_size in MB, or None when unlimited (-1) or unreadable."""
+ with conn.cursor() as cur:
+ cur.execute("SELECT setting::bigint FROM pg_settings WHERE name = 'max_slot_wal_keep_size'")
+ row = cur.fetchone()
+ if row is None or row[0] is None:
+ return None
+ value = int(row[0])
+ return value if value >= 0 else None
+
+
def get_slot_lag_bytes(conn: psycopg.Connection, slot_name: str) -> int | None:
"""Get the WAL lag in bytes for a replication slot.
diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py b/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py
index 42479f7fabc2..ddf3395760ce 100644
--- a/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py
@@ -1,3 +1,4 @@
+import pytest
from unittest.mock import MagicMock, patch
from posthog.temporal.data_imports.sources.postgres.cdc.adapter import PostgresCDCAdapter
@@ -96,6 +97,81 @@ class TestSetupResourcesPreflight:
assert mock_drop.call_args.args[1:] == ("s", "p")
+class TestRecreateSlot:
+ @patch(f"{_ADAPTER}.create_slot_and_publication")
+ @patch(f"{_ADAPTER}.create_slot", return_value="0/AA")
+ @patch(f"{_ADAPTER}.publication_exists", return_value=True)
+ @patch(f"{_ADAPTER}.drop_slot")
+ @patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
+ def test_drops_and_recreates_slot_against_existing_publication(
+ self, _conn, mock_drop, _pub_exists, mock_create, mock_create_slot_and_pub
+ ) -> None:
+ source = _source(
+ cdc_enabled=True,
+ cdc_management_mode="posthog",
+ cdc_slot_name="posthog_slot",
+ cdc_publication_name="posthog_pub",
+ )
+
+ fields = PostgresCDCAdapter().recreate_slot(source, tables=["users", "orders"])
+
+ assert fields == {"cdc_consistent_point": "0/AA"}
+ mock_drop.assert_called_once()
+ assert mock_drop.call_args.args[1] == "posthog_slot"
+ mock_create.assert_called_once()
+ assert mock_create.call_args.args[1] == "posthog_slot"
+ mock_create_slot_and_pub.assert_not_called()
+
+ @patch(f"{_ADAPTER}.create_slot_and_publication", return_value="0/BB")
+ @patch(f"{_ADAPTER}.create_slot")
+ @patch(f"{_ADAPTER}.publication_exists", return_value=False)
+ @patch(f"{_ADAPTER}.drop_slot")
+ @patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
+ def test_recreates_publication_when_posthog_managed_and_missing(
+ self, _conn, mock_drop, _pub_exists, mock_create, mock_create_slot_and_pub
+ ) -> None:
+ source = _source(
+ cdc_enabled=True,
+ cdc_management_mode="posthog",
+ cdc_slot_name="posthog_slot",
+ cdc_publication_name="posthog_pub",
+ )
+
+ fields = PostgresCDCAdapter().recreate_slot(source, tables=["users"])
+
+ assert fields == {"cdc_consistent_point": "0/BB"}
+ mock_create_slot_and_pub.assert_called_once()
+ assert mock_create_slot_and_pub.call_args.args[1:3] == ("posthog_slot", "posthog_pub")
+ assert mock_create_slot_and_pub.call_args.kwargs["tables"] == ["users"]
+ mock_create.assert_not_called()
+
+ @patch(f"{_ADAPTER}.create_slot_and_publication")
+ @patch(f"{_ADAPTER}.create_slot")
+ @patch(f"{_ADAPTER}.publication_exists", return_value=False)
+ @patch(f"{_ADAPTER}.drop_slot")
+ @patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
+ def test_raises_when_self_managed_publication_missing(
+ self, _conn, mock_drop, _pub_exists, mock_create, mock_create_slot_and_pub
+ ) -> None:
+ source = _source(
+ cdc_enabled=True,
+ cdc_management_mode="self_managed",
+ cdc_slot_name="posthog_slot",
+ cdc_publication_name="customer_pub",
+ )
+
+ with pytest.raises(RuntimeError, match="does not exist"):
+ PostgresCDCAdapter().recreate_slot(source, tables=["users"])
+
+ mock_create.assert_not_called()
+ mock_create_slot_and_pub.assert_not_called()
+
+ def test_raises_without_slot_name(self) -> None:
+ source = _source(cdc_enabled=True)
+ with pytest.raises(RuntimeError, match="no slot name"):
+ PostgresCDCAdapter().recreate_slot(source, tables=[])
+
+
class TestAlterPublicationMembership:
@patch(f"{_ADAPTER}.add_table_to_publication")
@patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_slot_manager.py b/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_slot_manager.py
index c9164ce5a233..8047d9831f43 100644
--- a/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_slot_manager.py
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_slot_manager.py
@@ -8,10 +8,13 @@ from unittest import mock
from unittest.mock import MagicMock
import psycopg.errors
+from parameterized import parameterized
from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import (
add_table_to_publication,
cdc_pg_connection,
+ get_max_slot_wal_keep_size_mb,
+ is_slot_invalidation_error,
remove_table_from_publication,
)
from posthog.temporal.data_imports.sources.postgres.postgres import SSL_REQUIRED_AFTER_DATE
@@ -56,6 +59,76 @@ class TestAddTableToPublication:
conn.commit.assert_not_called()
+class TestIsSlotInvalidationError:
+ @parameterized.expand(
+ [
+ (
+ "invalidated_max_reserved_size",
+ psycopg.errors.ObjectNotInPrerequisiteState(
+ 'can no longer get changes from replication slot "posthog_019e51352190"\n'
+ "DETAIL: This slot has been invalidated because it exceeded the maximum reserved size."
+ ),
+ True,
+ ),
+ (
+ "invalidated_pg17_wording",
+ psycopg.errors.ObjectNotInPrerequisiteState(
+ 'This replication slot has been invalidated due to "wal_removed".'
+ ),
+ True,
+ ),
+ (
+ "advance_on_invalidated_slot",
+ psycopg.errors.ObjectNotInPrerequisiteState(
+ "cannot advance replication slot that has not previously reserved WAL"
+ ),
+ True,
+ ),
+ (
+ "slot_dropped",
+ psycopg.errors.UndefinedObject('replication slot "posthog_019e51352190" does not exist'),
+ True,
+ ),
+ (
+ "publication_missing_is_not_slot_loss",
+ psycopg.errors.UndefinedObject('publication "posthog_pub" does not exist'),
+ False,
+ ),
+ (
+ "other_prerequisite_error",
+ psycopg.errors.ObjectNotInPrerequisiteState("logical decoding requires wal_level >= logical"),
+ False,
+ ),
+ ("unrelated_error", RuntimeError("connection lost"), False),
+ ]
+ )
+ def test_detection(self, _name, exc, expected):
+ assert is_slot_invalidation_error(exc) is expected
+
+ def test_detects_error_in_exception_chain(self):
+ cause = psycopg.errors.ObjectNotInPrerequisiteState(
+ 'can no longer get changes from replication slot "posthog_x"'
+ )
+ wrapper = RuntimeError("read failed")
+ wrapper.__cause__ = cause
+ assert is_slot_invalidation_error(wrapper) is True
+
+
+class TestGetMaxSlotWalKeepSizeMb:
+ @parameterized.expand(
+ [
+ ("configured", (5120,), 5120),
+ ("unlimited", (-1,), None),
+ ("missing_setting", None, None),
+ ]
+ )
+ def test_parsing(self, _name, row, expected):
+ conn, cursor = _mock_conn()
+ cursor.fetchone.return_value = row
+
+ assert get_max_slot_wal_keep_size_mb(conn) == expected
+
+
class TestRemoveTableFromPublication:
def test_remove_table_success(self):
conn, cursor = _mock_conn()
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 2545cc89dfb1..763fce26214e 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -48,6 +48,10 @@ from posthog.temporal.data_imports.sources.common.schema import SourceSchema, bu
from posthog.temporal.data_imports.sources.common.sql import filter_dwh_columns_by_enabled_columns, sql_schema_metadata
from posthog.temporal.data_imports.sources.common.sql.base import SQLSource
from posthog.temporal.data_imports.sources.custom.source import MAX_CUSTOM_SOURCES_PER_TEAM, manifest_request_hosts
+from posthog.temporal.data_imports.sources.postgres.cdc.config import (
+ DEFAULT_LAG_CRITICAL_THRESHOLD_MB,
+ DEFAULT_LAG_WARNING_THRESHOLD_MB,
+)
from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import cdc_pg_connection
from posthog.temporal.data_imports.sources.postgres.postgres import get_primary_key_columns, source_requires_ssl
from posthog.temporal.data_imports.sources.postgres.source import PostgresSource
@@ -1691,8 +1695,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
{
"cdc_enabled": True,
"cdc_auto_drop_slot": payload.get("cdc_auto_drop_slot", True),
- "cdc_lag_warning_threshold_mb": payload.get("cdc_lag_warning_threshold_mb", 1024),
- "cdc_lag_critical_threshold_mb": payload.get("cdc_lag_critical_threshold_mb", 10240),
+ "cdc_lag_warning_threshold_mb": payload.get(
+ "cdc_lag_warning_threshold_mb", DEFAULT_LAG_WARNING_THRESHOLD_MB
+ ),
+ "cdc_lag_critical_threshold_mb": payload.get(
+ "cdc_lag_critical_threshold_mb", DEFAULT_LAG_CRITICAL_THRESHOLD_MB
+ ),
}
)
job_inputs.update(resource_fields)
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index 8e2817b1cb5a..4d1308565412 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -7501,8 +7501,8 @@ def _make_postgres_source(
"cdc_slot_name": slot_name,
"cdc_publication_name": pub_name,
"cdc_auto_drop_slot": True,
- "cdc_lag_warning_threshold_mb": 1024,
- "cdc_lag_critical_threshold_mb": 10240,
+ "cdc_lag_warning_threshold_mb": 512,
+ "cdc_lag_critical_threshold_mb": 2048,
"cdc_consistent_point": "0/12345",
}
)
@@ -7736,8 +7736,8 @@ class TestEnableCDC(APIBaseTest):
payload.get("cdc_publication_name") or f"posthog_pub_{source_model.id.hex[:12]}"
),
"cdc_auto_drop_slot": payload.get("cdc_auto_drop_slot", True),
- "cdc_lag_warning_threshold_mb": payload.get("cdc_lag_warning_threshold_mb", 1024),
- "cdc_lag_critical_threshold_mb": payload.get("cdc_lag_critical_threshold_mb", 10240),
+ "cdc_lag_warning_threshold_mb": payload.get("cdc_lag_warning_threshold_mb", 512),
+ "cdc_lag_critical_threshold_mb": payload.get("cdc_lag_critical_threshold_mb", 2048),
"cdc_consistent_point": "0/ABCDEF",
}
)
@@ -8280,8 +8280,8 @@ class TestUpdateCDCSettings(APIBaseTest):
assert ji["cdc_publication_name"] == original_pub
assert ji["cdc_management_mode"] == original_mode
# Thresholds preserved at defaults.
- assert int(ji["cdc_lag_warning_threshold_mb"]) == 1024
- assert int(ji["cdc_lag_critical_threshold_mb"]) == 10240
+ assert int(ji["cdc_lag_warning_threshold_mb"]) == 512
+ assert int(ji["cdc_lag_critical_threshold_mb"]) == 2048
def test_update_cdc_settings_empty_payload_is_unchanged(self) -> None:
source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)