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): harden CDC table syncs (#65458)

Daniel RC1c7ebfc63c41
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.py
index 7ac158ef8781..96032d06e22e 100644
--- a/posthog/temporal/data_imports/cdc/activities.py
+++ b/posthog/temporal/data_imports/cdc/activities.py
@@ -33,6 +33,7 @@ from posthog.temporal.data_imports.cdc.batcher import (
enrich_delete_rows,
)
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
@@ -194,7 +195,8 @@ class CDCExtractActivity:
job_id=job_id,
schema_id=str(schema.id),
source_id=str(source.id),
- resource_name=schema.name,
+ # Fall back to `name` for entries persisted before resource_name was stored.
+ resource_name=run_meta.get("resource_name", schema.name),
sync_type=typing.cast(SyncTypeLiteral, "cdc"),
run_uuid=run_uuid,
logger=log,
@@ -203,6 +205,7 @@ class CDCExtractActivity:
cdc_table_mode=run_meta.get("cdc_table_mode"),
workflow_id=current_workflow_id(),
workflow_run_id=current_workflow_run_id(),
+ **self._partition_kwargs(schema),
)
from posthog.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult
@@ -318,6 +321,7 @@ class CDCExtractActivity:
cdc_table_mode=tracker.cdc_table_mode,
workflow_id=current_workflow_id(),
workflow_run_id=current_workflow_run_id(),
+ **self._partition_kwargs(schema),
)
try:
producer.send_batch_notification(
@@ -361,6 +365,8 @@ class CDCExtractActivity:
entry = {
"job_id": str(tracker.job.id),
"run_uuid": tracker.run_uuid,
+ # Replayed by the deferred flush so it targets the same Delta table this batch went to.
+ "resource_name": tracker.write_resource_name,
"data_folder": tracker.s3_writer.get_data_folder(),
"schema_path": None, # written on finalization
"total_batches": 0,
@@ -395,6 +401,34 @@ class CDCExtractActivity:
total_rows=tracker.total_rows,
)
+ # ------------------------------------------------------------------
+ # Storage naming
+ # ------------------------------------------------------------------
+ def _consolidated_resource_name(self, schema: ExternalDataSchema) -> str:
+ """Storage name for the consolidated table — must match the snapshot pipeline's.
+
+ The CDC stream must target the same folder, otherwise streamed changes
+ land in a parallel Delta table no query reads. `name` and folder diverge
+ for rows renamed bare→qualified (`name="public.users"`, folder `users`).
+ """
+ _table_storage_name, folder_name = resolve_table_and_folder_names(schema.name, schema.resolved_s3_folder_name)
+ return folder_name
+
+ def _partition_kwargs(self, schema: ExternalDataSchema) -> dict[str, typing.Any]:
+ """Replay snapshot partitioning so CDC rows match the target Delta.
+
+ Without this, partitioned targets silently drop CDC rows. No-op when unpartitioned.
+ """
+ if not schema.partitioning_enabled:
+ return {}
+ return {
+ "partition_count": schema.partition_count,
+ "partition_size": schema.partition_size,
+ "partition_keys": schema.partitioning_keys,
+ "partition_mode": schema.partition_mode,
+ "partition_format": schema.partition_format,
+ }
+
# ------------------------------------------------------------------
# Per-flush processing
# ------------------------------------------------------------------
@@ -424,15 +458,23 @@ class CDCExtractActivity:
enriched_table = enrich_delete_rows(raw_table, key_columns)
+ # Consolidated shares the snapshot's canonical folder; the `_cdc` companion is
+ # CDC-only and stays self-consistent with its `name`-keyed snapshot seed.
batch_writes: list[tuple[pa.Table, str, str]] = []
if cdc_table_mode == "consolidated":
- batch_writes.append((deduplicate_table(enriched_table, key_columns), schema.name, "incremental_merge"))
+ consolidated_name = self._consolidated_resource_name(schema)
+ batch_writes.append(
+ (deduplicate_table(enriched_table, key_columns), consolidated_name, "incremental_merge")
+ )
elif cdc_table_mode == "cdc_only":
batch_writes.append(
(build_scd2_table(enriched_table, key_columns), f"{schema.name}_cdc", "scd2_append")
)
elif cdc_table_mode == "both":
- batch_writes.append((deduplicate_table(enriched_table, key_columns), schema.name, "incremental_merge"))
+ consolidated_name = self._consolidated_resource_name(schema)
+ batch_writes.append(
+ (deduplicate_table(enriched_table, key_columns), consolidated_name, "incremental_merge")
+ )
batch_writes.append(
(build_scd2_table(enriched_table, key_columns), f"{schema.name}_cdc", "scd2_append")
)
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 320fc5323c6a..6ff526e7a569 100644
--- a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -56,7 +56,20 @@ def _make_source(source_id=None, job_inputs=None):
return source
-def _make_schema(name, cdc_mode="streaming", cdc_table_mode="consolidated", source=None, schema_id=None):
+def _make_schema(
+ name,
+ cdc_mode="streaming",
+ cdc_table_mode="consolidated",
+ source=None,
+ schema_id=None,
+ s3_folder_name=None,
+ partitioning_enabled=False,
+ partitioning_keys=None,
+ partition_mode=None,
+ partition_format=None,
+ partition_count=None,
+ partition_size=None,
+):
schema = MagicMock()
schema.id = schema_id or uuid.uuid4()
schema.name = name
@@ -69,6 +82,14 @@ def _make_schema(name, cdc_mode="streaming", cdc_table_mode="consolidated", sour
schema.cdc_table_mode = cdc_table_mode
schema.should_sync = True
schema.deleted = False
+ # Real values (not MagicMocks) so storage-name and partition helpers evaluate deterministically.
+ schema.resolved_s3_folder_name = s3_folder_name
+ schema.partitioning_enabled = partitioning_enabled
+ schema.partitioning_keys = partitioning_keys
+ schema.partition_mode = partition_mode
+ schema.partition_format = partition_format
+ schema.partition_count = partition_count
+ schema.partition_size = partition_size
schema.save = MagicMock()
return schema
@@ -310,6 +331,53 @@ class TestFlushDeferredRuns:
assert mock_producer.flush.call_count == 3
assert schema.sync_type_config["cdc_deferred_runs"] == []
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
+ def test_deferred_flush_uses_stored_resource_name_and_replays_partition_config(self, MockProducer):
+ """Deferred flush targets the stored Delta resource and replays partition config."""
+ mock_producer = MagicMock()
+ MockProducer.return_value = mock_producer
+
+ source = _make_source()
+ # Folder pinned bare while `name` is qualified, plus partitioning — exercises both fixes.
+ schema = _make_schema(
+ "public.users",
+ cdc_mode="streaming",
+ source=source,
+ s3_folder_name="users",
+ partitioning_enabled=True,
+ partitioning_keys=["id"],
+ partition_mode="numerical",
+ partition_size=1_000_000,
+ )
+ schema.sync_type_config["cdc_deferred_runs"] = [
+ {
+ "job_id": "job-1",
+ "run_uuid": "run-1",
+ "resource_name": "users",
+ "data_folder": "s3://bucket/data/",
+ "schema_path": "s3://bucket/schema.json",
+ "total_batches": 1,
+ "total_rows": 10,
+ "batch_results": [
+ {
+ "s3_path": "s3://bucket/data/part-0000.parquet",
+ "row_count": 10,
+ "byte_size": 1024,
+ "batch_index": 0,
+ "timestamp_ns": 123456789,
+ }
+ ],
+ }
+ ]
+
+ _make_extract_activity(source)._flush_deferred_runs(schema)
+
+ kwargs = MockProducer.call_args.kwargs
+ assert kwargs["resource_name"] == "users"
+ assert kwargs["partition_keys"] == ["id"]
+ assert kwargs["partition_mode"] == "numerical"
+ assert kwargs["partition_size"] == 1_000_000
+
class TestBuildEventNameMap:
@pytest.mark.parametrize(
@@ -1108,6 +1176,154 @@ class TestCDCExtractActivity:
resource_names = {call.kwargs["resource_name"] for call in MockProducer.call_args_list}
assert resource_names == {"users", "users_cdc"}
+ @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_consolidated_table_uses_pinned_folder_name_not_schema_name(
+ self,
+ mock_close_conns,
+ MockJob,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ MockS3Writer,
+ MockProducer,
+ mock_activity,
+ ):
+ """Consolidated CDC writes use the pinned folder for bare→qualified schemas."""
+ source = _make_source()
+ # `name` is qualified, but the folder was pinned to the original bare path during migration.
+ schema = _make_schema("public.users", cdc_mode="streaming", source=source, s3_folder_name="users")
+ events = [_make_event(op="I", table="public.users", position="0/100", columns={"id": 1, "name": "Alice"})]
+
+ 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)
+
+ mock_s3.write_batch.assert_called_once()
+ assert MockProducer.call_count == 1
+ # The fix: storage resource name is the pinned folder ("users"), not "public.users".
+ assert MockProducer.call_args.kwargs["resource_name"] == "users"
+
+ @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_partition_config_replayed_to_loader_when_snapshot_partitioned(
+ self,
+ mock_close_conns,
+ MockJob,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ MockS3Writer,
+ MockProducer,
+ mock_activity,
+ ):
+ """Partitioned snapshots replay their partition config to CDC batch notifications."""
+ source = _make_source()
+ schema = _make_schema(
+ "users",
+ cdc_mode="streaming",
+ source=source,
+ partitioning_enabled=True,
+ partitioning_keys=["id"],
+ partition_mode="numerical",
+ partition_size=1_000_000,
+ )
+ events = [_make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"})]
+
+ 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)
+
+ assert MockProducer.call_count == 1
+ kwargs = MockProducer.call_args.kwargs
+ assert kwargs["partition_keys"] == ["id"]
+ assert kwargs["partition_mode"] == "numerical"
+ assert kwargs["partition_size"] == 1_000_000
+
+ @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_partition_config_omitted_when_snapshot_unpartitioned(
+ self,
+ mock_close_conns,
+ MockJob,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ MockS3Writer,
+ MockProducer,
+ mock_activity,
+ ):
+ """Unpartitioned snapshots do not send partition config to CDC batch notifications."""
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source, partitioning_enabled=False)
+ events = [_make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"})]
+
+ _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)
+
+ assert MockProducer.call_count == 1
+ kwargs = MockProducer.call_args.kwargs
+ assert kwargs.get("partition_keys") is None
+ assert kwargs.get("partition_mode") is None
+
@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/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py b/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py
index 0ff003ae266b..3cd9cbe10366 100644
--- a/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py
@@ -11,8 +11,10 @@ from posthog.temporal.data_imports.sources.postgres.cdc.config import PostgresCD
from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import (
add_table_to_publication,
cdc_pg_connection,
+ create_publication,
create_slot,
create_slot_and_publication,
+ drop_publication,
drop_slot,
drop_slot_and_publication,
get_max_slot_wal_keep_size_mb,
@@ -154,9 +156,13 @@ class PostgresCDCAdapter:
management_mode: Literal["posthog", "self_managed"] = (
"self_managed" if payload.get("cdc_management_mode") == "self_managed" else "posthog"
)
- slot_name = payload.get("cdc_slot_name") or f"posthog_{source.id.hex[:12]}"
+ default_slot_name = f"posthog_{source.id.hex[:12]}"
+ slot_name = payload.get("cdc_slot_name") or default_slot_name
default_pub_name = "posthog_pub" if management_mode == "self_managed" else f"posthog_pub_{source.id.hex[:12]}"
pub_name = payload.get("cdc_publication_name") or default_pub_name
+ uses_default_posthog_resources = (
+ management_mode == "posthog" and slot_name == default_slot_name and pub_name == default_pub_name
+ )
resource_fields: dict[str, Any] = {
"cdc_management_mode": management_mode,
@@ -165,22 +171,41 @@ class PostgresCDCAdapter:
}
if management_mode == "posthog":
+ created_publication = False
+ created_slot = False
try:
with cdc_pg_connection(source) as conn:
- # Bail on pre-existing names so the rollback below only ever drops what we created.
- if slot_exists(conn, slot_name):
+ slot_present = slot_exists(conn, slot_name)
+ publication_present = publication_exists(conn, pub_name)
+ # Default names are source-id derived, so pre-existing resources are recoverable
+ # PostHog state from this source. Custom-name conflicts still belong to the user/DBA.
+ if uses_default_posthog_resources and slot_present:
+ if not publication_present:
+ create_publication(conn, pub_name, tables=[])
+ logger.info("Adopted existing CDC slot/publication for source_id=%s", source.id)
+ return resource_fields, None
+ if slot_present:
return {}, f"A replication slot named '{slot_name}' already exists on your database."
- if publication_exists(conn, pub_name):
+ if uses_default_posthog_resources and publication_present:
+ resource_fields["cdc_consistent_point"] = create_slot(conn, slot_name)
+ logger.info("Adopted existing CDC publication for source_id=%s", source.id)
+ return resource_fields, None
+ if publication_present:
return {}, f"A publication named '{pub_name}' already exists on your database."
- resource_fields["cdc_consistent_point"] = create_slot_and_publication(
- conn, slot_name, pub_name, tables=[]
- )
+ create_publication(conn, pub_name, tables=[])
+ created_publication = True
+ resource_fields["cdc_consistent_point"] = create_slot(conn, slot_name)
+ created_slot = True
except Exception as e:
logger.exception("Failed to create CDC slot and publication: %s", e)
- # Both verified absent above, so dropping anything present now is safe.
try:
with cdc_pg_connection(source, connect_timeout=10) as conn:
- drop_slot_and_publication(conn, slot_name, pub_name)
+ if created_slot and created_publication:
+ drop_slot_and_publication(conn, slot_name, pub_name)
+ elif created_slot:
+ drop_slot(conn, slot_name)
+ elif created_publication:
+ drop_publication(conn, pub_name)
except Exception as rollback_error:
logger.exception("Failed to roll back partial CDC slot/publication: %s", rollback_error)
return {}, f"Failed to create replication slot: {e}"
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 985310dbb0c7..f800347d4d41 100644
--- a/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.py
+++ b/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.py
@@ -63,6 +63,18 @@ def create_slot_and_publication(
Returns the consistent_point LSN from slot creation.
"""
+ create_publication(conn, pub_name, tables)
+ consistent_point = create_slot(conn, slot_name)
+ logger.info("Created publication '%s' with slot '%s'", pub_name, slot_name)
+ return consistent_point
+
+
+def create_publication(
+ conn: psycopg.Connection,
+ pub_name: str,
+ tables: list[tuple[str, str]],
+) -> None:
+ """Create a publication, optionally pre-populated with schema-qualified tables."""
with conn.cursor() as cur:
if tables:
table_list = sql.SQL(", ").join(
@@ -82,13 +94,9 @@ def create_slot_and_publication(
sql.Identifier(pub_name),
)
)
- # Must commit before creating the slot — PG forbids logical slot
- # creation in a transaction that has performed writes.
+ # Commit immediately so callers can create a replication slot on the same connection next.
conn.commit()
-
- consistent_point = create_slot(conn, slot_name)
- logger.info("Created publication '%s' with slot '%s'", pub_name, slot_name)
- return consistent_point
+ logger.info("Created publication '%s'", pub_name)
def create_slot(conn: psycopg.Connection, slot_name: str) -> str:
@@ -141,6 +149,14 @@ def drop_slot_and_publication(
) -> None:
"""Drop a replication slot and publication. Best-effort — logs and continues on errors."""
drop_slot(conn, slot_name)
+ drop_publication(conn, pub_name)
+
+
+def drop_publication(
+ conn: psycopg.Connection,
+ pub_name: str,
+) -> None:
+ """Drop a publication. Best-effort — logs and continues on errors."""
with conn.cursor() as cur:
try:
cur.execute(
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 549cf6d9d2a1..70e79d417cf9 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,5 @@
+import uuid
+
import pytest
from unittest.mock import MagicMock, patch
@@ -17,6 +19,7 @@ def _source(**cdc_overrides):
**cdc_overrides,
}
source = MagicMock()
+ source.id = uuid.UUID("019ef4e8-3bfd-0000-63c8-31abf0d57db8")
source.job_inputs = job_inputs
return source
@@ -30,12 +33,13 @@ def _fake_conn():
class TestSetupResourcesPreflight:
@patch(f"{_ADAPTER}.drop_slot_and_publication")
- @patch(f"{_ADAPTER}.create_slot_and_publication")
+ @patch(f"{_ADAPTER}.create_publication")
+ @patch(f"{_ADAPTER}.create_slot")
@patch(f"{_ADAPTER}.publication_exists", return_value=False)
@patch(f"{_ADAPTER}.slot_exists", return_value=True)
@patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
def test_posthog_refuses_when_slot_already_exists(
- self, _conn, _slot_exists, _pub_exists, mock_create, mock_drop
+ self, _conn, _slot_exists, _pub_exists, mock_create_slot, mock_create_publication, mock_drop
) -> None:
fields, error = PostgresCDCAdapter().setup_resources(
_source(), {"cdc_management_mode": "posthog", "cdc_slot_name": "existing_slot"}
@@ -43,25 +47,85 @@ class TestSetupResourcesPreflight:
assert fields == {}
assert error is not None and "already exists" in error
# Must not create, and must not roll back (drop) a slot it didn't create.
- mock_create.assert_not_called()
+ mock_create_slot.assert_not_called()
+ mock_create_publication.assert_not_called()
mock_drop.assert_not_called()
@patch(f"{_ADAPTER}.drop_slot_and_publication")
- @patch(f"{_ADAPTER}.create_slot_and_publication")
+ @patch(f"{_ADAPTER}.create_publication")
+ @patch(f"{_ADAPTER}.create_slot")
@patch(f"{_ADAPTER}.publication_exists", return_value=True)
@patch(f"{_ADAPTER}.slot_exists", return_value=False)
@patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
def test_posthog_refuses_when_publication_already_exists(
- self, _conn, _slot_exists, _pub_exists, mock_create, mock_drop
+ self, _conn, _slot_exists, _pub_exists, mock_create_slot, mock_create_publication, mock_drop
) -> None:
fields, error = PostgresCDCAdapter().setup_resources(
_source(), {"cdc_management_mode": "posthog", "cdc_publication_name": "existing_pub"}
)
assert fields == {}
assert error is not None and "already exists" in error
- mock_create.assert_not_called()
+ mock_create_slot.assert_not_called()
+ mock_create_publication.assert_not_called()
mock_drop.assert_not_called()
+ @patch(f"{_ADAPTER}.create_slot")
+ @patch(f"{_ADAPTER}.create_publication")
+ @patch(f"{_ADAPTER}.publication_exists", return_value=True)
+ @patch(f"{_ADAPTER}.slot_exists", return_value=True)
+ @patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
+ def test_posthog_adopts_existing_default_slot_and_publication(
+ self, _conn, _slot_exists, _pub_exists, mock_create_publication, mock_create_slot
+ ) -> None:
+ source = _source()
+ fields, error = PostgresCDCAdapter().setup_resources(source, {"cdc_management_mode": "posthog"})
+
+ assert error is None
+ assert fields == {
+ "cdc_management_mode": "posthog",
+ "cdc_slot_name": "posthog_019ef4e83bfd",
+ "cdc_publication_name": "posthog_pub_019ef4e83bfd",
+ }
+ mock_create_slot.assert_not_called()
+ mock_create_publication.assert_not_called()
+
+ @patch(f"{_ADAPTER}.create_slot")
+ @patch(f"{_ADAPTER}.create_publication")
+ @patch(f"{_ADAPTER}.publication_exists", return_value=False)
+ @patch(f"{_ADAPTER}.slot_exists", return_value=True)
+ @patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
+ def test_posthog_recreates_missing_default_publication_when_adopting_slot(
+ self, _conn, _slot_exists, _pub_exists, mock_create_publication, mock_create_slot
+ ) -> None:
+ source = _source()
+ fields, error = PostgresCDCAdapter().setup_resources(source, {"cdc_management_mode": "posthog"})
+
+ assert error is None
+ assert fields["cdc_slot_name"] == "posthog_019ef4e83bfd"
+ assert fields["cdc_publication_name"] == "posthog_pub_019ef4e83bfd"
+ mock_create_publication.assert_called_once()
+ assert mock_create_publication.call_args.args[1] == "posthog_pub_019ef4e83bfd"
+ mock_create_slot.assert_not_called()
+
+ @patch(f"{_ADAPTER}.create_slot", return_value="0/AA")
+ @patch(f"{_ADAPTER}.create_publication")
+ @patch(f"{_ADAPTER}.publication_exists", return_value=True)
+ @patch(f"{_ADAPTER}.slot_exists", return_value=False)
+ @patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
+ def test_posthog_adopts_existing_default_publication_and_creates_missing_slot(
+ self, _conn, _slot_exists, _pub_exists, mock_create_publication, mock_create_slot
+ ) -> None:
+ source = _source()
+ fields, error = PostgresCDCAdapter().setup_resources(source, {"cdc_management_mode": "posthog"})
+
+ assert error is None
+ assert fields["cdc_slot_name"] == "posthog_019ef4e83bfd"
+ assert fields["cdc_publication_name"] == "posthog_pub_019ef4e83bfd"
+ assert fields["cdc_consistent_point"] == "0/AA"
+ mock_create_slot.assert_called_once()
+ assert mock_create_slot.call_args.args[1] == "posthog_019ef4e83bfd"
+ mock_create_publication.assert_not_called()
+
@patch(f"{_ADAPTER}.drop_slot")
@patch(f"{_ADAPTER}.create_slot")
@patch(f"{_ADAPTER}.publication_exists", return_value=True)
@@ -78,23 +142,27 @@ class TestSetupResourcesPreflight:
mock_create.assert_not_called()
mock_drop.assert_not_called()
- @patch(f"{_ADAPTER}.drop_slot_and_publication")
- @patch(f"{_ADAPTER}.create_slot_and_publication", side_effect=RuntimeError("boom"))
+ @patch(f"{_ADAPTER}.drop_publication")
+ @patch(f"{_ADAPTER}.drop_slot")
+ @patch(f"{_ADAPTER}.create_slot", side_effect=RuntimeError("boom"))
+ @patch(f"{_ADAPTER}.create_publication")
@patch(f"{_ADAPTER}.publication_exists", return_value=False)
@patch(f"{_ADAPTER}.slot_exists", return_value=False)
@patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)
def test_posthog_rolls_back_only_after_verifying_absence(
- self, _conn, _slot_exists, _pub_exists, _create, mock_drop
+ self, _conn, _slot_exists, _pub_exists, mock_create_publication, _create_slot, mock_drop_slot, mock_drop_pub
) -> None:
- # Both verified absent, then create fails → safe to drop what we just made.
+ # Publication was created before slot creation failed → only the publication is rolled back.
fields, error = PostgresCDCAdapter().setup_resources(
_source(),
{"cdc_management_mode": "posthog", "cdc_slot_name": "s", "cdc_publication_name": "p"},
)
assert fields == {}
assert error is not None and "boom" in error
- mock_drop.assert_called_once()
- assert mock_drop.call_args.args[1:] == ("s", "p")
+ mock_create_publication.assert_called_once()
+ mock_drop_slot.assert_not_called()
+ mock_drop_pub.assert_called_once()
+ assert mock_drop_pub.call_args.args[1] == "p"
class TestRecreateSlot:
diff --git a/posthog/temporal/data_imports/util.py b/posthog/temporal/data_imports/util.py
index eee38f3e933b..f9efbda721c5 100644
--- a/posthog/temporal/data_imports/util.py
+++ b/posthog/temporal/data_imports/util.py
@@ -93,8 +93,6 @@ async def prepare_s3_files_for_querying(
all_file_values = all_files.values() if isinstance(all_files, dict) else all_files
directories = [f["Key"] for f in all_file_values if f["type"] == "directory"]
- await _log(f"Found existing directories: {directories}")
-
timestamped_query_folders: list[tuple[str, int]] = []
for directory in directories:
match = query_folder_pattern.match(directory)
@@ -103,6 +101,10 @@ async def prepare_s3_files_for_querying(
timestamped_query_folders.sort(key=lambda x: x[1])
total_dirs = len(timestamped_query_folders)
+ await _log(
+ f"Found {len(directories)} existing directories; "
+ f"{total_dirs} match query folders for table {normalized_table_name}"
+ )
for index, directory in enumerate(timestamped_query_folders):
directory_path, directory_timestamp = directory
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 4e0872a52c20..d981686e80d3 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -854,6 +854,13 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
new_job_inputs = {**existing_job_inputs, **incoming_job_inputs}
+ # CDC resource ownership changes must go through the CDC-specific endpoints.
+ for key in _CDC_EXPOSED_JOB_INPUT_KEYS:
+ if key in existing_job_inputs:
+ new_job_inputs[key] = existing_job_inputs[key]
+ else:
+ new_job_inputs.pop(key, None)
+
# If the connection target changed, require credentials to be re-entered. Covers
# both the generic `host` field and source-specific URL fields like ServiceNow's
# `instance_url`, so a stored credential can't be redirected to a new host.
@@ -973,7 +980,11 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
apply_sql_warehouse_schema_clear_migration(instance, old_schema)
source_config: Config = source.parse_config(new_job_inputs)
- validated_data["job_inputs"] = source_config.to_dict()
+ validated_job_inputs = source_config.to_dict()
+ for key in _CDC_EXPOSED_JOB_INPUT_KEYS:
+ if key in existing_job_inputs:
+ validated_job_inputs[key] = existing_job_inputs[key]
+ validated_data["job_inputs"] = validated_job_inputs
if job_inputs_were_submitted:
if isinstance(source, (PostgresSource, MySQLSource)):
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 fbde68b50d70..fa0aab7c5e57 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
@@ -426,6 +426,70 @@ class TestExternalDataSource(APIBaseTest):
source.refresh_from_db()
assert source.direct_query_enabled is False
+ @patch(
+ "posthog.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials_for_access_method",
+ return_value=(True, None),
+ )
+ def test_patch_external_data_source_preserves_cdc_config_when_schema_cleared(self, _mock_validate):
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="Postgres",
+ created_by=self.user,
+ job_inputs={
+ "host": "localhost",
+ "port": 5432,
+ "database": "testdb",
+ "user": "test",
+ "password": "test",
+ "schema": "public",
+ "cdc_enabled": True,
+ "cdc_management_mode": "posthog",
+ "cdc_slot_name": "posthog_slot",
+ "cdc_publication_name": "posthog_pub",
+ "cdc_auto_drop_slot": False,
+ "cdc_lag_warning_threshold_mb": 512,
+ "cdc_lag_critical_threshold_mb": 1024,
+ "cdc_consistent_point": "0/AA",
+ },
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={
+ "job_inputs": {
+ "host": "localhost",
+ "port": 5432,
+ "database": "testdb",
+ "user": "test",
+ "schema": "",
+ "cdc_enabled": False,
+ "cdc_management_mode": "self_managed",
+ "cdc_slot_name": "attacker_slot",
+ "cdc_publication_name": "attacker_pub",
+ "cdc_auto_drop_slot": True,
+ "cdc_lag_warning_threshold_mb": 1,
+ "cdc_lag_critical_threshold_mb": 2,
+ "cdc_consistent_point": "0/BAD",
+ }
+ },
+ format="json",
+ )
+
+ assert response.status_code == 200, response.json()
+ source.refresh_from_db()
+ assert source.job_inputs["schema"] == ""
+ assert str(source.job_inputs["cdc_enabled"]) == "True"
+ assert source.job_inputs["cdc_management_mode"] == "posthog"
+ assert source.job_inputs["cdc_slot_name"] == "posthog_slot"
+ assert source.job_inputs["cdc_publication_name"] == "posthog_pub"
+ assert str(source.job_inputs["cdc_auto_drop_slot"]) == "False"
+ assert str(source.job_inputs["cdc_lag_warning_threshold_mb"]) == "512"
+ assert str(source.job_inputs["cdc_lag_critical_threshold_mb"]) == "1024"
+ assert source.job_inputs["cdc_consistent_point"] == "0/AA"
+
@patch(
"products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",
return_value=False,
@@ -8607,12 +8671,18 @@ class TestEnableCDC(APIBaseTest):
@patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.publication_exists", return_value=False)
@patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.slot_exists", return_value=False)
@patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.drop_slot_and_publication")
- @patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.create_slot_and_publication")
+ @patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.drop_slot")
+ @patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.drop_publication")
+ @patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.create_slot")
+ @patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.create_publication")
@patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.cdc_pg_connection")
def test_enable_cdc_posthog_rolls_back_partial_slot_on_failure(
self,
mock_cdc_pg_connection,
- mock_create_slot_and_publication,
+ mock_create_publication,
+ mock_create_slot,
+ mock_drop_publication,
+ mock_drop_slot,
mock_drop_slot_and_publication,
_mock_slot_exists,
_mock_publication_exists,
@@ -8625,7 +8695,8 @@ class TestEnableCDC(APIBaseTest):
mock_cdc_pg_connection.return_value.__enter__.return_value = object()
mock_cdc_pg_connection.return_value.__exit__.return_value = None
- mock_create_slot_and_publication.side_effect = RuntimeError("max_replication_slots reached")
+ # Publication is created first; the slot creation then fails (e.g. max_replication_slots reached).
+ mock_create_slot.side_effect = RuntimeError("max_replication_slots reached")
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/enable_cdc/",
@@ -8640,11 +8711,12 @@ class TestEnableCDC(APIBaseTest):
assert response.status_code == 400
assert "max_replication_slots reached" in response.json()["message"]
- # Best-effort cleanup must run with the exact slot + publication we tried to create.
- mock_drop_slot_and_publication.assert_called_once()
- call = mock_drop_slot_and_publication.call_args
- assert call.args[1] == "leaky_slot"
- assert call.args[2] == "leaky_pub"
+ # Only the publication was created before the slot failed, so rollback drops just the publication.
+ mock_create_publication.assert_called_once()
+ mock_drop_publication.assert_called_once()
+ assert mock_drop_publication.call_args.args[1] == "leaky_pub"
+ mock_drop_slot.assert_not_called()
+ mock_drop_slot_and_publication.assert_not_called()
# Source's job_inputs must NOT have been persisted with cdc_enabled — we never reached save().
source.refresh_from_db()
diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
index 5f1947c055b4..a43546ee4880 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
@@ -316,8 +316,8 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormPro
<div className="font-normal mb-2">
<div className="font-semibold">Both</div>
<p className="m-0 text-secondary text-sm">
- CDC history table plus an auto-generated view for the current state
- (<code>valid_to IS NULL</code>).
+ Consolidated current-state table plus a separate <code>_cdc</code>
+ -suffixed history table.
</p>
</div>
),