: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(sources): postgres multi-schema doesn't toggle should_sync on discovery (#60662)
Jovan Sakovic43e3cbf4539d
diff --git a/products/data_warehouse/backend/management/commands/repair_qualified_schema_duplicates.py b/products/data_warehouse/backend/management/commands/repair_qualified_schema_duplicates.pynew file mode 100644index 000000000000..eb0d05ce5d84--- /dev/null+++ b/products/data_warehouse/backend/management/commands/repair_qualified_schema_duplicates.py@@ -0,0 +1,148 @@+"""Repair schemas mis-disabled (and duplicated) by the qualified/bare name mismatch.++Schema discovery once compared stored vs discovered names by raw equality, so a table named+under a different qualification than its stored row (`public.users` vs bare `users`) was read as+removed — disabling the live row and inserting an other-qualification duplicate. The discovery+fix stops this going forward; this command repairs rows already mangled.++Only acts on the unambiguous fingerprint: a source with two same-table rows (one qualified, one+bare) where exactly one carries the live table (``table_id``) and the other is a clean phantom+(no ``table_id``, never synced, disabled). It re-enables the live row via ``update_should_sync``+(reconciling the Temporal schedule) and soft-deletes the phantom. Anything ambiguous (two live+rows, a synced twin, a lone disabled row) is reported and left untouched. Idempotent.++Usage:+ # Dry-run (default) — reports what it would do, changes nothing+ python manage.py repair_qualified_schema_duplicates++ # Live run+ python manage.py repair_qualified_schema_duplicates --live-run++ # Restrict to one source / team (defaults to source-type Postgres)+ python manage.py repair_qualified_schema_duplicates --live-run --source-id <uuid>+ python manage.py repair_qualified_schema_duplicates --live-run --team-id 2+"""++from __future__ import annotations++from collections import defaultdict+from typing import Any++from django.core.management.base import BaseCommand++import structlog++from products.data_warehouse.backend.types import ExternalDataSourceType+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, update_should_sync+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++logger = structlog.get_logger(__name__)+++def _is_qualified(name: str) -> bool:+ return "." in name+++def _unqualified(name: str) -> str:+ return name.rpartition(".")[2]+++class Command(BaseCommand):+ help = "Re-enable live schemas wrongly disabled by the qualified/bare name mismatch and soft-delete phantom duplicates."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument(+ "--live-run",+ action="store_true",+ help="Apply changes (default is dry-run).",+ )+ parser.add_argument(+ "--source-type",+ type=str,+ default=ExternalDataSourceType.POSTGRES,+ help="Source type to repair (default: Postgres — the only type affected by this bug).",+ )+ parser.add_argument(+ "--source-id",+ type=str,+ default=None,+ help="Restrict to a single ExternalDataSource id.",+ )+ parser.add_argument(+ "--team-id",+ type=int,+ default=None,+ help="Restrict to sources belonging to this team.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ live_run: bool = options["live_run"]+ source_type_filter: str = options["source_type"]+ source_id_filter: str | None = options["source_id"]+ team_id_filter: int | None = options["team_id"]++ sources = ExternalDataSource.objects.exclude(deleted=True).filter(source_type=source_type_filter)+ if source_id_filter is not None:+ sources = sources.filter(id=source_id_filter)+ if team_id_filter is not None:+ sources = sources.filter(team_id=team_id_filter)++ reenabled = 0+ soft_deleted = 0+ skipped_ambiguous = 0++ for source in sources.iterator(chunk_size=200):+ schemas = list(ExternalDataSchema.objects.filter(source_id=source.id).exclude(deleted=True))++ by_table: dict[str, list[ExternalDataSchema]] = defaultdict(list)+ for schema in schemas:+ by_table[_unqualified(schema.name)].append(schema)++ for unqualified, group in by_table.items():+ if len(group) < 2:+ continue++ live = [s for s in group if s.table_id is not None]+ phantoms = [s for s in group if s.table_id is None and s.last_synced_at is None and not s.should_sync]++ # One live row + a phantom of the other qualification is the bug fingerprint.+ # Two live rows = legit multi-schema; anything else is ambiguous — leave it.+ if len(live) != 1 or not phantoms:+ if len(live) != 1:+ skipped_ambiguous += 1+ logger.info(+ "Skipping ambiguous schema group",+ source_id=str(source.id),+ team_id=source.team_id,+ table=unqualified,+ names=[s.name for s in group],+ )+ continue++ live_schema = live[0]+ twins = [p for p in phantoms if _is_qualified(p.name) != _is_qualified(live_schema.name)]+ if not twins:+ continue++ if not live_schema.should_sync:+ self.stdout.write(+ f"{'[live] ' if live_run else '[dry-run] '}re-enable {live_schema.name!r} "+ f"(source={source.id}, team={source.team_id})"+ )+ if live_run:+ update_should_sync(schema_id=str(live_schema.id), team_id=source.team_id, should_sync=True)+ reenabled += 1++ for twin in twins:+ self.stdout.write(+ f"{'[live] ' if live_run else '[dry-run] '}soft-delete phantom {twin.name!r} "+ f"(source={source.id}, team={source.team_id})"+ )+ if live_run:+ twin.soft_delete()+ soft_deleted += 1++ self.stdout.write(+ f"Done (live_run={live_run}). reenabled={reenabled} "+ f"soft_deleted={soft_deleted} skipped_ambiguous={skipped_ambiguous}"+ )diff --git a/products/data_warehouse/backend/sync_status.py b/products/data_warehouse/backend/sync_status.pyindex 71c4ac52b3eb..31896a98d881 100644--- a/products/data_warehouse/backend/sync_status.py+++ b/products/data_warehouse/backend/sync_status.py@@ -28,6 +28,14 @@ def _ensure_utc(dt: datetime) -> datetime:return dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC)+def _is_stale(schema: ExternalDataSchema, now: datetime) -> bool:+ """Stale once the last sync is older than 2x the cadence; unknown cadence or never-synced is not stale."""+ interval = schema.sync_frequency_interval+ if interval is None or schema.last_synced_at is None:+ return False+ return (now - _ensure_utc(schema.last_synced_at)) > interval * STALE_RUNNING_MULTIPLIER++def _active_external_data_schemas(warehouse_table: DataWarehouseTable) -> list[ExternalDataSchema]:preloaded = cast(list[ExternalDataSchema] | None,@@ -90,28 +98,42 @@ def _build_warning_for_schema()if schema_status == ExternalDataSchema.Status.PAUSED or not schema.should_sync:- return build(- status=ExternalDataSchema.Status.PAUSED,- message=f"Sync of `{table_name}` (from {source_type}) is paused. Results reflect the last successful sync.",- )-+ if schema.last_synced_at is None:+ message = (+ f"Sync of `{table_name}` (from {source_type}) is paused and hasn't completed a sync yet "+ "— the table may be empty or incomplete."+ )+ else:+ ago = humanize.naturaltime(now - _ensure_utc(schema.last_synced_at))+ if _is_stale(schema, now):+ message = (+ f"Sync of `{table_name}` (from {source_type}) is paused. "+ f"Results reflect the last successful sync from {ago}."+ )+ else:+ message = (+ f"Sync of `{table_name}` (from {source_type}) is paused — results are current as of "+ f"{ago}, but won't update until syncing is re-enabled."+ )+ return build(status=ExternalDataSchema.Status.PAUSED, message=message)++ # Enabled and healthy: warn only once data is actually stale (covers RUNNING and idle COMPLETED).+ last_synced = schema.last_synced_at+ if last_synced is None or not _is_stale(schema, now):+ return None++ ago = humanize.naturaltime(now - _ensure_utc(last_synced))if schema_status == ExternalDataSchema.Status.RUNNING:- interval = schema.sync_frequency_interval- if interval is None or schema.last_synced_at is None:- return None- last_synced = _ensure_utc(schema.last_synced_at)- if (now - last_synced) <= interval * STALE_RUNNING_MULTIPLIER:- return None- return build(- status=ExternalDataSchema.Status.RUNNING,- message=(- f"`{table_name}` (from {source_type}) last completed syncing "- f"{humanize.naturaltime(now - last_synced)}, more than twice its configured sync interval. "- "A new sync is in progress but results may be out of date."- ),+ message = (+ f"`{table_name}` (from {source_type}) last completed syncing {ago}, more than twice its "+ "configured sync interval. A new sync is in progress but results may be out of date.")-- return None+ else:+ message = (+ f"`{table_name}` (from {source_type}) last synced {ago}, more than twice its configured "+ "sync interval. Results may be out of date."+ )+ return build(status=schema_status or ExternalDataSchema.Status.RUNNING, message=message)def get_warehouse_sync_warnings(diff --git a/products/data_warehouse/backend/test/test_repair_qualified_schema_duplicates.py b/products/data_warehouse/backend/test/test_repair_qualified_schema_duplicates.pynew file mode 100644index 000000000000..dbfc0b556c09--- /dev/null+++ b/products/data_warehouse/backend/test/test_repair_qualified_schema_duplicates.py@@ -0,0 +1,147 @@+from datetime import UTC, datetime+from io import StringIO++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command++from products.data_warehouse.backend.types import ExternalDataSourceType+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.table import DataWarehouseTable++_TEMPORAL = "products.warehouse_sources.backend.models.external_data_schema"+++class TestRepairQualifiedSchemaDuplicates(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="source_id",+ connection_id="connection_id",+ source_type=ExternalDataSourceType.POSTGRES,+ )++ def _table(self, name: str) -> DataWarehouseTable:+ return DataWarehouseTable.objects.create(+ name=name,+ format=DataWarehouseTable.TableFormat.Parquet,+ team=self.team,+ external_data_source=self.source,+ url_pattern="https://bucket/team_1/*",+ columns={"id": "String"},+ )++ def _schema(+ self, name: str, *, should_sync: bool, table: DataWarehouseTable | None, last_synced_at=None, source=None+ ):+ return ExternalDataSchema.objects.create(+ name=name,+ team=self.team,+ source=source or self.source,+ should_sync=should_sync,+ table=table,+ last_synced_at=last_synced_at,+ )++ def _run(self, *args: str) -> str:+ out = StringIO()+ # update_should_sync touches Temporal when re-enabling; stub those calls.+ with (+ patch(f"{_TEMPORAL}.external_data_workflow_exists", return_value=True),+ patch(f"{_TEMPORAL}.unpause_external_data_schedule") as unpause,+ ):+ call_command("repair_qualified_schema_duplicates", *args, stdout=out)+ self.unpause = unpause+ return out.getvalue()++ def test_dry_run_changes_nothing(self) -> None:+ live = self._schema("public.campaign_runs", should_sync=False, table=self._table("postgres_campaign_runs"))+ phantom = self._schema("campaign_runs", should_sync=False, table=None)++ self._run() # dry-run default++ live.refresh_from_db()+ phantom.refresh_from_db()+ assert live.should_sync is False+ assert phantom.deleted is not True++ def test_live_run_reenables_live_and_soft_deletes_phantom(self) -> None:+ live = self._schema("public.campaign_runs", should_sync=False, table=self._table("postgres_campaign_runs"))+ phantom = self._schema("campaign_runs", should_sync=False, table=None)++ self._run("--live-run")++ live.refresh_from_db()+ phantom.refresh_from_db()+ assert live.should_sync is True+ assert phantom.deleted is True+ self.unpause.assert_called_once()++ def test_live_run_works_when_live_row_is_bare(self) -> None:+ # Symmetric case: the synced row is bare and the phantom is qualified.+ live = self._schema("campaign_runs", should_sync=False, table=self._table("postgres_campaign_runs"))+ phantom = self._schema("public.campaign_runs", should_sync=False, table=None)++ self._run("--live-run")++ live.refresh_from_db()+ phantom.refresh_from_db()+ assert live.should_sync is True+ assert phantom.deleted is True++ def test_multi_schema_two_live_rows_untouched(self) -> None:+ # Legit multi-schema: same table name in two schemas, both synced — must not be touched.+ a = self._schema("public.users", should_sync=True, table=self._table("postgres_public_users"))+ b = self._schema("analytics.users", should_sync=True, table=self._table("postgres_analytics_users"))++ out = self._run("--live-run")++ a.refresh_from_db()+ b.refresh_from_db()+ assert a.should_sync is True and a.deleted is not True+ assert b.should_sync is True and b.deleted is not True+ assert "skipped_ambiguous=1" in out++ def test_lone_disabled_row_not_reenabled(self) -> None:+ # No phantom twin → ambiguous (could be intentionally disabled) → leave it alone.+ lone = self._schema("public.campaign_runs", should_sync=False, table=self._table("postgres_campaign_runs"))++ self._run("--live-run")++ lone.refresh_from_db()+ assert lone.should_sync is False++ def test_phantom_that_has_synced_is_not_deleted(self) -> None:+ live = self._schema("public.campaign_runs", should_sync=False, table=self._table("postgres_campaign_runs"))+ # This twin has a last_synced_at, so it isn't a clean phantom — don't delete or re-enable blindly.+ not_phantom = self._schema(+ "campaign_runs", should_sync=False, table=None, last_synced_at=datetime(2026, 1, 1, tzinfo=UTC)+ )++ self._run("--live-run")++ live.refresh_from_db()+ not_phantom.refresh_from_db()+ assert live.should_sync is False+ assert not_phantom.deleted is not True++ def test_source_id_scoping(self) -> None:+ other_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="other",+ connection_id="other",+ source_type=ExternalDataSourceType.POSTGRES,+ )+ other_live = self._schema(+ "public.campaign_runs", should_sync=False, table=self._table("other_live"), source=other_source+ )+ self._schema("campaign_runs", should_sync=False, table=None, source=other_source)++ # Scope to self.source only — other_source must be left alone.+ self._run("--live-run", f"--source-id={self.source.id}")++ other_live.refresh_from_db()+ assert other_live.should_sync is Falsediff --git a/products/data_warehouse/backend/test/test_sync_status.py b/products/data_warehouse/backend/test/test_sync_status.pyindex 67fea5035a1c..54285b01ca00 100644--- a/products/data_warehouse/backend/test/test_sync_status.py+++ b/products/data_warehouse/backend/test/test_sync_status.py@@ -160,6 +160,54 @@ class TestWarehouseSyncWarnings(BaseTest):# status must be consistent with the "paused" message, not the raw schema status (Completed).assert warnings[0].status == ExternalDataSchema.Status.PAUSED+ def test_paused_but_fresh_does_not_imply_staleness(self) -> None:+ self._make_schema(+ status=ExternalDataSchema.Status.COMPLETED,+ should_sync=False,+ sync_frequency_interval=timedelta(hours=6),+ last_synced_at=self.now - timedelta(minutes=36),+ )+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)+ assert len(warnings) == 1+ message = warnings[0].message+ assert warnings[0].status == ExternalDataSchema.Status.PAUSED+ assert "paused" in message.lower()+ assert "current as of" in message+ assert "won't update" in message+ assert "reflect the last successful sync" not in message++ def test_paused_and_stale_reflects_last_sync(self) -> None:+ self._make_schema(+ status=ExternalDataSchema.Status.PAUSED,+ should_sync=False,+ sync_frequency_interval=timedelta(hours=6),+ last_synced_at=self.now - timedelta(hours=20),+ )+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)+ assert len(warnings) == 1+ assert "reflect the last successful sync" in warnings[0].message++ def test_paused_and_never_synced(self) -> None:+ self._make_schema(+ status=ExternalDataSchema.Status.PAUSED,+ should_sync=False,+ last_synced_at=None,+ )+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)+ assert len(warnings) == 1+ assert "hasn't completed a sync yet" in warnings[0].message++ def test_warning_when_completed_but_stale(self) -> None:+ self._make_schema(+ status=ExternalDataSchema.Status.COMPLETED,+ sync_frequency_interval=timedelta(hours=6),+ last_synced_at=self.now - timedelta(hours=13),+ )+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)+ assert len(warnings) == 1+ assert warnings[0].status == ExternalDataSchema.Status.COMPLETED+ assert "out of date" in warnings[0].message+def test_uses_preloaded_schemas_when_available(self) -> None:"""If `_active_external_data_schemas` is set on the table, it's used directly without a DB query."""fake_schema = MagicMock(spec=ExternalDataSchema)diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 5451ee6d656d..fd3f6ffdda4c 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -447,9 +447,24 @@ def sync_old_schemas_with_new_schemas(_update_labels(old_schemas, new_schemas)new_schema_names = list(new_schemas.keys())- schemas_to_create = [name for name in new_schema_names if name not in old_schemas_names]- schemas_to_possibly_delete = [schema for schema in old_schemas_names if schema not in new_schema_names]+ # Discovery names a table qualified (`schema.table`) or bare (`table`) depending on config, so+ # bare and qualified mean the same table — else a live row is wrongly disabled/duplicated. Two+ # qualified names still need exact equality so same-named tables in different schemas stay distinct.+ def _same_table(a: str, b: str) -> bool:+ one_qualified = ("." in a) != ("." in b)+ return a == b or (one_qualified and a.rpartition(".")[2] == b.rpartition(".")[2])++ # Create discovered names not already stored; flag stored names discovery no longer reports.+ schemas_to_create: list[str] = []+ for new_name in new_schema_names:+ if not any(_same_table(new_name, old_name) for old_name in old_schemas_names):+ schemas_to_create.append(new_name)++ schemas_to_possibly_delete: list[str] = []+ for old_name in old_schemas_names:+ if not any(_same_table(old_name, new_name) for new_name in new_schema_names):+ schemas_to_possibly_delete.append(old_name)deleted_schemas: list[str] = []actually_created: list[str] = []diff --git a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.pynew file mode 100644index 000000000000..1553936cdb95--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py@@ -0,0 +1,89 @@+import uuid++from posthog.test.base import BaseTest++from parameterized import parameterized++from products.warehouse_sources.backend.models.external_data_schema import (+ ExternalDataSchema,+ sync_old_schemas_with_new_schemas,+)+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.table import DataWarehouseTable+++# Managed/scheduled discovery calls sync_old_schemas_with_new_schemas with no rename step, so a+# qualified/bare name mismatch against the stored row used to flip the live row to should_sync=False.+class TestSchemaDiscoveryReconcile(BaseTest):+ def _make_source(self) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Postgres",+ created_by=self.user,+ job_inputs={"host": "localhost", "port": 5432, "schema": "public"},+ )++ def _make_synced_schema(self, source: ExternalDataSource, name: str) -> ExternalDataSchema:+ table = DataWarehouseTable.objects.create(+ name=f"postgres_{name}".replace(".", "_"),+ format=DataWarehouseTable.TableFormat.Parquet,+ team=self.team,+ url_pattern="https://bucket/team_1/*",+ external_data_source=source,+ columns={"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64"}},+ )+ return ExternalDataSchema.objects.create(+ team_id=self.team.pk,+ source_id=source.pk,+ name=name,+ should_sync=True,+ status=ExternalDataSchema.Status.COMPLETED,+ table=table,+ )++ @parameterized.expand(+ [+ # (stored name on the live synced row, the single name discovery currently emits)+ ("stored_qualified_discovery_bare", "public.campaign_runs", "campaign_runs"),+ ("stored_bare_discovery_qualified", "campaign_runs", "public.campaign_runs"),+ ]+ )+ def test_discovery_does_not_disable_live_synced_schema_on_qualification_mismatch(+ self, _name: str, stored_name: str, discovered_name: str+ ) -> None:+ source = self._make_source()+ synced_schema = self._make_synced_schema(source, stored_name)++ # Discovery returns the same physical table under the other qualification.+ sync_old_schemas_with_new_schemas(+ {discovered_name: None},+ source_id=str(source.pk),+ team_id=self.team.pk,+ )++ synced_schema.refresh_from_db()+ assert synced_schema.should_sync is True, (+ f"live synced schema {stored_name!r} was disabled when discovery emitted {discovered_name!r} "+ "— qualification mismatch must not be treated as a removed table"+ )+ assert synced_schema.table_id is not None++ def test_multi_schema_same_named_tables_stay_distinct(self) -> None:+ # Multi-schema mode (no single schema configured) emits everything qualified. A new+ # same-named table in another schema must be created, not collapsed onto the existing one.+ source = self._make_source()+ existing = self._make_synced_schema(source, "public.users")++ created, _deleted = sync_old_schemas_with_new_schemas(+ {"public.users": None, "analytics.users": None},+ source_id=str(source.pk),+ team_id=self.team.pk,+ )++ existing.refresh_from_db()+ assert existing.should_sync is True+ assert "analytics.users" in created+ assert ExternalDataSchema.objects.filter(source_id=source.pk, name="analytics.users").exists()