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.

feat(data-warehouse): add CDC error taxonomy and friendly messages (#65590)

Daniel RC599e80f09380
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.py
index 7fb008e31ef0..8407ed500ab3 100644
--- a/posthog/temporal/data_imports/cdc/activities.py
+++ b/posthog/temporal/data_imports/cdc/activities.py
@@ -20,6 +20,7 @@ from django.db import close_old_connections
import pyarrow as pa
import structlog
+import posthoganalytics
from temporalio import activity
from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
@@ -32,12 +33,15 @@ from posthog.temporal.data_imports.cdc.batcher import (
deduplicate_table,
enrich_delete_rows,
)
+from posthog.temporal.data_imports.cdc.errors import MAX_FRIENDLY_MESSAGE_LENGTH, CDCErrorInfo, classify_cdc_error
from posthog.temporal.data_imports.cdc.types import ChangeEvent
from posthog.temporal.data_imports.pipelines.helpers import resolve_table_and_folder_names
from posthog.temporal.data_imports.pipelines.pipeline_v3.kafka.common import SyncTypeLiteral
from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer import PostgresProducer
from posthog.temporal.data_imports.pipelines.pipeline_v3.s3.writer import S3BatchWriter
+from posthog.temporal.data_imports.util import NonRetryableException
from posthog.temporal.data_imports.workflow_activities.create_job_model import _build_schema_snapshot
+from posthog.utils import get_machine_id
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
@@ -563,10 +567,8 @@ class CDCExtractActivity:
return
except Exception as recovery_exc:
self.log.exception("cdc_slot_recovery_failed")
- self._handle_failure(recovery_exc)
- raise
- self._handle_failure(exc)
- raise
+ self._fail(recovery_exc)
+ self._fail(exc)
finally:
if self.reader is not None:
self.reader.close()
@@ -946,7 +948,6 @@ class CDCExtractActivity:
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 = error
job.finished_at = dt.datetime.now(tz=dt.UTC)
job.save(update_fields=["status", "latest_error", "finished_at", "updated_at"])
@@ -991,16 +992,50 @@ class CDCExtractActivity:
self.log.info("cdc_slot_recovery_complete", schemas_reset=len(self.cdc_schemas))
- def _handle_failure(self, exc: Exception) -> None:
+ def _fail(self, exc: Exception) -> typing.NoReturn:
+ """Persist a friendly failure, emit analytics, and re-raise.
+
+ Non-retryable classifications raise ``NonRetryableException`` so the workflow's retry
+ policy stops re-running a deterministic failure; retryable ones re-raise as-is to let
+ Temporal retry.
+ """
+ info = self._handle_failure(exc)
+ if not info.retryable:
+ self._capture_non_retryable(info)
+ raise NonRetryableException(info.friendly_message) from exc
+ raise exc
+
+ def _handle_failure(self, exc: Exception) -> CDCErrorInfo:
+ """Classify the failure, store the friendly message on the jobs/schemas, return the info."""
self.log.exception("cdc_extract_failed")
- self._fail_created_jobs(str(exc))
+ info = classify_cdc_error(exc, self.adapter)
+ friendly = info.friendly_message[:MAX_FRIENDLY_MESSAGE_LENGTH]
+ self._fail_created_jobs(friendly)
for schema in self.cdc_schemas:
schema.status = ExternalDataSchema.Status.FAILED
- # NOTE: may need to truncate if stack traces grow unwieldy
- schema.latest_error = str(exc)
+ schema.latest_error = friendly
schema.save(update_fields=["status", "latest_error", "updated_at"])
- # Mirror the failure as a per-schema log line so it shows up in the Syncs panel.
- self._schema_log(schema).error("cdc_extract_schema_failed", error=str(exc))
+ # User-facing column gets the friendly copy; the raw error still routes to structured
+ # logs / the Syncs log viewer for debugging.
+ self._schema_log(schema).error(
+ "cdc_extract_schema_failed", error=str(exc), category=info.category, retryable=info.retryable
+ )
+ return info
+
+ def _capture_non_retryable(self, info: CDCErrorInfo) -> None:
+ # Best-effort: analytics must never mask the NonRetryableException the caller is about to raise.
+ try:
+ posthoganalytics.capture(
+ distinct_id=get_machine_id(),
+ event="cdc extraction non-retryable error",
+ properties={
+ "team_id": self.inputs.team_id,
+ "source_id": str(self.inputs.source_id),
+ "category": str(info.category),
+ },
+ )
+ except Exception:
+ self.log.warning("cdc_non_retryable_capture_failed", exc_info=True)
def _finalize_success(self) -> None:
now = dt.datetime.now(tz=dt.UTC)
diff --git a/posthog/temporal/data_imports/cdc/adapters.py b/posthog/temporal/data_imports/cdc/adapters.py
index 6d6cfbdf22ab..7773714a7b9c 100644
--- a/posthog/temporal/data_imports/cdc/adapters.py
+++ b/posthog/temporal/data_imports/cdc/adapters.py
@@ -24,6 +24,7 @@ from posthog.temporal.data_imports.sources.postgres.cdc.adapter import PostgresC
from products.data_warehouse.backend.types import ExternalDataSourceType
if TYPE_CHECKING:
+ from posthog.temporal.data_imports.cdc.errors import CDCErrorInfo
from posthog.temporal.data_imports.cdc.types import CDCStreamReader
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -71,6 +72,12 @@ class CDCSourceAdapter(Protocol[CDCConfigT_co]):
such that it cannot be resumed and must be recreated."""
...
+ def classify_error(self, exc: BaseException) -> CDCErrorInfo | None:
+ """Interpret a single engine-specific exception as a CDC error category, or None
+ when unrecognized (the caller falls back to the engine-agnostic default). Mirrors
+ ``is_slot_invalidation_error``: keeps psycopg/engine specifics out of the shared layer."""
+ ...
+
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
diff --git a/posthog/temporal/data_imports/cdc/errors.py b/posthog/temporal/data_imports/cdc/errors.py
new file mode 100644
index 000000000000..21ecdbac4094
--- /dev/null
+++ b/posthog/temporal/data_imports/cdc/errors.py
@@ -0,0 +1,133 @@
+"""CDC error taxonomy.
+
+Classifies an extraction failure into a user-facing category with a friendly,
+credential-safe message and a retryable flag. Engine-agnostic: the engine-specific
+interpretation (which psycopg exception means "authentication failed", etc.) lives
+behind ``CDCSourceAdapter.classify_error`` in each source's adapter, mirroring the
+``is_slot_invalidation_error`` seam. This module owns the shared vocabulary, the
+user-facing copy, and the orchestration-level fallbacks.
+"""
+
+from __future__ import annotations
+
+import enum
+import dataclasses
+from collections.abc import Iterator
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from posthog.temporal.data_imports.cdc.adapters import CDCSourceAdapter
+
+# Friendly messages land in the user-visible `latest_error`; cap them so the column stays tidy.
+MAX_FRIENDLY_MESSAGE_LENGTH = 500
+
+
+class CDCErrorCategory(enum.StrEnum):
+ AUTH_FAILED = "auth_failed"
+ SSL_REQUIRED = "ssl_required"
+ CONNECTION_FAILED = "connection_failed"
+ SLOT_MISSING = "slot_missing"
+ PUBLICATION_MISSING = "publication_missing"
+ SLOT_IN_USE = "slot_in_use"
+ WAL_DECODE_ERROR = "wal_decode_error"
+ TRANSACTION_TOO_LARGE = "transaction_too_large"
+ UNKNOWN = "unknown"
+
+
[email protected](frozen=True)
+class CDCErrorInfo:
+ category: CDCErrorCategory
+ friendly_message: str
+ retryable: bool
+
+
+class CDCTransactionTooLargeError(Exception):
+ """A single source transaction exceeded the in-memory decode budget.
+
+ Non-retryable: re-decoding replays the same oversized transaction. The decoder guard
+ that raises this lives in the source-specific decoder; the type is defined here so the
+ shared classifier owns the mapping to ``TRANSACTION_TOO_LARGE``.
+ """
+
+
+# (friendly_message, retryable) per category. Messages are STATIC templates — they never
+# interpolate host/user/password or raw exception text, so stored copy can't leak credentials.
+_CATEGORY_DEFAULTS: dict[CDCErrorCategory, tuple[str, bool]] = {
+ CDCErrorCategory.AUTH_FAILED: (
+ "Could not authenticate with the source database. Check the configured username and "
+ "password, then re-enable change data capture.",
+ False,
+ ),
+ CDCErrorCategory.SSL_REQUIRED: (
+ "Could not establish a required encrypted (SSL) connection to the source database. Check "
+ "that the database accepts SSL connections, then re-enable change data capture.",
+ False,
+ ),
+ CDCErrorCategory.CONNECTION_FAILED: (
+ "Could not connect to the source database. PostHog will keep retrying — if this persists, "
+ "check that the database is reachable and accepting connections.",
+ True,
+ ),
+ CDCErrorCategory.SLOT_MISSING: (
+ "The replication slot no longer exists on the source database, so changes can no longer be "
+ "read. Disable and re-enable change data capture to recreate it and re-sync.",
+ False,
+ ),
+ CDCErrorCategory.PUBLICATION_MISSING: (
+ "The publication used for change data capture no longer exists on the source database. "
+ "Recreate it, or disable and re-enable change data capture, then re-sync.",
+ False,
+ ),
+ CDCErrorCategory.SLOT_IN_USE: (
+ "The replication slot is currently in use by another connection. PostHog will retry shortly.",
+ True,
+ ),
+ CDCErrorCategory.WAL_DECODE_ERROR: (
+ "PostHog could not decode the change stream from the source database. This usually points to "
+ "an unsupported column type or replication setting. Contact support if it persists.",
+ False,
+ ),
+ CDCErrorCategory.TRANSACTION_TOO_LARGE: (
+ "A single database transaction contained more changes than change data capture can process at "
+ "once. Reduce the size of bulk operations on the source, then re-sync.",
+ False,
+ ),
+ CDCErrorCategory.UNKNOWN: (
+ "Change data capture hit an unexpected error. PostHog will retry automatically — if it "
+ "persists, check the source's sync logs or contact support.",
+ True,
+ ),
+}
+
+
+def cdc_error_info(category: CDCErrorCategory) -> CDCErrorInfo:
+ """Build the canonical ``CDCErrorInfo`` for a category from the shared copy table."""
+ message, retryable = _CATEGORY_DEFAULTS[category]
+ return CDCErrorInfo(category=category, friendly_message=message, retryable=retryable)
+
+
+def _iter_cause_chain(exc: BaseException) -> Iterator[BaseException]:
+ """Yield ``exc`` and every exception in its ``__cause__``/``__context__`` chain once."""
+ seen: set[int] = set()
+ current: BaseException | None = exc
+ while current is not None and id(current) not in seen:
+ seen.add(id(current))
+ yield current
+ current = current.__cause__ or current.__context__
+
+
+def classify_cdc_error(exc: BaseException, adapter: CDCSourceAdapter | None) -> CDCErrorInfo:
+ """Classify a CDC extraction failure into a user-facing ``CDCErrorInfo``.
+
+ Walks the exception's cause chain. Orchestration-level errors that any engine can hit are
+ matched here; engine-specific interpretation is delegated to ``adapter.classify_error``.
+ Falls back to a retryable ``unknown`` so a misclassification never strands a recoverable run.
+ """
+ for err in _iter_cause_chain(exc):
+ if isinstance(err, CDCTransactionTooLargeError):
+ return cdc_error_info(CDCErrorCategory.TRANSACTION_TOO_LARGE)
+ if adapter is not None:
+ info = adapter.classify_error(err)
+ if info is not None:
+ return info
+ return cdc_error_info(CDCErrorCategory.UNKNOWN)
diff --git a/posthog/temporal/data_imports/cdc/tests/test_errors.py b/posthog/temporal/data_imports/cdc/tests/test_errors.py
new file mode 100644
index 000000000000..2a2fe05e1e84
--- /dev/null
+++ b/posthog/temporal/data_imports/cdc/tests/test_errors.py
@@ -0,0 +1,99 @@
+import psycopg.errors
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.cdc.errors import (
+ MAX_FRIENDLY_MESSAGE_LENGTH,
+ CDCErrorCategory,
+ CDCErrorInfo,
+ CDCTransactionTooLargeError,
+ cdc_error_info,
+ classify_cdc_error,
+)
+from posthog.temporal.data_imports.sources.postgres.cdc.adapter import PostgresCDCAdapter
+
+
+class _StubAdapter:
+ """Minimal adapter that classifies only exceptions whose message contains a marker."""
+
+ def __init__(self, marker: str, category: CDCErrorCategory) -> None:
+ self._marker = marker
+ self._category = category
+ self.seen: list[BaseException] = []
+
+ def classify_error(self, exc: BaseException) -> CDCErrorInfo | None:
+ self.seen.append(exc)
+ return cdc_error_info(self._category) if self._marker in str(exc) else None
+
+
+class TestCDCErrorInfo:
+ @parameterized.expand(
+ [
+ (CDCErrorCategory.AUTH_FAILED, False),
+ (CDCErrorCategory.SSL_REQUIRED, False),
+ (CDCErrorCategory.CONNECTION_FAILED, True),
+ (CDCErrorCategory.SLOT_MISSING, False),
+ (CDCErrorCategory.PUBLICATION_MISSING, False),
+ (CDCErrorCategory.SLOT_IN_USE, True),
+ (CDCErrorCategory.WAL_DECODE_ERROR, False),
+ (CDCErrorCategory.TRANSACTION_TOO_LARGE, False),
+ (CDCErrorCategory.UNKNOWN, True),
+ ]
+ )
+ def test_retryable_flag(self, category, expected_retryable):
+ info = cdc_error_info(category)
+ assert info.category is category
+ assert info.retryable is expected_retryable
+
+ def test_every_category_has_a_capped_non_empty_message(self):
+ for category in CDCErrorCategory:
+ info = cdc_error_info(category)
+ assert info.friendly_message
+ assert len(info.friendly_message) <= MAX_FRIENDLY_MESSAGE_LENGTH
+
+
+class TestClassifyCDCError:
+ def test_delegates_to_adapter(self):
+ adapter = _StubAdapter("boom", CDCErrorCategory.AUTH_FAILED)
+ info = classify_cdc_error(RuntimeError("boom"), adapter) # type: ignore[arg-type]
+ assert info.category is CDCErrorCategory.AUTH_FAILED
+ assert info.retryable is False
+
+ def test_unknown_when_adapter_returns_none(self):
+ adapter = _StubAdapter("never", CDCErrorCategory.AUTH_FAILED)
+ info = classify_cdc_error(RuntimeError("something else"), adapter) # type: ignore[arg-type]
+ assert info.category is CDCErrorCategory.UNKNOWN
+ assert info.retryable is True
+
+ def test_unknown_when_adapter_missing(self):
+ info = classify_cdc_error(RuntimeError("anything"), None)
+ assert info.category is CDCErrorCategory.UNKNOWN
+
+ def test_walks_cause_chain(self):
+ # The classifiable error is the cause; the outer wrapper is opaque.
+ cause = psycopg.errors.InvalidPassword("password authentication failed")
+ wrapper = RuntimeError("extraction failed")
+ wrapper.__cause__ = cause
+ info = classify_cdc_error(wrapper, PostgresCDCAdapter())
+ assert info.category is CDCErrorCategory.AUTH_FAILED
+
+ def test_transaction_too_large_is_classified_without_adapter(self):
+ info = classify_cdc_error(CDCTransactionTooLargeError("500001 events"), None)
+ assert info.category is CDCErrorCategory.TRANSACTION_TOO_LARGE
+ assert info.retryable is False
+
+ def test_non_psycopg_exception_with_slot_message_is_not_classified(self):
+ # A non-psycopg exception whose message happens to contain slot/auth patterns must not be
+ # misclassified as non-retryable — only psycopg exceptions carry these patterns meaningfully.
+ exc = RuntimeError("replication slot my_slot does not exist")
+ info = classify_cdc_error(exc, PostgresCDCAdapter())
+ assert info.category is CDCErrorCategory.UNKNOWN
+ assert info.retryable is True
+
+ def test_friendly_message_never_echoes_raw_exception(self):
+ # A connection error carrying secrets must classify to the static friendly copy,
+ # never interpolate the raw message — no credential/host leakage into latest_error.
+ exc = psycopg.OperationalError("connection failed: password=hunter2 host=secret.db.internal:5432")
+ info = classify_cdc_error(exc, PostgresCDCAdapter())
+ assert info.category is CDCErrorCategory.CONNECTION_FAILED
+ assert "hunter2" not in info.friendly_message
+ assert "secret.db.internal" not in info.friendly_message
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 01bf2fa1e8d2..417466dc3ff0 100644
--- a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -15,7 +15,10 @@ from posthog.temporal.data_imports.cdc.activities import (
cdc_extract_activity,
cleanup_orphan_slots_activity,
)
+from posthog.temporal.data_imports.cdc.errors import CDCErrorCategory, cdc_error_info
from posthog.temporal.data_imports.cdc.types import ChangeEvent
+from posthog.temporal.data_imports.sources.postgres.cdc.adapter import PostgresCDCAdapter
+from posthog.temporal.data_imports.util import NonRetryableException
def _make_event(
@@ -131,6 +134,7 @@ def _setup_mocks(
mock_adapter = MagicMock()
mock_adapter.create_reader.return_value = mock_reader
mock_adapter.is_slot_invalidation_error.return_value = False
+ mock_adapter.classify_error.return_value = None # default: unrecognized -> unknown/retryable
mock_get_adapter.return_value = mock_adapter
mock_s3 = MagicMock()
@@ -756,6 +760,7 @@ class TestCDCExtractActivity:
mock_adapter = MagicMock()
mock_adapter.create_reader.return_value = mock_reader
mock_adapter.is_slot_invalidation_error.return_value = False
+ mock_adapter.classify_error.return_value = None
mock_get_adapter.return_value = mock_adapter
inputs = CDCExtractInput(team_id=1, source_id=source.id)
@@ -810,9 +815,10 @@ class TestCDCExtractActivity:
with pytest.raises(RuntimeError, match="S3 write failed"):
cdc_extract_activity(inputs)
- # Schema should be marked as FAILED
+ # Schema is marked FAILED with the friendly message — the raw error never reaches the user.
assert schema.status == "Failed"
- assert "S3 write failed" in schema.latest_error
+ assert schema.latest_error == cdc_error_info(CDCErrorCategory.UNKNOWN).friendly_message
+ assert "S3 write failed" not in schema.latest_error
# Slot should NOT have been advanced
mock_reader.confirm_position.assert_not_called()
@@ -1597,6 +1603,149 @@ class TestSlotAdvanceTransactionSafety:
assert advanced_positions == expected_advances
+class TestErrorClassification:
+ """Failures store a friendly, credential-safe message; non-retryable ones stop Temporal retries."""
+
+ @patch("posthog.temporal.data_imports.cdc.activities.get_machine_id", return_value="machine-1")
+ @patch("posthog.temporal.data_imports.cdc.activities.posthoganalytics")
+ @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_retryable_error_raises_nonretryable_and_captures(
+ self,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ mock_activity,
+ mock_posthoganalytics,
+ mock_get_machine_id,
+ ):
+ source = _make_source()
+ MockSourceModel.objects.get.return_value = source
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ mock_get_schemas.return_value = [schema]
+
+ mock_reader = MagicMock()
+ mock_reader.read_changes.side_effect = psycopg.errors.InvalidPassword(
+ 'password authentication failed for user "test"'
+ )
+ 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_adapter.classify_error = PostgresCDCAdapter().classify_error # exercise real classification
+ 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")
+
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
+ with pytest.raises(NonRetryableException):
+ cdc_extract_activity(inputs)
+
+ assert schema.status == "Failed"
+ assert schema.latest_error == cdc_error_info(CDCErrorCategory.AUTH_FAILED).friendly_message
+
+ mock_posthoganalytics.capture.assert_called_once()
+ captured = mock_posthoganalytics.capture.call_args.kwargs
+ assert captured["event"] == "cdc extraction non-retryable error"
+ assert captured["properties"]["category"] == "auth_failed"
+ assert captured["properties"]["source_id"] == str(source.id)
+ mock_reader.close.assert_called_once()
+
+ @patch("posthog.temporal.data_imports.cdc.activities.get_machine_id", return_value="machine-1")
+ @patch("posthog.temporal.data_imports.cdc.activities.posthoganalytics")
+ @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_analytics_failure_does_not_mask_nonretryable(
+ self,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ mock_activity,
+ mock_posthoganalytics,
+ mock_get_machine_id,
+ ):
+ source = _make_source()
+ MockSourceModel.objects.get.return_value = source
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ mock_get_schemas.return_value = [schema]
+
+ mock_reader = MagicMock()
+ mock_reader.read_changes.side_effect = psycopg.errors.InvalidPassword(
+ 'password authentication failed for user "test"'
+ )
+ 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_adapter.classify_error = PostgresCDCAdapter().classify_error
+ 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")
+
+ # Analytics is down — it must not swallow or replace the NonRetryableException.
+ mock_posthoganalytics.capture.side_effect = RuntimeError("analytics down")
+
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
+ with pytest.raises(NonRetryableException):
+ cdc_extract_activity(inputs)
+
+ assert schema.latest_error == cdc_error_info(CDCErrorCategory.AUTH_FAILED).friendly_message
+
+ @patch("posthog.temporal.data_imports.cdc.activities.get_machine_id", return_value="machine-1")
+ @patch("posthog.temporal.data_imports.cdc.activities.posthoganalytics")
+ @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_retryable_error_reraises_original_and_does_not_capture(
+ self,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ mock_activity,
+ mock_posthoganalytics,
+ mock_get_machine_id,
+ ):
+ source = _make_source()
+ MockSourceModel.objects.get.return_value = source
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ mock_get_schemas.return_value = [schema]
+
+ mock_reader = MagicMock()
+ mock_reader.read_changes.side_effect = psycopg.OperationalError(
+ 'connection to server at "db" failed: Connection refused'
+ )
+ 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_adapter.classify_error = PostgresCDCAdapter().classify_error
+ 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")
+
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
+ # Retryable: the ORIGINAL error propagates so Temporal retries — not NonRetryableException.
+ with pytest.raises(psycopg.OperationalError, match="Connection refused"):
+ cdc_extract_activity(inputs)
+
+ assert schema.latest_error == cdc_error_info(CDCErrorCategory.CONNECTION_FAILED).friendly_message
+ mock_posthoganalytics.capture.assert_not_called()
+
+
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."""
@@ -1621,6 +1770,7 @@ class TestSlotInvalidationRecovery:
mock_adapter = MagicMock()
mock_adapter.create_reader.return_value = mock_reader
mock_adapter.is_slot_invalidation_error.return_value = True
+ mock_adapter.classify_error.return_value = None
mock_get_adapter.return_value = mock_adapter
mock_activity.heartbeat = MagicMock()
@@ -1725,7 +1875,9 @@ class TestSlotInvalidationRecovery:
cdc_extract_activity(inputs)
assert schema.status == "Failed"
- assert "cannot recreate slot" in schema.latest_error
+ # The raw recovery error stays in the logs; the user-facing column gets friendly copy.
+ assert schema.latest_error == cdc_error_info(CDCErrorCategory.UNKNOWN).friendly_message
+ assert "cannot recreate slot" not in schema.latest_error
mock_reader.close.assert_called_once()
@patch("posthog.temporal.data_imports.cdc.activities.activity")
diff --git a/posthog/temporal/data_imports/cdc/workflows.py b/posthog/temporal/data_imports/cdc/workflows.py
index e6ecf956a7d0..312c72b90d89 100644
--- a/posthog/temporal/data_imports/cdc/workflows.py
+++ b/posthog/temporal/data_imports/cdc/workflows.py
@@ -55,6 +55,7 @@ class CDCExtractionWorkflow(PostHogWorkflow):
initial_interval=dt.timedelta(seconds=30),
maximum_interval=dt.timedelta(minutes=5),
maximum_attempts=3,
+ non_retryable_error_types=["NonRetryableException"],
),
)
diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py b/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py
index 3cd9cbe10366..97f01211a4c2 100644
--- a/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py
@@ -7,7 +7,9 @@ from collections.abc import Iterator
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Literal
+from posthog.temporal.data_imports.cdc.errors import cdc_error_info
from posthog.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfig
+from posthog.temporal.data_imports.sources.postgres.cdc.errors import classify_postgres_cdc_error
from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import (
add_table_to_publication,
cdc_pg_connection,
@@ -28,6 +30,7 @@ from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import (
from posthog.temporal.data_imports.sources.postgres.postgres import source_requires_ssl
if TYPE_CHECKING:
+ from posthog.temporal.data_imports.cdc.errors import CDCErrorInfo
from posthog.temporal.data_imports.cdc.types import CDCStreamReader
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -111,6 +114,10 @@ class PostgresCDCAdapter:
def is_slot_invalidation_error(self, exc: BaseException) -> bool:
return is_slot_invalidation_error(exc)
+ def classify_error(self, exc: BaseException) -> CDCErrorInfo | None:
+ category = classify_postgres_cdc_error(exc)
+ return cdc_error_info(category) if category is not None else None
+
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.
diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/errors.py b/posthog/temporal/data_imports/sources/postgres/cdc/errors.py
new file mode 100644
index 000000000000..bd1bad974cc6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/errors.py
@@ -0,0 +1,74 @@
+"""Postgres-specific CDC error classification.
+
+Maps psycopg exceptions (and their message markers) raised on the WAL data path or the
+management connection to the engine-agnostic ``CDCErrorCategory`` taxonomy. Mirrors the
+``is_slot_invalidation_error`` seam: the shared layer owns the taxonomy and user-facing copy,
+this module owns the Postgres interpretation.
+"""
+
+from __future__ import annotations
+
+import struct
+
+import psycopg
+import psycopg.errors
+
+from posthog.temporal.data_imports.cdc.errors import CDCErrorCategory
+
+# Server requires (or rejects) an encrypted connection. Kept specific so a transient
+# "SSL connection has been closed unexpectedly" stays a retryable connection failure.
+_SSL_REQUIRED_MARKERS = (
+ "server does not support ssl",
+ "ssl connection is required",
+ "ssl was required",
+)
+
+_AUTH_MARKERS = (
+ "authentication failed",
+ "no password supplied",
+)
+
+
+def classify_postgres_cdc_error(exc: BaseException) -> CDCErrorCategory | None:
+ """Classify a single Postgres exception into a ``CDCErrorCategory``.
+
+ Returns None when the exception isn't a recognizable Postgres CDC failure, so the
+ shared classifier can keep walking the cause chain and fall back to ``unknown``.
+ """
+ # struct.error => the pgoutput binary stream couldn't be unpacked.
+ if isinstance(exc, struct.error):
+ return CDCErrorCategory.WAL_DECODE_ERROR
+
+ # Guard all string-based checks: only psycopg exceptions carry these message patterns.
+ # A non-psycopg exception whose message happens to contain e.g. "does not exist" would
+ # otherwise be misclassified as non-retryable SLOT_MISSING, permanently stopping retries.
+ if not isinstance(exc, psycopg.Error):
+ return None
+
+ message = str(exc).lower()
+
+ # Slot held by another connection (e.g. a previous run still draining): "replication
+ # slot ... is active for PID ...". Retryable — it frees up on its own.
+ if "is active for pid" in message:
+ return CDCErrorCategory.SLOT_IN_USE
+
+ if "does not exist" in message:
+ if "replication slot" in message:
+ return CDCErrorCategory.SLOT_MISSING
+ if "publication" in message:
+ return CDCErrorCategory.PUBLICATION_MISSING
+
+ # Authentication (SQLSTATE class 28) surfaces either as a mapped subclass (server-side)
+ # or a bare OperationalError with a libpq message (connection-time). Check before the
+ # generic OperationalError fallback, which these subclass.
+ if isinstance(exc, psycopg.errors.InvalidPassword | psycopg.errors.InvalidAuthorizationSpecification):
+ return CDCErrorCategory.AUTH_FAILED
+ if any(marker in message for marker in _AUTH_MARKERS):
+ return CDCErrorCategory.AUTH_FAILED
+
+ if isinstance(exc, psycopg.OperationalError):
+ if any(marker in message for marker in _SSL_REQUIRED_MARKERS):
+ return CDCErrorCategory.SSL_REQUIRED
+ return CDCErrorCategory.CONNECTION_FAILED
+
+ return None
diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_errors.py b/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_errors.py
new file mode 100644
index 000000000000..b20b25f847d1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_errors.py
@@ -0,0 +1,82 @@
+import struct
+
+import psycopg.errors
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.cdc.errors import CDCErrorCategory
+from posthog.temporal.data_imports.sources.postgres.cdc.errors import classify_postgres_cdc_error
+
+
+class TestClassifyPostgresCDCError:
+ @parameterized.expand(
+ [
+ (
+ "invalid_password_class",
+ psycopg.errors.InvalidPassword('password authentication failed for user "posthog"'),
+ CDCErrorCategory.AUTH_FAILED,
+ ),
+ (
+ "invalid_authorization_class",
+ psycopg.errors.InvalidAuthorizationSpecification("no pg_hba.conf entry for host"),
+ CDCErrorCategory.AUTH_FAILED,
+ ),
+ (
+ "auth_message_on_operational_error",
+ psycopg.OperationalError('connection failed: password authentication failed for user "x"'),
+ CDCErrorCategory.AUTH_FAILED,
+ ),
+ (
+ "ssl_required",
+ psycopg.OperationalError("server does not support SSL, but SSL was required"),
+ CDCErrorCategory.SSL_REQUIRED,
+ ),
+ (
+ "ssl_close_is_connection_not_ssl_required",
+ psycopg.OperationalError("SSL connection has been closed unexpectedly"),
+ CDCErrorCategory.CONNECTION_FAILED,
+ ),
+ (
+ "connection_refused",
+ psycopg.OperationalError("connection to server at localhost, port 5432 failed: Connection refused"),
+ CDCErrorCategory.CONNECTION_FAILED,
+ ),
+ (
+ "slot_missing",
+ psycopg.errors.UndefinedObject('replication slot "posthog_slot" does not exist'),
+ CDCErrorCategory.SLOT_MISSING,
+ ),
+ (
+ "publication_missing",
+ psycopg.errors.UndefinedObject('publication "posthog_pub" does not exist'),
+ CDCErrorCategory.PUBLICATION_MISSING,
+ ),
+ (
+ "slot_in_use",
+ psycopg.errors.ObjectInUse('replication slot "posthog_slot" is active for PID 123'),
+ CDCErrorCategory.SLOT_IN_USE,
+ ),
+ (
+ "wal_decode_struct_error",
+ struct.error("unpack requires a buffer of 4 bytes"),
+ CDCErrorCategory.WAL_DECODE_ERROR,
+ ),
+ (
+ "unrelated_runtime_error",
+ RuntimeError("S3 write failed"),
+ None,
+ ),
+ (
+ "undefined_table_is_not_slot_or_publication",
+ psycopg.errors.UndefinedTable('relation "public.orders" does not exist'),
+ None,
+ ),
+ ]
+ )
+ def test_classification(self, _name, exc, expected):
+ assert classify_postgres_cdc_error(exc) is expected
+
+ def test_slot_in_use_takes_precedence_over_does_not_exist_wording(self):
+ # An "is active for PID" message must classify as retryable slot_in_use even if it
+ # mentions the slot — never as the non-retryable slot_missing.
+ exc = psycopg.errors.ObjectInUse('replication slot "posthog_slot" is active for PID 99')
+ assert classify_postgres_cdc_error(exc) is CDCErrorCategory.SLOT_IN_USE