: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): check CDC primary keys under each table's schema (#99600)
Tom Owersfb0ca7361e90
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsxindex ce06e6eacecc..99d93ce63a4d 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx@@ -31,7 +31,7 @@ import { ExternalDataSourceType, SourceConfig } from '~/queries/schema/schema-geimport { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/types'import SchemaForm from '../../shared/components/forms/SchemaForm'-import { supportsDirectQuery } from '../../shared/components/forms/schemaGroupingUtils'+import { splitQualifiedTableName, supportsDirectQuery } from '../../shared/components/forms/schemaGroupingUtils'import SourceForm, { SourceAccessMethodSelector, getSourceQueryMode } from '../../shared/components/forms/SourceForm'import { SyncProgressStep } from '../../shared/components/forms/SyncProgressStep'import { WebhookSetupForm } from '../../shared/components/forms/WebhookSetupForm'@@ -417,17 +417,21 @@ function CDCSelfManagedSetupDialog(): JSX.Element | null {const pubName = (payload.cdc_publication_name as string) || 'posthog_pub'const dbUser = (sourceConnectionDetails?.payload?.user as string) || '<your_user>'- const tableList =+ // Discovery names a table `schema.table` when the source reads every schema, so each name has+ // to be split before it goes into SQL. A source pinned to one schema lists bare names.+ const qualifiedTables =cdcTableNames.length > 0- ? cdcTableNames.map((t) => `"${schema}"."${t}"`).join(', ')- : `"${schema}"."your_table"`+ ? cdcTableNames.map((t) => splitQualifiedTableName(t, schema))+ : [{ schemaName: schema, tableName: 'your_table' }]+ const tableList = qualifiedTables.map(({ schemaName, tableName }) => `"${schemaName}"."${tableName}"`).join(', ')+ const usageSchemas = [...new Set(qualifiedTables.map(({ schemaName }) => schemaName))]const sql = `-- 1. Grants for the PostHog user-- Reading a replication slot requires REPLICATION (or rds_replication on RDS).-- Run ONE of the lines below, depending on your environment:ALTER USER "${dbUser}" WITH REPLICATION; -- self-hosted / most clouds-- GRANT rds_replication TO "${dbUser}"; -- AWS RDS-GRANT USAGE ON SCHEMA "${schema}" TO "${dbUser}";+${usageSchemas.map((schemaName) => `GRANT USAGE ON SCHEMA "${schemaName}" TO "${dbUser}";`).join('\n')}GRANT SELECT ON ${tableList} TO "${dbUser}";-- 2. Publication covering the ${cdcTableNames.length} selected table${cdcTableNames.length === 1 ? '' : 's'}@@ -437,7 +441,7 @@ CREATE PUBLICATION "${pubName}" FOR TABLE ${tableList}WITH (publish_via_partition_root = true);-- Later, to add a new table to the publication:--- ALTER PUBLICATION "${pubName}" ADD TABLE "${schema}"."new_table";`+-- ALTER PUBLICATION "${pubName}" ADD TABLE "${usageSchemas[0]}"."new_table";`const handleCopy = async (): Promise<void> => {await copyToClipboard(sql, 'Setup SQL')diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/prerequisite_validator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/prerequisite_validator.pyindex c69430fcfe2d..64659f208f06 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/prerequisite_validator.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/prerequisite_validator.py@@ -12,6 +12,8 @@ from typing import Literalimport psycopgfrom psycopg import sql+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.slot_manager import (publication_exists,slot_exists,@@ -20,24 +22,35 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.clogger = logging.getLogger(__name__)+@frozen+class _QualifiedTable:+ schema: str+ table: str++def validate_cdc_prerequisites(conn: psycopg.Connection,management_mode: Literal["posthog", "self_managed"],tables: list[str],- schema: str = "public",+ schema: str | None = "public",slot_name: str | None = None,publication_name: str | None = None,) -> list[str]:"""Validate that the database is ready for CDC.+ `schema` is the single schema the source is configured to read. Pass None when the source+ reads every schema, because schema discovery then names each table `schema.table` and the+ entries in `tables` carry their own schema.+Returns a list of user-facing error messages. Empty list = valid."""errors: list[str] = []+ qualified_tables = _resolve_table_schemas(tables, schema)errors.extend(_check_pg_version(conn))errors.extend(_check_wal_level(conn))- errors.extend(_check_tables_have_primary_keys(conn, schema, tables))- errors.extend(_check_select_permission(conn, schema, tables))+ errors.extend(_check_tables_have_primary_keys(conn, qualified_tables))+ errors.extend(_check_select_permission(conn, qualified_tables))if management_mode == "posthog":errors.extend(_check_replication_role(conn))@@ -97,7 +110,27 @@ def _check_wal_level(conn: psycopg.Connection) -> list[str]:return []-def _check_tables_have_primary_keys(conn: psycopg.Connection, schema: str, tables: list[str]) -> list[str]:+def _resolve_table_schemas(tables: list[str], schema: str | None) -> list[_QualifiedTable]:+ """Pair each table with the schema that holds it.++ A source configured for one schema lists bare table names, so they all take that schema. A+ source that reads every schema lists them as `schema.table`, which must be split before a+ catalog lookup, because `relname` holds the table name alone.+ """+ if schema is not None:+ return [_QualifiedTable(schema=schema, table=table) for table in tables]++ resolved: list[_QualifiedTable] = []+ for table in tables:+ schema_name, separator, table_name = table.partition(".")+ if separator:+ resolved.append(_QualifiedTable(schema=schema_name, table=table_name))+ else:+ resolved.append(_QualifiedTable(schema="public", table=table))+ return resolved+++def _check_tables_have_primary_keys(conn: psycopg.Connection, tables: list[_QualifiedTable]) -> list[str]:"""Each target table must have a primary key.Uses pg_catalog rather than information_schema because information_schema views@@ -109,36 +142,41 @@ def _check_tables_have_primary_keys(conn: psycopg.Connection, schema: str, tableerrors: list[str] = []with conn.cursor() as cur:- for table in tables:+ for qualified in tables:cur.execute(sql.SQL("SELECT COUNT(*) FROM pg_index i ""JOIN pg_class c ON c.oid = i.indrelid ""JOIN pg_namespace n ON n.oid = c.relnamespace ""WHERE i.indisprimary AND n.nspname = {} AND c.relname = {}"- ).format(sql.Literal(schema), sql.Literal(table))+ ).format(sql.Literal(qualified.schema), sql.Literal(qualified.table)))row = cur.fetchone()if row is None or row[0] == 0:- errors.append(f"Table '{schema}.{table}' has no primary key. CDC requires a primary key on each table.")+ errors.append(+ f"Table '{qualified.schema}.{qualified.table}' has no primary key. "+ "CDC requires a primary key on each table."+ )return errors-def _check_select_permission(conn: psycopg.Connection, schema: str, tables: list[str]) -> list[str]:+def _check_select_permission(conn: psycopg.Connection, tables: list[_QualifiedTable]) -> list[str]:"""Check SELECT permission on target tables."""errors: list[str] = []with conn.cursor() as cur:- for table in tables:+ for qualified in tables:try:cur.execute(- sql.SQL("SELECT 1 FROM {}.{} LIMIT 0").format(sql.Identifier(schema), sql.Identifier(table))+ sql.SQL("SELECT 1 FROM {}.{} LIMIT 0").format(+ sql.Identifier(qualified.schema), sql.Identifier(qualified.table)+ ))except psycopg.errors.InsufficientPrivilege:conn.rollback()- errors.append(f"No SELECT permission on table '{schema}.{table}'.")+ errors.append(f"No SELECT permission on table '{qualified.schema}.{qualified.table}'.")except psycopg.errors.UndefinedTable:conn.rollback()- errors.append(f"Table '{schema}.{table}' does not exist.")+ errors.append(f"Table '{qualified.schema}.{qualified.table}' does not exist.")return errorsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_prerequisite_validator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_prerequisite_validator.pyindex b5822febab96..3c56739ddd50 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_prerequisite_validator.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_prerequisite_validator.py@@ -55,12 +55,15 @@ _WAL_REPLICA = ("wal_level", [("replica",)])# PK check uses pg_catalog (pg_index) — match on "indisprimary"_HAS_PK = ("indisprimary", [(1,)])_NO_PK = ("indisprimary", [(0,)])+# The primary-key lookup is also a COUNT, so the slot-capacity patterns name their own relation.+# This one matches only when the schema and the table reach pg_catalog as separate literals.+_PK_ON_ANALYTICS_EVENTS = ("Literal('analytics'), SQL(' AND c.relname = '), Literal('events')", [(1,)])# Replication role check — the OR expression returns a single boolean_HAS_REPL_ROLE = ("rolreplication", [(True,)])_NO_REPL_ROLE = ("rolreplication", [(False,)])_MAX_SLOTS_10 = ("max_replication_slots", [("10",)])-_SLOT_COUNT_2 = ("COUNT", [("2",)])-_SLOT_COUNT_10 = ("COUNT", [("10",)])+_SLOT_COUNT_2 = ("FROM pg_replication_slots", [("2",)])+_SLOT_COUNT_10 = ("FROM pg_replication_slots", [("10",)])_SLOT_EXISTS = ("slot_name", [(1,)])_SLOT_NOT_EXISTS: tuple[str, list] = ("slot_name", [])_PUB_EXISTS = ("pubname", [(1,)])@@ -113,6 +116,15 @@ class TestValidateCDCPrerequisites:errors = validate_cdc_prerequisites(conn=conn, management_mode="posthog", tables=["orders"])assert any("primary key" in e for e in errors)+ def test_qualified_table_is_checked_under_its_own_schema(self):+ # A source with no single schema configured lists its tables as `schema.table`. A relname+ # lookup for the whole string finds no primary key on a table that has one.+ conn = _mock_conn([_PG_15, _WAL_LOGICAL, _PK_ON_ANALYTICS_EVENTS, _HAS_REPL_ROLE, _MAX_SLOTS_10, _SLOT_COUNT_2])+ errors = validate_cdc_prerequisites(+ conn=conn, management_mode="posthog", tables=["analytics.events"], schema=None+ )+ assert errors == []+def test_no_replication_role(self):conn = _mock_conn([_PG_15, _WAL_LOGICAL, _HAS_PK, _NO_REPL_ROLE, _MAX_SLOTS_10, _SLOT_COUNT_2])errors = validate_cdc_prerequisites(conn=conn, management_mode="posthog", tables=["users"])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex d43f2415cd9b..0c464d02a6f2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -1492,7 +1492,9 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDateam_id=team_id,)try:- schema = config.schema.strip() if isinstance(config.schema, str) and config.schema.strip() else "public"+ # A blank schema means discovery enumerated every schema and named each table+ # `schema.table`, so the validator has to read the schema off each entry.+ schema = config.schema.strip() if isinstance(config.schema, str) and config.schema.strip() else Nonereturn validate_cdc_prerequisites(conn=conn,management_mode=management_mode, # type: ignore[arg-type]