: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(data-warehouse): stop alerting on syncs the user turned off (#93270)
Luke Belton72a849c76fd5
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex bacf584a7201..47056480196b 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -853,6 +853,11 @@ field_exclusions: dict[AuditableScope, list[str]] = {# schema save (even ones that don't touch this field) — the extra queries have# deadlocked with concurrent DDL in production."table",+ # Written by the model on the stop-syncing transition to record whether PostHog halted+ # the schema itself, so it is derived state and not user intent. Diffing it also puts a+ # second change on the entry that turns syncing on or off, which makes the schema+ # activity feed read "updated schema" in place of "enabled schema".+ "auto_disabled_at",],"Evaluation": [# The fail-closed relation cannot be resolved outside a team scope; the handler diffs IDs instead.diff --git a/posthog/test/activity_logging/test_external_data_schema_activity_logging.py b/posthog/test/activity_logging/test_external_data_schema_activity_logging.pyindex 832f33739436..844705e87af1 100644--- a/posthog/test/activity_logging/test_external_data_schema_activity_logging.py+++ b/posthog/test/activity_logging/test_external_data_schema_activity_logging.py@@ -1,5 +1,7 @@from typing import get_args+from django.utils import timezone+from posthog.models.activity_logging.activity_log import ActivityScope, field_exclusionsfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.test.activity_log_utils import ActivityLogTestHelper@@ -20,7 +22,8 @@ class TestExternalDataSchemaActivityLogging(ActivityLogTestHelper):self.assertIn("status", external_data_schema_exclusions)self.assertIn("table", external_data_schema_exclusions)self.assertIn("destination_links", external_data_schema_exclusions)- self.assertEqual(len(external_data_schema_exclusions), 6)+ self.assertIn("auto_disabled_at", external_data_schema_exclusions)+ self.assertEqual(len(external_data_schema_exclusions), 7)def test_external_data_schema_scope_in_activity_log_types(self):self.assertIn("ExternalDataSchema", get_args(ActivityScope))@@ -82,6 +85,26 @@ class TestExternalDataSchemaActivityLogging(ActivityLogTestHelper):assert deleted_change is not Noneself.assertEqual(deleted_change["after"], True)+ def test_enabling_an_auto_disabled_schema_logs_only_the_enabled_change(self):+ external_data_source = self.create_external_data_source()++ source_obj = ExternalDataSource.objects.get(id=external_data_source["id"])+ schema = source_obj.schemas.first()+ assert schema is not None++ ExternalDataSchema.objects.filter(pk=schema.pk).update(should_sync=False, auto_disabled_at=timezone.now())+ self.clear_activity_logs()++ disabled_schema = ExternalDataSchema.objects.get(pk=schema.pk)+ disabled_schema.should_sync = True+ disabled_schema.save()++ activity_logs = self.get_activity_logs_for_item("ExternalDataSchema", str(schema.id))+ self.assertEqual(len(activity_logs), 1)++ changes = activity_logs[0].detail.get("changes", [])+ self.assertEqual([change["field"] for change in changes], ["enabled"])+def test_external_data_schema_relationship_logging(self):external_data_source = self.create_external_data_source()diff --git a/products/data_warehouse/backend/logic/external_data_source/notifications.py b/products/data_warehouse/backend/logic/external_data_source/notifications.pyindex 074f36b2add5..81809a3def50 100644--- a/products/data_warehouse/backend/logic/external_data_source/notifications.py+++ b/products/data_warehouse/backend/logic/external_data_source/notifications.py@@ -26,6 +26,14 @@ MAX_SCHEMAS_PER_DIGEST_EMAIL = 30# the first day past this age and stamps a fresh time, spacing reminders evenly.RENOTIFY_STILL_FAILING_AFTER = dt.timedelta(days=7)+# A schema the user switched off is not a failure to chase: it will not run again, and nobody+# asked it to. Its last status stays Failed for the syncs UI, so the digest cannot read status+# alone. `auto_disabled_at` marks the other way syncing stops, where PostHog halted the schema+# after an error that retrying would not fix; that one still needs the email, because only the+# user can repair the source and turn syncing back on. CDC breakage halts a schema without+# flipping `should_sync`, so it stays in the digest either way.+SCHEMA_STOPPED_BY_USER = Q(should_sync=False, auto_disabled_at__isnull=True)+def get_team_ids_with_recent_sync_failures(lookback: dt.timedelta = dt.timedelta(hours=26),@@ -42,6 +50,8 @@ def get_team_ids_with_recent_sync_failures(never syncs again. Their last email is older than `renotify_after`, so theyget a reminder instead of silence.+ Schemas the user switched off are left out entirely, per `SCHEMA_STOPPED_BY_USER`.+The lookback exceeds the 24h digest day on purpose: a failure just after the10:00 UTC rollover, blocked because that digest day's email already went out,is 24h15m+ old by the next catch-up run — a 24h lookback would drop it forever@@ -61,6 +71,7 @@ def get_team_ids_with_recent_sync_failures(return list(ExternalDataSchema.objects.exclude(deleted=True).exclude(source__deleted=True)+ .exclude(SCHEMA_STOPPED_BY_USER).filter(status=ExternalDataSchemaStatus.FAILED).filter(Exists(unnotified_failed_job) | Q(last_error_notified_at__lt=renotify_cutoff)).values_list("team_id", flat=True)@@ -77,10 +88,11 @@ def notify_external_data_sync_failures(notification, or has stayed failed for longer than `renotify_after` since its lastemail. The last case reminds the team about a paused schema, which never runs againand so produces no newer failed run to re-trigger the digest on its own. Schemas of a- deleted source are excluded entirely. Runs inside the digest Celery task; exceptions- are swallowed so a notification problem never crash-loops the task. Throttling to one- email per team per digest day happens in the email layer via the MessagingRecord- campaign key, so scheduling this for every failed job is safe.+ deleted source, and schemas the user switched off (see `SCHEMA_STOPPED_BY_USER`), are+ excluded entirely. Runs inside the digest Celery task; exceptions are swallowed so a+ notification problem never crash-loops the task. Throttling to one email per team per+ digest day happens in the email layer via the MessagingRecord campaign key, so+ scheduling this for every failed job is safe."""try:renotify_cutoff = dt.datetime.now(dt.UTC) - renotify_after@@ -92,6 +104,7 @@ def notify_external_data_sync_failures(failing_schemas = list(ExternalDataSchema.objects.exclude(deleted=True).exclude(source__deleted=True)+ .exclude(SCHEMA_STOPPED_BY_USER).filter(team_id=team_id, status=ExternalDataSchemaStatus.FAILED).filter(Q(last_error_notified_at__isnull=True)diff --git a/products/data_warehouse/backend/logic/external_data_source/test/test_notifications.py b/products/data_warehouse/backend/logic/external_data_source/test/test_notifications.pyindex c2cb48f090d8..8f339812980a 100644--- a/products/data_warehouse/backend/logic/external_data_source/test/test_notifications.py+++ b/products/data_warehouse/backend/logic/external_data_source/test/test_notifications.py@@ -48,12 +48,15 @@ class TestNotifyExternalDataSyncFailures:should_sync=True,latest_error="transient error",)+ # PostHog stopped this one itself after a non-retryable error, so it stays in the digest:+ # only the user can repair the source and turn syncing back on.ExternalDataSchema.objects.create(name="Invoice",team=team,source=source,status=ExternalDataSchema.Status.FAILED,should_sync=False,+ auto_disabled_at=dt.datetime.now(dt.UTC),latest_error="Invalid API key",)# CDC breakage halts syncing without flipping should_sync — it must still read as@@ -118,6 +121,9 @@ class TestNotifyExternalDataSyncFailures:(ExternalDataSchema.Status.BILLING_LIMIT_REACHED, True, False),(ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW, True, False),(ExternalDataSchema.Status.FAILED, True, True),+ # The user switched syncing off. The status stays Failed for the syncs UI, but+ # there is nothing left to chase, so the digest must not report it.+ (ExternalDataSchema.Status.FAILED, False, False),],)def test_does_not_send_for_non_failing_or_deleted_schemas(self, status, should_sync, deleted):@@ -286,6 +292,7 @@ class TestNotifyExternalDataSyncFailures:source=source,status=ExternalDataSchema.Status.FAILED,should_sync=False,+ auto_disabled_at=dt.datetime.now(dt.UTC) - notified_age,latest_error="Invalid API key",last_error_notified_at=dt.datetime.now(dt.UTC) - notified_age,)@@ -305,6 +312,8 @@ class TestGetTeamIdsWithRecentSyncFailures:schema_deleted: bool = False,source_deleted: bool = False,last_error_notified_at: dt.datetime | None = None,+ should_sync: bool = True,+ auto_disabled_at: dt.datetime | None = None,) -> Team:team, source = _create_team_and_source()if source_deleted:@@ -315,6 +324,8 @@ class TestGetTeamIdsWithRecentSyncFailures:source=source,status=schema_status,deleted=schema_deleted,+ should_sync=should_sync,+ auto_disabled_at=auto_disabled_at,latest_error="boom",last_error_notified_at=last_error_notified_at,)@@ -336,20 +347,23 @@ class TestGetTeamIdsWithRecentSyncFailures:assert get_team_ids_with_recent_sync_failures() == [team.pk]@pytest.mark.parametrize(- "schema_status,job_age,schema_deleted,source_deleted",+ "schema_status,job_age,schema_deleted,source_deleted,should_sync",[- (ExternalDataSchema.Status.FAILED, dt.timedelta(hours=30), False, False),- (ExternalDataSchema.Status.COMPLETED, dt.timedelta(hours=2), False, False),- (ExternalDataSchema.Status.FAILED, dt.timedelta(hours=2), True, False),- (ExternalDataSchema.Status.FAILED, dt.timedelta(hours=2), False, True),+ (ExternalDataSchema.Status.FAILED, dt.timedelta(hours=30), False, False, True),+ (ExternalDataSchema.Status.COMPLETED, dt.timedelta(hours=2), False, False, True),+ (ExternalDataSchema.Status.FAILED, dt.timedelta(hours=2), True, False, True),+ (ExternalDataSchema.Status.FAILED, dt.timedelta(hours=2), False, True, True),+ # Switched off by the user, so the catch-up sweep has nothing to chase.+ (ExternalDataSchema.Status.FAILED, dt.timedelta(hours=2), False, False, False),],)- def test_excludes_non_actionable_teams(self, schema_status, job_age, schema_deleted, source_deleted):+ def test_excludes_non_actionable_teams(self, schema_status, job_age, schema_deleted, source_deleted, should_sync):self._create_schema_with_job(schema_status=schema_status,job_finished_at=dt.datetime.now(dt.UTC) - job_age,schema_deleted=schema_deleted,source_deleted=source_deleted,+ should_sync=should_sync,)assert get_team_ids_with_recent_sync_failures() == []@@ -382,12 +396,15 @@ class TestGetTeamIdsWithRecentSyncFailures:assert get_team_ids_with_recent_sync_failures() == [team.pk]def test_includes_still_failing_schema_past_the_renotify_window(self):- # No recent failed run (30h stale) and the last email is 8 days old: the team- # would drop out forever without the re-notify path.+ # PostHog halted this schema itself, so it never runs again. No recent failed run+ # (30h stale) and the last email is 8 days old: the team would drop out forever+ # without the re-notify path.team = self._create_schema_with_job(schema_status=ExternalDataSchema.Status.FAILED,job_finished_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=30),last_error_notified_at=dt.datetime.now(dt.UTC) - dt.timedelta(days=8),+ should_sync=False,+ auto_disabled_at=dt.datetime.now(dt.UTC) - dt.timedelta(days=9),)assert get_team_ids_with_recent_sync_failures() == [team.pk]diff --git a/products/warehouse_sources/backend/migrations/0163_externaldataschema_auto_disabled_at.py b/products/warehouse_sources/backend/migrations/0163_externaldataschema_auto_disabled_at.pynew file mode 100644index 000000000000..6846ae0166bf--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0163_externaldataschema_auto_disabled_at.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.17 on 2026-09-02 12:02++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0162_repin_shopify_api_version"),+ ]++ operations = [+ migrations.AddField(+ model_name="externaldataschema",+ name="auto_disabled_at",+ field=models.DateTimeField(+ blank=True,+ help_text="When PostHog stopped syncing this schema itself, after an error that retrying would not fix. Null while syncing is on, and while syncing is off because the user turned it off.",+ null=True,+ ),+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex d26649395fc7..d7f5f8752a79 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0162_repin_shopify_api_version+0163_externaldataschema_auto_disabled_atdiff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 4fa2aa71544f..0f2954ee2a85 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -138,6 +138,15 @@ class ExternalDataSchemaQuerySet(models.QuerySet["ExternalDataSchema"]):"""disabling = kwargs.get("should_sync") is Falsedeleting = kwargs.get("deleted") is True++ # `auto_disabled_at` is written by `save()`, which a bulk write skips. The auto-disable+ # path always runs through `update_should_sync`, which saves the instance, so a bulk+ # write that names `should_sync` is the user's decision. An earlier halt must not+ # outlive it, or a schema nobody halted stays in the failure digest. An explicit value+ # still wins, so a caller can stage a halted row.+ if "should_sync" in kwargs and "auto_disabled_at" not in kwargs:+ kwargs["auto_disabled_at"] = None+transitioning: list[tuple[uuid.UUID, int]] = []if disabling or deleting:predicate = models.Q()@@ -167,6 +176,12 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldsource = models.ForeignKey("warehouse_sources.ExternalDataSource", related_name="schemas", on_delete=models.CASCADE)table = models.ForeignKey("warehouse_sources.DataWarehouseTable", on_delete=models.SET_NULL, null=True, blank=True)should_sync = models.BooleanField(default=True)+ auto_disabled_at = models.DateTimeField(+ null=True,+ blank=True,+ help_text="When PostHog stopped syncing this schema itself, after an error that retrying would not fix. "+ "Null while syncing is on, and while syncing is off because the user turned it off.",+ )latest_error = models.TextField(null=True, blank=True, help_text="The latest error that occurred when syncing this schema.")@@ -242,6 +257,30 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldreturn "disabled"return None+ def _apply_auto_disabled_marker(self, teardown_kind: str | None, update_fields: Iterable[str] | None) -> bool:+ """Record whether PostHog stopped this schema itself. Returns whether the value changed.++ The failure digest emails a team about a schema PostHog halted, and stays quiet about one+ the user switched off, so which of the two happened must outlive the write that stopped+ the schema. Only the auto-disable path supplies an error message through+ ``sync_disable_context``, and that is what tells the two apart. A save that leaves+ ``should_sync`` False without performing the disable transition keeps the existing stamp,+ so the pipeline's frequent bookkeeping saves cannot erase it.+ """+ if update_fields is not None and "should_sync" not in update_fields:+ return False+ if self.should_sync:+ marker = None+ elif teardown_kind == "disabled":+ context = _sync_disable_context.get()+ marker = timezone.now() if context is not None and context.error_message else None+ else:+ return False+ if marker == self.auto_disabled_at:+ return False+ self.auto_disabled_at = marker+ return True+def save(self, *args: Any, skip_activity_log: bool = False, **kwargs: Any) -> None:# Populate the S3 folder on first write so the column is always authoritative for new rows.# Legacy/qualified rows set it explicitly before renaming (see `_qualify_legacy_row`); this@@ -257,6 +296,11 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField# dispatched only after it succeeds.teardown_kind = self._sync_teardown_kind(kwargs.get("update_fields"))+ if self._apply_auto_disabled_marker(teardown_kind, kwargs.get("update_fields")):+ scoped_fields = kwargs.get("update_fields")+ if scoped_fields is not None:+ kwargs["update_fields"] = {*scoped_fields, "auto_disabled_at"}+if skip_activity_log:# Internal pipeline-driven bookkeeping saves (sync_type_config / xmin state) don't need# an audit trail. Bypass ModelActivityMixin.save() so we skip its extra _get_before_updatediff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 9eac4a85d9c0..bb3e0b31526b 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@@ -11026,6 +11026,37 @@ class TestDisableCDC(APIBaseTest):assert non_cdc_schema.sync_type == ExternalDataSchema.SyncType.INCREMENTALassert non_cdc_schema.should_sync is True+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.cleanup_resources",+ return_value=None,+ )+ def test_disable_cdc_clears_an_earlier_auto_disable(self, _cleanup) -> None:+ # PostHog can halt a CDC schema before the user gives up on CDC. The halt must not+ # survive their disable, or the failure digest keeps emailing them about a sync+ # they switched off themselves.+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)++ halted_schema = ExternalDataSchema.objects.create(+ name="cdc_table",+ team_id=self.team.pk,+ source_id=source.pk,+ sync_type=ExternalDataSchema.SyncType.CDC,+ should_sync=True,+ )+ ExternalDataSchema.objects.filter(pk=halted_schema.pk).update(+ should_sync=False,+ status=ExternalDataSchema.Status.FAILED,+ auto_disabled_at=timezone.now(),+ )++ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/disable_cdc/",+ )+ assert response.status_code == 200, response.content++ halted_schema.refresh_from_db()+ assert halted_schema.auto_disabled_at is None+@patch("products.warehouse_sources.backend.presentation.views.external_data_source.purge_buffer_prefix")def test_disable_cdc_requires_editor_on_every_table(self, mock_purge) -> None:# A table can be locked below source-level editor; the per-table gate must rundiff --git a/products/warehouse_sources/backend/tests/test_sync_teardown.py b/products/warehouse_sources/backend/tests/test_sync_teardown.pyindex 8e8e9da9434c..a2ab45dff06b 100644--- a/products/warehouse_sources/backend/tests/test_sync_teardown.py+++ b/products/warehouse_sources/backend/tests/test_sync_teardown.py@@ -153,6 +153,82 @@ class TestDisableChokepointDispatch:exclude_workflow_id=job.workflow_id,)+ @pytest.mark.parametrize(+ "halted_by_posthog",+ [False, True],+ ids=["user_switched_it_off", "posthog_halted_it"],+ )+ def test_disable_records_who_stopped_the_sync(self, halted_by_posthog, team, django_capture_on_commit_callbacks):+ schema, _job = _create_schema_with_running_job(team)++ with (+ patch(TASK_DELAY),+ patch(+ "products.data_warehouse.backend.logic.data_load.service.external_data_workflow_exists",+ return_value=False,+ ),+ django_capture_on_commit_callbacks(execute=True),+ ):+ if halted_by_posthog:+ update_should_sync(+ schema_id=str(schema.id),+ team_id=team.pk,+ should_sync=False,+ disable_error_message="Your account does not have access to this table",+ )+ else:+ schema.should_sync = False+ schema.save()++ schema.refresh_from_db()+ assert (schema.auto_disabled_at is not None) is halted_by_posthog++ def test_re_enabling_clears_the_record_of_an_earlier_halt(self, team):+ # A record left behind by an earlier halt must not outlive the re-enable, or a later+ # disable puts a schema nobody halted back into the failure digest.+ schema, _job = _create_schema_with_running_job(team)+ with patch(TASK_DELAY):+ ExternalDataSchema.objects.filter(pk=schema.pk).update(should_sync=False, auto_disabled_at=timezone.now())+ schema.refresh_from_db()++ schema.should_sync = True+ schema.save()+ schema.refresh_from_db()+ assert schema.auto_disabled_at is None++ ExternalDataSchema.objects.filter(pk=schema.pk).update(should_sync=False)++ schema.refresh_from_db()+ assert schema.auto_disabled_at is None++ def test_bulk_disable_clears_the_record_of_an_earlier_halt(self, team, django_capture_on_commit_callbacks):+ # `disable_cdc` turns schemas off with a bulk update, which bypasses save(). A halt+ # recorded before it would survive, and keep the failure digest emailing the team+ # about a sync they switched off themselves.+ schema, _job = _create_schema_with_running_job(team)++ with (+ patch(TASK_DELAY),+ patch(+ "products.data_warehouse.backend.logic.data_load.service.external_data_workflow_exists",+ return_value=False,+ ),+ django_capture_on_commit_callbacks(execute=True),+ ):+ update_should_sync(+ schema_id=str(schema.id),+ team_id=team.pk,+ should_sync=False,+ disable_error_message="Your account does not have access to this table",+ )+ schema.refresh_from_db()+ assert schema.auto_disabled_at is not None++ ExternalDataSchema.objects.filter(pk=schema.pk).update(sync_type=None, should_sync=False)++ schema.refresh_from_db()+ assert schema.auto_disabled_at is None+class TestSweepStoppedSchemaSyncs:@pytest.mark.parametrize("deleted", [False, True], ids=["disabled", "deleted"])