: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
feat(data-warehouse): show in-progress person/group property syncs (#78269)
Tom Owersbf6eb6478117
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex b56437607019..4bf2db1291d7 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -16,7 +16,7 @@ Do NOT:"""from collections.abc import Iterable-from datetime import datetime+from datetime import datetime, timedeltafrom enum import Enumfrom typing import TYPE_CHECKING, Any, Optional, castfrom uuid import UUID@@ -91,6 +91,7 @@ from products.customer_analytics.backend.models import (EventStream,EventStreamMember,SyncStatus,+ SyncTrigger,TargetType,)from products.customer_analytics.backend.models.account import (@@ -1344,6 +1345,7 @@ def _to_custom_property_source_view(if isinstance(enrichment, _ResolveEnrichmentInline):schema = _resolve_person_source_schema(source, user_access_control)latest = source.sync_runs.order_by("-created_at").first() if schema is not None else None+ _expire_stale_running_runs(source.team_id, [latest])else:schema, latest = enrichmentif schema is not None:@@ -1406,6 +1408,7 @@ def _batch_source_enrichment(.distinct("source_id")}enrichment: dict[Any, tuple[Any, CustomPropertySyncRun | None]] = {}+ authorized_runs: list[CustomPropertySyncRun | None] = []for source in person_sources:schema = schemas_by_id.get(source.external_data_schema_id)if (@@ -1415,7 +1418,12 @@ def _batch_source_enrichment():schema = Nonelatest = latest_run_by_source_id.get(source.id) if schema is not None else None+ # Only mutate runs the caller can view; expiring runs for hidden schemas would let a+ # denied viewer flip their status through the source-list endpoint.+ if latest is not None:+ authorized_runs.append(latest)enrichment[source.id] = (schema, latest)+ _expire_stale_running_runs(team_id, authorized_runs)return enrichment@@ -1489,11 +1497,40 @@ def _enqueue_sync_if_enabled(source: CustomPropertySource) -> None:_WAREHOUSE_PROFILE_TARGETS = (TargetType.PERSON.value, TargetType.GROUP.value)+# A run row only reaches a terminal state when its activity records one, so a sync that died before+# getting there — an import that failed ahead of the person-property step, a killed worker — would sit+# "running" forever, misreporting the source and keeping its sync/backfill buttons disabled. Six hours+# matches the sync activity's start_to_close timeout, so nothing live is behind an older row.+STALE_RUNNING_RUN_AFTER = timedelta(hours=6)+STALE_RUNNING_RUN_ERROR = "This run never reported a result. The sync may have failed before it ran."+++def _expire_stale_running_runs(team_id: int, runs: "Iterable[CustomPropertySyncRun | None]") -> None:+ """Fail abandoned 'running' rows, both in the database and in the passed-in objects so the caller+ serializes what it just wrote. Runs on the read paths the UI polls, so a stuck row self-heals."""+ cutoff = timezone.now() - STALE_RUNNING_RUN_AFTER+ stale = [+ run+ for run in runs+ if run is not None and run.status == SyncStatus.RUNNING.value and (run.started_at or run.created_at) < cutoff+ ]+ if not stale:+ return+ finished_at = timezone.now()+ CustomPropertySyncRun.objects.for_team(team_id).filter(id__in=[run.id for run in stale]).update(+ status=SyncStatus.FAILED.value, finished_at=finished_at, error=STALE_RUNNING_RUN_ERROR+ )+ for run in stale:+ run.status = SyncStatus.FAILED.value+ run.finished_at = finished_at+ run.error = STALE_RUNNING_RUN_ERROR++def _create_running_runs(team_id: int, schema_id: str, trigger: str) -> list[Any]:"""Insert a 'running' run for each enabled person/group source on the schema that isn't already- running. The UI shows these as in-progress and disables the trigger while they exist; the backfill- activity reconciles them to their terminal state (see record_sync_run). Skipping sources that- already have a running run makes this a no-op when a backfill for the table is already in flight+ running. The UI shows these as in-progress and disables the trigger while they exist; the sync and+ backfill activities reconcile them to their terminal state (see record_sync_run). Skipping sources+ that already have a running run makes this a no-op when a run for the table is already in flight(coalesced). Returns the source ids a placeholder was created for, so the caller can reconcile themto FAILED if the workflow start never happens (see ``_fail_created_runs``)."""with transaction.atomic():@@ -1510,11 +1547,12 @@ def _create_running_runs(team_id: int, schema_id: str, trigger: str) -> list[Any)if not sources:return []- already_running = set(- CustomPropertySyncRun.objects.for_team(team_id)- .filter(source__in=sources, status=SyncStatus.RUNNING.value)- .values_list("source_id", flat=True)+ running = list(+ CustomPropertySyncRun.objects.for_team(team_id).filter(source__in=sources, status=SyncStatus.RUNNING.value))+ # An abandoned row must not coalesce away a fresh trigger.+ _expire_stale_running_runs(team_id, running)+ already_running = {run.source_id for run in running if run.status == SyncStatus.RUNNING.value}to_create = [source for source in sources if source.id not in already_running]now = timezone.now()CustomPropertySyncRun.objects.bulk_create(@@ -1641,10 +1679,18 @@ def trigger_person_property_sync(trigger_schema_sync,)+ # Open the run rows before the sync starts, so the history shows it in progress right away and the+ # trigger buttons stay disabled until it settles. The person-property activity reconciles them+ # when the import reaches it (see record_sync_run).+ created_source_ids = _create_running_runs(team_id, schema_id, SyncTrigger.SYNC.value)try:trigger_schema_sync(team_id=team_id, schema_id=schema_id)except ExternalDataSchemaSyncPausedError as e:+ _fail_created_runs(team_id, created_source_ids, "Warehouse syncs are paused for this project")raise WarehouseSyncPausedError(str(e)) from e+ except Exception:+ _fail_created_runs(team_id, created_source_ids, "Failed to start sync")+ raisereturn True@@ -1837,7 +1883,8 @@ def list_custom_property_sync_runs(_assert_warehouse_source_viewer(team_id, source.external_data_schema_id, user_access_control)queryset = CustomPropertySyncRun.objects.for_team(team_id).filter(source_id=source_id).order_by("-created_at")total_count = queryset.count()- page = queryset[offset : offset + limit]+ page = list(queryset[offset : offset + limit])+ _expire_stale_running_runs(team_id, page)return [_to_sync_run_view(run) for run in page], total_countdiff --git a/products/customer_analytics/backend/facade/custom_property_source_person_test.py b/products/customer_analytics/backend/facade/custom_property_source_person_test.pyindex 18f926d07a5c..75433a7075f2 100644--- a/products/customer_analytics/backend/facade/custom_property_source_person_test.py+++ b/products/customer_analytics/backend/facade/custom_property_source_person_test.py@@ -1,12 +1,15 @@+from datetime import timedeltafrom uuid import uuid4from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.utils import timezone+from parameterized import parameterizedfrom products.customer_analytics.backend.facade import api-from products.customer_analytics.backend.models import CustomPropertySource, TargetType+from products.customer_analytics.backend.models import CustomPropertySource, CustomPropertySyncRun, TargetTypefrom products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixinfrom products.customer_analytics.backend.test.factories import create_custom_property_definitionfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -261,6 +264,89 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):self.team.id, source.id, offset=0, limit=10, user_access_control=self._uac(allowed=False))+ @patch("products.warehouse_sources.backend.facade.temporal.trigger_schema_sync")+ @patch("products.customer_analytics.backend.facade.api.person_properties_flag_enabled", return_value=True)+ def test_trigger_sync_opens_a_running_run(self, _flag, _trigger_schema_sync):+ # The sync itself only records a run once it finishes, so without this the history stays blank+ # and the trigger buttons stay clickable for the whole import.+ source = self._create(user_access_control=self._uac(allowed=True))+ assert (+ api.trigger_person_property_sync(+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=True)+ )+ is True+ )++ run = CustomPropertySyncRun.objects.unscoped().get(source_id=source.id)+ assert run.status == "running" and run.trigger == "sync"+ assert run.started_at is not None and run.finished_at is None++ @patch(+ "products.warehouse_sources.backend.facade.temporal.trigger_schema_sync",+ side_effect=RuntimeError("temporal unreachable"),+ )+ @patch("products.customer_analytics.backend.facade.api.person_properties_flag_enabled", return_value=True)+ def test_trigger_sync_fails_its_run_when_the_sync_never_starts(self, _flag, _trigger_schema_sync):+ # Nothing downstream will reconcile a run whose sync never started, so it would sit 'running'+ # and keep the source's buttons disabled.+ source = self._create(user_access_control=self._uac(allowed=True))+ with self.assertRaises(RuntimeError):+ api.trigger_person_property_sync(+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=True)+ )++ run = CustomPropertySyncRun.objects.unscoped().get(source_id=source.id)+ assert run.status == "failed" and run.error == "Failed to start sync"++ @parameterized.expand(+ [+ ("stale", api.STALE_RUNNING_RUN_AFTER + timedelta(minutes=1), "failed"),+ ("in_flight", timedelta(minutes=5), "running"),+ ]+ )+ def test_abandoned_running_runs_expire_when_read(self, _name, age, expected_status):+ # A run whose activity died never reaches a terminal state on its own; left alone it reports the+ # source as perpetually syncing and blocks every retry.+ source = self._create(user_access_control=self._uac(allowed=True))+ run = CustomPropertySyncRun.objects.create(+ team_id=self.team.id,+ source_id=source.id,+ schema_id=self.schema.id,+ trigger="sync",+ status="running",+ started_at=timezone.now() - age,+ )++ views, _ = api.list_custom_property_sync_runs(+ self.team.id, source.id, offset=0, limit=10, user_access_control=self._uac(allowed=True)+ )++ assert views[0].status == expected_status+ run.refresh_from_db()+ assert run.status == expected_status++ def test_listing_sources_only_expires_runs_the_caller_can_view(self):+ # The source-list page expires abandoned running runs as it enriches. A caller denied+ # warehouse-source viewer access can't see the source's status, so it must not flip that+ # source's run either — otherwise the list endpoint mutates rows hidden from the caller.+ source = self._create(user_access_control=self._uac(allowed=True))+ run = CustomPropertySyncRun.objects.create(+ team_id=self.team.id,+ source_id=source.id,+ schema_id=self.schema.id,+ trigger="sync",+ status="running",+ started_at=timezone.now() - (api.STALE_RUNNING_RUN_AFTER + timedelta(minutes=1)),+ )++ api.list_custom_property_sources(self.team.id, offset=0, limit=10, user_access_control=self._uac(allowed=False))+ run.refresh_from_db()+ assert run.status == "running"++ api.list_custom_property_sources(self.team.id, offset=0, limit=10, user_access_control=self._uac(allowed=True))+ run.refresh_from_db()+ assert run.status == "failed"+@patch("products.customer_analytics.backend.facade.api.person_properties_flag_enabled", return_value=True)def test_triggers_reject_disabled_source(self, _flag):# A disabled source can't be re-triggered: sync returns False (→ 400) and backfill None (→ 400).diff --git a/products/customer_analytics/backend/logic/person_property_runs.py b/products/customer_analytics/backend/logic/person_property_runs.pyindex 59452c276f14..5f80cdf12f02 100644--- a/products/customer_analytics/backend/logic/person_property_runs.py+++ b/products/customer_analytics/backend/logic/person_property_runs.py@@ -25,9 +25,15 @@ logger = structlog.get_logger(__name__)# Auto-disable a source after this many consecutive failures, matching the account sync path.MAX_CONSECUTIVE_SYNC_FAILURES = 5-# Triggers that pre-create a "running" row (from the UI/auto path) which this recorder then reconciles-# to its terminal state, so one backfill is one row rather than a running + a completed pair.-_UI_TRIGGERS = frozenset({SyncTrigger.MANUAL.value, SyncTrigger.BACKFILL.value})+# 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.+_BACKFILL_TRIGGERS = frozenset({SyncTrigger.MANUAL.value, SyncTrigger.BACKFILL.value})+_SYNC_TRIGGERS = frozenset({SyncTrigger.SCHEDULED.value, SyncTrigger.SYNC.value})++# Triggers set by a user action. The pipeline reports every import-driven run as "scheduled", so a+# row created by "Sync now" keeps its own trigger when the terminal record lands on it.+_USER_TRIGGERS = frozenset({SyncTrigger.SYNC.value, SyncTrigger.MANUAL.value})def _parse_iso(value: str | None) -> datetime | None:@@ -39,9 +45,27 @@ def _parse_iso(value: str | None) -> datetime | None:return None+def _find_reconcilable_run(team_id: int, source, record: PersonPropertySyncRunRecord):+ """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+ job_id: a retried attempt updates the one row instead of inserting a fresh row (and re-counting+ 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)+ if record.job_id:+ run = runs.filter(job_id=record.job_id).order_by("-created_at").first()+ if run is not None:+ return run+ triggers = _BACKFILL_TRIGGERS if record.trigger in _BACKFILL_TRIGGERS else _SYNC_TRIGGERS+ return runs.filter(status=SyncStatus.RUNNING.value, trigger__in=triggers).order_by("-created_at").first()++def record_sync_run(record: PersonPropertySyncRunRecord) -> None:- """Create the run row and update the source's status fields. Swallows its own errors: run- bookkeeping must never fail the sync that produced it."""+ """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,@@ -59,26 +83,7 @@ def record_sync_run(record: PersonPropertySyncRunRecord) -> None:finished_at = _parse_iso(record.finished_at)succeeded = record.status == SyncStatus.COMPLETED.value- # Manual/backfill runs pre-create a "running" row (UI progress + double-submit guard);- # reconcile the newest one to its terminal state so it's one row, not a running+terminal- # pair. Scheduled runs ride a warehouse import job whose activity retries up to 3 times, so- # dedup them on job_id: a retried attempt updates the one row instead of inserting a fresh- # row (and re-counting the failure) each attempt.- run = None- if record.trigger in _UI_TRIGGERS:- run = (- CustomPropertySyncRun.objects.for_team(record.team_id)- .filter(source=source, status=SyncStatus.RUNNING.value)- .order_by("-created_at")- .first()- )- elif record.job_id:- run = (- CustomPropertySyncRun.objects.for_team(record.team_id)- .filter(source=source, job_id=record.job_id)- .order_by("-created_at")- .first()- )+ 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).@@ -99,6 +104,10 @@ def record_sync_run(record: PersonPropertySyncRunRecord) -> None:"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()@@ -107,6 +116,12 @@ def record_sync_run(record: PersonPropertySyncRunRecord) -> None: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.diff --git a/products/customer_analytics/backend/logic/person_property_runs_test.py b/products/customer_analytics/backend/logic/person_property_runs_test.pyindex 39800007e6b9..7e758a78e1f1 100644--- a/products/customer_analytics/backend/logic/person_property_runs_test.py+++ b/products/customer_analytics/backend/logic/person_property_runs_test.py@@ -3,6 +3,8 @@ from uuid import uuid4from posthog.test.base import APIBaseTest+from parameterized import parameterized+from products.customer_analytics.backend.logic.person_property_runs import (MAX_CONSECUTIVE_SYNC_FAILURES,record_sync_run,@@ -112,17 +114,51 @@ class TestRecordSyncRun(TeamScopedTestMixin, APIBaseTest):assert run.id == placeholder.idassert run.status == "completed" and run.produced == 5- def test_scheduled_run_leaves_a_running_placeholder_untouched(self):- # A scheduled sync must not hijack a backfill's running placeholder; it always inserts its own.+ @parameterized.expand([("running",), ("completed",)])+ def test_scheduled_run_leaves_a_running_placeholder_untouched(self, status):+ # A scheduled sync must not hijack a backfill's running placeholder — not when it opens its own+ # run either; it always inserts its own row.placeholder = CustomPropertySyncRun.objects.create(team_id=self.team.id, source=self.source, schema_id=self.schema_id, trigger="backfill", status="running")- record_sync_run(self._record(trigger="scheduled", status="completed"))+ record_sync_run(self._record(trigger="scheduled", status=status))assert CustomPropertySyncRun.objects.unscoped().filter(source=self.source).count() == 2placeholder.refresh_from_db()assert placeholder.status == "running"+ def test_running_record_opens_a_row_without_folding_onto_the_source(self):+ # A sync that has only started says nothing about the source's health: stamping last_synced_at+ # or clearing the error would show the UI a green "Synced" for a run still in flight.+ self.source.consecutive_failures = 2+ self.source.last_sync_error = "boom"+ self.source.save()++ record_sync_run(self._record(status="running", finished_at="", rows_read=0, changed=0, existing=0, produced=0))++ run = CustomPropertySyncRun.objects.unscoped().get(source_id=self.source.id)+ assert run.status == "running" and run.finished_at is None+ self.source.refresh_from_db()+ assert self.source.consecutive_failures == 2+ assert self.source.last_sync_error == "boom"+ assert self.source.last_synced_at is None++ def test_scheduled_record_reconciles_a_sync_now_row_and_keeps_its_trigger(self):+ # "Sync now" opens the row, then rides the ordinary import pipeline, which reports itself as+ # 'scheduled'. The terminal record must land on that row rather than adding a second one, and+ # must not relabel a run the user asked for as scheduled.+ opened = CustomPropertySyncRun.objects.create(+ team_id=self.team.id, source=self.source, schema_id=self.schema_id, trigger="sync", status="running"+ )+ record_sync_run(self._record(trigger="scheduled", status="completed", produced=3))++ runs = CustomPropertySyncRun.objects.unscoped().filter(source=self.source)+ assert runs.count() == 1+ run = runs.get()+ assert run.id == opened.id+ assert run.status == "completed" and run.produced == 3+ assert run.trigger == "sync"+def test_scheduled_retry_dedups_on_job_id_and_counts_failure_once(self):# The scheduled sync activity retries up to 3 times, calling the recorder on each failed# attempt. Dedup on job_id so retries update the one row instead of inserting a fresh faileddiff --git a/products/customer_analytics/backend/migrations/0029_alter_custompropertysyncrun_trigger.py b/products/customer_analytics/backend/migrations/0029_alter_custompropertysyncrun_trigger.pynew file mode 100644index 000000000000..39f80e909dde--- /dev/null+++ b/products/customer_analytics/backend/migrations/0029_alter_custompropertysyncrun_trigger.py@@ -0,0 +1,25 @@+# Generated by Django 5.2.14 on 2026-08-05 11:44++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0028_accountchannelsummary_messages"),+ ]++ operations = [+ migrations.AlterField(+ model_name="custompropertysyncrun",+ name="trigger",+ field=models.CharField(+ choices=[+ ("scheduled", "scheduled"),+ ("sync", "sync"),+ ("manual", "manual"),+ ("backfill", "backfill"),+ ],+ max_length=20,+ ),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 47db7f4d92f9..7edcb6f1d46c 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0028_accountchannelsummary_messages+0029_alter_custompropertysyncrun_triggerdiff --git a/products/customer_analytics/backend/models/custom_property_sync_run.py b/products/customer_analytics/backend/models/custom_property_sync_run.pyindex 3b648fa5d590..0ea890baf7df 100644--- a/products/customer_analytics/backend/models/custom_property_sync_run.py+++ b/products/customer_analytics/backend/models/custom_property_sync_run.py@@ -7,6 +7,10 @@ from posthog.models.utils import CreatedMetaFields, UUIDModelclass SyncTrigger(models.TextChoices):# A run started automatically as a child of the underlying warehouse sync.SCHEDULED = "scheduled", "scheduled"+ # The same warehouse sync, started from the UI ("Sync now"). Rides the scheduled pipeline, so the+ # activity records its outcome as "scheduled" — the recorder keeps this trigger on the row so the+ # history still shows who asked for it.+ SYNC = "sync", "sync"# A full-table backfill the user kicked off from the UI (the "Backfill" button).MANUAL = "manual", "manual"# A full-table read from S3 to populate historical rows a new/changed mapping never saw.diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 2f9602deaf4b..5202df8a6557 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -401,7 +401,11 @@ class CustomPropertySyncRunSerializer(DataclassSerializer):id = serializers.UUIDField(read_only=True)trigger = serializers.CharField(read_only=True,- help_text="What started the run: 'scheduled' (rode a warehouse sync), 'manual', or 'backfill'.",+ help_text=(+ "What started the run: 'scheduled' (rode a warehouse sync), 'sync' (a warehouse sync "+ "started from the UI), 'manual' (a backfill started from the UI), or 'backfill' (the "+ "automatic backfill run when a mapping is created or re-enabled)."+ ),)status = serializers.CharField(read_only=True, help_text="Run status: 'running', 'completed', or 'failed'.")started_at = serializers.DateTimeField(read_only=True, allow_null=True, help_text="When the run began.")diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 0f4cdc213490..6e741b26ae0e 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -723,7 +723,7 @@ export interface CustomPropertyOptionApi {*/export interface CustomPropertySyncRunApi {readonly id: string- /** What started the run: 'scheduled' (rode a warehouse sync), 'manual', or 'backfill'. */+ /** What started the run: 'scheduled' (rode a warehouse sync), 'sync' (a warehouse sync started from the UI), 'manual' (a backfill started from the UI), or 'backfill' (the automatic backfill run when a mapping is created or re-enabled). */readonly trigger: string/** Run status: 'running', 'completed', or 'failed'. */readonly status: stringdiff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsxindex d87500a37dc6..60c9edd29fc2 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'-import { IconInfo, IconPencil, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'-import { LemonButton, LemonTable, LemonTableColumns, Tooltip } from '@posthog/lemon-ui'+import { IconPencil, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'+import { LemonButton, LemonTable, LemonTableColumns, Spinner, Tooltip } from '@posthog/lemon-ui'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'import { TZLabel } from 'lib/components/TZLabel'@@ -31,6 +31,15 @@ const TAG_TYPE_BY_RUN_STATUS: Record<string, LemonTagType> = {failed: 'danger',}+// The stored trigger values, as something a person reading their run history can act on. 'manual' is+// the Backfill button; 'backfill' is the one the system runs itself when a mapping is set up.+const RUN_TRIGGERS: Record<string, { label: string; type: LemonTagType }> = {+ scheduled: { label: 'Scheduled', type: 'default' },+ sync: { label: 'Sync now', type: 'option' },+ manual: { label: 'Backfill', type: 'option' },+ backfill: { label: 'Auto backfill', type: 'default' },+}+// Labels that differ between the person- and group-target views of the same warehouse-sync machinery.type ProfileLabels = { entity: string; entityPlural: string; keyColumn: string }const LABELS_BY_TARGET: Record<'person' | 'group', ProfileLabels> = {@@ -38,6 +47,10 @@ const LABELS_BY_TARGET: Record<'person' | 'group', ProfileLabels> = {group: { entity: 'group', entityPlural: 'groups', keyColumn: 'Group key column' },}+function RunCount({ value }: { value: number }): JSX.Element {+ return <span className={value ? 'font-medium' : 'text-secondary'}>{value}</span>+}+// Run history for one source, loaded lazily when its row is expanded.function ProfilePropertyRuns({ sourceId, labels }: { sourceId: string; labels: ProfileLabels }): JSX.Element {const { runsBySourceId, runsLoadingBySourceId } = useValues(customPropertyDefinitionsLogic)@@ -46,12 +59,19 @@ function ProfilePropertyRuns({ sourceId, labels }: { sourceId: string; labels: Pconst columns: LemonTableColumns<CustomPropertySyncRunApi> = [{title: 'Status',+ tooltip:+ 'Whether the run finished. A completed run that updated nobody is normal: a sync only looks at rows the warehouse import itself changed.',render: (_, run) => {const note = runOutcomeNote(run, labels.entityPlural)return (<div className="flex items-center gap-2"><Tooltip title={run.error ?? undefined}>- <LemonTag type={TAG_TYPE_BY_RUN_STATUS[run.status] ?? 'default'}>{run.status}</LemonTag>+ <LemonTag+ type={TAG_TYPE_BY_RUN_STATUS[run.status] ?? 'default'}+ icon={run.status === 'running' ? <Spinner /> : undefined}+ >+ {run.status}+ </LemonTag></Tooltip>{note && (<Tooltip title={note.tooltip}>@@ -62,29 +82,36 @@ function ProfilePropertyRuns({ sourceId, labels }: { sourceId: string; labels: P)},},- { title: 'Trigger', dataIndex: 'trigger' },{- title: (- <Tooltip title="Warehouse rows this sync staged. A sync only stages rows the import itself added or changed, so a quiet table reads zero.">- <span>Rows read</span>- </Tooltip>- ),- render: (_, run) => run.rows_read,+ title: 'Trigger',+ tooltip: 'What started the run: the table\'s sync schedule, or a "Sync now" or "Backfill" you asked for.',+ render: (_, run) => {+ const trigger = RUN_TRIGGERS[run.trigger]+ return <LemonTag type={trigger?.type ?? 'default'}>{trigger?.label ?? run.trigger}</LemonTag>+ },},{- title: (- <Tooltip title="Rows whose mapped values differ from what was last sent. Rows that already match are skipped, even on a full refresh.">- <span>Changed</span>- </Tooltip>- ),- render: (_, run) => run.changed,+ title: 'Rows read',+ tooltip:+ 'Warehouse rows this sync staged. A sync only stages rows the import itself added or changed, so a quiet table reads zero.',+ align: 'right',+ render: (_, run) => <RunCount value={run.rows_read} />,},{- title: `Affected ${labels.entityPlural}`,- render: (_, run) => run.existing,+ title: 'Updated',+ tooltip: `How many ${labels.entityPlural} this run updated, out of the rows whose mapped values changed. Rows that already hold the values last sent are skipped, even on a full refresh.`,+ align: 'right',+ render: (_, run) => (+ <span className="whitespace-nowrap">+ <RunCount value={run.existing} />+ <span className="text-secondary"> of {run.changed} changed</span>+ </span>+ ),},{title: `Skipped (no ${labels.entity})`,+ tooltip: `Changed rows dropped because their key column value matched no existing ${labels.entity}. The most common reason a property never shows up.`,+ align: 'right',render: (_, run) => <span className="text-secondary">{run.skipped_missing_person}</span>,},{@@ -106,6 +133,7 @@ function ProfilePropertyRuns({ sourceId, labels }: { sourceId: string; labels: Ploading={runsLoadingBySourceId[sourceId] ?? false}rowKey="id"size="small"+ nouns={['run', 'runs']}emptyState="No runs yet."/>)@@ -115,7 +143,7 @@ function ProfilePropertyRuns({ sourceId, labels }: { sourceId: string; labels: P// column mappings, shows the next scheduled sync, lets you trigger a sync or backfill, and expands to// run history. Parametrized by target so the person and group settings entries share one implementation.function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person' | 'group' }): JSX.Element {- const { definitions, definitionsLoading, triggeringSourceIds } = useValues(customPropertyDefinitionsLogic)+ const { definitions, definitionsInitialLoading, triggeringSourceIds } = useValues(customPropertyDefinitionsLogic)const { openCreateModal, openEditModal, deleteDefinition, triggerSync, triggerBackfill, loadRuns } =useActions(customPropertyDefinitionsLogic)const restrictionReason = useRestrictedArea({@@ -147,6 +175,7 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person},{title: labels.keyColumn,+ tooltip: `The warehouse column holding each row's ${targetType === 'person' ? 'distinct ID' : 'group key'}. It's how a row is matched to ${labels.entityPlural} — rows with no match are skipped.`,render: (_, definition) =>definition.source?.key_column ? (<code>{definition.source.key_column}</code>@@ -156,6 +185,7 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person},{title: 'Mapped properties',+ tooltip: `Which warehouse column is written to which ${labels.entity} property.`,render: (_, definition) => {const map = (definition.source?.column_property_map ?? {}) as Record<string, string>const entries = Object.entries(map)@@ -175,15 +205,25 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person},{title: 'Sync',+ tooltip: 'State of the most recent run. Expand the row to see the full history.',render: (_, definition) => {if (!definition.source) {return <span className="text-secondary">—</span>}+ const latestRun = definition.source.latest_run+ if (latestRun?.status === 'running') {+ return (+ <Tooltip title="A sync or backfill is running for this table right now.">+ <LemonTag type="primary" icon={<Spinner />}>+ Syncing+ </LemonTag>+ </Tooltip>+ )+ }const status = sourceSyncStatus(definition.source)// Only report an affected count for a finished run — an in-progress/failed run's count// isn't "the last run". status.tooltip is undefined for the synced/pending states, so// build the title from the present parts rather than interpolating undefined into it.- const latestRun = definition.source.latest_runconst affected = latestRun?.status === 'completed' ? latestRun.existing : undefinedconst tooltipTitle =[@@ -199,7 +239,6 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person{status.level === 'synced' && definition.source.last_synced_at && (<TZLabel time={definition.source.last_synced_at} className="text-secondary" />)}- {affected != null && <IconInfo className="text-secondary" />}</span></Tooltip>)@@ -207,6 +246,7 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person},{title: 'Next sync',+ tooltip: "When the table's warehouse sync is next due. Approximate — it drifts if the schedule was paused.",render: (_, definition) =>definition.source?.next_sync_at ? (<TZLabel time={definition.source.next_sync_at} className="text-secondary" />@@ -231,7 +271,7 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'personicon={<IconRefresh />}tooltip="Sync now — re-runs the warehouse sync for this table"onClick={() => source && triggerSync({ sourceId: source.id })}- loading={triggering}+ loading={triggering || running}disabledReason={disabledReason}/><LemonButton@@ -281,7 +321,9 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person<LemonTablecolumns={columns}dataSource={profileDefinitions}- loading={definitionsLoading}+ // Only the first load blanks the table. Polling for a running sync refreshes the same+ // list every few seconds, and a skeleton on every poll would make the page unusable.+ loading={definitionsInitialLoading}rowKey="id"expandable={{rowExpandable: (definition) => !!definition.source,diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.tsindex 06e57eb3aafa..f87193e519bf 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts@@ -41,11 +41,12 @@ export type CustomPropertyTargetType = 'account' | 'person' | 'group'// Poll until a source's run settles so the UI reflects completion without a manual refresh: fast at// first (a small table finishes in seconds), then slower, and bounded so a stuck run can't poll-// forever. 10 × 3s + 30 × 10s ≈ 5.5 minutes.+// forever. 10 × 3s + 120 × 15s ≈ 30 minutes — a "Sync now" waits on a full warehouse import, which+// takes far longer than the person-property step it triggers.const RUNS_POLL_INTERVAL_MS = 3000-const RUNS_POLL_SLOW_INTERVAL_MS = 10000+const RUNS_POLL_SLOW_INTERVAL_MS = 15000const RUNS_POLL_FAST_ATTEMPTS = 10-const RUNS_POLL_MAX_ATTEMPTS = 40+const RUNS_POLL_MAX_ATTEMPTS = 130// A run that has reached one of these is finished — anything else (including no run row yet, which// is the state right after a trigger while the workflow starts up) means keep polling.@@ -193,6 +194,7 @@ export interface customPropertyDefinitionsLogicValues {customPropertyFormTouches: Record<string, boolean>customPropertyFormValidationErrors: DeepPartialMap<CustomPropertyFormValues, ValidationErrorType>definitions: CustomPropertyDefinitionApi[]+ definitionsInitialLoading: booleandefinitionsLoading: booleaneditingDefinition: CustomPropertyDefinitionApi | nulleditingReferences: readonly CustomPropertyReferenceApi[]@@ -433,6 +435,7 @@ export interface customPropertyDefinitionsLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface customPropertyDefinitionsLogicMeta {__keaTypeGenInternalSelectorTypes: {+ definitionsInitialLoading: (definitionsLoading: boolean, definitions: CustomPropertyDefinitionApi[]) => booleanmaterializedViews: (savedQueries: DataWarehouseSavedQuery[]) => DataWarehouseSavedQuery[]selectedSourceColumns: (savedQueries: DataWarehouseSavedQuery[],@@ -840,6 +843,13 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic},})),selectors({+ // Only true before the list has ever landed. `definitionsLoading` also goes true on every+ // poll while a sync runs, and a table that blanks itself every few seconds is unusable.+ definitionsInitialLoading: [+ (s) => [s.definitionsLoading, s.definitions],+ (definitionsLoading: boolean, definitions: CustomPropertyDefinitionApi[]): boolean =>+ definitionsLoading && definitions.length === 0,+ ],materializedViews: [(s) => [s.savedQueries],(savedQueries: DataWarehouseSavedQuery[]): DataWarehouseSavedQuery[] =>diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.pyindex 4788ef1225fd..1bd21a0294f6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_sync import (record_completed_runs,record_failed_runs,+ record_started_runs,run_person_property_sync,)@@ -67,6 +68,13 @@ async def sync_warehouse_person_properties_activity(inputs: PersonPropertySyncAclog.info(f"Starting person-property sync for {inputs.source_type}/{inputs.schema_name}")start = time.monotonic()started_at = datetime.now(UTC).isoformat()+ await record_started_runs(+ team_id=inputs.team_id,+ schema_id=str(inputs.schema_id),+ job_id=inputs.job_id,+ trigger="scheduled",+ started_at=started_at,+ )try:async with Heartbeater():result = await run_person_property_sync(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.pyindex e94e82eb9de2..790c6e68903b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py@@ -672,6 +672,39 @@ def _record()+async def record_started_runs(+ *, team_id: int, schema_id: str, job_id: str | None, trigger: str, started_at: str+) -> None:+ """Open a 'running' run row per source the schema feeds, so a sync in flight shows up in the UI+ instead of appearing only once it finishes. The terminal record reconciles the same row (see+ record_sync_run). Never raises — bookkeeping must not fail the sync it describes."""+ try:+ sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(+ team_id, schema_id+ )+ for source in sources or []:+ await database_sync_to_async(_record, thread_sensitive=False)(+ team_id=team_id,+ schema_id=schema_id,+ job_id=job_id,+ trigger=trigger,+ status="running",+ started_at=started_at,+ finished_at="",+ ps=PerSourceResult(source_id=str(source.source_id)),+ error=None,+ )+ except Exception as e:+ logger.exception(+ "person-property run: failed to record started runs",+ team_id=team_id,+ schema_id=schema_id,+ job_id=job_id,+ trigger=trigger,+ )+ capture_exception(e, {"team_id": team_id, "schema_id": schema_id, "trigger": trigger})++async def record_completed_runs(*,team_id: int,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a48c9bb3844a..b78c103287df 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16536,7 +16536,7 @@ export namespace Schemas {*/export interface CustomPropertySyncRun {readonly id: string;- /** What started the run: 'scheduled' (rode a warehouse sync), 'manual', or 'backfill'. */+ /** What started the run: 'scheduled' (rode a warehouse sync), 'sync' (a warehouse sync started from the UI), 'manual' (a backfill started from the UI), or 'backfill' (the automatic backfill run when a mapping is created or re-enabled). */readonly trigger: string;/** Run status: 'running', 'completed', or 'failed'. */readonly status: string;