: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(postgres): qualify each table by its own schema when rebuilding CDC publication (#64938)
Tom Owers2acd5a1ece67
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.pyindex 7db1186a7ef9..7ac158ef8781 100644--- a/posthog/temporal/data_imports/cdc/activities.py+++ b/posthog/temporal/data_imports/cdc/activities.py@@ -635,25 +635,32 @@ class CDCExtractActivity:columns=filtered,)+ def _qualified_table_name(self, schema: ExternalDataSchema) -> str:+ """Resolve a CDC schema row to its source-qualified `schema.table` name.++ Prefers stored schema_metadata, then a dotted display name, then the source's+ default schema — so a row stored bare (`orders`) still resolves to its real+ source location (`public.orders`).+ """+ default_schema = (self.source.job_inputs or {}).get("schema") if self.source else None+ 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):+ return f"{src_schema}.{src_table}"+ if "." in schema.name:+ return schema.name+ return f"{default_schema or 'public'}.{schema.name}"+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 Nonemapping: 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[self._qualified_table_name(schema)] = schema.namemapping.setdefault(schema.name, schema.name) # also match a bare-emitted namereturn mapping@@ -922,7 +929,9 @@ class CDCExtractActivity: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])+ resource_fields = self.adapter.recreate_slot(+ self.source, tables=[self._qualified_table_name(s) 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"])diff --git a/posthog/temporal/data_imports/cdc/adapters.py b/posthog/temporal/data_imports/cdc/adapters.pyindex c14093e9cf38..6d6cfbdf22ab 100644--- a/posthog/temporal/data_imports/cdc/adapters.py+++ b/posthog/temporal/data_imports/cdc/adapters.py@@ -74,9 +74,10 @@ class CDCSourceAdapter(Protocol[CDCConfigT_co]):def recreate_slot(self, source: ExternalDataSource, tables: list[str]) -> dict[str, Any]:"""Drop and recreate the change-stream resource after invalidation, against theexisting 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)."""+ the schema-qualified (``schema.table``) 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: ...diff --git a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.pyindex dd8b44f17491..320fc5323c6a 100644--- a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py+++ b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py@@ -1438,7 +1438,7 @@ class TestSlotInvalidationRecovery:# 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"])+ mock_adapter.recreate_slot.assert_called_once_with(source, tables=["public.users"])assert source.job_inputs["cdc_consistent_point"] == "0/AA"source.save.assert_called()@@ -1451,6 +1451,37 @@ class TestSlotInvalidationRecovery: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_recreate_passes_source_qualified_table_names(+ self,+ mock_close_conns,+ MockSourceModel,+ mock_get_schemas,+ mock_get_adapter,+ mock_activity,+ ):+ # Recovery must resolve each schema's real source location from its metadata,+ # not assume every table lives in the source's default schema. Otherwise a table+ # in a non-default schema gets jammed under `public` and the publication rebuild+ # fails with `relation "public.tll.students" does not exist`.+ source, schema, mock_reader, mock_adapter = self._setup(+ mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity+ )+ schema.name = "students"+ schema.sync_type_config["schema_metadata"] = {"source_schema": "tll", "source_table_name": "students"}+ mock_adapter.recreate_slot.return_value = {"cdc_consistent_point": "0/AA"}++ inputs = CDCExtractInput(team_id=1, source_id=source.id)+ cdc_extract_activity(inputs)++ mock_adapter.recreate_slot.assert_called_once_with(source, tables=["tll.students"])+ assert source.job_inputs["cdc_consistent_point"] == "0/AA"+ source.save.assert_called()+@patch("posthog.temporal.data_imports.cdc.activities.activity")@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")@patch.object(CDCExtractActivity, "_get_cdc_schemas")diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py b/posthog/temporal/data_imports/sources/postgres/cdc/adapter.pyindex 6d20b4360f6e..0ff003ae266b 100644--- a/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py+++ b/posthog/temporal/data_imports/sources/postgres/cdc/adapter.py@@ -33,6 +33,15 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+def _split_qualified_table(qualified: str, default_schema: str) -> tuple[str, str]:+ """Split a ``schema.table`` name into ``(schema, table)``, falling back to+ ``default_schema`` for a bare table name."""+ if "." in qualified:+ table_schema, table_name = qualified.split(".", 1)+ return table_schema, table_name+ return default_schema, qualified++class PostgresCDCAdapter:def parse_cdc_config(self, source: ExternalDataSource) -> PostgresCDCConfig:return PostgresCDCConfig.from_source(source)@@ -103,14 +112,17 @@ class PostgresCDCAdapter:def recreate_slot(self, source: ExternalDataSource, tables: list[str]) -> dict[str, Any]:"""Drop the dead replication slot and create a fresh one against the existingpublication, 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).++ ``tables`` are schema-qualified ``schema.table`` names — a publication can span+ schemas, so each table keeps its own schema rather than inheriting the source's+ default. 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)+ default_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):@@ -120,7 +132,10 @@ class PostgresCDCAdapter:"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+ conn,+ cdc_config.slot_name,+ cdc_config.publication_name,+ tables=[_split_qualified_table(t, default_schema) for t in tables],)else:consistent_point = create_slot(conn, cdc_config.slot_name)@@ -143,8 +158,6 @@ class PostgresCDCAdapter: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- schema = self._resolve_schema(source)-resource_fields: dict[str, Any] = {"cdc_management_mode": management_mode,"cdc_slot_name": slot_name,@@ -160,7 +173,7 @@ class PostgresCDCAdapter:if publication_exists(conn, pub_name):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, schema, tables=[]+ conn, slot_name, pub_name, tables=[])except Exception as e:logger.exception("Failed to create CDC slot and publication: %s", e)diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.py b/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.pyindex 33434d45de6e..985310dbb0c7 100644--- a/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.py+++ b/posthog/temporal/data_imports/sources/postgres/cdc/slot_manager.py@@ -53,17 +53,21 @@ def create_slot_and_publication(conn: psycopg.Connection,slot_name: str,pub_name: str,- schema: str,- tables: list[str],+ tables: list[tuple[str, str]],) -> str:"""Create a publication and replication slot.+ ``tables`` is a list of ``(schema, table)`` pairs — each table is qualified by+ its own schema, since a publication can span schemas. An empty list creates an+ empty publication (tables added later via ALTER PUBLICATION ADD TABLE).+Returns the consistent_point LSN from slot creation."""with conn.cursor() as cur:if tables:table_list = sql.SQL(", ").join(- sql.SQL("{}.{}").format(sql.Identifier(schema), sql.Identifier(t)) for t in tables+ sql.SQL("{}.{}").format(sql.Identifier(table_schema), sql.Identifier(table_name))+ for table_schema, table_name in tables)cur.execute(sql.SQL("CREATE PUBLICATION {} FOR TABLE {} WITH (publish_via_partition_root = true)").format(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.pyindex 3382cf9e4642..549cf6d9d2a1 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@@ -122,13 +122,24 @@ class TestRecreateSlot:assert mock_create.call_args.args[1] == "posthog_slot"mock_create_slot_and_pub.assert_not_called()+ @pytest.mark.parametrize(+ "tables,expected_pairs",+ [+ # Bare names fall back to the source's default schema.+ (["users"], [("public", "users")]),+ # A schema-qualified name keeps its own schema; a bare name still uses the default.+ # Regression: previously every table was forced under the source default schema,+ # so `tll.students` became `public."tll.students"` and CREATE PUBLICATION failed.+ (["tll.students", "orders"], [("tll", "students"), ("public", "orders")]),+ ],+ )@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+ def test_recreates_publication_qualifying_each_table_by_its_own_schema(+ self, _conn, mock_drop, _pub_exists, mock_create, mock_create_slot_and_pub, tables, expected_pairs) -> None:source = _source(cdc_enabled=True,@@ -137,12 +148,12 @@ class TestRecreateSlot:cdc_publication_name="posthog_pub",)- fields = PostgresCDCAdapter().recreate_slot(source, tables=["users"])+ fields = PostgresCDCAdapter().recreate_slot(source, tables=tables)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"]+ assert mock_create_slot_and_pub.call_args.kwargs["tables"] == expected_pairsmock_create.assert_not_called()@patch(f"{_ADAPTER}.create_slot_and_publication")