: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(warehouse-sources): match qualified schema names in CDC key lookups (#86510)
Daniel RC0f1907cadc1a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex 0e83aff67121..2514cfdbe00b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -851,7 +851,7 @@ class CDCExtractActivity:self.log.info("wal_changes_read", event_count=self.event_count, tables=list(self.all_table_names))- self._handle_pk_changes_post_wal()+ self._detect_pk_changes_post_wal()truncated_tables = self._handle_truncates()if self.event_count == 0:@@ -1054,15 +1054,20 @@ class CDCExtractActivity:# Fall back to information_schema for any tables missing PKsmissing_pk_tables = [t for t in cdc_table_names if t not in self.pk_columns_by_table]if missing_pk_tables:- db_schema = (self.source.job_inputs or {}).get("schema", "public")- queried_pks = self.reader.get_primary_key_columns(db_schema, missing_pk_tables)+ queried_pks = self._query_pk_columns(missing_pk_tables)self.pk_columns_by_table.update(queried_pks)# Persist discovered PKs to avoid re-queryingfor schema in self.cdc_schemas:- if schema.name in queried_pks:- self._update_schema_sync_type_config(- schema, updates={"primary_key_columns": queried_pks[schema.name]}- )+ if schema.name not in queried_pks:+ continue+ # Only schemas with no stored key reach here, so this is always a first write. Its+ # table merged on an empty key until now, which means the rows already in it were+ # never keyed. Log it so an operator can decide whether that table needs a+ # re-snapshot rather than having the merge key appear from nowhere.+ self._schema_log(schema).warning(+ "cdc_pk_columns_first_write", table=schema.name, discovered=queried_pks[schema.name]+ )+ self._update_schema_sync_type_config(schema, updates={"primary_key_columns": queried_pks[schema.name]})self.log.info("pk_columns_loaded", tables=list(self.pk_columns_by_table.keys()))@@ -1080,6 +1085,32 @@ class CDCExtractActivity:retained.add(inc)self.enabled_columns_by_table[schema.name] = retained+ def _query_pk_columns(self, table_names: list[str]) -> dict[str, list[str]]:+ """Look up primary keys in the source catalog, keyed back on `ExternalDataSchema.name`.++ Schema names are qualified (`schema.table`) while the catalog lookup takes one namespace+ plus bare relation names, so a name has to be split for the query and rejoined for the+ result. Passing the qualified name straight through matched no catalog row, so any schema+ without a stored primary key fell back to an empty merge key. Splitting on the first dot and+ defaulting to the source's namespace matches how the tables are resolved when they are added+ to the publication.+ """+ assert self.source is not None+ default_namespace = (self.source.job_inputs or {}).get("schema", "public")+ names_by_namespace: dict[str, dict[str, str]] = {}+ for name in table_names:+ namespace, dot, relation = name.partition(".")+ if not dot:+ namespace, relation = default_namespace, name+ names_by_namespace.setdefault(namespace, {})[relation] = name++ resolved: dict[str, list[str]] = {}+ for namespace, relations_by_name in names_by_namespace.items():+ queried = self.reader.get_primary_key_columns(namespace, list(relations_by_name))+ for relation, pk_columns in queried.items():+ resolved[relations_by_name[relation]] = pk_columns+ return resolved+def _project_event_columns(self, event: ChangeEvent) -> ChangeEvent:retained = self.enabled_columns_by_table.get(event.table_name)if retained is None:@@ -1285,18 +1316,25 @@ class CDCExtractActivity:# ------------------------------------------------------------------# Post-WAL handling# ------------------------------------------------------------------- def _handle_pk_changes_post_wal(self) -> None:- """Detect PK column changes that surfaced during decoding."""+ def _detect_pk_changes_post_wal(self) -> None:+ """Report tables whose replica identity key stopped matching the primary key we merge on.++ Detection only. Adopting the new key here would re-key a live Delta table whose existing+ rows were merged under the old one, so every row already in the table would be duplicated+ rather than replaced from that point on. The safe remediation is a full re-snapshot of the+ table, which is an operator decision, not something a WAL read should trigger on its own.+ """for table_name in self.all_table_names:decoder_pks = self.reader.get_decoder_key_columns(table_name)stored_pks = self.pk_columns_by_table.get(table_name, [])- if decoder_pks and decoder_pks != stored_pks:- pk_schema = self.schema_by_name.get(table_name)- pk_log = self._schema_log(pk_schema) if pk_schema is not None else self.log- pk_log.warning("pk_columns_changed", table=table_name, old=stored_pks, new=decoder_pks)- self.pk_columns_by_table[table_name] = decoder_pks- if pk_schema is not None:- self._update_schema_sync_type_config(pk_schema, updates={"primary_key_columns": decoder_pks})+ # Compared as sets because pg_catalog orders the stored key by index position while the+ # decoder reports it in table column order, so a composite key can differ in order+ # without having changed.+ if not decoder_pks or set(decoder_pks) == set(stored_pks):+ continue+ pk_schema = self.schema_by_name.get(table_name)+ pk_log = self._schema_log(pk_schema) if pk_schema is not None else self.log+ pk_log.warning("cdc_pk_columns_diverged", table=table_name, stored=stored_pks, wal=decoder_pks)def _handle_truncates(self) -> list[str]:"""Process any truncated tables observed during decoding.diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.pyindex cd7bcb713336..86e828feae70 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py@@ -2920,6 +2920,112 @@ class TestFailureVisibilityJobs:assert created_for == {schema_a, schema_b}+class TestPKColumnLoading:+ def _activity(self, schemas, queried_pks=None, default_namespace="public"):+ source = _make_source()+ source.job_inputs = {**source.job_inputs, "schema": default_namespace}+ act = _make_extract_activity(source)+ act.cdc_schemas = schemas+ for schema in schemas:+ schema.source = source+ act.reader = MagicMock()+ act.reader.get_primary_key_columns.side_effect = lambda namespace, relations: {+ relation: pks for relation, pks in (queried_pks or {}).get(namespace, {}).items() if relation in relations+ }+ return act++ def test_qualified_name_is_split_for_the_query_and_rejoined_for_the_result(self):+ # The catalog filters on the bare relation name inside one namespace, so a qualified+ # ExternalDataSchema.name matched nothing and the table synced with no merge key.+ schema = _make_schema("cdc_test.orders")+ act = self._activity([schema], queried_pks={"cdc_test": {"orders": ["id"]}})++ act._load_pk_columns()++ assert act.reader.get_primary_key_columns.call_args.args == ("cdc_test", ["orders"])+ assert act.pk_columns_by_table == {"cdc_test.orders": ["id"]}+ assert schema.sync_type_config["primary_key_columns"] == ["id"]+ warnings = [call.args[0] for call in act.log.bind.return_value.warning.call_args_list]+ assert "cdc_pk_columns_first_write" in warnings++ def test_bare_name_falls_back_to_the_source_namespace(self):+ schema = _make_schema("orders")+ act = self._activity([schema], queried_pks={"analytics": {"orders": ["id"]}}, default_namespace="analytics")++ act._load_pk_columns()++ assert act.reader.get_primary_key_columns.call_args.args == ("analytics", ["orders"])+ assert act.pk_columns_by_table == {"orders": ["id"]}++ def test_tables_are_grouped_by_namespace(self):+ # One query per namespace, and two tables sharing a relation name stay distinct.+ act = self._activity(+ [_make_schema("cdc_test.orders"), _make_schema("public.orders")],+ queried_pks={"cdc_test": {"orders": ["id"]}, "public": {"orders": ["uuid"]}},+ )++ act._load_pk_columns()++ queried_namespaces = {call.args[0] for call in act.reader.get_primary_key_columns.call_args_list}+ assert queried_namespaces == {"cdc_test", "public"}+ assert act.pk_columns_by_table == {"cdc_test.orders": ["id"], "public.orders": ["uuid"]}++ def test_stored_keys_are_not_requeried(self):+ schema = _make_schema("cdc_test.orders")+ schema.sync_type_config["primary_key_columns"] = ["id"]+ act = self._activity([schema])++ act._load_pk_columns()++ act.reader.get_primary_key_columns.assert_not_called()+ assert act.pk_columns_by_table == {"cdc_test.orders": ["id"]}+++class TestPKDivergenceDetection:+ def _activity(self, decoder_pks, stored_pks, table="cdc_test.orders"):+ source = _make_source()+ schema = _make_schema(table, source=source)+ act = _make_extract_activity(source)+ act.cdc_schemas = [schema]+ act.schema_by_name = {table: schema}+ act.all_table_names = {table}+ act.pk_columns_by_table = {table: stored_pks}+ act.reader = MagicMock()+ act.reader.get_decoder_key_columns.return_value = decoder_pks+ return act, schema++ @parameterized.expand(+ [+ # The qualified name is the whole point: it is what ExternalDataSchema.name holds, and+ # the decoder used to match only the bare relation name, so this never fired.+ ("key_gained_a_column", ["id", "tenant_id"], ["id"], True),+ ("key_replaced", ["uuid"], ["id"], True),+ # pg_catalog orders by index position, the decoder by column position.+ ("same_key_different_order", ["tenant_id", "id"], ["id", "tenant_id"], False),+ ("unchanged", ["id"], ["id"], False),+ # What REPLICA IDENTITY FULL and NOTHING both report.+ ("no_key_in_wal", [], ["id"], False),+ ]+ )+ def test_divergence_warns_only_on_a_real_change(self, _name, decoder_pks, stored_pks, expect_warning):+ act, _schema = self._activity(decoder_pks, stored_pks)++ act._detect_pk_changes_post_wal()++ warnings = [call.args[0] for call in act.log.bind.return_value.warning.call_args_list]+ assert ("cdc_pk_columns_diverged" in warnings) is expect_warning++ def test_diverged_key_is_not_persisted_over_the_merge_key(self):+ # Re-keying a live Delta table duplicates every row already merged under the old key, so a+ # detected change stays a signal until an operator re-snapshots the table.+ act, schema = self._activity(["id", "tenant_id"], ["id"])++ act._detect_pk_changes_post_wal()++ assert "primary_key_columns" not in schema.sync_type_config+ assert act.pk_columns_by_table["cdc_test.orders"] == ["id"]++class _ScriptedReader:"""Reader stub that serves preconfigured WAL pages to the bounded read loop.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.pyindex dc4821bcba57..6a21da38d863 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py@@ -73,6 +73,9 @@ class RelationColumn:type_modifier: int+_REPLICA_IDENTITY_FULL = 2++@dataclassclass Relation:"""Cached relation (table) metadata from an R message."""@@ -359,11 +362,34 @@ class PgOutputDecoder:# --- Helpers ---def get_key_columns(self, table_name: str) -> list[str]:- """Return column names that are part of the replica identity key for a table."""+ """Return the column names forming the replica identity key, or [] if there is no usable one.++ Callers key on `ExternalDataSchema.name`, which is qualified (`schema.table`) for every+ source created through the API, so matching only the bare relation name returned [] for all+ of them and made the caller's key-change detection dead code.+ """+ relation = self._find_relation_by_name(table_name)+ if relation is None:+ return []+ # replica_identity 2 = FULL, which flags every column as part of the key. That names no key:+ # merging on every column makes each row version its own key, so updates accumulate instead+ # of replacing. Checked by identity rather than by "all columns flagged", so a table whose+ # declared PK genuinely covers every column still works.+ if relation.replica_identity == _REPLICA_IDENTITY_FULL:+ return []+ return [col.name for col in relation.columns if col.flags & 1]++ def _find_relation_by_name(self, table_name: str) -> Relation | None:+ """Match `schema.table` first, falling back to the bare table name for schema rows that+ predate qualification. Bare matching alone is also ambiguous once two source schemas expose+ the same table name."""+ bare_match: Relation | None = Nonefor relation in self._relations.values():- if relation.table_name == table_name:- return [col.name for col in relation.columns if col.flags & 1]- return []+ if relation.qualified_name == table_name:+ return relation+ if bare_match is None and relation.table_name == table_name:+ bare_match = relation+ return bare_matchdef _get_relation(self, relation_id: int) -> Relation | None:relation = self._relations.get(relation_id)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.pyindex 53604e9c668d..7c7eb9dcd34a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py@@ -16,6 +16,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.c_OID_TEXT,PG_EPOCH_OFFSET_US,PgOutputDecoder,+ Relation,+ RelationColumn,_pg_timestamp_to_datetime,)@@ -557,3 +559,41 @@ class TestTransactionBufferGuard:decoder.decode_message(_make_insert(1, [("t", "2")]), "0/1")events = decoder.decode_message(_make_commit(), "0/1")assert len(events) == 2+++class TestReplicaIdentityKeyColumns:+ def _decoder_with(self, replica_identity: int = 0, key_flags: tuple[int, ...] = (1, 0, 0)) -> PgOutputDecoder:+ decoder = PgOutputDecoder()+ decoder._relations[1] = Relation(+ relation_id=1,+ schema_name="cdc_test",+ table_name="orders",+ replica_identity=replica_identity,+ columns=[+ RelationColumn(flags=flags, name=name, type_oid=_OID_INT8, type_modifier=-1)+ for flags, name in zip(key_flags, ["id", "tenant_id", "total"])+ ],+ )+ return decoder++ @parameterized.expand(+ [+ ("qualified", "cdc_test.orders", ["id"]),+ ("bare", "orders", ["id"]),+ ("other_schema", "public.orders", []),+ ]+ )+ def test_lookup_by_name(self, _name, lookup, expected):+ assert self._decoder_with().get_key_columns(lookup) == expected++ def test_full_replica_identity_yields_no_key(self):+ # FULL flags every column, so adopting it as the key would make the merge key the whole row+ # and every update would insert instead of replace.+ decoder = self._decoder_with(replica_identity=2, key_flags=(1, 1, 1))++ assert decoder.get_key_columns("cdc_test.orders") == []++ def test_declared_key_covering_every_column_survives(self):+ decoder = self._decoder_with(replica_identity=0, key_flags=(1, 1, 1))++ assert decoder.get_key_columns("cdc_test.orders") == ["id", "tenant_id", "total"]