: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): classify Redshift materialized views correctly (#84705)
jake sciottoc47f874cebf0
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 a4369590799e..feafc5c655db 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@@ -383,6 +383,33 @@ def _rollback_if_aborted(connection: psycopg.Connection) -> None:connection.rollback()+def _recover_after_failed_probe(connection: psycopg.Connection) -> None:+ """Roll back a best-effort probe's aborted transaction, swallowing a lost connection."""+ try:+ _rollback_if_aborted(connection)+ except Exception:+ pass+++def _is_materialized_view(cursor: psycopg.Cursor, schema: str, table_name: str) -> bool:+ """Is this relation a materialized view?++ Redshift exposes no `pg_matviews`, so the `pg_views` lookup that classifies a regular view+ never matches a materialized one — `svv_mv_info` is the only catalog that lists them.+ Best-effort: a role that can't read the system view degrades to the `pg_views` answer rather+ than failing discovery.+ """+ query = sql.SQL("SELECT {table} IN (SELECT name FROM svv_mv_info WHERE schema_name = {schema}) as res").format(+ schema=sql.Literal(schema), table=sql.Literal(table_name)+ )+ try:+ row = cursor.execute(query).fetchone()+ except Exception:+ _recover_after_failed_probe(cursor.connection)+ return False+ return row is not None and row[0] is True++def _libpq_rows_per_chunk() -> int:"""Rows per libpq chunk while streaming, or 1 where chunked delivery isn't available.@@ -612,6 +639,15 @@ class DisplayNameIndex:bare_tables: list[str]+@frozen+class QualifiedRelation:+ """A relation addressed by namespace and name. Both are strings, so keeping them named+ stops a `COUNT(*)` being aimed at `name.schema`."""++ schema: str+ name: str++class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycopg.Connection, Any]):# `psycopg.Cursor` does not satisfy `_CursorLike` (its `execute`# signature uses `params` instead of `args`, and accepts `Query`@@ -808,8 +844,10 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco`svv_table_info.tbl_rows` is a Redshift system table that givescheap row count estimates for materialized tables; views aren'tin it, so they fall through to a (slower) `UNION ALL` of- `COUNT(*)` queries. Errors are swallowed — schema discovery- keeps working without row counts.+ `COUNT(*)` queries. A materialized view is in neither under its+ own name — its storage is registered under an internal one — so+ `svv_mv_info` routes it onto the `COUNT(*)` path too. Errors are+ swallowed — schema discovery keeps working without row counts."""if not tables:return {}@@ -842,23 +880,24 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco"SELECT schemaname, viewname FROM pg_views WHERE schemaname = ANY(%(schemas)s) AND viewname = ANY(%(names)s)",params,)- view_pairs = [- (schema_name, view_name)+ to_count = [+ QualifiedRelation(schema=schema_name, name=view_name)for schema_name, view_name in cursor.fetchall()if (schema_name, view_name) in index.display_by_pair]+ to_count.extend(self._materialized_views(conn, cursor, index, params))- if view_pairs:+ if to_count:view_counts = [sql.SQL("SELECT {schema_lit} AS schema_name, {view_lit} AS table_name, COUNT(*) AS row_count FROM {schema}.{view}").format(- schema_lit=sql.Literal(schema_name),- view_lit=sql.Literal(view_name),- schema=sql.Identifier(schema_name),- view=sql.Identifier(view_name),+ schema_lit=sql.Literal(relation.schema),+ view_lit=sql.Literal(relation.name),+ schema=sql.Identifier(relation.schema),+ view=sql.Identifier(relation.name),)- for schema_name, view_name in view_pairs+ for relation in to_count]cursor.execute(sql.SQL(" UNION ALL ").join(view_counts))for schema_name, table_name, row_count in cursor.fetchall():@@ -870,6 +909,36 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoreturn result+ @staticmethod+ def _materialized_views(+ conn: psycopg.Connection,+ cursor: Any,+ index: DisplayNameIndex,+ params: dict,+ ) -> list[QualifiedRelation]:+ """Each requested relation that is a materialized view.++ Isolated from the caller's `except` so a role without access to `svv_mv_info` loses only+ the materialized-view counts, not every count in the batch. The rollback matters for the+ same reason: a failed probe aborts the transaction, and the `COUNT(*)` batch that follows+ runs on the same connection.+ """+ try:+ cursor.execute(+ "SELECT schema_name, name FROM svv_mv_info WHERE schema_name = ANY(%(schemas)s) AND name = ANY(%(names)s)",+ params,+ )+ rows = cursor.fetchall()+ except Exception:+ _recover_after_failed_probe(conn)+ return []++ return [+ QualifiedRelation(schema=schema_name, name=view_name)+ for schema_name, view_name in rows+ if (schema_name, view_name) in index.display_by_pair+ ]+def get_leading_index_columns(self,conn: psycopg.Connection,@@ -980,8 +1049,14 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoschema: str,table_name: str,logger: 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, 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.+ """query = sql.SQL("""SELECTkcu.column_name@@ -1007,9 +1082,16 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoreturn [row[0] for row in rows]if logger is not None:- logger.warning(- f"No primary keys found for {table_name}. If the table is not a view, (a) does the table have a primary key set? (b) is the primary key returned from querying information_schema?"- )+ 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."+ )return Nonedef has_duplicate_primary_keys(@@ -1073,12 +1155,14 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycologger: FilteringBoundLogger | None = None,) -> Table[RedshiftColumn]:"""Return rich column metadata for building a PyArrow schema."""- # Check if it's a view- is_view_query = sql.SQL(- "SELECT {table} IN (SELECT viewname FROM pg_views WHERE schemaname = {schema}) as res"- ).format(schema=sql.Literal(schema), table=sql.Literal(table_name))- is_view_res = cursor.execute(is_view_query).fetchone()- is_view = is_view_res is not None and is_view_res[0] is True+ is_mat_view = _is_materialized_view(cursor, schema, table_name)+ is_view = False+ if not is_mat_view:+ is_view_query = sql.SQL(+ "SELECT {table} IN (SELECT viewname FROM pg_views WHERE schemaname = {schema}) as res"+ ).format(schema=sql.Literal(schema), table=sql.Literal(table_name))+ is_view_res = cursor.execute(is_view_query).fetchone()+ is_view = is_view_res is not None and is_view_res[0] is Truequery = sql.SQL("""SELECT@@ -1123,7 +1207,11 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco))- table_type: Literal["view", "table"] = "view" if is_view else "table"+ table_type: Literal["table", "view", "materialized_view"] = "table"+ if is_mat_view:+ table_type = "materialized_view"+ elif is_view:+ table_type = "view"return Table(name=table_name, parents=(schema,), columns=columns, type=table_type)def get_rows_to_sync(@@ -1305,7 +1393,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco)try:logger.debug("Getting primary keys...")- primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name, logger)+ primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name, logger, full_table.type)if primary_keys:logger.debug(f"Found primary keys: {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 d7bc46f210ec..0edea274f50c 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@@ -330,6 +330,35 @@ class TestGetPrimaryKeysForTable:cursor.fetchall.return_value = [("id",), ("email",)]assert impl.get_primary_keys_for_table(cursor, "public", "t") == ["id", "email"]+ @pytest.mark.parametrize(+ "table_type,expected_phrase",+ [+ ("view", "A view cannot have a primary key"),+ ("materialized_view", "A materialized view cannot have a primary key"),+ ],+ )+ def test_warns_that_a_relation_without_a_key_cannot_have_one(+ self, impl, cursor, logger, table_type, expected_phrase+ ):+ # Neither relation can declare a PRIMARY KEY in Redshift, so the empty result is final —+ # the message has to name the remedies rather than send the operator looking for a key.+ cursor.fetchall.return_value = []++ impl.get_primary_keys_for_table(cursor, "public", "t", logger, table_type)++ warning = logger.warning.call_args.args[0]+ assert expected_phrase in warning+ assert "full table replication" in warning++ def test_warns_about_a_missing_key_on_a_table(self, impl, cursor, logger):+ cursor.fetchall.return_value = []++ impl.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+class TestGetTableMetadata:def test_builds_table_with_columns(self, impl, cursor):@@ -350,9 +379,31 @@ class TestGetTableMetadata:def test_marks_view_when_is_view_true(self, impl, cursor):cursor.execute.return_value = cursor+ # svv_mv_info probe first, then pg_views.+ cursor.fetchone.side_effect = [(False,), (True,)]+ cursor.__iter__.return_value = iter([("id", "integer", "NO", None, None)])+ table = impl.get_table_metadata(cursor, "public", "myview")+ assert table.type == "view"++ def test_marks_materialized_view_when_svv_mv_info_matches(self, impl, cursor):+ # Redshift has no `pg_matviews`, so the `pg_views` lookup alone reported every+ # materialized view as a plain table.+ cursor.execute.return_value = cursor+ cursor.fetchone.side_effect = [(True,)]+ cursor.__iter__.return_value = iter([("id", "integer", "NO", None, None)])++ table = impl.get_table_metadata(cursor, "public", "daily_totals")++ assert table.type == "materialized_view"++ def test_falls_back_to_the_view_check_when_the_mv_probe_fails(self, impl, cursor):+ # A role without access to `svv_mv_info` must still get a classified relation.+ cursor.execute.side_effect = [Exception("permission denied for relation svv_mv_info"), cursor, cursor]cursor.fetchone.return_value = (True,)cursor.__iter__.return_value = iter([("id", "integer", "NO", None, None)])+table = impl.get_table_metadata(cursor, "public", "myview")+assert table.type == "view"def test_populates_numeric_precision_and_scale_for_decimals(self, impl, cursor):@@ -971,10 +1022,11 @@ class TestGetRowCounts:conn = MagicMock()cur = MagicMock()cur.__enter__.return_value = cur- # 1: SET statement_timeout, 2: svv_table_info, 3: pg_views, 4: UNION ALL view counts.+ # 1: SET statement_timeout, 2: svv_table_info, 3: pg_views, 4: svv_mv_info, 5: UNION ALL counts.cur.fetchall.side_effect = [[("analytics", "events", 500)], # svv_table_info (materialized tables)[("public", "events")], # pg_views (views aren't in svv_table_info)+ [], # svv_mv_info[("public", "events", 42)], # COUNT(*) per view]conn.cursor.return_value = cur@@ -984,6 +1036,37 @@ class TestGetRowCounts:# Same table name in two namespaces stays distinct; the view falls through to COUNT(*).assert result == {"analytics.events": 500, "public.events": 42}+ def test_materialized_view_falls_through_to_count_query(self, impl):+ # A materialized view is in neither `svv_table_info` (registered under an internal name)+ # nor `pg_views`, so without the `svv_mv_info` probe it got no row count at all.+ conn = MagicMock()+ cur = MagicMock()+ cur.__enter__.return_value = cur+ cur.fetchall.side_effect = [+ [], # svv_table_info+ [], # pg_views+ [("public", "daily_totals")], # svv_mv_info+ [("public", "daily_totals", 7)], # COUNT(*)+ ]+ conn.cursor.return_value = cur++ assert impl.get_row_counts(conn, _make_config(), ["daily_totals"]) == {"daily_totals": 7}++ def test_failed_materialized_view_probe_keeps_the_other_counts(self, impl):+ # The probe is isolated so a role without access to `svv_mv_info` loses only the+ # materialized-view counts, not every count in the batch.+ conn = MagicMock()+ cur = MagicMock()+ cur.__enter__.return_value = cur+ cur.execute.side_effect = [None, None, None, Exception("permission denied for relation svv_mv_info")]+ cur.fetchall.side_effect = [+ [("public", "users", 500)], # svv_table_info+ [], # pg_views+ ]+ conn.cursor.return_value = cur++ assert impl.get_row_counts(conn, _make_config(), ["users"]) == {"users": 500}+def test_returns_empty_on_exception(self, impl):conn = MagicMock()cur = MagicMock()