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.

feat(customer-analytics): notify owners when property syncs disable (#104499)

posthog[bot]06370cc86123
diff --git a/products/customer_analytics/backend/logic/account_property_runs.py b/products/customer_analytics/backend/logic/account_property_runs.py
index ba52bc57a521..32324ca18a3f 100644
--- a/products/customer_analytics/backend/logic/account_property_runs.py
+++ b/products/customer_analytics/backend/logic/account_property_runs.py
@@ -6,6 +6,10 @@ from django.utils import timezone
from posthog.dataclasses import frozen
+from products.customer_analytics.backend.logic.custom_property_source_health import (
+ record_sync_failure,
+ record_sync_success,
+)
from products.customer_analytics.backend.models import CustomPropertySource, TargetType
from products.customer_analytics.backend.models.custom_property_sync_run import (
CustomPropertySyncRun,
@@ -34,7 +38,6 @@ class AccountPropertySyncRunOutcome:
_ACCOUNT_SEGMENTS = {segment.value for segment in SyncSegment}
-_MAX_CONSECUTIVE_SYNC_FAILURES = 5
def start_account_property_sync_runs(
@@ -176,27 +179,17 @@ def _update_source_status_for_terminal_runs(
failed_runs = [run for run in runs if run.status == SyncStatus.FAILED.value]
if failed_runs:
- source.consecutive_failures = (source.consecutive_failures or 0) + 1
- source.last_sync_error = next((run.error for run in failed_runs if run.error), None)
- if source.consecutive_failures >= _MAX_CONSECUTIVE_SYNC_FAILURES:
- source.is_enabled = False
- source.save(
- update_fields=[
- "consecutive_failures",
- "last_sync_error",
- "is_enabled",
- "updated_at",
- ]
+ record_sync_failure(
+ source,
+ error=next((run.error for run in failed_runs if run.error), None),
+ disable_event_id=job_id,
)
continue
finished_at = max((run.finished_at for run in runs if run.finished_at is not None), default=None)
if finished_at is None:
continue
- source.last_synced_at = finished_at
- source.last_sync_error = None
- source.consecutive_failures = 0
- source.save(update_fields=["last_synced_at", "last_sync_error", "consecutive_failures", "updated_at"])
+ record_sync_success(source, finished_at=finished_at)
def finalize_account_property_sync_runs(
diff --git a/products/customer_analytics/backend/logic/account_property_runs_test.py b/products/customer_analytics/backend/logic/account_property_runs_test.py
index 9aee609128a5..72649a18a237 100644
--- a/products/customer_analytics/backend/logic/account_property_runs_test.py
+++ b/products/customer_analytics/backend/logic/account_property_runs_test.py
@@ -1,6 +1,7 @@
from datetime import timedelta
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.apps import apps
from django.utils import timezone
@@ -14,6 +15,7 @@ from products.customer_analytics.backend.logic.account_property_runs import (
start_account_property_sync_runs,
update_account_property_sync_runs_phase,
)
+from products.customer_analytics.backend.logic.custom_property_source_health import MAX_CONSECUTIVE_SYNC_FAILURES
from products.customer_analytics.backend.models import CustomPropertySource, CustomPropertySyncRun
from products.customer_analytics.backend.models.custom_property_sync_run import SyncPhase, SyncSegment, SyncStatus
from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
@@ -21,6 +23,8 @@ from products.customer_analytics.backend.test.factories import create_custom_pro
DataWarehouseSavedQuery = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
+HEALTH_SERVICE = "products.customer_analytics.backend.logic.custom_property_source_health"
+
class TestAccountPropertyRuns(TeamScopedTestMixin, BaseTest):
def setUp(self) -> None:
@@ -249,3 +253,21 @@ class TestAccountPropertyRuns(TeamScopedTestMixin, BaseTest):
assert (tracked.status, tracked.phase, tracked.produced) == ("completed", "completed", 3)
assert (ignored.status, ignored.phase, ignored.error) == ("running", "staging", None)
assert CustomPropertySyncRun.objects.for_team(self.team.id).filter(source=self.source).count() == 2
+
+ @patch(f"{HEALTH_SERVICE}.notify_source_auto_disabled")
+ def test_the_fifth_failed_sync_disables_the_source_and_tells_its_owner_once(self, mock_notify) -> None:
+ self.source.consecutive_failures = MAX_CONSECUTIVE_SYNC_FAILURES - 1
+ self.source.save(update_fields=["consecutive_failures"])
+ self._start_runs()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ finalize_account_property_sync_runs(
+ self.context,
+ status=SyncStatus.FAILED,
+ phase=SyncPhase.STAGING,
+ error="Couldn't prepare warehouse rows.",
+ )
+
+ self.source.refresh_from_db()
+ assert self.source.is_enabled is False
+ mock_notify.assert_called_once_with(team_id=self.team.id, source_id=self.source.id, disable_event_id="job-1")
diff --git a/products/customer_analytics/backend/logic/custom_property_source_disabled_notice.py b/products/customer_analytics/backend/logic/custom_property_source_disabled_notice.py
new file mode 100644
index 000000000000..f6c6e49556c2
--- /dev/null
+++ b/products/customer_analytics/backend/logic/custom_property_source_disabled_notice.py
@@ -0,0 +1,183 @@
+from datetime import datetime, time, timedelta
+from hashlib import sha256
+from uuid import NAMESPACE_URL, UUID, uuid5
+
+from django.db import connection, transaction
+from django.utils import timezone
+
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team, User
+from posthog.models.team.team import DEPRECATED_ATTRS
+from posthog.permissions import posthog_feature_flag_enabled
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG
+from products.customer_analytics.backend.facade.contracts import CreateCustomerTaskInput
+from products.customer_analytics.backend.logic.customer_tasks import create_customer_task
+from products.customer_analytics.backend.models import CustomerTask, CustomPropertySource
+from products.notifications.backend.facade.api import (
+ NotificationData,
+ NotificationType,
+ Priority,
+ SourceType,
+ TargetType,
+ create_notification,
+)
+from products.notifications.backend.facade.enums import NotificationOnlyResourceType
+
+logger = structlog.get_logger(__name__)
+
+TITLE_MAX_LENGTH = 255
+TASK_NAME_MAX_LENGTH = 400
+CONFIGURATION_ACCOUNTS_PATH = "/customer_analytics/configuration?tab=customer-analytics-accounts"
+DISABLED_BODY = (
+ "PostHog disabled this sync after five consecutive failures. Review the latest run, fix the "
+ "source, then re-enable the sync."
+)
+
+
+def notify_source_auto_disabled(*, team_id: int, source_id: UUID, disable_event_id: str) -> None:
+ log = logger.bind(team_id=team_id, source_id=str(source_id), disable_event_id=disable_event_id)
+ try:
+ source = (
+ CustomPropertySource.objects.for_team(team_id)
+ .select_related("definition", "created_by")
+ .filter(id=source_id)
+ .first()
+ )
+ if source is None:
+ log.info("custom_property_source_disabled.source_gone")
+ return
+
+ owner = source.created_by
+ if owner is None or not owner.is_active:
+ log.info("custom_property_source_disabled.owner_unavailable")
+ return
+
+ team = (
+ Team.objects.select_related("parent_team")
+ .defer(*(f"parent_team__{attr}" for attr in DEPRECATED_ATTRS))
+ .filter(id=team_id)
+ .first()
+ )
+ if team is None:
+ log.info("custom_property_source_disabled.team_gone")
+ return
+
+ access = UserAccessControl(user=owner, team=team, organization_id=str(team.organization_id))
+ if not access.has_project_access:
+ log.info("custom_property_source_disabled.owner_without_project_access")
+ return
+
+ name = source.definition.name
+ _notify_owner(team=team, owner=owner, source=source, name=name, disable_event_id=disable_event_id, log=log)
+ _open_owner_task(team=team, owner=owner, source=source, name=name, disable_event_id=disable_event_id, log=log)
+ except Exception as error:
+ capture_exception(error)
+ log.exception("custom_property_source_disabled.dispatch_failed")
+
+
+def _notify_owner(
+ *,
+ team: Team,
+ owner: User,
+ source: CustomPropertySource,
+ name: str,
+ disable_event_id: str,
+ log: structlog.BoundLogger,
+) -> None:
+ try:
+ create_notification(
+ NotificationData(
+ team_id=team.id,
+ notification_type=NotificationType.PIPELINE_FAILURE,
+ priority=Priority.NORMAL,
+ title=f"Warehouse property sync disabled: {name}"[:TITLE_MAX_LENGTH],
+ body=DISABLED_BODY,
+ target_type=TargetType.USER,
+ target_id=str(owner.id),
+ resource_type=NotificationOnlyResourceType.PIPELINE,
+ resource_id=str(source.id),
+ source_url=CONFIGURATION_ACCOUNTS_PATH,
+ source_type=SourceType.CUSTOMER_ANALYTICS,
+ source_id=str(source.id),
+ idempotency_key=_notification_idempotency_key(source.id, disable_event_id),
+ )
+ )
+ except Exception as error:
+ capture_exception(error)
+ log.exception("custom_property_source_disabled.notification_failed")
+
+
+def _open_owner_task(
+ *,
+ team: Team,
+ owner: User,
+ source: CustomPropertySource,
+ name: str,
+ disable_event_id: str,
+ log: structlog.BoundLogger,
+) -> None:
+ try:
+ if not posthog_feature_flag_enabled(
+ CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG,
+ str(owner.distinct_id),
+ organization_id=team.organization_id,
+ team_id=team.id,
+ ):
+ log.info("custom_property_source_disabled.tasks_unavailable")
+ return
+
+ canonical_team = team.parent_team or team
+ access = UserAccessControl(
+ user=owner,
+ team=canonical_team,
+ organization_id=str(canonical_team.organization_id),
+ )
+ if not access.has_project_access or not access.check_access_level_for_resource("customer_task", "editor"):
+ log.info("custom_property_source_disabled.tasks_unavailable")
+ return
+
+ task_id = _task_id(team_id=canonical_team.id, source_id=source.id, disable_event_id=disable_event_id)
+ with transaction.atomic():
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [canonical_team.id, str(task_id)])
+ if CustomerTask.objects.for_team(canonical_team.id).filter(id=task_id).exists():
+ return
+ create_customer_task(
+ team=canonical_team,
+ input=CreateCustomerTaskInput(
+ name=f"Fix warehouse property sync: {name}"[:TASK_NAME_MAX_LENGTH],
+ description=DISABLED_BODY,
+ assigned_to_id=owner.id,
+ due_at=_end_of_next_business_day(team),
+ ),
+ actor=None,
+ user_access_control=access,
+ task_id=task_id,
+ )
+ except Exception as error:
+ capture_exception(error)
+ log.exception("custom_property_source_disabled.task_failed")
+
+
+def _notification_idempotency_key(source_id: UUID, disable_event_id: str) -> str:
+ event_hash = sha256(disable_event_id.encode()).hexdigest()[:32]
+ return f"custom-property-source:{source_id}:disabled:{event_hash}"
+
+
+def _task_id(*, team_id: int, source_id: UUID, disable_event_id: str) -> UUID:
+ return uuid5(
+ NAMESPACE_URL,
+ f"posthog:customer-task:{team_id}:custom-property-source-disabled:{source_id}:{disable_event_id}",
+ )
+
+
+def _end_of_next_business_day(team: Team) -> datetime:
+ tz = team.timezone_info
+ day = timezone.now().astimezone(tz).date() + timedelta(days=1)
+ while day.weekday() >= 5:
+ day += timedelta(days=1)
+ return datetime.combine(day, time(23, 59, 59), tzinfo=tz)
diff --git a/products/customer_analytics/backend/logic/custom_property_source_health.py b/products/customer_analytics/backend/logic/custom_property_source_health.py
new file mode 100644
index 000000000000..e0fcf6952d5b
--- /dev/null
+++ b/products/customer_analytics/backend/logic/custom_property_source_health.py
@@ -0,0 +1,49 @@
+from datetime import datetime
+from functools import partial
+from uuid import UUID
+
+from django.db import transaction
+
+from products.customer_analytics.backend.logic.custom_property_source_disabled_notice import notify_source_auto_disabled
+from products.customer_analytics.backend.models import CustomPropertySource
+
+MAX_CONSECUTIVE_SYNC_FAILURES = 5
+
+
+def record_sync_success(source: CustomPropertySource, *, finished_at: datetime | None) -> None:
+ source.last_synced_at = finished_at
+ source.last_sync_error = None
+ source.consecutive_failures = 0
+ source.save(update_fields=["last_synced_at", "last_sync_error", "consecutive_failures", "updated_at"])
+
+
+def record_sync_failure(
+ source: CustomPropertySource,
+ *,
+ error: str | None,
+ disable_event_id: str,
+ count_failure: bool = True,
+) -> bool:
+ was_enabled = source.is_enabled
+ if count_failure:
+ source.consecutive_failures = (source.consecutive_failures or 0) + 1
+ source.last_sync_error = error
+ if source.consecutive_failures >= MAX_CONSECUTIVE_SYNC_FAILURES:
+ source.is_enabled = False
+ source.save(update_fields=["consecutive_failures", "last_sync_error", "is_enabled", "updated_at"])
+
+ auto_disabled = was_enabled and not source.is_enabled
+ if auto_disabled:
+ _schedule_owner_notice(team_id=source.team_id, source_id=source.id, disable_event_id=disable_event_id)
+ return auto_disabled
+
+
+def _schedule_owner_notice(*, team_id: int, source_id: UUID, disable_event_id: str) -> None:
+ transaction.on_commit(
+ partial(
+ notify_source_auto_disabled,
+ team_id=team_id,
+ source_id=source_id,
+ disable_event_id=disable_event_id,
+ )
+ )
diff --git a/products/customer_analytics/backend/logic/custom_property_source_health_test.py b/products/customer_analytics/backend/logic/custom_property_source_health_test.py
new file mode 100644
index 000000000000..619693f517f6
--- /dev/null
+++ b/products/customer_analytics/backend/logic/custom_property_source_health_test.py
@@ -0,0 +1,94 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from products.customer_analytics.backend.logic.custom_property_source_health import (
+ MAX_CONSECUTIVE_SYNC_FAILURES,
+ record_sync_failure,
+ record_sync_success,
+)
+from products.customer_analytics.backend.models import CustomPropertySource
+from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
+from products.customer_analytics.backend.test.factories import create_custom_property_definition
+
+SERVICE = "products.customer_analytics.backend.logic.custom_property_source_health"
+
+
+@patch(f"{SERVICE}.notify_source_auto_disabled")
+class TestCustomPropertySourceHealth(TeamScopedTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ self.source = CustomPropertySource.objects.create(
+ team=self.team,
+ definition=definition,
+ key_column="external_id",
+ source_column="plan",
+ )
+
+ def _fail(self, *, job_id: str = "job-1", count_failure: bool = True) -> bool:
+ with self.captureOnCommitCallbacks(execute=True):
+ return record_sync_failure(self.source, error="boom", disable_event_id=job_id, count_failure=count_failure)
+
+ def test_source_stays_enabled_until_the_threshold(self, mock_notify) -> None:
+ for _ in range(MAX_CONSECUTIVE_SYNC_FAILURES - 1):
+ assert self._fail() is False
+
+ self.source.refresh_from_db()
+ assert self.source.is_enabled is True
+ mock_notify.assert_not_called()
+
+ def test_the_threshold_failure_disables_and_tells_the_owner_once(self, mock_notify) -> None:
+ self.source.consecutive_failures = MAX_CONSECUTIVE_SYNC_FAILURES - 1
+ self.source.save()
+
+ assert self._fail() is True
+
+ self.source.refresh_from_db()
+ assert self.source.is_enabled is False
+ mock_notify.assert_called_once_with(team_id=self.team.id, source_id=self.source.id, disable_event_id="job-1")
+
+ def test_a_failure_on_an_already_disabled_source_tells_nobody_again(self, mock_notify) -> None:
+ self.source.consecutive_failures = MAX_CONSECUTIVE_SYNC_FAILURES
+ self.source.is_enabled = False
+ self.source.save()
+
+ assert self._fail(job_id="job-2") is False
+ mock_notify.assert_not_called()
+
+ def test_an_uncounted_failure_does_not_move_the_streak(self, mock_notify) -> None:
+ self.source.consecutive_failures = MAX_CONSECUTIVE_SYNC_FAILURES - 1
+ self.source.save()
+
+ assert self._fail(count_failure=False) is False
+
+ self.source.refresh_from_db()
+ assert self.source.consecutive_failures == MAX_CONSECUTIVE_SYNC_FAILURES - 1
+ assert self.source.is_enabled is True
+ mock_notify.assert_not_called()
+
+ def test_success_clears_the_streak_and_the_error(self, _mock_notify) -> None:
+ self.source.consecutive_failures = 3
+ self.source.last_sync_error = "boom"
+ self.source.save()
+
+ finished_at = timezone.now()
+ record_sync_success(self.source, finished_at=finished_at)
+
+ stored = CustomPropertySource.objects.for_team(self.team.id).get(id=self.source.id)
+ assert stored.consecutive_failures == 0
+ assert stored.last_sync_error is None
+ assert stored.last_synced_at == finished_at
+
+ def test_a_later_disablement_after_re_enabling_tells_the_owner_again(self, mock_notify) -> None:
+ self.source.consecutive_failures = MAX_CONSECUTIVE_SYNC_FAILURES - 1
+ self.source.save()
+ self._fail(job_id="job-1")
+
+ self.source.is_enabled = True
+ self.source.consecutive_failures = MAX_CONSECUTIVE_SYNC_FAILURES - 1
+ self.source.save()
+ self._fail(job_id="job-2")
+
+ assert [call.kwargs["disable_event_id"] for call in mock_notify.call_args_list] == ["job-1", "job-2"]
diff --git a/products/customer_analytics/backend/logic/person_property_runs.py b/products/customer_analytics/backend/logic/person_property_runs.py
index 2ee8f022062c..bef71fe3e798 100644
--- a/products/customer_analytics/backend/logic/person_property_runs.py
+++ b/products/customer_analytics/backend/logic/person_property_runs.py
@@ -8,10 +8,16 @@ account-path ``sourceSyncStatus`` UI helper works for person sources too.
from datetime import datetime
+from django.db import transaction
+
import structlog
from posthog.exceptions_capture import capture_exception
+from products.customer_analytics.backend.logic.custom_property_source_health import (
+ record_sync_failure,
+ record_sync_success,
+)
from products.customer_analytics.backend.models import (
CustomPropertySource,
CustomPropertySyncRun,
@@ -22,9 +28,6 @@ from products.warehouse_sources.backend.facade.hooks import BINDING_KIND_SAVED_Q
logger = structlog.get_logger(__name__)
-# Auto-disable a source after this many consecutive failures, matching the account sync path.
-MAX_CONSECUTIVE_SYNC_FAILURES = 5
-
# A run row is reconciled only within its own pipeline: the backfill path reads the whole table from
# S3, the sync path rides a warehouse import job. Keeping them apart means a scheduled sync can't
# resolve a backfill's in-progress row (and vice versa) when both are in flight for the same source.
@@ -53,7 +56,9 @@ def _parse_iso(value: str | None) -> datetime | None:
return None
-def _find_reconcilable_run(team_id: int, source, record: PersonPropertySyncRunRecord):
+def _find_reconcilable_run(
+ team_id: int, source: CustomPropertySource, record: PersonPropertySyncRunRecord
+) -> CustomPropertySyncRun | None:
"""The existing row this record belongs to, or None to insert a new one.
Scheduled runs ride a warehouse import job whose activity retries up to 3 times, so they dedup on
@@ -61,7 +66,7 @@ def _find_reconcilable_run(team_id: int, source, record: PersonPropertySyncRunRe
the failure) each attempt. Otherwise the record reconciles the newest in-progress row from its own
pipeline — either a placeholder the UI created on "Sync now"/"Backfill" (progress + double-submit
guard) or the row the activity opened when it started."""
- runs = CustomPropertySyncRun.objects.for_team(team_id).filter(source=source)
+ runs = CustomPropertySyncRun.objects.for_team(team_id).select_for_update().filter(source=source)
if record.job_id:
run = runs.filter(job_id=record.job_id).order_by("-created_at").first()
if run is not None:
@@ -71,9 +76,6 @@ def _find_reconcilable_run(team_id: int, source, record: PersonPropertySyncRunRe
def record_sync_run(record: PersonPropertySyncRunRecord) -> None:
- """Create or reconcile the run row and update the source's status fields. A ``running`` record
- only opens the row — the source's status fields are folded in when the run reaches a terminal
- state. Swallows its own errors: run bookkeeping must never fail the sync that produced it."""
log = logger.bind(
team_id=record.team_id,
source_id=record.source_id,
@@ -83,90 +85,79 @@ def record_sync_run(record: PersonPropertySyncRunRecord) -> None:
status=record.status,
)
try:
- source = CustomPropertySource.objects.for_team(record.team_id).filter(id=record.source_id).first()
- if source is None:
- # The source was deleted between the run starting and finishing — nothing to record.
- log.info("person-property run recorder: source no longer exists, skipping")
- return
-
- finished_at = _parse_iso(record.finished_at)
- succeeded = record.status == SyncStatus.COMPLETED.value
-
- run = _find_reconcilable_run(record.team_id, source, record)
- # Captured before the row is overwritten below: an activity retry re-recording the same
- # already-failed job must not increment consecutive_failures again (that would auto-disable
- # the source from retry noise rather than distinct failed syncs).
- already_failed = run is not None and run.status == SyncStatus.FAILED.value
-
- fields: dict = {
- **_binding_fields(record),
- "job_id": record.job_id,
- "trigger": record.trigger,
- "status": record.status,
- "started_at": _parse_iso(record.started_at),
- "finished_at": finished_at,
- "rows_read": record.rows_read,
- "changed": record.changed,
- "existing": record.existing,
- "produced": record.produced,
- "skipped_missing_person": record.skipped_missing_person,
- "error": record.error,
- }
- if run is not None:
- # The pipeline reports every import-driven run as "scheduled"; don't relabel a row the
- # user started that way.
- if run.trigger in _USER_TRIGGERS:
- fields.pop("trigger")
- for attr, value in fields.items():
- setattr(run, attr, value)
- run.save()
- else:
- CustomPropertySyncRun.objects.for_team(record.team_id).create(
- team_id=record.team_id, source=source, **fields
+ with transaction.atomic():
+ source = (
+ CustomPropertySource.objects.for_team(record.team_id)
+ .select_for_update()
+ .filter(id=record.source_id)
+ .first()
)
+ if source is None:
+ log.info("person-property run recorder: source no longer exists, skipping")
+ return
+
+ finished_at = _parse_iso(record.finished_at)
+ succeeded = record.status == SyncStatus.COMPLETED.value
+ run = _find_reconcilable_run(record.team_id, source, record)
+ already_failed = run is not None and run.status == SyncStatus.FAILED.value
+
+ fields: dict = {
+ **_binding_fields(record),
+ "job_id": record.job_id,
+ "trigger": record.trigger,
+ "status": record.status,
+ "started_at": _parse_iso(record.started_at),
+ "finished_at": finished_at,
+ "rows_read": record.rows_read,
+ "changed": record.changed,
+ "existing": record.existing,
+ "produced": record.produced,
+ "skipped_missing_person": record.skipped_missing_person,
+ "error": record.error,
+ }
+ if run is not None:
+ if run.trigger in _USER_TRIGGERS:
+ fields.pop("trigger")
+ for attr, value in fields.items():
+ setattr(run, attr, value)
+ run.save()
+ else:
+ run = CustomPropertySyncRun.objects.for_team(record.team_id).create(
+ team_id=record.team_id, source=source, **fields
+ )
- if record.status == SyncStatus.RUNNING.value:
- # The run has only opened — nothing to fold onto the source until it settles, and
- # clearing the last error here would hide a still-relevant failure.
- log.info("person-property run recorded: running")
- return
-
- if succeeded:
- # Idempotent: safe to fold onto the source again if a prior attempt failed then a retry
- # succeeded — resets the failure streak and stamps the last-synced time.
- source.last_synced_at = finished_at
- source.last_sync_error = None
- source.consecutive_failures = 0
- source.save(update_fields=["last_synced_at", "last_sync_error", "consecutive_failures", "updated_at"])
- log.info(
- "person-property run recorded: completed",
- rows_read=record.rows_read,
- changed=record.changed,
- existing=record.existing,
- produced=record.produced,
- skipped_missing_person=record.skipped_missing_person,
- )
- else:
- if not already_failed:
- source.consecutive_failures = (source.consecutive_failures or 0) + 1
- source.last_sync_error = record.error
- auto_disabled = source.consecutive_failures >= MAX_CONSECUTIVE_SYNC_FAILURES
- if auto_disabled:
- source.is_enabled = False
- source.save(update_fields=["consecutive_failures", "last_sync_error", "is_enabled", "updated_at"])
- log.warning(
- "person-property run recorded: failed",
- consecutive_failures=source.consecutive_failures,
- auto_disabled=auto_disabled,
- error=record.error,
- )
- if auto_disabled:
- log.error(
- "person-property source auto-disabled after consecutive failures",
+ if record.status == SyncStatus.RUNNING.value:
+ log.info("person-property run recorded: running")
+ return
+
+ if succeeded:
+ record_sync_success(source, finished_at=finished_at)
+ log.info(
+ "person-property run recorded: completed",
+ rows_read=record.rows_read,
+ changed=record.changed,
+ existing=record.existing,
+ produced=record.produced,
+ skipped_missing_person=record.skipped_missing_person,
+ )
+ else:
+ auto_disabled = record_sync_failure(
+ source,
+ error=record.error,
+ disable_event_id=record.job_id or str(run.id),
+ count_failure=not already_failed,
+ )
+ log.warning(
+ "person-property run recorded: failed",
consecutive_failures=source.consecutive_failures,
+ auto_disabled=auto_disabled,
+ error=record.error,
)
- except Exception as e:
- # Run bookkeeping must never fail the sync/backfill that produced it, but the failure itself
- # is worth surfacing — a persistently failing recorder means the UI silently drifts from reality.
+ if auto_disabled:
+ log.error(
+ "person-property source auto-disabled after consecutive failures",
+ consecutive_failures=source.consecutive_failures,
+ )
+ except Exception as error:
log.exception("person-property run recorder failed")
- capture_exception(e)
+ capture_exception(error)
diff --git a/products/customer_analytics/backend/logic/person_property_runs_test.py b/products/customer_analytics/backend/logic/person_property_runs_test.py
index 8a929b1c9191..d548cae582d8 100644
--- a/products/customer_analytics/backend/logic/person_property_runs_test.py
+++ b/products/customer_analytics/backend/logic/person_property_runs_test.py
@@ -2,13 +2,12 @@ from datetime import UTC, datetime
from uuid import uuid4
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from parameterized import parameterized
-from products.customer_analytics.backend.logic.person_property_runs import (
- MAX_CONSECUTIVE_SYNC_FAILURES,
- record_sync_run,
-)
+from products.customer_analytics.backend.logic.custom_property_source_health import MAX_CONSECUTIVE_SYNC_FAILURES
+from products.customer_analytics.backend.logic.person_property_runs import record_sync_run
from products.customer_analytics.backend.models import CustomPropertySource, CustomPropertySyncRun, TargetType
from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
from products.customer_analytics.backend.test.factories import create_custom_property_definition
@@ -16,6 +15,8 @@ from products.warehouse_sources.backend.facade.hooks import PersonPropertySyncRu
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+HEALTH_SERVICE = "products.customer_analytics.backend.logic.custom_property_source_health"
+
class TestRecordSyncRun(TeamScopedTestMixin, APIBaseTest):
def setUp(self):
@@ -195,3 +196,16 @@ class TestRecordSyncRun(TeamScopedTestMixin, APIBaseTest):
run = CustomPropertySyncRun.objects.unscoped().get(source_id=self.source.id)
assert str(run.saved_query_id) == "7bd1a4de-0000-4000-8000-000000000001"
assert run.schema_id is None
+
+ @patch(f"{HEALTH_SERVICE}.notify_source_auto_disabled")
+ def test_the_disabling_failure_tells_the_owner_once_across_retries(self, mock_notify):
+ self.source.consecutive_failures = MAX_CONSECUTIVE_SYNC_FAILURES - 1
+ self.source.save()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ record_sync_run(self._record(status="failed", error="boom"))
+ record_sync_run(self._record(status="failed", error="boom"))
+
+ self.source.refresh_from_db()
+ assert self.source.is_enabled is False
+ mock_notify.assert_called_once_with(team_id=self.team.id, source_id=self.source.id, disable_event_id="job-1")
diff --git a/products/customer_analytics/backend/test/test_custom_property_source_disabled_notice.py b/products/customer_analytics/backend/test/test_custom_property_source_disabled_notice.py
new file mode 100644
index 000000000000..b6c39f40564d
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_custom_property_source_disabled_notice.py
@@ -0,0 +1,214 @@
+from datetime import UTC, datetime, time
+from zoneinfo import ZoneInfo
+
+import time_machine
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.access_control.backend.models.access_control import AccessControl
+from products.customer_analytics.backend.facade import contracts
+from products.customer_analytics.backend.logic.custom_property_source_disabled_notice import (
+ CONFIGURATION_ACCOUNTS_PATH,
+ notify_source_auto_disabled,
+)
+from products.customer_analytics.backend.logic.customer_task_digest import build_customer_task_digest
+from products.customer_analytics.backend.logic.customer_tasks import list_customer_tasks
+from products.customer_analytics.backend.logic.task_digest_delivery import task_digest_enabled
+from products.customer_analytics.backend.models import (
+ CustomerTask,
+ CustomerTaskActivity,
+ CustomPropertySource,
+ UserCustomerAnalyticsConfig,
+)
+from products.customer_analytics.backend.models.customer_task import CustomerTaskStatus
+from products.customer_analytics.backend.test.factories import create_custom_property_definition
+from products.notifications.backend.facade.enums import NotificationType, Priority, TargetType
+
+SERVICE = "products.customer_analytics.backend.logic.custom_property_source_disabled_notice"
+
+
+@time_machine.travel("2026-09-18T18:00:00Z", tick=False)
+@patch(f"{SERVICE}.posthog_feature_flag_enabled", return_value=True)
+@patch(f"{SERVICE}.create_notification")
+class TestNotifySourceAutoDisabled(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.timezone = "America/Los_Angeles"
+ self.team.save(update_fields=["timezone"])
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan tier")
+ self.source = CustomPropertySource.objects.for_team(self.team.id).create(
+ team=self.team,
+ definition=definition,
+ created_by=self.user,
+ key_column="external_id",
+ source_column="plan",
+ is_enabled=False,
+ )
+
+ def _notify(self, disable_event_id: str = "job-1") -> None:
+ notify_source_auto_disabled(team_id=self.team.id, source_id=self.source.id, disable_event_id=disable_event_id)
+
+ def test_the_owner_gets_one_notification_pointing_at_configuration(self, mock_create, _mock_flag) -> None:
+ self._notify()
+
+ data = mock_create.call_args.args[0]
+ assert data.notification_type == NotificationType.PIPELINE_FAILURE
+ assert data.priority == Priority.NORMAL
+ assert data.target_type == TargetType.USER
+ assert data.target_id == str(self.user.id)
+ assert data.title == "Warehouse property sync disabled: Plan tier"
+ assert data.source_url == CONFIGURATION_ACCOUNTS_PATH
+ assert data.source_id == str(self.source.id)
+ assert data.idempotency_key.startswith(f"custom-property-source:{self.source.id}:disabled:")
+ assert len(data.idempotency_key) <= 128
+
+ def test_the_notification_body_keeps_the_raw_warehouse_error_out(self, mock_create, _mock_flag) -> None:
+ self.source.last_sync_error = "could not connect to warehouse-host-42: relation users missing"
+ self.source.save()
+
+ self._notify()
+
+ assert "warehouse-host-42" not in mock_create.call_args.args[0].body
+
+ def test_one_open_task_is_visible_to_the_owner_and_digest(self, _mock_create, _mock_flag) -> None:
+ config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).create(
+ team=self.team,
+ user=self.user,
+ properties={"task_digest": {"enabled": True, "send_time": "09:00", "cadence": "weekdays"}},
+ )
+
+ self._notify()
+
+ task = CustomerTask.objects.for_team(self.team.id).get()
+ assert task.name == "Fix warehouse property sync: Plan tier"
+ assert task.assigned_to_id == self.user.id
+ assert task.account_id is None
+ assert task.status == CustomerTaskStatus.OPEN
+ assert task.created_by_id is None
+ assert task.due_at is not None
+ local_due_at = task.due_at.astimezone(ZoneInfo(self.team.timezone))
+ assert local_due_at.date().isoformat() == "2026-09-21"
+ assert local_due_at.time() == time(23, 59, 59)
+
+ access = UserAccessControl(user=self.user, team=self.team)
+ tasks, count = list_customer_tasks(
+ team_id=self.team.id,
+ user_access_control=access,
+ filters=contracts.CustomerTaskListFilters(assigned_to="me"),
+ offset=0,
+ limit=10,
+ )
+ assert count == 1
+ assert [item.id for item in tasks] == [task.id]
+ with patch(
+ "products.customer_analytics.backend.logic.task_digest_delivery.posthoganalytics.feature_enabled",
+ return_value=True,
+ ):
+ assert task_digest_enabled(config)
+ digest = build_customer_task_digest(
+ user=self.user,
+ team=self.team,
+ reference_time=datetime(2026, 9, 21, 12, tzinfo=UTC),
+ )
+ assert digest is not None
+ assert [item.name for item in digest.due_today] == [task.name]
+
+ def test_a_repeated_delivery_creates_one_task_activity_and_access_grant(self, _mock_create, _mock_flag) -> None:
+ self._notify()
+ self._notify()
+
+ task = CustomerTask.objects.for_team(self.team.id).get()
+ assert CustomerTaskActivity.objects.for_team(self.team.id).filter(task=task).count() == 1
+ assert (
+ AccessControl.objects.filter(
+ team=self.team,
+ resource="customer_task",
+ resource_id=str(task.id),
+ access_level="editor",
+ ).count()
+ == 1
+ )
+
+ def test_a_later_disablement_creates_a_second_task(self, _mock_create, _mock_flag) -> None:
+ self._notify(disable_event_id="job-1")
+ self._notify(disable_event_id="job-2")
+
+ assert CustomerTask.objects.for_team(self.team.id).count() == 2
+
+ def test_long_job_ids_fit_notification_idempotency_limits(self, mock_create, _mock_flag) -> None:
+ self._notify(disable_event_id="j" * 400)
+
+ data = mock_create.call_args.args[0]
+ assert len(data.idempotency_key) <= 128
+ assert len(data.source_id) <= 64
+
+ def test_an_inactive_owner_is_skipped_without_notifying_the_project(self, mock_create, _mock_flag) -> None:
+ self.user.is_active = False
+ self.user.save()
+
+ self._notify()
+
+ mock_create.assert_not_called()
+ assert not CustomerTask.objects.for_team(self.team.id).exists()
+
+ def test_a_source_with_no_owner_is_skipped(self, mock_create, _mock_flag) -> None:
+ self.source.created_by = None
+ self.source.save()
+
+ self._notify()
+
+ mock_create.assert_not_called()
+ assert not CustomerTask.objects.for_team(self.team.id).exists()
+
+ def test_an_owner_without_project_membership_is_skipped(self, mock_create, _mock_flag) -> None:
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).delete()
+
+ self._notify()
+
+ mock_create.assert_not_called()
+ assert not CustomerTask.objects.for_team(self.team.id).exists()
+
+ def test_the_notification_still_goes_out_when_tasks_are_flag_disabled(self, mock_create, mock_flag) -> None:
+ mock_flag.return_value = False
+
+ self._notify()
+
+ mock_create.assert_called_once()
+ assert not CustomerTask.objects.for_team(self.team.id).exists()
+
+ def test_the_notification_still_goes_out_when_task_access_is_disabled(self, mock_create, _mock_flag) -> None:
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.ACCESS_CONTROL, "key": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="customer_analytics",
+ resource_id=None,
+ organization_member=membership,
+ access_level="none",
+ )
+
+ self._notify()
+
+ mock_create.assert_called_once()
+ assert not CustomerTask.objects.for_team(self.team.id).exists()
+
+ def test_a_failed_notification_does_not_stop_the_task(self, mock_create, _mock_flag) -> None:
+ mock_create.side_effect = RuntimeError("transport down")
+
+ self._notify()
+
+ assert CustomerTask.objects.for_team(self.team.id).count() == 1
+
+ def test_a_failed_task_does_not_stop_the_notification(self, mock_create, _mock_flag) -> None:
+ with patch(f"{SERVICE}.create_customer_task", side_effect=RuntimeError("task unavailable")):
+ self._notify()
+
+ mock_create.assert_called_once()
+ assert not CustomerTask.objects.for_team(self.team.id).exists()
diff --git a/products/customer_analytics/skills/references/troubleshooting.md b/products/customer_analytics/skills/references/troubleshooting.md
index 17e1eeefca78..0becaa27f5d7 100644
--- a/products/customer_analytics/skills/references/troubleshooting.md
+++ b/products/customer_analytics/skills/references/troubleshooting.md
@@ -35,7 +35,10 @@ Check, in order: the source's `is_enabled`, whether the underlying table is stil
**`last_sync_error` is set, or `consecutive_failures` is climbing.**
Read the error text on the source and on the most recent run. Treat a failing underlying warehouse sync as
the first suspect, because the property update rides off that sync. Diagnose that with
-`diagnosing-failed-warehouse-syncs` before touching the mapping.
+`diagnosing-failed-warehouse-syncs` before touching the mapping. After five consecutive failures, PostHog
+disables the source and notifies the person who configured it. If Customer analytics tasks are available to
+that person, PostHog also assigns them a task due by the end of the next business day. The task enters an email
+digest only when that person has enabled task digests.
**"Sync now" is rejected with a monthly sync limit message.**
`custom-property-sources-sync` runs a real, billable import, so it honors the team's sync pause the same way
diff --git a/products/customer_analytics/skills/setting-up-warehouse-properties/SKILL.md b/products/customer_analytics/skills/setting-up-warehouse-properties/SKILL.md
index d3ebfb51a6ad..9b8a22d618d4 100644
--- a/products/customer_analytics/skills/setting-up-warehouse-properties/SKILL.md
+++ b/products/customer_analytics/skills/setting-up-warehouse-properties/SKILL.md
@@ -130,6 +130,9 @@ A run that reads rows but shows `existing: 0` is the wrong-key-column case almos
update" is answered by the table's sync frequency.
- A source that fails repeatedly is **disabled automatically** after five consecutive failures. Re-enabling it
resets the streak and triggers a fresh backfill.
+- When that happens, the person who created the source gets a notification. If Customer analytics tasks are
+ available to them, PostHog also assigns them a task. The task reaches email only if they have turned the task
+ digest on.
- "Sync now" runs the underlying table, which for a synced table is a real, billable warehouse sync, and for a
materialized view is a materialization. It is not a cheap no-op — do not call it to "check" a mapping when
`custom-property-sources-runs-list` answers the question for free.