: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): stop Redshift claiming a table has no primary key (#84740)
jake sciottoca3623748460
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.pyindex feafc5c655db..d8f480305277 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py@@ -391,6 +391,59 @@ def _recover_after_failed_probe(connection: psycopg.Connection) -> None:pass+def _reads_primary_keys(cursor: psycopg.Cursor, schema: str) -> bool | None:+ """Can this connection read primary-key constraints in `schema` at all?++ `information_schema.table_constraints` exposes only the objects the role holds privileges on,+ so an empty result for one table means either "no key is declared" or "no privilege to see the+ one that is", and the two need opposite advice. Finding a key on any table in the schema+ settles it: the role can read the view, so an empty per-table result is a real absence.++ `None` when the probe itself fails, which settles nothing either way.+ """+ query = sql.SQL("""+ SELECT 1+ FROM information_schema.table_constraints+ WHERE table_schema = {schema} AND constraint_type = 'PRIMARY KEY'+ LIMIT 1""").format(schema=sql.Literal(schema))+ try:+ return cursor.execute(query).fetchone() is not None+ except Exception:+ _recover_after_failed_probe(cursor.connection)+ return None+++def _no_primary_key_warning(+ cursor: psycopg.Cursor,+ schema: str,+ table_name: str,+ table_type: Literal["table", "view", "materialized_view"] | None,+) -> str:+ """The warning for a table whose primary-key lookup came back empty.++ Each branch states only what the empty result actually establishes, so the operator is never+ sent after a key that cannot exist or that we merely failed to read.+ """+ if table_type in ("view", "materialized_view"):+ relation = "materialized view" if table_type == "materialized_view" else "view"+ return (+ f"No primary keys found for {table_name}. A {relation} cannot have a primary key. "+ "Select a primary key manually to enable incremental sync, or use full table replication instead."+ )++ if _reads_primary_keys(cursor, schema):+ return (+ f"No primary key is set on {table_name}. Select one manually to enable incremental sync, "+ "or use full table replication instead."+ )++ return (+ f"Could not determine a primary key for {table_name}. Either none is set, or PostHog's role "+ f"cannot read constraints in schema {schema}. Check the role has SELECT on the table. You can "+ "also select a primary key manually, or use full table replication instead."+ )++def _is_materialized_view(cursor: psycopg.Cursor, schema: str, table_name: str) -> bool:"""Is this relation a materialized view?@@ -767,11 +820,17 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoconfig: RedshiftSourceConfig,tables: list[str],) -> dict[str, list[str] | None]:- """Detect primary keys for all tables in a single query.+ """Detect primary keys for all tables in a single query, each in declared column order.Permission-sensitive — some Redshift deployments restrict accessto `information_schema.table_constraints`. Swallow and log anyfailure so schema discovery keeps working without PKs.++ A swallowed failure returns every table as `None`, which the base+ contract cannot distinguish from "declares no key". The sync path+ re-runs the lookup per table and says which it is+ (`_no_primary_key_warning`); surfacing the difference at discovery+ needs a channel on `SourceSchema` that does not exist yet."""result: dict[str, list[str] | None] = dict.fromkeys(tables)if not tables:@@ -793,11 +852,15 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoWHERE tc.table_schema = ANY({schemas})AND tc.table_name = ANY({names})AND tc.constraint_type = 'PRIMARY KEY'+ ORDER BY tc.table_schema, tc.table_name, kcu.ordinal_position""").format(schemas=sql.Literal(index.schemas), names=sql.Literal(index.bare_tables)))rows = cursor.fetchall()except Exception as e:- structlog.get_logger().warning("Failed to detect primary keys for Redshift schemas", exc_info=e)+ structlog.get_logger().warning(+ "Primary keys for Redshift schemas are undetermined, not absent: the detection query failed",+ exc_info=e,+ )return resultpks: dict[str, list[str]] = collections.defaultdict(list)@@ -1051,11 +1114,10 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycologger: FilteringBoundLogger | None = None,table_type: Literal["table", "view", "materialized_view"] | None = None,) -> list[str] | None:- """Return the primary-key column names for a single table, or None.+ """Return the primary-key column names for a single table in declared order, or None.- `table_type` only shapes the warning on an empty result: on a view or materialized view a- primary key cannot exist, so the message names the remedies instead of asking the operator- to go looking for a key.+ `table_type` only shapes the warning on an empty result, which is ambiguous on its own:+ see `_no_primary_key_warning` for what each case establishes."""query = sql.SQL("""SELECT@@ -1069,9 +1131,9 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoWHEREtc.table_schema = {schema}AND tc.table_name = {table}- AND tc.constraint_type = 'PRIMARY KEY'""").format(- schema=sql.Literal(schema), table=sql.Literal(table_name)- )+ AND tc.constraint_type = 'PRIMARY KEY'+ ORDER BY+ kcu.ordinal_position""").format(schema=sql.Literal(schema), table=sql.Literal(table_name))if logger is not None:_explain_query(cursor, query, logger)@@ -1082,16 +1144,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoreturn [row[0] for row in rows]if logger is not None:- if table_type in ("view", "materialized_view"):- relation = "materialized view" if table_type == "materialized_view" else "view"- logger.warning(- f"No primary keys found for {table_name}. A {relation} cannot have a primary key. "- "Select a primary key manually to enable incremental sync, or use full table replication instead."- )- else:- logger.warning(- f"No primary keys found for {table_name}. Check that the table has a primary key set, and that querying information_schema returns it."- )+ logger.warning(_no_primary_key_warning(cursor, schema, table_name, table_type))return Nonedef has_duplicate_primary_keys(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.pyindex 0edea274f50c..99590e0f7004 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py@@ -350,14 +350,51 @@ class TestGetPrimaryKeysForTable:assert expected_phrase in warningassert "full table replication" in warning- def test_warns_about_a_missing_key_on_a_table(self, impl, cursor, logger):+ def test_warns_that_a_table_declares_no_key_when_the_role_can_read_constraints(self, impl, cursor, logger):+ # A key found elsewhere in the schema proves the role can read `table_constraints`, so this+ # table's empty result is a real absence and the message can say so outright.cursor.fetchall.return_value = []+ cursor.execute.return_value = cursor+ cursor.fetchone.return_value = (1,)++ impl.get_primary_keys_for_table(cursor, "public", "t", logger, "table")++ assert "No primary key is set on t" in logger.warning.call_args.args[0]++ @pytest.mark.parametrize("probe_outcome", ["sees_nothing", "probe_fails"])+ def test_does_not_claim_a_table_is_keyless_when_detection_is_undetermined(+ self, impl, cursor, logger, probe_outcome+ ):+ # The reported bug: an unreadable key and an absent key both produce zero rows, and the+ # message asserted the second. Asserting absence here sends the operator to set keys by+ # hand for a condition they may not have.+ cursor.fetchall.return_value = []+ cursor.execute.return_value = cursor+ cursor.fetchone.return_value = None+ if probe_outcome == "probe_fails":+ # Only the privilege probe is a LIMIT 1, so this fails it without counting calls.+ def fail_the_probe(query, *args):+ if "LIMIT 1" in query.as_string():+ raise Exception("permission denied")+ return cursor++ cursor.execute.side_effect = fail_the_probeimpl.get_primary_keys_for_table(cursor, "public", "t", logger, "table")warning = logger.warning.call_args.args[0]- assert "information_schema" in warning- assert "cannot have a primary key" not in warning+ assert "Could not determine a primary key" in warning+ assert "No primary key is set" not in warning++ def test_orders_composite_key_columns_by_declared_position(self, impl, cursor):+ # Without ORDER BY, Redshift returns the constraint's columns in arbitrary order and a+ # composite key is assembled wrong, which silently corrupts incremental merge matching.+ cursor.fetchall.return_value = [("a",), ("b",)]++ impl.get_primary_keys_for_table(cursor, "public", "t")++ assert "ORDER BY" in cursor.execute.call_args.args[0].as_string()+ assert "kcu.ordinal_position" in cursor.execute.call_args.args[0].as_string()class TestGetTableMetadata: