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): match CDC WAL events to bare-named schemas (#64660)

Daniel RCb77563ccabe9
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.py
index 8763d7159ff8..f484f4d185f6 100644
--- a/posthog/temporal/data_imports/cdc/activities.py
+++ b/posthog/temporal/data_imports/cdc/activities.py
@@ -628,6 +628,28 @@ class CDCExtractActivity:
columns=filtered,
)
+ def _build_event_name_map(self) -> dict[str, str]:
+ """Map each schema's source-qualified `schema.table` name to its stored `name`.
+
+ WAL events are always qualified (`public.orders`) but `name` may be stored bare
+ (`orders`), so an exact-equality match silently drops every change for a bare row.
+ """
+ default_schema = (self.source.job_inputs or {}).get("schema") if self.source else None
+ mapping: dict[str, str] = {}
+ for schema in self.cdc_schemas:
+ metadata = schema.sync_type_config.get("schema_metadata") or {}
+ src_schema = metadata.get("source_schema")
+ src_table = metadata.get("source_table_name")
+ if isinstance(src_schema, str) and isinstance(src_table, str):
+ qualified = f"{src_schema}.{src_table}"
+ elif "." in schema.name:
+ qualified = schema.name
+ else:
+ qualified = f"{default_schema or 'public'}.{schema.name}"
+ mapping[qualified] = schema.name
+ mapping.setdefault(schema.name, schema.name) # also match a bare-emitted name
+ return mapping
+
# ------------------------------------------------------------------
# WAL read loop with periodic micro-batch flushes
# ------------------------------------------------------------------
@@ -639,17 +661,20 @@ class CDCExtractActivity:
extractions that hit the activity timeout don't have to replay events
on the next run.
"""
- cdc_table_names = {s.name for s in self.cdc_schemas}
+ event_name_to_schema_name = self._build_event_name_map()
self.batcher = ChangeEventBatcher()
for event in self.reader.read_changes():
activity.heartbeat()
- # The publication should be scoped to CDC-enabled tables only, so in
- # practice this filter is a no-op. It's a safety net in case the
- # publication includes extra tables (e.g. self-managed mode).
- if event.table_name not in cdc_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)
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 311588fe2a7e..a0bce70d97a8 100644
--- a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -276,6 +276,35 @@ class TestFlushDeferredRuns:
assert schema.sync_type_config["cdc_deferred_runs"] == []
+class TestBuildEventNameMap:
+ @pytest.mark.parametrize(
+ "schema_name,schema_metadata,source_schema_config,wal_event_name,expected_canonical",
+ [
+ # Path 1: schema_metadata resolves the source-qualified name.
+ ("orders", {"source_schema": "public", "source_table_name": "orders"}, None, "public.orders", "orders"),
+ # Path 2: no metadata, but `name` is already schema-qualified.
+ ("public.orders", None, None, "public.orders", "public.orders"),
+ # Path 3: no metadata, bare name — falls back to the source's default schema.
+ ("orders", None, "analytics", "analytics.orders", "orders"),
+ # Path 3: no metadata, bare name, no default schema — falls back to "public".
+ ("orders", None, None, "public.orders", "orders"),
+ ],
+ )
+ def test_resolves_wal_event_name_to_canonical_schema_name(
+ self, schema_name, schema_metadata, source_schema_config, wal_event_name, expected_canonical
+ ):
+ source = _make_source(job_inputs={"schema": source_schema_config} if source_schema_config else {})
+ schema = _make_schema(schema_name, cdc_mode="streaming", source=source)
+ schema.sync_type_config = {"cdc_mode": "streaming", "cdc_table_mode": "consolidated"}
+ if schema_metadata is not None:
+ schema.sync_type_config["schema_metadata"] = schema_metadata
+
+ activity_obj = _make_extract_activity(source)
+ activity_obj.cdc_schemas = [schema]
+
+ assert activity_obj._build_event_name_map().get(wal_event_name) == expected_canonical
+
+
class TestCDCExtractActivity:
"""Integration tests for cdc_extract_activity with mocked external deps."""
@@ -329,6 +358,63 @@ class TestCDCExtractActivity:
mock_reader.confirm_position.assert_called_once_with("0/200")
mock_reader.close.assert_called_once()
+ @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_bare_named_schema_matches_schema_qualified_wal_events(
+ self,
+ mock_close_conns,
+ MockJob,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ MockS3Writer,
+ MockProducer,
+ mock_activity,
+ ):
+ """A schema whose `name` is stored bare (no `public.` prefix) must still match the
+ schema-qualified table name the WAL stream emits. Otherwise every change is silently
+ dropped and the table goes stale despite a healthy slot."""
+ source = _make_source()
+ # `name` is bare, but schema_metadata resolves the real source location.
+ schema = _make_schema("product_productintegrationevent", cdc_mode="streaming", source=source)
+ schema.sync_type_config["schema_metadata"] = {
+ "source_schema": "public",
+ "source_table_name": "product_productintegrationevent",
+ }
+ schema.sync_type_config["primary_key_columns"] = ["id"]
+ # WAL events arrive schema-qualified, as Postgres logical decoding always emits them.
+ events = [
+ _make_event(op="I", table="public.product_productintegrationevent", position="0/100"),
+ ]
+
+ 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,
+ )
+
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
+ cdc_extract_activity(inputs)
+
+ # The change was captured, not dropped by the table-name filter.
+ mock_s3.write_batch.assert_called()
+ mock_producer.send_batch_notification.assert_called()
+ mock_reader.confirm_position.assert_called_once_with("0/100")
+
@patch("posthog.temporal.data_imports.cdc.activities.activity")
@patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 30b0e1c04db2..f8a53c958973 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -1847,10 +1847,34 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
on failure, or None on success. Callers decide whether to delete the source
on failure (create flow does; enable_cdc does not).
"""
+ management_mode = payload.get("cdc_management_mode", "posthog")
+ logger.info(
+ "Setting up CDC resources for source",
+ source_id=str(source_model.pk),
+ source_type=source_model.source_type,
+ management_mode=management_mode,
+ )
+
resource_fields, error = adapter.setup_resources(source_model, payload)
if error is not None:
+ logger.warning(
+ "CDC resource setup failed",
+ source_id=str(source_model.pk),
+ source_type=source_model.source_type,
+ management_mode=management_mode,
+ error=error,
+ )
return error
+ logger.info(
+ "CDC resources provisioned",
+ source_id=str(source_model.pk),
+ management_mode=management_mode,
+ slot_name=resource_fields.get("cdc_slot_name"),
+ publication_name=resource_fields.get("cdc_publication_name"),
+ resource_keys=sorted(resource_fields.keys()),
+ )
+
job_inputs = dict(source_model.job_inputs or {})
job_inputs.update(
{
diff --git a/products/data_warehouse/backend/data_load/service.py b/products/data_warehouse/backend/data_load/service.py
index abd9b75c37f5..441324c0e8ca 100644
--- a/products/data_warehouse/backend/data_load/service.py
+++ b/products/data_warehouse/backend/data_load/service.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING
from django.conf import settings
+import structlog
import temporalio
from asgiref.sync import async_to_sync
from temporalio.client import (
@@ -48,6 +49,8 @@ if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+logger = structlog.get_logger(__name__)
+
def _jitter_timedelta(max_jitter: timedelta, rng: random.Random) -> tuple[int, int]:
total_seconds = max_jitter.total_seconds()
@@ -486,10 +489,16 @@ def sync_cdc_extraction_schedule(source: ExternalDataSource, create: bool = Fals
schedule_id = _get_cdc_extraction_schedule_id(str(source.id))
if not cdc_schemas:
+ # No active CDC schemas left — dropping the schedule silently stops all CDC sync.
+ logger.info(
+ "Deleting CDC extraction schedule — no active CDC schemas",
+ source_id=str(source.id),
+ schedule_id=schedule_id,
+ )
try:
delete_external_data_schedule(schedule_id)
except Exception:
- pass
+ logger.exception("Failed to delete CDC extraction schedule", schedule_id=schedule_id)
return
min_interval = cdc_min_interval(schema.sync_frequency_interval for schema in cdc_schemas)
@@ -497,6 +506,15 @@ def sync_cdc_extraction_schedule(source: ExternalDataSource, create: bool = Fals
temporal = sync_connect()
schedule = get_cdc_extraction_schedule(source, min_interval)
+ logger.info(
+ "Syncing CDC extraction schedule",
+ source_id=str(source.id),
+ schedule_id=schedule_id,
+ create=create,
+ cdc_schema_count=len(cdc_schemas),
+ min_interval_seconds=min_interval.total_seconds(),
+ )
+
if create:
create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=True)
else: