Skip to content

: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.

fix(warehouse-sources): explain table ownership failures in CDC setup (#103902)

posthog[bot]2dc123e54521
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py
index b0cda945378a..083e359ddca4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py
@@ -83,6 +83,13 @@ class CDCSourceAdapter(Protocol[CDCConfigT_co]):
customer/upstream connection failures as error-tracking noise."""
...
+ def customer_fixable_error_message(self, exc: BaseException) -> str | None:
+ """A user-facing explanation when the exception reports something the customer can fix on
+ their own database (PG: ownership of a published table, a missing replication grant, a
+ connection that points at a read replica), or None for anything else. Callers surface the
+ message as a 400 without capturing it, because the fix is not a code change."""
+ ...
+
def classify_error(self, exc: BaseException) -> CDCErrorInfo | None:
"""Interpret a single engine-specific exception as a CDC error category, or None
when unrecognized (the caller falls back to the engine-agnostic default). Mirrors
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
index c254fec30915..0de055c7094b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
@@ -134,9 +134,19 @@ def _repair_locked(source: ExternalDataSource) -> int:
purge_buffer_prefix(source.team_id, str(schema_id), log, strict=True)
default_schema = (source.job_inputs or {}).get("schema")
- resource_fields = adapter.recreate_slot(
- source, tables=[cdc_qualified_table_name(schema, default_schema) for schema in cdc_schemas]
- )
+ try:
+ resource_fields = adapter.recreate_slot(
+ source, tables=[cdc_qualified_table_name(schema, default_schema) for schema in cdc_schemas]
+ )
+ except Exception as e:
+ # A missing grant on the source database is the customer's to fix, so it must reach them as
+ # advice instead of a raw engine error captured into error tracking. The schemas are already
+ # back in snapshot mode and the broken markers still stand, so a repair re-run after the fix
+ # lands picks up from here.
+ customer_message = adapter.customer_fixable_error_message(e)
+ if customer_message is None:
+ raise
+ raise CDCRepairError(customer_message) from e
source.job_inputs = {**(source.job_inputs or {}), **resource_fields}
source.status = ExternalDataSource.Status.RUNNING
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
index 29854026f614..9d0814749921 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
@@ -48,14 +48,27 @@ logger = logging.getLogger(__name__)
_retry_logger = structlog.get_logger(__name__)
-def _slot_setup_error_message(exc: Exception) -> str:
- """User-facing message for a failed slot/publication setup.
+def _customer_fixable_setup_message(exc: BaseException) -> str | None:
+ """User-facing advice when a slot/publication setup failure is one the customer can fix on
+ their own database, or None for anything else.
When the failure is a lack of replication privilege — the most common CDC blocker —
point at the simplest fix rather than only echoing the raw error: switch the affected
tables to Incremental sync, which needs only SELECT.
"""
message = str(exc).lower()
+ # PostgreSQL rejects CREATE PUBLICATION FOR TABLE and ALTER PUBLICATION ADD TABLE with this
+ # wording when the connecting role does not own the table. A role with REPLICATION and SELECT
+ # but no ownership reaches that point, so it needs its own guidance: the replication grant the
+ # permission branch below asks for does not fix it.
+ if "must be owner of" in message:
+ return (
+ f"Could not publish the tables CDC syncs: {exc} "
+ "PostgreSQL only lets a table's owner publish it. Make the database user the owner of "
+ "these tables, or add it to the role that owns them. If you can't change ownership, "
+ "switch these tables to Incremental sync instead of CDC. Incremental needs only SELECT "
+ "permission."
+ )
is_permission_error = isinstance(exc, psycopg.errors.InsufficientPrivilege) or (
"permission denied" in message or "must be superuser" in message
)
@@ -75,7 +88,12 @@ def _slot_setup_error_message(exc: Exception) -> str:
"Connect to the primary database, or switch these tables to Incremental sync, which "
"needs only SELECT."
)
- return f"Failed to create replication slot: {exc}"
+ return None
+
+
+def _slot_setup_error_message(exc: Exception) -> str:
+ """User-facing message for a failed slot/publication setup."""
+ return _customer_fixable_setup_message(exc) or f"Failed to create replication slot: {exc}"
def _split_qualified_table(qualified: str, default_schema: str) -> tuple[str, str]:
@@ -169,6 +187,9 @@ class PostgresCDCAdapter:
# None points at a bug in our code.
return isinstance(exc, psycopg.OperationalError | BaseSSHTunnelForwarderError | HostNotAllowedError)
+ def customer_fixable_error_message(self, exc: BaseException) -> str | None:
+ return _customer_fixable_setup_message(exc)
+
def classify_error(self, exc: BaseException) -> CDCErrorInfo | None:
category = classify_postgres_cdc_error(exc)
return cdc_error_info(category) if category is not None else None
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.py
index 64659f208f06..ce385f4dda24 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
@@ -55,6 +55,7 @@ def validate_cdc_prerequisites(
if management_mode == "posthog":
errors.extend(_check_replication_role(conn))
errors.extend(_check_replication_slot_capacity(conn))
+ errors.extend(_check_table_ownership(conn, qualified_tables))
elif management_mode == "self_managed":
# Self-managed: the DBA creates the publication out-of-band, PostHog creates
# and owns the slot at source-creation time. So we only verify the publication
@@ -180,6 +181,48 @@ def _check_select_permission(conn: psycopg.Connection, tables: list[_QualifiedTa
return errors
+def _check_table_ownership(conn: psycopg.Connection, tables: list[_QualifiedTable]) -> list[str]:
+ """Each target table must be owned by the connecting role (PostHog-managed mode).
+
+ PostHog builds the publication itself, and PostgreSQL only lets a table's owner put it
+ in one. A role with REPLICATION and SELECT but no ownership passes every other check
+ here and then fails at CREATE PUBLICATION / ALTER PUBLICATION ADD TABLE with
+ "must be owner of table". Membership in the owning role counts as ownership, which is
+ what pg_has_role reports.
+
+ A table with no pg_class row is skipped, because the primary-key and SELECT checks
+ already report it as missing.
+ """
+ if not tables:
+ return []
+
+ errors: list[str] = []
+ with conn.cursor() as cur:
+ for qualified in tables:
+ cur.execute(
+ sql.SQL(
+ "SELECT pg_has_role(current_user, c.relowner, 'USAGE') FROM pg_class c "
+ "JOIN pg_namespace n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = {} AND c.relname = {}"
+ ).format(sql.Literal(qualified.schema), sql.Literal(qualified.table))
+ )
+ row = cur.fetchone()
+ if row is not None and row[0] is False:
+ # The user pastes this command, so the identifiers must survive PostgreSQL's
+ # folding of unquoted names to lower case. A table named "Orders" is addressed by
+ # ALTER TABLE public.Orders as `orders`, which does not exist.
+ quoted_name = sql.Identifier(qualified.schema, qualified.table).as_string(None)
+ errors.append(
+ f"The database user does not own table '{qualified.schema}.{qualified.table}'. "
+ "PostgreSQL only lets a table's owner publish it, and CDC publishes every table it syncs. "
+ f"Grant ownership with ALTER TABLE {quoted_name} OWNER TO <username>, "
+ "or add the user to the role that owns the table with GRANT <owner_role> TO <username>. "
+ "If you can't change ownership, switch this table to Incremental sync instead of CDC. "
+ "Incremental needs only SELECT permission."
+ )
+ return errors
+
+
def _check_replication_role(conn: psycopg.Connection) -> list[str]:
"""Check if current user can create logical replication slots (PostHog-managed mode).
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py
index 45976666fbdd..1eddae9f54c2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py
@@ -187,6 +187,15 @@ class TestSlotSetupErrorMessage:
error = _slot_setup_error_message(Exception("ERROR: must be superuser or replication role"))
assert "Incremental sync" in error
+ def test_table_ownership_error_points_at_ownership_not_replication(self) -> None:
+ # A role with REPLICATION and SELECT but no ownership gets this from CREATE PUBLICATION.
+ # The generic permission message asks for replication access, which does not fix it.
+ error = _slot_setup_error_message(psycopg.errors.InsufficientPrivilege("must be owner of table orders"))
+ assert "must be owner of table orders" in error
+ assert "owner" in error
+ assert "replication" not in error.lower()
+ assert "Incremental sync" in error
+
def test_read_only_transaction_error_points_at_primary(self) -> None:
error = _slot_setup_error_message(Exception("cannot execute CREATE PUBLICATION in a read-only transaction"))
assert "primary database" in error
diff --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.py
index 3c56739ddd50..9b32a25d3e27 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
@@ -1,3 +1,4 @@
+import pytest
from unittest.mock import MagicMock
import psycopg
@@ -64,6 +65,8 @@ _NO_REPL_ROLE = ("rolreplication", [(False,)])
_MAX_SLOTS_10 = ("max_replication_slots", [("10",)])
_SLOT_COUNT_2 = ("FROM pg_replication_slots", [("2",)])
_SLOT_COUNT_10 = ("FROM pg_replication_slots", [("10",)])
+_OWNS_TABLES = ("pg_has_role", [(True,)])
+_DOES_NOT_OWN_TABLES = ("pg_has_role", [(False,)])
_SLOT_EXISTS = ("slot_name", [(1,)])
_SLOT_NOT_EXISTS: tuple[str, list] = ("slot_name", [])
_PUB_EXISTS = ("pubname", [(1,)])
@@ -130,6 +133,49 @@ class TestValidateCDCPrerequisites:
errors = validate_cdc_prerequisites(conn=conn, management_mode="posthog", tables=["users"])
assert any("replication slots" in e.lower() for e in errors)
+ # A role with REPLICATION and SELECT but no ownership passes every other check and then fails
+ # at CREATE PUBLICATION with "must be owner of table" during enable or repair. The user pastes
+ # the ALTER TABLE the message names, so a mixed-case name has to stay quoted in it.
+ @pytest.mark.parametrize(
+ "table,expected_command",
+ [
+ ("users", 'ALTER TABLE "public"."users" OWNER TO'),
+ ("Orders", 'ALTER TABLE "public"."Orders" OWNER TO'),
+ ],
+ )
+ def test_table_not_owned_by_database_user(self, table, expected_command):
+ conn = _mock_conn(
+ [_PG_15, _WAL_LOGICAL, _HAS_PK, _HAS_REPL_ROLE, _MAX_SLOTS_10, _SLOT_COUNT_2, _DOES_NOT_OWN_TABLES]
+ )
+ errors = validate_cdc_prerequisites(conn=conn, management_mode="posthog", tables=[table])
+ assert any(f"does not own table 'public.{table}'" in e for e in errors)
+ assert any(expected_command in e for e in errors)
+
+ def test_owned_table_passes_ownership_check(self):
+ conn = _mock_conn([_PG_15, _WAL_LOGICAL, _HAS_PK, _HAS_REPL_ROLE, _MAX_SLOTS_10, _SLOT_COUNT_2, _OWNS_TABLES])
+ errors = validate_cdc_prerequisites(conn=conn, management_mode="posthog", tables=["users"])
+ assert errors == []
+
+ def test_self_managed_skips_ownership_check(self):
+ # The DBA owns the publication in self-managed mode, so PostHog never publishes the table
+ # and ownership is not required.
+ conn = _mock_conn(
+ [
+ _PG_15,
+ _WAL_LOGICAL,
+ _HAS_PK,
+ _HAS_REPL_ROLE,
+ _MAX_SLOTS_10,
+ _SLOT_COUNT_2,
+ _DOES_NOT_OWN_TABLES,
+ _PUB_EXISTS,
+ ]
+ )
+ errors = validate_cdc_prerequisites(
+ conn=conn, management_mode="self_managed", tables=["users"], publication_name="my_pub"
+ )
+ assert errors == []
+
def test_no_replication_slot_capacity(self):
conn = _mock_conn([_PG_15, _WAL_LOGICAL, _HAS_PK, _HAS_REPL_ROLE, _MAX_SLOTS_10, _SLOT_COUNT_10])
errors = validate_cdc_prerequisites(conn=conn, management_mode="posthog", tables=["users"])
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 46345e0414bd..0eeb3716e7e2 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -11695,6 +11695,30 @@ class TestRepairCDC(APIBaseTest):
mock_trigger.assert_not_called()
mock_unpause_extraction.assert_not_called()
+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.recreate_slot",
+ side_effect=psycopg.errors.InsufficientPrivilege("must be owner of table orders"),
+ )
+ def test_repair_cdc_table_ownership_failure_is_not_captured(self, _mock_recreate, mock_capture) -> None:
+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)
+ ExternalDataSchema.objects.create(
+ name="orders",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ sync_type_config={"cdc_mode": "streaming", "cdc_broken": BROKEN_MARKER},
+ )
+
+ response = self._repair(source)
+ assert response.status_code == 400
+ message = response.json()["message"]
+ assert "must be owner of table orders" in message
+ assert "Incremental sync" in message
+ # A missing grant on the customer's database is not a PostHog exception.
+ mock_capture.assert_not_called()
+
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.recreate_slot"
)