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(data-warehouse): add person-property sync management + backfill (#72843)

Tom Owersf45fb6a69283
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 7ccb1b10a171..5fe56dac8c93 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -99,6 +99,7 @@ rules:
|CustomOAuth2Integration
|CustomPropertyDefinition
|CustomPropertySource
+ |CustomPropertySyncRun
|CustomPropertyValue
|DAG
|Dashboard
@@ -413,6 +414,7 @@ rules:
|CustomOAuth2Integration
|CustomPropertyDefinition
|CustomPropertySource
+ |CustomPropertySyncRun
|CustomPropertyValue
|DAG
|Dashboard
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6b5d9df6a6e3..618b0db6b056 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7011,9 +7011,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-privacy--light:
hash: v1.k794b7964.8a66709400822bfa0ce716ad8ab87c844f6e255d6d147ffc1d0786ae6f0c88a4.YpDwS8AJgUCgRHrbfP00tREEmFzdh7uSlh1jUPiZwgk
scenes-app-settings-environment--settings-environment-product-analytics--dark:
- hash: v1.k794b7964.e30df90f25ceca35f4dedd3855f2e2c7db30e3af9ee7c5cd4ae9438ac1c126ab.6JpAbAsV7tuGsBzLRPrf-gM5jkVm7eUOc6v2NOjp3LY
+ hash: v1.k794b7964.f0bb165601b375795b1440ba408d76fb5a24321c168532c927ec3667a242ae37.WtinNtrrUMh5H-EeXUWPQo-C-4h1ro_YhnnqfXousu4
scenes-app-settings-environment--settings-environment-product-analytics--light:
- hash: v1.k794b7964.3695b8b1a50589b9b22613f79babe60778b46eae48ef135b8d4f8764f849770e.fwT9nSm0coPxf710QcF_HY9xWzxBZyaipgJb0A4Z0MA
+ hash: v1.k794b7964.70bf7959ecd4f39a1ac0d069beec0f6cdaf24d9afaee70e70b4cf75619f56de5.xQCvIAWzmRCUGafz6moNuItTspGJA6dwjKLb3mE16Uk
scenes-app-settings-environment--settings-environment-replay--dark:
hash: v1.k794b7964.420f87c12f0437816ce82f7e13a45851e78a6e84198cbd81262c964a90bdc47e.CaLkZAptUT5gtkAbv8PMsSfuCUSfKnhks4ojIwUks0E
scenes-app-settings-environment--settings-environment-replay--light:
@@ -7083,9 +7083,9 @@ snapshots:
scenes-app-settings-project--settings-project-integrations--light:
hash: v1.k794b7964.1934174417b65042ff2e3e967e833f604198ee713c7f7711f67b57646d9326a1.DxQZ3xs0WrHP48Y9r13SVaHcJsN4h1KJVK-NSPUSXpg
scenes-app-settings-project--settings-project-product-analytics--dark:
- hash: v1.k794b7964.c2ca88569dd635dbb5b760fb1e56ac07f5e68c8dcb4255653794dc46f7325d3f.Koq_w77vEWShB--BvyLeITY5j7jdA96Z3pwRmBV6glY
+ hash: v1.k794b7964.925784616ac6ad5cb556351ede1916440226c9089930265fc96df7e14863046c.6iXpmU_M40nsD_JokXYH4Ey-T5YaQsEB1jGl35jRBgo
scenes-app-settings-project--settings-project-product-analytics--light:
- hash: v1.k794b7964.3b73b00f400d4f8793faf7f17c775acf1d382cd78eec312858f9504c9557e328.q5KhmBFvDReRabYVObsdvnFPiHgZAKhk67YoxY60KNE
+ hash: v1.k794b7964.527360edf55b268b83ba976288336721af6da9af6088605669a4395b5a9b7a20.qnXEVYP868iG2Q0bj-z9_tORjlspkGdyJEMj5GDuG-8
scenes-app-settings-project--settings-project-replay--dark:
hash: v1.k794b7964.420f87c12f0437816ce82f7e13a45851e78a6e84198cbd81262c964a90bdc47e.MbG5FcxBuIFHRdrwoHEbyKJb_Pz8doVuDwvq1AaJeXM
scenes-app-settings-project--settings-project-replay--light:
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 24814b68e14d..14679dde9dc7 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -441,6 +441,15 @@ export const SETTINGS_MAP: SettingSection[] = [
flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],
keywords: ['accounts', 'group', 'b2b'],
},
+ {
+ id: 'customer-analytics-person-properties',
+ title: 'Person properties from the warehouse',
+ description:
+ 'Sync warehouse table columns onto matching people as person properties, and manage their schedule, backfills, and run history.',
+ component: <WarehousePersonPropertiesSetting />,
+ flag: 'WAREHOUSE_PERSON_PROPERTIES',
+ keywords: ['warehouse', 'person', 'properties', 'sync', 'backfill'],
+ },
],
},
{
@@ -906,15 +915,6 @@ export const SETTINGS_MAP: SettingSection[] = [
component: <PersonDisplayNameProperties />,
keywords: ['name', 'email', 'identity', 'display'],
},
- {
- id: 'warehouse-person-properties',
- title: 'Person properties from the warehouse',
- description:
- 'Sync columns from a data warehouse table onto matching people as person properties, usable in feature flags, cohorts and insights.',
- component: <WarehousePersonPropertiesSetting />,
- flag: 'WAREHOUSE_PERSON_PROPERTIES',
- keywords: ['warehouse', 'person', 'properties', 'sync', 'custom property'],
- },
{
id: 'person-last-seen-at',
title: 'Person last seen tracking',
diff --git a/frontend/src/scenes/settings/settingsSceneLogic.ts b/frontend/src/scenes/settings/settingsSceneLogic.ts
index d8e23cc1ab09..fa2ac5e255e3 100644
--- a/frontend/src/scenes/settings/settingsSceneLogic.ts
+++ b/frontend/src/scenes/settings/settingsSceneLogic.ts
@@ -27,6 +27,7 @@ const LEGACY_SETTINGS_SECTIONS: Record<string, SettingSectionId> = {
// section (docs, CDP filter warnings, bookmarks) redirect to the setting's current home.
const MOVED_SETTINGS: Record<string, SettingSectionId> = {
'internal-user-filtering': 'project-customization',
+ 'warehouse-person-properties': 'environment-customer-analytics',
}
const hasHashParam = (hashParams: Params, key: string): boolean => Object.prototype.hasOwnProperty.call(hashParams, key)
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index e28cb99da655..a293467638a3 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -120,6 +120,7 @@ export type SettingId =
| 'csp-reporting'
| 'customer-analytics-accounts'
| 'customer-analytics-dashboard-events'
+ | 'customer-analytics-person-properties'
| 'customer-analytics-usage-metrics'
| 'customization-irl'
| 'data-theme'
@@ -212,7 +213,6 @@ export type SettingId =
| 'path-cleaning'
| 'person-display-name'
| 'person-last-seen-at'
- | 'warehouse-person-properties'
| 'personal-api-keys'
| 'personal-integrations-github'
| 'personal-integrations-slack'
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index d573014763cc..894dc9080427 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -245,6 +245,8 @@ from products.warehouse_sources.backend.facade.temporal import (
ACTIVITIES as DATA_SYNC_ACTIVITIES,
METADATA_ACTIVITIES as DATA_WAREHOUSE_METADATA_ACTIVITIES,
METADATA_WORKFLOWS as DATA_WAREHOUSE_METADATA_WORKFLOWS,
+ PERSON_PROPERTY_BACKFILL_ACTIVITIES,
+ PERSON_PROPERTY_BACKFILL_WORKFLOWS,
PERSON_PROPERTY_SYNC_ACTIVITIES,
PERSON_PROPERTY_SYNC_WORKFLOWS,
WORKFLOWS as DATA_SYNC_WORKFLOWS,
@@ -280,8 +282,14 @@ _task_queue_specs = [
),
(
settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
- DATA_WAREHOUSE_METADATA_WORKFLOWS + SEMANTIC_ENRICHMENT_WORKFLOWS + PERSON_PROPERTY_SYNC_WORKFLOWS,
- DATA_WAREHOUSE_METADATA_ACTIVITIES + SEMANTIC_ENRICHMENT_ACTIVITIES + PERSON_PROPERTY_SYNC_ACTIVITIES,
+ DATA_WAREHOUSE_METADATA_WORKFLOWS
+ + SEMANTIC_ENRICHMENT_WORKFLOWS
+ + PERSON_PROPERTY_SYNC_WORKFLOWS
+ + PERSON_PROPERTY_BACKFILL_WORKFLOWS,
+ DATA_WAREHOUSE_METADATA_ACTIVITIES
+ + SEMANTIC_ENRICHMENT_ACTIVITIES
+ + PERSON_PROPERTY_SYNC_ACTIVITIES
+ + PERSON_PROPERTY_BACKFILL_ACTIVITIES,
),
(
settings.DATA_MODELING_TASK_QUEUE,
diff --git a/products/customer_analytics/backend/apps.py b/products/customer_analytics/backend/apps.py
index afa5cebbbb87..64b3e0fa4e96 100644
--- a/products/customer_analytics/backend/apps.py
+++ b/products/customer_analytics/backend/apps.py
@@ -17,8 +17,10 @@ class CustomerAnalyticsConfig(AppConfig):
"""
from products.warehouse_sources.backend.facade.hooks import (
PersonPropertySourceProjection,
+ PersonPropertySyncRunRecord,
PersonPropertySyncSource,
register_person_property_projection,
+ register_person_property_sync_recorder,
register_person_property_sync_sources,
)
@@ -36,5 +38,11 @@ class CustomerAnalyticsConfig(AppConfig):
return person_property_sync_sources(team_id, schema_id)
+ def _run_recorder(record: PersonPropertySyncRunRecord) -> None:
+ from products.customer_analytics.backend.logic.person_property_runs import record_sync_run # noqa: PLC0415
+
+ record_sync_run(record)
+
register_person_property_projection(_projection_resolver)
register_person_property_sync_sources(_sync_sources_resolver)
+ register_person_property_sync_recorder(_run_recorder)
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 3281f8719c49..737bf53aa047 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -24,6 +24,7 @@ from django.apps import apps
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import Exists, OuterRef, Prefetch, Q
+from django.utils import timezone
import structlog
from celery import current_app
@@ -68,7 +69,9 @@ from products.customer_analytics.backend.models import (
CustomerProfileConfig,
CustomPropertyDefinition,
CustomPropertySource,
+ CustomPropertySyncRun,
DisplayType,
+ SyncStatus,
TargetType,
)
from products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties
@@ -646,6 +649,12 @@ class ResourceForbiddenError(Exception):
matching the ``AccessControlPermission.has_object_permission`` path it replaces."""
+class WarehouseSyncPausedError(Exception):
+ """Raised when a person-property "sync now" is triggered while the team's warehouse
+ syncing is paused (monthly limit reached). The view maps this to 400 with the same
+ message the canonical warehouse schema reload/resync endpoints return."""
+
+
# Re-export the "not found" exceptions so the view can branch to 404 without importing the
# models. They are model ``DoesNotExist`` subclasses raised by the team-scoped detail fetches.
Account_DoesNotExist = Account.DoesNotExist
@@ -883,6 +892,8 @@ def delete_customer_profile_config(
def _to_custom_property_definition_view(
definition: CustomPropertyDefinition,
references: list[contracts.CustomPropertyReference] | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+ enrichment_by_source_id: "dict[Any, tuple[Any, CustomPropertySyncRun | None]] | None" = None,
) -> contracts.CustomPropertyDefinitionView:
return contracts.CustomPropertyDefinitionView(
id=definition.id,
@@ -895,7 +906,7 @@ def _to_custom_property_definition_view(
created_by=definition.created_by_id,
updated_at=definition.updated_at,
references=references or [],
- source=_definition_source_view(definition),
+ source=_definition_source_view(definition, user_access_control, enrichment_by_source_id),
options=_to_custom_property_options(definition.options),
)
@@ -936,14 +947,25 @@ def _custom_property_references_by_definition_id(
}
-def _definition_source_view(definition: CustomPropertyDefinition) -> contracts.CustomPropertySourceView | None:
+def _definition_source_view(
+ definition: CustomPropertyDefinition,
+ user_access_control: "UserAccessControl | None" = None,
+ enrichment_by_source_id: "dict[Any, tuple[Any, CustomPropertySyncRun | None]] | None" = None,
+) -> contracts.CustomPropertySourceView | None:
"""The source bound to this definition (reverse one-to-one ``source``), or None. List reads
- ``select_related("source")`` so this stays a cache hit; detail reads pay one extra query."""
+ ``select_related("source")`` so this stays a cache hit; detail reads pay one extra query. Warehouse
+ schedule/run enrichment is gated on the caller's warehouse-source viewer access, and batched by the
+ list path via ``enrichment_by_source_id`` to avoid per-row queries."""
try:
source = definition.source
except CustomPropertySource.DoesNotExist:
return None
- return _to_custom_property_source_view(source)
+ enrichment = (
+ enrichment_by_source_id.get(source.id, _RESOLVE_ENRICHMENT_INLINE)
+ if enrichment_by_source_id is not None
+ else _RESOLVE_ENRICHMENT_INLINE
+ )
+ return _to_custom_property_source_view(source, user_access_control, enrichment)
def list_custom_property_definitions(
@@ -955,13 +977,23 @@ def list_custom_property_definitions(
read workflows — see ``_can_read_workflow_references``."""
queryset = CustomPropertyDefinition.objects.filter(team_id=team_id).select_related("source").order_by("name")
total_count = queryset.count()
- page = queryset[offset : offset + limit]
+ page = list(queryset[offset : offset + limit])
references = (
_custom_property_references_by_definition_id(team_id)
if _can_read_workflow_references(user_access_control)
else {}
)
- return [_to_custom_property_definition_view(d, references.get(str(d.id), [])) for d in page], total_count
+ sources: list[CustomPropertySource] = []
+ for d in page:
+ try:
+ sources.append(d.source)
+ except CustomPropertySource.DoesNotExist:
+ pass
+ enrichment = _batch_source_enrichment(team_id, sources, user_access_control)
+ return [
+ _to_custom_property_definition_view(d, references.get(str(d.id), []), user_access_control, enrichment)
+ for d in page
+ ], total_count
def get_custom_property_definition(
@@ -975,7 +1007,7 @@ def get_custom_property_definition(
references = _custom_property_references_by_definition_id(team_id, definition_id=str(definition.id)).get(
str(definition.id), []
)
- return _to_custom_property_definition_view(definition, references)
+ return _to_custom_property_definition_view(definition, references, user_access_control)
def list_custom_property_value_suggestions(team_id: int, definition_id: str, search: str | None) -> list[str]:
@@ -1033,6 +1065,7 @@ def update_custom_property_definition(
organization_id,
user: "User",
was_impersonated: bool,
+ user_access_control: "UserAccessControl | None" = None,
) -> contracts.CustomPropertyDefinitionView | None:
"""Apply ``fields`` (only the keys the caller sent) to a team-scoped definition. Returns the
updated view, or None when no definition matches the id for this team (→ 404)."""
@@ -1073,7 +1106,7 @@ def update_custom_property_definition(
was_impersonated=was_impersonated,
previous=previous,
)
- return _to_custom_property_definition_view(definition)
+ return _to_custom_property_definition_view(definition, user_access_control=user_access_control)
def delete_custom_property_definition(
@@ -1110,7 +1143,94 @@ class CustomPropertySourceValidationError(Exception):
already source-backed (→ 400)."""
-def _to_custom_property_source_view(source: CustomPropertySource) -> contracts.CustomPropertySourceView:
+def _to_sync_run_view(run: "CustomPropertySyncRun") -> contracts.CustomPropertySyncRunView:
+ return contracts.CustomPropertySyncRunView(
+ id=run.id,
+ trigger=run.trigger,
+ status=run.status,
+ started_at=run.started_at,
+ finished_at=run.finished_at,
+ rows_read=run.rows_read,
+ changed=run.changed,
+ existing=run.existing,
+ produced=run.produced,
+ skipped_missing_person=run.skipped_missing_person,
+ error=run.error,
+ created_at=run.created_at,
+ )
+
+
+def _resolve_person_source_schema(source: CustomPropertySource, user_access_control: "UserAccessControl | None") -> Any:
+ """The ``ExternalDataSchema`` (with ``.source`` loaded) backing a person source, or None when the
+ source has no warehouse binding or the caller lacks object-level ``external_data_source`` viewer
+ access. ``user_access_control`` None (service auth) skips the object check, matching
+ ``_enforce_object_access``. ``apps.get_model`` keeps this off a warehouse_sources internal import."""
+ if source.external_data_schema_id is None:
+ return None
+ schema_model = apps.get_model("warehouse_sources", "ExternalDataSchema")
+ schema = (
+ schema_model.objects.filter(id=source.external_data_schema_id, team_id=source.team_id)
+ .select_related("source")
+ .first()
+ )
+ if schema is None:
+ return None
+ if user_access_control is not None and not user_access_control.check_access_level_for_object(
+ schema.source, required_level="viewer"
+ ):
+ return None
+ return schema
+
+
+def _schema_schedule(schema: Any) -> tuple[float | None, datetime | None]:
+ """(sync_frequency_interval_seconds, next_sync_at) for a resolved schema, both None when the schema
+ has no sync frequency configured."""
+ interval = schema.sync_frequency_interval
+ if interval is None:
+ return None, None
+ next_sync_at = schema.last_synced_at + interval if schema.last_synced_at is not None else None
+ return interval.total_seconds(), next_sync_at
+
+
+# Sentinel so a caller can pass a prefetched (schema, latest_run) pair — including ``(None, None)``
+# for a person source the caller can't see — distinct from "resolve inline" (the detail path).
+class _ResolveEnrichmentInline:
+ pass
+
+
+_RESOLVE_ENRICHMENT_INLINE = _ResolveEnrichmentInline()
+
+
+def _to_custom_property_source_view(
+ source: CustomPropertySource,
+ user_access_control: "UserAccessControl | None" = None,
+ enrichment: "tuple[Any, CustomPropertySyncRun | None] | _ResolveEnrichmentInline" = _RESOLVE_ENRICHMENT_INLINE,
+) -> contracts.CustomPropertySourceView:
+ # Schedule + latest-run enrichment applies only to person sources; account sources leave it None.
+ # A person source is exactly the one bound to a warehouse schema (the facade enforces one binding),
+ # so this discriminates without a definition fetch. The enrichment exposes the underlying billable
+ # warehouse source's schedule and run metadata, so it's gated on the caller's warehouse-source viewer
+ # access — a caller without it sees the source but not its warehouse-derived metadata.
+ # ``enrichment`` lets list endpoints prefetch the schema + latest run in one batched query each
+ # (see ``_batch_source_enrichment``) instead of paying two queries per row.
+ sync_frequency_interval_seconds: float | None = None
+ next_sync_at: datetime | None = None
+ latest_run: contracts.CustomPropertySyncRunView | None = None
+ 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
+ else:
+ schema, latest = enrichment
+ if schema is not None:
+ sync_frequency_interval_seconds, next_sync_at = _schema_schedule(schema)
+ latest_run = _to_sync_run_view(latest) if latest is not None else None
+
+ # A person source's sync status (raw error text, failure streak, last-synced time) is produced by
+ # the underlying billable warehouse source, so it's warehouse-derived metadata gated the same way as
+ # the schedule/latest-run above — a caller without warehouse-source viewer access sees the mapping
+ # but not its status. Account sources have no warehouse binding; their status stays visible.
+ warehouse_status_visible = source.external_data_schema_id is None or schema is not None
+
return contracts.CustomPropertySourceView(
id=source.id,
definition=source.definition_id,
@@ -1120,15 +1240,57 @@ def _to_custom_property_source_view(source: CustomPropertySource) -> contracts.C
key_column=source.key_column,
column_property_map=source.column_property_map,
is_enabled=source.is_enabled,
- consecutive_failures=source.consecutive_failures,
- last_synced_at=source.last_synced_at,
- last_sync_error=source.last_sync_error,
+ consecutive_failures=source.consecutive_failures if warehouse_status_visible else 0,
+ last_synced_at=source.last_synced_at if warehouse_status_visible else None,
+ last_sync_error=source.last_sync_error if warehouse_status_visible else None,
created_at=source.created_at,
created_by=source.created_by_id,
updated_at=source.updated_at,
+ sync_frequency_interval_seconds=sync_frequency_interval_seconds,
+ next_sync_at=next_sync_at,
+ latest_run=latest_run,
)
+def _batch_source_enrichment(
+ team_id: int, sources: list[CustomPropertySource], user_access_control: "UserAccessControl | None"
+) -> dict[Any, "tuple[Any, CustomPropertySyncRun | None]"]:
+ """Resolve the schema (with warehouse-viewer access applied) and latest run for a page of person
+ sources in one query each, so a list endpoint doesn't issue two per-row queries (see the per-row
+ path in ``_to_custom_property_source_view``). Returns ``{source_id: (schema_or_None, latest_run)}``;
+ account sources (no warehouse binding) are absent, so they resolve inline to no enrichment."""
+ person_sources = [s for s in sources if s.external_data_schema_id is not None]
+ if not person_sources:
+ return {}
+ schema_model = apps.get_model("warehouse_sources", "ExternalDataSchema")
+ schemas_by_id = {
+ schema.id: schema
+ for schema in schema_model.objects.filter(
+ id__in={s.external_data_schema_id for s in person_sources}, team_id=team_id
+ ).select_related("source")
+ }
+ # Latest run per source in one query: DISTINCT ON (source_id) keeps the newest row per source.
+ latest_run_by_source_id: dict[Any, CustomPropertySyncRun] = {
+ run.source_id: run
+ for run in CustomPropertySyncRun.objects.for_team(team_id)
+ .filter(source_id__in=[s.id for s in person_sources])
+ .order_by("source_id", "-created_at")
+ .distinct("source_id")
+ }
+ enrichment: dict[Any, tuple[Any, CustomPropertySyncRun | None]] = {}
+ for source in person_sources:
+ schema = schemas_by_id.get(source.external_data_schema_id)
+ if (
+ schema is not None
+ and user_access_control is not None
+ and not user_access_control.check_access_level_for_object(schema.source, required_level="viewer")
+ ):
+ schema = None
+ latest = latest_run_by_source_id.get(source.id) if schema is not None else None
+ enrichment[source.id] = (schema, latest)
+ return enrichment
+
+
def _saved_query_belongs_to_team(team_id: int, saved_query_id) -> bool:
"""Whether the saved query exists for this team and isn't soft-deleted. Uses ``apps.get_model`` so
customer_analytics never imports data_modeling (which isn't a dependency)."""
@@ -1175,19 +1337,208 @@ def _enqueue_sync_if_enabled(source: CustomPropertySource) -> None:
transaction.on_commit(lambda: _enqueue_custom_property_sync(team_id, saved_query_id))
+def _create_running_runs(team_id: int, schema_id: str, trigger: str) -> list[Any]:
+ """Insert a 'running' run for each enabled person 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 (coalesced).
+ Returns the source ids a placeholder was created for, so the caller can reconcile them to FAILED if
+ the workflow start never happens (see ``_fail_created_runs``)."""
+ with transaction.atomic():
+ # Lock the candidate sources so a concurrent trigger for the same schema can't pass the
+ # "already running" check and insert a duplicate RUNNING row before this one commits.
+ sources = list(
+ CustomPropertySource.objects.for_team(team_id)
+ .filter(
+ external_data_schema_id=schema_id,
+ is_enabled=True,
+ definition__target_type=TargetType.PERSON.value,
+ )
+ .select_for_update()
+ )
+ 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)
+ )
+ to_create = [source for source in sources if source.id not in already_running]
+ now = timezone.now()
+ CustomPropertySyncRun.objects.bulk_create(
+ [
+ CustomPropertySyncRun(
+ team_id=team_id,
+ source=source,
+ schema_id=schema_id,
+ trigger=trigger,
+ status=SyncStatus.RUNNING.value,
+ started_at=now,
+ )
+ for source in to_create
+ ]
+ )
+ return [source.id for source in to_create]
+
+
+def _fail_created_runs(team_id: int, source_ids: list[Any], error: str) -> None:
+ """Reconcile the RUNNING placeholders just created for these sources to FAILED. Called when the
+ workflow start never happened (Temporal unreachable), so the rows don't sit 'running' forever with
+ the UI trigger disabled, and the next attempt isn't coalesced against a dead placeholder."""
+ if not source_ids:
+ return
+ CustomPropertySyncRun.objects.for_team(team_id).filter(
+ source_id__in=source_ids, status=SyncStatus.RUNNING.value
+ ).update(status=SyncStatus.FAILED.value, finished_at=timezone.now(), error=error)
+
+
+def _start_backfill(team_id: int, schema_id: str, trigger: str) -> None:
+ """Start the person-property backfill workflow. Failure must not fail the originating write."""
+ created_source_ids: list[Any] = []
+ try:
+ # Placeholder rows before starting, so the activity always finds a running row to reconcile.
+ created_source_ids = _create_running_runs(team_id, schema_id, trigger)
+ # The temporal client is heavy; keep it off the CA facade import (django.setup) path.
+ from products.warehouse_sources.backend.facade.temporal import start_person_property_backfill # noqa: PLC0415
+
+ start_person_property_backfill(team_id=team_id, schema_id=schema_id, trigger=trigger)
+ except Exception as e:
+ # The workflow never started, so nothing will reconcile the placeholders — fail them here.
+ _fail_created_runs(team_id, created_source_ids, "Failed to start backfill")
+ capture_exception(e)
+
+
+def _start_person_backfill_if_enabled(source: CustomPropertySource) -> None:
+ """Auto-start a backfill after a person source is created/enabled so historical rows populate
+ immediately rather than waiting for the next incremental sync. Person sources only (account
+ sources have no external_data_schema); deduped per table by the workflow id."""
+ if not source.is_enabled or source.external_data_schema_id is None:
+ return
+ team_id, schema_id = source.team_id, str(source.external_data_schema_id)
+ transaction.on_commit(lambda: _start_backfill(team_id, schema_id, "backfill"))
+
+
+def _triggerable_person_schema_id(team_id: int, source_id: str) -> str | None:
+ """The schema id to act on for a person-property trigger, or None when the source isn't a valid,
+ flag-enabled person source (→ the view returns 400)."""
+ source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).select_related("definition").first()
+ if source is None or source.external_data_schema_id is None:
+ return None
+ # A disabled source (e.g. auto-disabled after repeated failures) can't be re-triggered until it's
+ # re-enabled — otherwise the "sync now"/backfill actions would keep launching billable imports for
+ # a mapping the system already turned off.
+ if not source.is_enabled:
+ return None
+ if source.definition.target_type != TargetType.PERSON.value:
+ return None
+ if not person_properties_flag_enabled(team_id):
+ return None
+ return str(source.external_data_schema_id)
+
+
+def _assert_warehouse_source_access(
+ team_id: int,
+ external_data_schema_id: str | UUID | None,
+ user_access_control: "UserAccessControl | None",
+ level: str,
+) -> None:
+ """A person-property source drives a real (billable) warehouse source, so acting on it or reading
+ its warehouse metadata requires the caller's object-level ``external_data_source`` access at
+ ``level``, not account-scope access alone. Mirrors the canonical warehouse endpoints, which gate
+ through ``get_object``. ``None`` (service auth, which the permission layer skips object checks for)
+ is a no-op, matching ``_enforce_object_access``. Raises ``ResourceForbiddenError`` (→ 403) when the
+ caller is denied. ``apps.get_model`` keeps this off a warehouse_sources internal import."""
+ if user_access_control is None or external_data_schema_id is None:
+ return
+ schema_model = apps.get_model("warehouse_sources", "ExternalDataSchema")
+ schema = schema_model.objects.filter(id=external_data_schema_id, team_id=team_id).select_related("source").first()
+ if schema is None:
+ return
+ _enforce_object_access(schema.source, user_access_control, level)
+
+
+def _assert_warehouse_source_editor(
+ team_id: int, external_data_schema_id: str | UUID | None, user_access_control: "UserAccessControl | None"
+) -> None:
+ """Editor gate for acting on a person source — a manual sync/backfill, or creating/enabling the
+ mapping (which auto-triggers one)."""
+ _assert_warehouse_source_access(team_id, external_data_schema_id, user_access_control, "editor")
+
+
+def _assert_warehouse_source_viewer(
+ team_id: int, external_data_schema_id: str | UUID | None, user_access_control: "UserAccessControl | None"
+) -> None:
+ """Viewer gate for reading a person source's warehouse run metadata (row counts, schedule, sync
+ errors), which exposes its billable warehouse source."""
+ _assert_warehouse_source_access(team_id, external_data_schema_id, user_access_control, "viewer")
+
+
+def trigger_person_property_sync(
+ *, team_id: int, source_id: str, user_access_control: "UserAccessControl | None" = None
+) -> bool:
+ """ "Sync now" for a person source: trigger the underlying warehouse schema's sync (a real,
+ billable sync; the incremental person-property child runs off it). Returns False for an invalid
+ source (→ 400). Requires ``external_data_source`` editor access (→ 403) and honors the team's
+ warehouse sync pause (→ ``WarehouseSyncPausedError``)."""
+ schema_id = _triggerable_person_schema_id(team_id, source_id)
+ if schema_id is None:
+ return False
+ _assert_warehouse_source_editor(team_id, schema_id, user_access_control)
+ from products.warehouse_sources.backend.facade.temporal import ( # noqa: PLC0415
+ ExternalDataSchemaSyncPausedError,
+ trigger_schema_sync,
+ )
+
+ try:
+ trigger_schema_sync(team_id=team_id, schema_id=schema_id)
+ except ExternalDataSchemaSyncPausedError as e:
+ raise WarehouseSyncPausedError(str(e)) from e
+ return True
+
+
+def trigger_person_property_backfill(
+ *, team_id: int, source_id: str, trigger: str = "manual", user_access_control: "UserAccessControl | None" = None
+) -> bool | None:
+ """Start a backfill for a person source's table. Returns True (started), False (already running →
+ coalesced), or None for an invalid source (→ 400). Requires ``external_data_source`` editor access
+ (→ 403)."""
+ schema_id = _triggerable_person_schema_id(team_id, source_id)
+ if schema_id is None:
+ return None
+ _assert_warehouse_source_editor(team_id, schema_id, user_access_control)
+ # Placeholder rows before starting, so the activity always finds a running row to reconcile.
+ created_source_ids = _create_running_runs(team_id, schema_id, trigger)
+ from products.warehouse_sources.backend.facade.temporal import start_person_property_backfill # noqa: PLC0415
+
+ try:
+ return start_person_property_backfill(team_id=team_id, schema_id=schema_id, trigger=trigger)
+ except Exception:
+ # The workflow never started; reconcile the placeholders so the source isn't stuck 'running'
+ # with its trigger disabled, then surface the error to the caller.
+ _fail_created_runs(team_id, created_source_ids, "Failed to start backfill")
+ raise
+
+
def list_custom_property_sources(
- team_id: int, offset: int, limit: int
+ team_id: int, offset: int, limit: int, user_access_control: "UserAccessControl | None" = None
) -> tuple[list[contracts.CustomPropertySourceView], int]:
- """Custom-property sources for the team, newest first. Returns ``(page, total_count)``."""
+ """Custom-property sources for the team, newest first. Returns ``(page, total_count)``. Warehouse
+ schedule/run enrichment per source is gated on the caller's warehouse-source viewer access."""
queryset = CustomPropertySource.objects.for_team(team_id).order_by("-created_at")
total_count = queryset.count()
- page = queryset[offset : offset + limit]
- return [_to_custom_property_source_view(s) for s in page], total_count
+ page = list(queryset[offset : offset + limit])
+ enrichment = _batch_source_enrichment(team_id, page, user_access_control)
+ return [
+ _to_custom_property_source_view(s, user_access_control, enrichment.get(s.id, _RESOLVE_ENRICHMENT_INLINE))
+ for s in page
+ ], total_count
-def get_custom_property_source(team_id: int, source_id: str) -> contracts.CustomPropertySourceView | None:
+def get_custom_property_source(
+ team_id: int, source_id: str, user_access_control: "UserAccessControl | None" = None
+) -> contracts.CustomPropertySourceView | None:
source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).first()
- return _to_custom_property_source_view(source) if source is not None else None
+ return _to_custom_property_source_view(source, user_access_control) if source is not None else None
def create_custom_property_source(
@@ -1201,6 +1552,7 @@ def create_custom_property_source(
source_column: str | None = None,
external_data_schema_id: str | UUID | None = None,
column_property_map: dict | None = None,
+ user_access_control: "UserAccessControl | None" = None,
) -> contracts.CustomPropertySourceView:
definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
if definition is None:
@@ -1226,6 +1578,9 @@ def create_custom_property_source(
create_kwargs["column_property_map"] = _validate_column_property_map(column_property_map)
if not _external_data_schema_belongs_to_team(team_id, external_data_schema_id):
raise CustomPropertySourceValidationError("Warehouse schema not found for this team.")
+ # Mapping (and enabling) a warehouse table into person properties drives its billable source,
+ # so require the caller's warehouse-source editor access, not account-scope editor alone.
+ _assert_warehouse_source_editor(team_id, external_data_schema_id, user_access_control)
create_kwargs["external_data_schema_id"] = external_data_schema_id
else:
if saved_query_id is None or not source_column:
@@ -1250,11 +1605,12 @@ def create_custom_property_source(
raise
raise CustomPropertySourceValidationError("This custom property already has a source.")
_enqueue_sync_if_enabled(source)
- return _to_custom_property_source_view(source)
+ _start_person_backfill_if_enabled(source)
+ return _to_custom_property_source_view(source, user_access_control)
def update_custom_property_source(
- *, team_id: int, source_id: str, fields: dict[str, Any]
+ *, team_id: int, source_id: str, fields: dict[str, Any], user_access_control: "UserAccessControl | None" = None
) -> contracts.CustomPropertySourceView | None:
"""Apply ``fields`` (source_column / key_column / is_enabled) to a team-scoped source. Re-enabling
(is_enabled False→True) resets the failure streak and clears the last error. Returns None (→ 404)
@@ -1266,6 +1622,14 @@ def update_custom_property_source(
columns_changed = any(
attr in fields and fields[attr] != getattr(source, attr) for attr in ("source_column", "key_column")
)
+ # A person source's backfill drives its billable warehouse source, so any change that will trigger
+ # one — re-enabling, or changing the mapped columns while it stays enabled — requires the caller's
+ # warehouse-source editor access, not account-scope editor alone (matching create). Both routes reach
+ # _start_person_backfill_if_enabled below via ``reenabling or columns_changed``; ``is_enabled`` here is
+ # the post-update state that decides whether that helper actually starts a backfill.
+ will_be_enabled = fields.get("is_enabled", source.is_enabled) is True
+ if source.external_data_schema_id is not None and will_be_enabled and (reenabling or columns_changed):
+ _assert_warehouse_source_editor(team_id, source.external_data_schema_id, user_access_control)
for attr, value in fields.items():
setattr(source, attr, value)
if reenabling:
@@ -1275,7 +1639,8 @@ def update_custom_property_source(
# Only re-sync on a change that affects what gets written — not on every (possibly no-op) PATCH.
if reenabling or columns_changed:
_enqueue_sync_if_enabled(source)
- return _to_custom_property_source_view(source)
+ _start_person_backfill_if_enabled(source)
+ return _to_custom_property_source_view(source, user_access_control)
def delete_custom_property_source(*, team_id: int, source_id: str) -> bool:
@@ -1284,6 +1649,22 @@ def delete_custom_property_source(*, team_id: int, source_id: str) -> bool:
return deleted > 0
+def list_custom_property_sync_runs(
+ team_id: int, source_id: str, offset: int, limit: int, user_access_control: "UserAccessControl | None" = None
+) -> tuple[list[contracts.CustomPropertySyncRunView], int]:
+ """Person-property sync/backfill runs for a source, newest first. Returns ``(page, total_count)``.
+ Scoped by team and source, so a run of another team's/source's is never returned. The runs expose
+ the underlying warehouse source's row counts and raw sync errors, so reading them requires the
+ caller's warehouse-source viewer access (→ 403 via ``ResourceForbiddenError``)."""
+ source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).first()
+ if source is not None and source.external_data_schema_id is not None:
+ _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]
+ return [_to_sync_run_view(run) for run in page], total_count
+
+
# --- CustomerJourney ---
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 7739ae6f0284..2cadf620c1c6 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -382,6 +382,32 @@ class CustomPropertySourceView:
created_at: datetime | None = None
created_by: int | None = None
updated_at: datetime | None = None
+ # Person-target schedule visibility (None for account sources). ``sync_frequency_interval`` is
+ # in seconds; ``next_sync_at`` is approximate (last synced + interval), it drifts if the
+ # underlying schedule was paused. ``latest_run`` is the most recent sync/backfill run.
+ sync_frequency_interval_seconds: float | None = None
+ next_sync_at: datetime | None = None
+ latest_run: "CustomPropertySyncRunView | None" = None
+
+
+@stdlib_dataclass(frozen=True)
+class CustomPropertySyncRunView:
+ """One person-property sync/backfill run, as returned by the source ``runs`` endpoint and nested
+ on a source as ``latest_run``. The counts are the sync funnel (read -> changed -> existing (=
+ persons affected) -> produced; skipped_missing_person is changed rows with no matching person)."""
+
+ id: UUID | None = None
+ trigger: str = ""
+ status: str = ""
+ started_at: datetime | None = None
+ finished_at: datetime | None = None
+ rows_read: int = 0
+ changed: int = 0
+ existing: int = 0
+ produced: int = 0
+ skipped_missing_person: int = 0
+ error: str | None = None
+ created_at: datetime | None = None
@stdlib_dataclass(frozen=True)
diff --git a/products/customer_analytics/backend/facade/custom_property_source_person_test.py b/products/customer_analytics/backend/facade/custom_property_source_person_test.py
index dc467e31ce89..4295fda1cd01 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,6 +1,7 @@
from uuid import uuid4
from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -135,3 +136,104 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):
with self.assertRaises(api.CustomPropertySourceValidationError) as ctx:
self._create(definition_id=self.account_def.id, **overrides)
assert expected_message in str(ctx.exception)
+
+ @staticmethod
+ def _uac(allowed: bool) -> MagicMock:
+ uac = MagicMock()
+ uac.check_access_level_for_object.return_value = allowed
+ return uac
+
+ def test_create_person_source_requires_warehouse_source_editor(self):
+ # Mapping a warehouse table into person properties drives its billable source, so a caller
+ # without external_data_source editor access is refused even with account-scope editor.
+ with self.assertRaises(api.ResourceForbiddenError):
+ self._create(user_access_control=self._uac(allowed=False))
+ # The allow path still creates the source.
+ view = self._create(user_access_control=self._uac(allowed=True))
+ assert view.external_data_schema == self.schema.id
+
+ @patch("products.customer_analytics.backend.facade.api.person_properties_flag_enabled", return_value=True)
+ def test_trigger_sync_denied_without_warehouse_source_editor(self, _flag):
+ source = self._create()
+ with self.assertRaises(api.ResourceForbiddenError):
+ api.trigger_person_property_sync(
+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=False)
+ )
+
+ @patch("products.customer_analytics.backend.facade.api.person_properties_flag_enabled", return_value=True)
+ def test_trigger_backfill_denied_without_warehouse_source_editor(self, _flag):
+ source = self._create()
+ with self.assertRaises(api.ResourceForbiddenError):
+ api.trigger_person_property_backfill(
+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=False)
+ )
+
+ def test_update_columns_requires_warehouse_source_editor(self):
+ # Changing the mapped columns on an enabled person source auto-triggers a warehouse backfill, so
+ # it needs external_data_source editor access, not account-scope editor alone — the gate must
+ # cover column changes, not just re-enabling.
+ source = self._create(user_access_control=self._uac(allowed=True))
+ with self.assertRaises(api.ResourceForbiddenError):
+ api.update_custom_property_source(
+ team_id=self.team.id,
+ source_id=source.id,
+ fields={"key_column": "user_id"},
+ user_access_control=self._uac(allowed=False),
+ )
+
+ def test_disabling_source_does_not_require_warehouse_source_editor(self):
+ # Disabling never triggers a backfill, so it must not demand warehouse editor access.
+ source = self._create(user_access_control=self._uac(allowed=True))
+ view = api.update_custom_property_source(
+ team_id=self.team.id,
+ source_id=source.id,
+ fields={"is_enabled": False},
+ user_access_control=self._uac(allowed=False),
+ )
+ assert view is not None and view.is_enabled is False
+
+ def test_source_view_gates_warehouse_metadata_on_viewer_access(self):
+ from datetime import timedelta # noqa: PLC0415
+
+ self.schema.sync_frequency_interval = timedelta(hours=6)
+ self.schema.save(update_fields=["sync_frequency_interval"])
+ source = self._create(user_access_control=self._uac(allowed=True))
+ # Warehouse-derived sync status, including the raw error text from the backfill/sync activity.
+ CustomPropertySource.objects.filter(id=source.id).update(
+ last_sync_error="boom: internal warehouse detail", consecutive_failures=3
+ )
+
+ denied = api.get_custom_property_source(self.team.id, source.id, user_access_control=self._uac(allowed=False))
+ assert denied is not None
+ assert denied.sync_frequency_interval_seconds is None and denied.next_sync_at is None
+ # Status fields must be redacted too, not just the schedule — the raw error can leak warehouse detail.
+ assert denied.last_sync_error is None and denied.consecutive_failures == 0
+
+ allowed = api.get_custom_property_source(self.team.id, source.id, user_access_control=self._uac(allowed=True))
+ assert allowed is not None
+ assert allowed.sync_frequency_interval_seconds == timedelta(hours=6).total_seconds()
+ assert allowed.last_sync_error == "boom: internal warehouse detail" and allowed.consecutive_failures == 3
+
+ def test_list_sync_runs_requires_warehouse_source_viewer(self):
+ source = self._create(user_access_control=self._uac(allowed=True))
+ with self.assertRaises(api.ResourceForbiddenError):
+ api.list_custom_property_sync_runs(
+ self.team.id, source.id, offset=0, limit=10, user_access_control=self._uac(allowed=False)
+ )
+
+ @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).
+ source = self._create(is_enabled=False)
+ assert (
+ api.trigger_person_property_sync(
+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=True)
+ )
+ is False
+ )
+ assert (
+ api.trigger_person_property_backfill(
+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=True)
+ )
+ is None
+ )
diff --git a/products/customer_analytics/backend/logic/person_property_runs.py b/products/customer_analytics/backend/logic/person_property_runs.py
new file mode 100644
index 000000000000..59452c276f14
--- /dev/null
+++ b/products/customer_analytics/backend/logic/person_property_runs.py
@@ -0,0 +1,148 @@
+"""Persists person-property sync/backfill run outcomes.
+
+Registered as the data-import pipeline's run recorder (see apps.ready). Called from the warehouse
+sync/backfill activities, outside request context, so it scopes explicitly with ``for_team``. Writes
+a ``CustomPropertySyncRun`` row and folds the outcome back onto the source's status fields so the
+account-path ``sourceSyncStatus`` UI helper works for person sources too.
+"""
+
+from datetime import datetime
+
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+
+from products.customer_analytics.backend.models import (
+ CustomPropertySource,
+ CustomPropertySyncRun,
+ SyncStatus,
+ SyncTrigger,
+)
+from products.warehouse_sources.backend.facade.hooks import PersonPropertySyncRunRecord
+
+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})
+
+
+def _parse_iso(value: str | None) -> datetime | None:
+ if not value:
+ return None
+ try:
+ return datetime.fromisoformat(value)
+ except ValueError:
+ return None
+
+
+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."""
+ log = logger.bind(
+ team_id=record.team_id,
+ source_id=record.source_id,
+ schema_id=record.schema_id,
+ trigger=record.trigger,
+ 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
+
+ # 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()
+ )
+ # 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 = {
+ "schema_id": record.schema_id or None,
+ "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:
+ 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
+ )
+
+ 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",
+ consecutive_failures=source.consecutive_failures,
+ )
+ 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.
+ log.exception("person-property run recorder failed")
+ capture_exception(e)
diff --git a/products/customer_analytics/backend/logic/person_property_runs_test.py b/products/customer_analytics/backend/logic/person_property_runs_test.py
new file mode 100644
index 000000000000..39800007e6b9
--- /dev/null
+++ b/products/customer_analytics/backend/logic/person_property_runs_test.py
@@ -0,0 +1,151 @@
+from datetime import UTC, datetime
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+
+from products.customer_analytics.backend.logic.person_property_runs import (
+ MAX_CONSECUTIVE_SYNC_FAILURES,
+ 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
+from products.warehouse_sources.backend.facade.hooks import PersonPropertySyncRunRecord
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+
+class TestRecordSyncRun(TeamScopedTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ definition = create_custom_property_definition(
+ team_id=self.team.id, name="Plan tier", target_type=TargetType.PERSON.value
+ )
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_id="s", connection_id="c", status="Running", source_type="Stripe"
+ )
+ schema = ExternalDataSchema.objects.create(team=self.team, source=source, name="users")
+ self.source = CustomPropertySource.objects.create(
+ team=self.team,
+ definition=definition,
+ key_column="distinct_id",
+ external_data_schema=schema,
+ column_property_map={"plan": "plan_tier"},
+ is_enabled=True,
+ )
+ self.schema_id = str(schema.id)
+
+ def _record(self, **overrides) -> PersonPropertySyncRunRecord:
+ kwargs: dict = {
+ "team_id": self.team.id,
+ "schema_id": self.schema_id,
+ "source_id": str(self.source.id),
+ "job_id": "job-1",
+ "trigger": "scheduled",
+ "status": "completed",
+ "started_at": datetime(2026, 1, 1, tzinfo=UTC).isoformat(),
+ "finished_at": datetime(2026, 1, 1, 0, 1, tzinfo=UTC).isoformat(),
+ "rows_read": 10,
+ "changed": 4,
+ "existing": 3,
+ "produced": 3,
+ "skipped_missing_person": 1,
+ "error": None,
+ }
+ kwargs.update(overrides)
+ return PersonPropertySyncRunRecord(**kwargs)
+
+ def test_completed_run_persists_counts_and_clears_source_status(self):
+ # Regression: the person path never persisted a run or updated status; a silent no-op would
+ # leave the UI (and sourceSyncStatus) blank after a real sync.
+ record_sync_run(self._record())
+
+ run = CustomPropertySyncRun.objects.unscoped().get(source_id=self.source.id)
+ assert run.status == "completed"
+ assert (run.rows_read, run.changed, run.existing, run.produced, run.skipped_missing_person) == (10, 4, 3, 3, 1)
+ assert run.trigger == "scheduled"
+
+ self.source.refresh_from_db()
+ assert self.source.last_synced_at is not None
+ assert self.source.last_sync_error is None
+ assert self.source.consecutive_failures == 0
+
+ def test_failed_run_increments_failures_and_records_error(self):
+ self.source.consecutive_failures = 2
+ self.source.save()
+
+ record_sync_run(self._record(status="failed", error="boom"))
+
+ run = CustomPropertySyncRun.objects.unscoped().get(source_id=self.source.id)
+ assert run.status == "failed" and run.error == "boom"
+ self.source.refresh_from_db()
+ assert self.source.consecutive_failures == 3
+ assert self.source.last_sync_error == "boom"
+ assert self.source.is_enabled is True
+
+ def test_auto_disables_at_failure_cap(self):
+ # Regression: a source failing forever should stop syncing, matching the account path's cap.
+ self.source.consecutive_failures = MAX_CONSECUTIVE_SYNC_FAILURES - 1
+ self.source.save()
+
+ record_sync_run(self._record(status="failed", error="boom"))
+
+ self.source.refresh_from_db()
+ assert self.source.is_enabled is False
+
+ def test_unknown_source_is_a_noop(self):
+ # A run for a since-deleted source must not crash or orphan a row.
+ record_sync_run(self._record(source_id=str(uuid4())))
+ assert not CustomPropertySyncRun.objects.unscoped().filter(job_id="job-1").exists()
+
+ def test_backfill_reconciles_running_placeholder_in_place(self):
+ # The UI/auto path pre-creates a 'running' row; a backfill terminal record must update it in
+ # place (one row, not a running + completed pair) so the progress row resolves.
+ 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="backfill", status="completed", produced=5))
+
+ runs = CustomPropertySyncRun.objects.unscoped().filter(source=self.source)
+ assert runs.count() == 1
+ run = runs.get()
+ assert run.id == placeholder.id
+ assert 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.
+ 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"))
+
+ assert CustomPropertySyncRun.objects.unscoped().filter(source=self.source).count() == 2
+ placeholder.refresh_from_db()
+ assert placeholder.status == "running"
+
+ 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 failed
+ # row and re-incrementing the failure streak (which would auto-disable from retry noise).
+ record_sync_run(self._record(status="failed", error="boom"))
+ record_sync_run(self._record(status="failed", error="boom"))
+ record_sync_run(self._record(status="failed", error="boom"))
+
+ runs = CustomPropertySyncRun.objects.unscoped().filter(source=self.source, job_id="job-1")
+ assert runs.count() == 1
+ self.source.refresh_from_db()
+ assert self.source.consecutive_failures == 1
+
+ def test_scheduled_retry_that_finally_succeeds_clears_the_failure(self):
+ # A transient failure followed by a successful retry (same job_id) must resolve the row to
+ # completed and reset the source's failure streak / last-synced time.
+ record_sync_run(self._record(status="failed", error="boom"))
+ record_sync_run(self._record(status="completed", error=None))
+
+ runs = CustomPropertySyncRun.objects.unscoped().filter(source=self.source, job_id="job-1")
+ assert runs.count() == 1
+ assert runs.get().status == "completed"
+ self.source.refresh_from_db()
+ assert self.source.consecutive_failures == 0
+ assert self.source.last_synced_at is not None
+ assert self.source.last_sync_error is None
diff --git a/products/customer_analytics/backend/migrations/0018_custompropertysyncrun.py b/products/customer_analytics/backend/migrations/0018_custompropertysyncrun.py
new file mode 100644
index 000000000000..e18c1929fc51
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0018_custompropertysyncrun.py
@@ -0,0 +1,105 @@
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+from posthog.migration_helpers import AddForeignKeyNotValid
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0017_announcement_validate_fks"),
+ ("posthog", "1238_ducklakebackfill_earliest_event_date"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CustomPropertySyncRun",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("schema_id", models.UUIDField(blank=True, null=True)),
+ ("job_id", models.CharField(blank=True, max_length=400, null=True)),
+ (
+ "trigger",
+ models.CharField(
+ choices=[("scheduled", "scheduled"), ("manual", "manual"), ("backfill", "backfill")],
+ max_length=20,
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[("running", "running"), ("completed", "completed"), ("failed", "failed")],
+ default="running",
+ max_length=20,
+ ),
+ ),
+ ("started_at", models.DateTimeField(blank=True, null=True)),
+ ("finished_at", models.DateTimeField(blank=True, null=True)),
+ ("rows_read", models.PositiveIntegerField(default=0)),
+ ("changed", models.PositiveIntegerField(default=0)),
+ ("existing", models.PositiveIntegerField(default=0)),
+ ("produced", models.PositiveIntegerField(default=0)),
+ ("skipped_missing_person", models.PositiveIntegerField(default=0)),
+ ("error", models.TextField(blank=True, null=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "source",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="sync_runs",
+ to="customer_analytics.custompropertysource",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["team", "source", "-created_at"],
+ name="cpsr_team_source_created_idx",
+ )
+ ],
+ },
+ ),
+ AddForeignKeyNotValid(
+ model_name="custompropertysyncrun",
+ name="custompropertysyncrun_team_id_fk",
+ column="team_id",
+ to_table="posthog_team",
+ to_column="id",
+ ),
+ AddForeignKeyNotValid(
+ model_name="custompropertysyncrun",
+ name="custompropertysyncrun_created_by_id_fk",
+ column="created_by_id",
+ to_table="posthog_user",
+ to_column="id",
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/0019_custompropertysyncrun_validate_fks.py b/products/customer_analytics/backend/migrations/0019_custompropertysyncrun_validate_fks.py
new file mode 100644
index 000000000000..84171e122565
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0019_custompropertysyncrun_validate_fks.py
@@ -0,0 +1,14 @@
+from django.db import migrations
+
+from posthog.migration_helpers import ValidateForeignKey
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0018_custompropertysyncrun"),
+ ]
+
+ operations = [
+ ValidateForeignKey(model_name="custompropertysyncrun", name="custompropertysyncrun_created_by_id_fk"),
+ ValidateForeignKey(model_name="custompropertysyncrun", name="custompropertysyncrun_team_id_fk"),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index f307d45e3f3d..acf7c525badb 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0017_announcement_validate_fks
+0019_custompropertysyncrun_validate_fks
diff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.py
index 981ce7238b38..b344fed42be7 100644
--- a/products/customer_analytics/backend/models/__init__.py
+++ b/products/customer_analytics/backend/models/__init__.py
@@ -9,6 +9,7 @@ from .custom_property_definition import (
TargetType,
)
from .custom_property_source import CustomPropertySource
+from .custom_property_sync_run import CustomPropertySyncRun, SyncStatus, SyncTrigger
from .custom_property_value import CustomPropertyValue
from .customer_journey import CustomerJourney
from .customer_profile_config import CustomerProfileConfig
@@ -24,12 +25,15 @@ __all__ = [
"AnnouncementDelivery",
"CustomPropertyDefinition",
"CustomPropertySource",
+ "CustomPropertySyncRun",
"CustomPropertyValue",
"CustomerJourney",
"CustomerProfileConfig",
"DataType",
"DisplayType",
"RelationshipDefinition",
+ "SyncStatus",
+ "SyncTrigger",
"TargetType",
"TeamCustomerAnalyticsConfig",
]
diff --git a/products/customer_analytics/backend/models/custom_property_sync_run.py b/products/customer_analytics/backend/models/custom_property_sync_run.py
new file mode 100644
index 000000000000..3b648fa5d590
--- /dev/null
+++ b/products/customer_analytics/backend/models/custom_property_sync_run.py
@@ -0,0 +1,59 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UUIDModel
+
+
+class SyncTrigger(models.TextChoices):
+ # A run started automatically as a child of the underlying warehouse sync.
+ SCHEDULED = "scheduled", "scheduled"
+ # 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.
+ BACKFILL = "backfill", "backfill"
+
+
+class SyncStatus(models.TextChoices):
+ RUNNING = "running", "running"
+ COMPLETED = "completed", "completed"
+ FAILED = "failed", "failed"
+
+
+class CustomPropertySyncRun(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):
+ """One person-property sync run for a single source. Persists the funnel counts the sync/backfill
+ activities compute (which otherwise live only in Prometheus/logs) so the UI can show run history
+ and how many person profiles were affected."""
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False
+ )
+
+ source = models.ForeignKey(
+ "customer_analytics.CustomPropertySource", on_delete=models.CASCADE, related_name="sync_runs"
+ )
+ # The warehouse schema the rows came from. Kept as a plain id (not an FK) because a schema can be
+ # deleted while its historical runs stay meaningful.
+ schema_id = models.UUIDField(null=True, blank=True)
+ # The import job this run rode on. Null for backfill/manual runs that don't come from an import job.
+ job_id = models.CharField(max_length=400, null=True, blank=True)
+
+ trigger = models.CharField(max_length=20, choices=SyncTrigger.choices)
+ status = models.CharField(max_length=20, choices=SyncStatus.choices, default=SyncStatus.RUNNING)
+
+ started_at = models.DateTimeField(null=True, blank=True)
+ finished_at = models.DateTimeField(null=True, blank=True)
+
+ # Funnel: read -> changed (survived the snapshot diff) -> existing (distinct_id resolved to a
+ # person) -> produced (intent on Kafka); skipped_missing_person is the changed rows that dropped
+ # because no person matched.
+ rows_read = models.PositiveIntegerField(default=0)
+ changed = models.PositiveIntegerField(default=0)
+ existing = models.PositiveIntegerField(default=0)
+ produced = models.PositiveIntegerField(default=0)
+ skipped_missing_person = models.PositiveIntegerField(default=0)
+
+ error = models.TextField(null=True, blank=True)
+
+ class Meta:
+ indexes = [models.Index(fields=["team", "source", "-created_at"], name="cpsr_team_source_created_idx")]
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 7fcfcc3060d3..e86434d3412c 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -44,6 +44,7 @@ from products.customer_analytics.backend.facade.contracts import (
CustomPropertyOption,
CustomPropertyReference,
CustomPropertySourceView,
+ CustomPropertySyncRunView,
)
# Scope (value, label) pairs, kept in sync with ``CustomerProfileConfig.Scope``. Declared
@@ -306,6 +307,55 @@ class CustomPropertyReferenceSerializer(DataclassSerializer):
fields = ["id", "name", "status", "type"]
+class CustomPropertySyncRunSerializer(DataclassSerializer):
+ """One person-property sync or backfill run. Read-only: runs are created by the sync/backfill
+ pipeline, never through the API."""
+
+ 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'.",
+ )
+ 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.")
+ finished_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the run ended, or null while running."
+ )
+ rows_read = serializers.IntegerField(read_only=True, help_text="Warehouse rows scanned this run.")
+ changed = serializers.IntegerField(read_only=True, help_text="Rows whose mapped values changed since the last run.")
+ existing = serializers.IntegerField(
+ read_only=True, help_text="Person profiles updated (changed rows that matched an existing person)."
+ )
+ produced = serializers.IntegerField(
+ read_only=True, help_text="Property-update intents produced to the ingestion pipeline."
+ )
+ skipped_missing_person = serializers.IntegerField(
+ read_only=True, help_text="Changed rows dropped because no existing person matched the distinct id."
+ )
+ error = serializers.CharField(
+ read_only=True, allow_null=True, help_text="Error summary if the run failed, else null."
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the run row was recorded.")
+
+ class Meta:
+ dataclass = CustomPropertySyncRunView
+ ref_name = "CustomPropertySyncRun"
+ fields = [
+ "id",
+ "trigger",
+ "status",
+ "started_at",
+ "finished_at",
+ "rows_read",
+ "changed",
+ "existing",
+ "produced",
+ "skipped_missing_person",
+ "error",
+ "created_at",
+ ]
+
+
class CustomPropertySourceSerializer(DataclassSerializer):
"""Binds a materialized data-warehouse view column to a custom property definition; the view's
values are synced onto matching accounts on each materialization."""
@@ -371,6 +421,27 @@ class CustomPropertySourceSerializer(DataclassSerializer):
created_at = serializers.DateTimeField(read_only=True)
created_by = serializers.IntegerField(read_only=True, allow_null=True)
updated_at = serializers.DateTimeField(read_only=True, allow_null=True)
+ sync_frequency_interval_seconds = serializers.FloatField(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "Person sources only: how often the underlying warehouse schema syncs, in seconds. Null "
+ "for account sources or when unavailable."
+ ),
+ )
+ next_sync_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "Person sources only: approximate time of the next scheduled sync (last synced + interval). "
+ "Approximate — drifts if the schedule was paused. Null for account sources or if never synced."
+ ),
+ )
+ latest_run = CustomPropertySyncRunSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="Person sources only: the most recent sync/backfill run, or null if none yet.",
+ )
class Meta:
dataclass = CustomPropertySourceView
@@ -390,6 +461,9 @@ class CustomPropertySourceSerializer(DataclassSerializer):
"created_at",
"created_by",
"updated_at",
+ "sync_frequency_interval_seconds",
+ "next_sync_at",
+ "latest_run",
]
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index c21b5112992b..989f4d1414ad 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -14,7 +14,7 @@ from __future__ import annotations
import json
from dataclasses import asdict
-from typing import cast
+from typing import Any, cast
from uuid import UUID
from drf_spectacular.types import OpenApiTypes
@@ -30,8 +30,9 @@ from posthog.api.tagged_item import TaggedItemViewSetMixin
from posthog.exceptions import Conflict
from posthog.helpers.impersonation import is_impersonated
from posthog.models.user import User
-from posthog.permissions import is_service_auth
+from posthog.permissions import get_authenticator_scopes, is_service_auth
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
+from posthog.rbac.user_access_control import UserAccessControl, model_to_resource
from products.customer_analytics.backend.facade import api, contracts
from products.customer_analytics.backend.presentation.views.serializers import (
@@ -46,6 +47,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (
CustomPropertyDefinitionSerializer,
CustomPropertySourceSerializer,
CustomPropertySourceUpdateSerializer,
+ CustomPropertySyncRunSerializer,
CustomPropertyValueSerializer,
CustomPropertyValueSuggestionsResponseSerializer,
CustomPropertyValueWriteSerializer,
@@ -59,6 +61,46 @@ from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes
_OBJECT_READ_LEVEL = "viewer"
_OBJECT_WRITE_LEVEL = "editor"
+
+class _WarehouseScopeGatedAccessControl:
+ """Wraps ``UserAccessControl`` so object-level ``external_data_source`` access additionally
+ requires the request token to carry the matching ``external_data_source`` scope (``read`` for
+ viewer, ``write`` for editor). Person-property sources gate all warehouse read/write through
+ ``check_access_level_for_object`` on the linked ``external_data_source``, so folding the token
+ scope in here enforces the cross-resource scope on every path without threading it through the
+ facade. Session auth (no token scopes) and ``*`` tokens are unaffected — API scopes never gate
+ session requests, which stay RBAC-only. Everything else delegates to the wrapped instance."""
+
+ def __init__(self, inner: UserAccessControl, token_scopes: list[str]) -> None:
+ self._inner = inner
+ self._token_scopes = token_scopes
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._inner, name)
+
+ def check_access_level_for_object(self, obj: Any, required_level: Any, *args: Any, **kwargs: Any) -> bool:
+ if self._token_lacks_scope_for(obj, required_level):
+ return False
+ return self._inner.check_access_level_for_object(obj, required_level, *args, **kwargs)
+
+ def _token_lacks_scope_for(self, obj: Any, required_level: Any) -> bool:
+ scopes = self._token_scopes
+ if "*" in scopes or model_to_resource(obj) != "external_data_source":
+ return False
+ if "external_data_source:write" in scopes:
+ return False # write implies read, so it satisfies both viewer and editor
+ return not (required_level == "viewer" and "external_data_source:read" in scopes)
+
+
+def _warehouse_scoped_uac(view: Any) -> UserAccessControl:
+ """The view's ``UserAccessControl``, additionally gating ``external_data_source`` object access on
+ the request token's warehouse scope. A no-op for session/other non-token auth (no token scopes)."""
+ scopes = get_authenticator_scopes(getattr(view.request, "successful_authenticator", None))
+ if scopes is None:
+ return view.user_access_control
+ return cast(UserAccessControl, _WarehouseScopeGatedAccessControl(view.user_access_control, scopes))
+
+
# drf-spectacular auto-describes the pk path param for a model-backed viewset as
# "A UUID string identifying this <model>.". These viewsets reach the model through the
# facade (no ``queryset``), so the description is declared explicitly to keep the generated
@@ -210,14 +252,14 @@ class CustomPropertyDefinitionViewSet(
return self._paginate_via_facade(
request,
lambda offset, limit: api.list_custom_property_definitions(
- self.team_id, offset=offset, limit=limit, user_access_control=self.user_access_control
+ self.team_id, offset=offset, limit=limit, user_access_control=_warehouse_scoped_uac(self)
),
CustomPropertyDefinitionSerializer,
)
def retrieve(self, request: Request, *args, **kwargs) -> Response:
definition = api.get_custom_property_definition(
- self.team_id, self.kwargs["pk"], user_access_control=self.user_access_control
+ self.team_id, self.kwargs["pk"], user_access_control=_warehouse_scoped_uac(self)
)
if definition is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
@@ -287,6 +329,7 @@ class CustomPropertyDefinitionViewSet(
organization_id=self.organization.id,
user=cast(User, request.user),
was_impersonated=is_impersonated(request),
+ user_access_control=_warehouse_scoped_uac(self),
)
except api.CustomPropertyDefinitionConflictError as e:
raise Conflict(str(e))
@@ -429,12 +472,16 @@ class CustomPropertySourceViewSet(
def list(self, request: Request, *args, **kwargs) -> Response:
return self._paginate_via_facade(
request,
- lambda offset, limit: api.list_custom_property_sources(self.team_id, offset=offset, limit=limit),
+ lambda offset, limit: api.list_custom_property_sources(
+ self.team_id, offset=offset, limit=limit, user_access_control=_warehouse_scoped_uac(self)
+ ),
CustomPropertySourceSerializer,
)
def retrieve(self, request: Request, *args, **kwargs) -> Response:
- source = api.get_custom_property_source(self.team_id, self.kwargs["pk"])
+ source = api.get_custom_property_source(
+ self.team_id, self.kwargs["pk"], user_access_control=_warehouse_scoped_uac(self)
+ )
if source is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(CustomPropertySourceSerializer(instance=source).data)
@@ -454,18 +501,27 @@ class CustomPropertySourceViewSet(
key_column=data.key_column,
is_enabled=data.is_enabled,
user=cast(User, request.user),
+ user_access_control=_warehouse_scoped_uac(self),
)
except api.CustomPropertySourceValidationError as e:
raise ValidationError(str(e))
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
return Response(CustomPropertySourceSerializer(instance=source).data, status=status.HTTP_201_CREATED)
@extend_schema(request=CustomPropertySourceUpdateSerializer)
def update(self, request: Request, *args, **kwargs) -> Response:
write = CustomPropertySourceUpdateSerializer(data=request.data, partial=kwargs.pop("partial", False))
write.is_valid(raise_exception=True)
- source = api.update_custom_property_source(
- team_id=self.team_id, source_id=self.kwargs["pk"], fields=write.validated_data
- )
+ try:
+ source = api.update_custom_property_source(
+ team_id=self.team_id,
+ source_id=self.kwargs["pk"],
+ fields=write.validated_data,
+ user_access_control=_warehouse_scoped_uac(self),
+ )
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
if source is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(CustomPropertySourceSerializer(instance=source).data)
@@ -481,6 +537,64 @@ class CustomPropertySourceViewSet(
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(status=status.HTTP_204_NO_CONTENT)
+ @extend_schema(request=None, responses={202: OpenApiTypes.OBJECT})
+ @action(methods=["POST"], detail=True)
+ def sync(self, request: Request, *args, **kwargs) -> Response:
+ """Person sources only: trigger the underlying warehouse schema's sync now. This re-runs a
+ real (billable) warehouse sync; the incremental person-property update runs off it."""
+ try:
+ triggered = api.trigger_person_property_sync(
+ team_id=self.team_id, source_id=self.kwargs["pk"], user_access_control=_warehouse_scoped_uac(self)
+ )
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ except api.WarehouseSyncPausedError as e:
+ return Response({"message": str(e)}, status=status.HTTP_400_BAD_REQUEST)
+ if not triggered:
+ raise ValidationError("This action is only available for enabled person-property sources.")
+ return Response({"status": "triggered"}, status=status.HTTP_202_ACCEPTED)
+
+ @extend_schema(request=None, responses={202: OpenApiTypes.OBJECT})
+ @action(methods=["POST"], detail=True)
+ def backfill(self, request: Request, *args, **kwargs) -> Response:
+ """Person sources only: start a backfill that reads the whole warehouse table and populates
+ person properties for historical rows. Coalesces if one is already running for the table."""
+ try:
+ started = api.trigger_person_property_backfill(
+ team_id=self.team_id,
+ source_id=self.kwargs["pk"],
+ trigger="manual",
+ user_access_control=_warehouse_scoped_uac(self),
+ )
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ if started is None:
+ raise ValidationError("This action is only available for enabled person-property sources.")
+ return Response(
+ {"status": "started" if started else "already_running", "already_running": not started},
+ status=status.HTTP_202_ACCEPTED,
+ )
+
+ @extend_schema(responses={200: CustomPropertySyncRunSerializer(many=True)})
+ @action(methods=["GET"], detail=True)
+ def runs(self, request: Request, *args, **kwargs) -> Response:
+ """Person sources only: the source's sync/backfill run history, newest first. Gated on the
+ caller's warehouse-source viewer access, since the runs expose its row counts and sync errors."""
+ try:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_custom_property_sync_runs(
+ self.team_id,
+ self.kwargs["pk"],
+ offset=offset,
+ limit=limit,
+ user_access_control=_warehouse_scoped_uac(self),
+ ),
+ CustomPropertySyncRunSerializer,
+ )
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+
class CustomerJourneyViewSet(
TeamAndOrgViewSetMixin,
diff --git a/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py b/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py
new file mode 100644
index 000000000000..d107c6a1ffa9
--- /dev/null
+++ b/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py
@@ -0,0 +1,50 @@
+from unittest.mock import MagicMock
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.customer_analytics.backend.presentation.views.views import _WarehouseScopeGatedAccessControl
+
+
+class _Meta:
+ def __init__(self, model_name: str) -> None:
+ self.model_name = model_name
+
+
+class _FakeModel:
+ def __init__(self, model_name: str) -> None:
+ self._meta = _Meta(model_name)
+
+
+class TestWarehouseScopeGatedAccessControl(SimpleTestCase):
+ def _gate(self, scopes: list[str]) -> tuple[_WarehouseScopeGatedAccessControl, MagicMock]:
+ inner = MagicMock()
+ inner.check_access_level_for_object.return_value = True
+ return _WarehouseScopeGatedAccessControl(inner, scopes), inner
+
+ @parameterized.expand(
+ [
+ # (token scopes, required level, allowed?)
+ ("no_warehouse_scope_editor", ["account:write"], "editor", False),
+ ("no_warehouse_scope_viewer", ["account:read"], "viewer", False),
+ ("read_scope_covers_viewer", ["external_data_source:read"], "viewer", True),
+ ("read_scope_not_editor", ["external_data_source:read"], "editor", False),
+ ("write_scope_covers_editor", ["external_data_source:write"], "editor", True),
+ ("write_scope_covers_viewer", ["external_data_source:write"], "viewer", True),
+ ("wildcard_allows", ["*"], "editor", True),
+ ]
+ )
+ def test_external_data_source_object_gated_on_token_scope(self, _name, scopes, level, allowed):
+ gate, inner = self._gate(scopes)
+ result = gate.check_access_level_for_object(_FakeModel("externaldatasource"), required_level=level)
+ assert result is allowed
+ # When the token scope denies, the wrapped RBAC check is never consulted (fail closed on scope).
+ if not allowed:
+ inner.check_access_level_for_object.assert_not_called()
+
+ def test_non_warehouse_object_delegates(self):
+ # A different resource is unaffected by the warehouse scope gate — it delegates to the RBAC check.
+ gate, inner = self._gate(["account:write"])
+ assert gate.check_access_level_for_object(_FakeModel("dashboard"), required_level="editor") is True
+ inner.check_access_level_for_object.assert_called_once()
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 8ef6acee23f0..6a7da2e1448b 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -641,6 +641,45 @@ export interface CustomPropertyOptionApi {
color: CustomPropertyOptionColorEnumApi
}
+/**
+ * One person-property sync or backfill run. Read-only: runs are created by the sync/backfill
+ * pipeline, never through the API.
+ */
+export interface CustomPropertySyncRunApi {
+ readonly id: string
+ /** What started the run: 'scheduled' (rode a warehouse sync), 'manual', or 'backfill'. */
+ readonly trigger: string
+ /** Run status: 'running', 'completed', or 'failed'. */
+ readonly status: string
+ /**
+ * When the run began.
+ * @nullable
+ */
+ readonly started_at: string | null
+ /**
+ * When the run ended, or null while running.
+ * @nullable
+ */
+ readonly finished_at: string | null
+ /** Warehouse rows scanned this run. */
+ readonly rows_read: number
+ /** Rows whose mapped values changed since the last run. */
+ readonly changed: number
+ /** Person profiles updated (changed rows that matched an existing person). */
+ readonly existing: number
+ /** Property-update intents produced to the ingestion pipeline. */
+ readonly produced: number
+ /** Changed rows dropped because no existing person matched the distinct id. */
+ readonly skipped_missing_person: number
+ /**
+ * Error summary if the run failed, else null.
+ * @nullable
+ */
+ readonly error: string | null
+ /** When the run row was recorded. */
+ readonly created_at: string
+}
+
/**
* Binds a materialized data-warehouse view column to a custom property definition; the view's
* values are synced onto matching accounts on each materialization.
@@ -691,6 +730,18 @@ export interface CustomPropertySourceApi {
readonly created_by: number | null
/** @nullable */
readonly updated_at: string | null
+ /**
+ * Person sources only: how often the underlying warehouse schema syncs, in seconds. Null for account sources or when unavailable.
+ * @nullable
+ */
+ readonly sync_frequency_interval_seconds: number | null
+ /**
+ * Person sources only: approximate time of the next scheduled sync (last synced + interval). Approximate — drifts if the schedule was paused. Null for account sources or if never synced.
+ * @nullable
+ */
+ readonly next_sync_at: string | null
+ /** Person sources only: the most recent sync/backfill run, or null if none yet. */
+ readonly latest_run: CustomPropertySyncRunApi | null
}
/**
@@ -888,6 +939,15 @@ export interface PatchedCustomPropertySourceUpdateApi {
is_enabled?: boolean
}
+export interface PaginatedCustomPropertySyncRunListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: CustomPropertySyncRunApi[]
+}
+
export interface CustomerJourneyApi {
readonly id: string
insight: number
@@ -1274,6 +1334,21 @@ export type CustomPropertySourcesListParams = {
offset?: number
}
+export type CustomPropertySourcesBackfillCreate202 = { [key: string]: unknown }
+
+export type CustomPropertySourcesRunsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type CustomPropertySourcesSyncCreate202 = { [key: string]: unknown }
+
export type CustomerJourneysListParams = {
/**
* Number of results to return per page.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index abdd10a085fe..d68f4dcf2d33 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -27,7 +27,10 @@ import type {
CustomPropertyDefinitionsValuesRetrieveParams,
CustomPropertySourceApi,
CustomPropertySourceUpdateApi,
+ CustomPropertySourcesBackfillCreate202,
CustomPropertySourcesListParams,
+ CustomPropertySourcesRunsListParams,
+ CustomPropertySourcesSyncCreate202,
CustomPropertyValueApi,
CustomPropertyValueSuggestionsResponseApi,
CustomPropertyValueWriteApi,
@@ -46,6 +49,7 @@ import type {
PaginatedAnnouncementListApi,
PaginatedCustomPropertyDefinitionListApi,
PaginatedCustomPropertySourceListApi,
+ PaginatedCustomPropertySyncRunListApi,
PaginatedCustomerJourneyListApi,
PaginatedCustomerProfileConfigListApi,
PaginatedGroupUsageMetricListApi,
@@ -871,6 +875,86 @@ export const customPropertySourcesDestroy = async (
})
}
+export const getCustomPropertySourcesBackfillCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_sources/${id}/backfill/`
+}
+
+/**
+ * Person sources only: start a backfill that reads the whole warehouse table and populates
+ * person properties for historical rows. Coalesces if one is already running for the table.
+ */
+export const customPropertySourcesBackfillCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CustomPropertySourcesBackfillCreate202> => {
+ return apiMutator<CustomPropertySourcesBackfillCreate202>(
+ getCustomPropertySourcesBackfillCreateUrl(projectId, id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
+export const getCustomPropertySourcesRunsListUrl = (
+ projectId: string,
+ id: string,
+ params?: CustomPropertySourcesRunsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/custom_property_sources/${id}/runs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/custom_property_sources/${id}/runs/`
+}
+
+/**
+ * Person sources only: the source's sync/backfill run history, newest first. Gated on the
+ * caller's warehouse-source viewer access, since the runs expose its row counts and sync errors.
+ */
+export const customPropertySourcesRunsList = async (
+ projectId: string,
+ id: string,
+ params?: CustomPropertySourcesRunsListParams,
+ options?: RequestInit
+): Promise<PaginatedCustomPropertySyncRunListApi> => {
+ return apiMutator<PaginatedCustomPropertySyncRunListApi>(
+ getCustomPropertySourcesRunsListUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getCustomPropertySourcesSyncCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_sources/${id}/sync/`
+}
+
+/**
+ * Person sources only: trigger the underlying warehouse schema's sync now. This re-runs a
+ * real (billable) warehouse sync; the incremental person-property update runs off it.
+ */
+export const customPropertySourcesSyncCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CustomPropertySourcesSyncCreate202> => {
+ return apiMutator<CustomPropertySourcesSyncCreate202>(getCustomPropertySourcesSyncCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getCustomerJourneysListUrl = (projectId: string, params?: CustomerJourneysListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx
index 80cb800264d6..553ea283d2ee 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconPencil, IconPlus, IconTrash } from '@posthog/icons'
+import { IconInfo, IconPencil, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTableColumns, Tooltip } from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
@@ -9,7 +9,10 @@ import { TeamMembershipLevel } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
-import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type {
+ CustomPropertyDefinitionApi,
+ CustomPropertySyncRunApi,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
import { customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
import { CustomPropertyModal } from './CustomPropertyModal'
@@ -22,11 +25,63 @@ const TAG_TYPE_BY_SYNC_LEVEL: Record<SourceSyncStatusLevel, LemonTagType> = {
pending: 'default',
}
-// Project-settings view of the warehouse → person property sources: the same definitions managed on
-// the Customer analytics accounts page, filtered to person targets and created straight into 'person'.
+const TAG_TYPE_BY_RUN_STATUS: Record<string, LemonTagType> = {
+ completed: 'success',
+ running: 'primary',
+ failed: 'danger',
+}
+
+// Run history for one source, loaded lazily when its row is expanded.
+function PersonPropertyRuns({ sourceId }: { sourceId: string }): JSX.Element {
+ const { runsBySourceId, runsLoadingBySourceId } = useValues(customPropertyDefinitionsLogic)
+ const runs = runsBySourceId[sourceId] ?? []
+
+ const columns: LemonTableColumns<CustomPropertySyncRunApi> = [
+ {
+ title: 'Status',
+ render: (_, run) => (
+ <Tooltip title={run.error ?? undefined}>
+ <LemonTag type={TAG_TYPE_BY_RUN_STATUS[run.status] ?? 'default'}>{run.status}</LemonTag>
+ </Tooltip>
+ ),
+ },
+ { title: 'Trigger', dataIndex: 'trigger' },
+ { title: 'Rows produced', render: (_, run) => run.produced },
+ { title: 'Affected persons', render: (_, run) => run.existing },
+ {
+ title: 'Skipped (no person)',
+ render: (_, run) => <span className="text-secondary">{run.skipped_missing_person}</span>,
+ },
+ {
+ title: 'Started',
+ render: (_, run) =>
+ run.started_at ? <TZLabel time={run.started_at} /> : <span className="text-secondary">—</span>,
+ },
+ {
+ title: 'Finished',
+ render: (_, run) =>
+ run.finished_at ? <TZLabel time={run.finished_at} /> : <span className="text-secondary">—</span>,
+ },
+ ]
+
+ return (
+ <LemonTable
+ columns={columns}
+ dataSource={runs}
+ loading={runsLoadingBySourceId[sourceId] ?? false}
+ rowKey="id"
+ size="small"
+ emptyState="No runs yet."
+ />
+ )
+}
+
+// First-class Customer analytics view of the warehouse → person property sources: manages the person
+// mappings, shows the next scheduled sync, lets you trigger a sync or backfill, and expands to run history.
export function WarehousePersonPropertiesSetting(): JSX.Element {
- const { definitions, definitionsLoading } = useValues(customPropertyDefinitionsLogic)
- const { openCreateModal, openEditModal, deleteDefinition } = useActions(customPropertyDefinitionsLogic)
+ const { definitions, definitionsLoading, triggeringSourceIds } = useValues(customPropertyDefinitionsLogic)
+ const { openCreateModal, openEditModal, deleteDefinition, triggerSync, triggerBackfill, loadRuns } =
+ useActions(customPropertyDefinitionsLogic)
const restrictionReason = useRestrictedArea({
scope: RestrictionScope.Project,
minimumAccessLevel: TeamMembershipLevel.Admin,
@@ -88,40 +143,84 @@ export function WarehousePersonPropertiesSetting(): JSX.Element {
return <span className="text-secondary">—</span>
}
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_run
+ const affected = latestRun?.status === 'completed' ? latestRun.existing : undefined
+ const tooltipTitle =
+ [status.tooltip, affected != null ? `${affected} people affected on the last run` : null]
+ .filter(Boolean)
+ .join(' — ') || undefined
return (
- <Tooltip title={status.tooltip}>
+ <Tooltip title={tooltipTitle}>
<span className="flex items-center gap-2">
<LemonTag type={TAG_TYPE_BY_SYNC_LEVEL[status.level]}>{status.label}</LemonTag>
{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>
)
},
},
+ {
+ title: 'Next sync',
+ render: (_, definition) =>
+ definition.source?.next_sync_at ? (
+ <TZLabel time={definition.source.next_sync_at} className="text-secondary" />
+ ) : (
+ <span className="text-secondary">—</span>
+ ),
+ },
{
title: '',
width: 0,
- render: (_, definition) => (
- <div className="flex gap-1 justify-end">
- <LemonButton
- size="small"
- icon={<IconPencil />}
- tooltip="Edit"
- onClick={() => openEditModal(definition)}
- disabledReason={restrictionReason}
- />
- <LemonButton
- size="small"
- status="danger"
- icon={<IconTrash />}
- tooltip="Delete"
- onClick={() => confirmDelete(definition)}
- disabledReason={restrictionReason}
- />
- </div>
- ),
+ render: (_, definition) => {
+ const source = definition.source
+ const triggering = !!source && triggeringSourceIds.includes(source.id)
+ const running = source?.latest_run?.status === 'running'
+ // A run is in flight for this table; block a second trigger and show it as busy.
+ const busyReason = running ? 'A sync or backfill is already running for this table' : undefined
+ const disabledReason = restrictionReason ?? (!source ? 'No source configured' : undefined) ?? busyReason
+ return (
+ <div className="flex gap-1 justify-end">
+ <LemonButton
+ size="small"
+ icon={<IconRefresh />}
+ tooltip="Sync now — re-runs the warehouse sync for this table"
+ onClick={() => source && triggerSync({ sourceId: source.id })}
+ loading={triggering}
+ disabledReason={disabledReason}
+ />
+ <LemonButton
+ size="small"
+ tooltip="Backfill — reads the whole table to fill in historical rows"
+ onClick={() => source && triggerBackfill({ sourceId: source.id })}
+ loading={triggering || running}
+ disabledReason={disabledReason}
+ >
+ Backfill
+ </LemonButton>
+ <LemonButton
+ size="small"
+ icon={<IconPencil />}
+ tooltip="Edit"
+ onClick={() => openEditModal(definition)}
+ disabledReason={restrictionReason}
+ />
+ <LemonButton
+ size="small"
+ status="danger"
+ icon={<IconTrash />}
+ tooltip="Delete"
+ onClick={() => confirmDelete(definition)}
+ disabledReason={restrictionReason}
+ />
+ </div>
+ )
+ },
},
]
@@ -142,6 +241,12 @@ export function WarehousePersonPropertiesSetting(): JSX.Element {
dataSource={personDefinitions}
loading={definitionsLoading}
rowKey="id"
+ expandable={{
+ rowExpandable: (definition) => !!definition.source,
+ onRowExpand: (definition) => definition.source && loadRuns({ sourceId: definition.source.id }),
+ expandedRowRender: (definition) =>
+ definition.source ? <PersonPropertyRuns sourceId={definition.source.id} /> : null,
+ }}
emptyState="No warehouse-backed person properties yet. Add one to sync warehouse columns onto people."
/>
<CustomPropertyModal />
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
index 8b82c70dcc51..dbef610c18a8 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
@@ -17,15 +17,19 @@ import {
customPropertyDefinitionsDestroy,
customPropertyDefinitionsList,
customPropertyDefinitionsPartialUpdate,
+ customPropertySourcesBackfillCreate,
customPropertySourcesCreate,
customPropertySourcesDestroy,
customPropertySourcesPartialUpdate,
+ customPropertySourcesRunsList,
+ customPropertySourcesSyncCreate,
} from 'products/customer_analytics/frontend/generated/api'
import type {
CustomPropertyDefinitionApi,
CustomPropertyDisplayTypeEnumApi,
CustomPropertyOptionApi,
CustomPropertyReferenceApi,
+ CustomPropertySyncRunApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
import { NEW_OPTION_ID_PREFIX, isNumericDisplayType, optionLabelError } from './customPropertyTypes'
@@ -33,6 +37,11 @@ import { NEW_OPTION_ID_PREFIX, isNumericDisplayType, optionLabelError } from './
export type CustomPropertySourceMode = 'manual' | 'data_warehouse' | 'workflow'
export type CustomPropertyTargetType = 'account' | 'person'
+// After triggering a sync/backfill, poll until the source's run settles so the UI reflects
+// completion without a manual refresh. Bounded so a stuck run can't poll forever.
+const RUNS_POLL_INTERVAL_MS = 3000
+const RUNS_POLL_MAX_ATTEMPTS = 20
+
// One warehouse-column → person-property pair in the person-target editor. Serialized to the
// backend's `column_property_map` object ({column: property}) on save.
export interface ColumnPropertyMapping {
@@ -165,6 +174,8 @@ export interface customPropertyDefinitionsLogicValues {
newWorkflowUrlLoading: boolean
personPropertyDefinitions: PropertyDefinition[]
personPropertyDefinitionsLoading: boolean
+ runsBySourceId: Record<string, CustomPropertySyncRunApi[]>
+ runsLoadingBySourceId: Record<string, boolean>
savedQueries: DataWarehouseSavedQuery[]
savedQueriesLoading: boolean
selectedSourceColumns: string[]
@@ -173,12 +184,16 @@ export interface customPropertyDefinitionsLogicValues {
selectedWarehouseSchemaId: string | null
serializedColumnPropertyMap: Record<string, string>
showCustomPropertyFormErrors: boolean
+ triggeringSourceIds: string[]
warehouseTables: DataWarehouseTable[]
warehouseTablesLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface customPropertyDefinitionsLogicActions {
+ addTriggeringSource: ({ sourceId }: { sourceId: string }) => {
+ sourceId: string
+ }
closeModal: () => {
value: true
}
@@ -248,6 +263,9 @@ export interface customPropertyDefinitionsLogicActions {
personPropertyDefinitions: PropertyDefinition[]
payload?: any
}
+ loadRuns: ({ sourceId }: { sourceId: string }) => {
+ sourceId: string
+ }
loadSavedQueries: () => any
loadSavedQueriesFailure: (
error: string,
@@ -305,9 +323,22 @@ export interface customPropertyDefinitionsLogicActions {
openEditModal: (definition: CustomPropertyDefinitionApi) => {
definition: CustomPropertyDefinitionApi
}
+ pollRunsStatus: ({ sourceId }: { sourceId: string }) => {
+ sourceId: string
+ }
+ removeTriggeringSource: ({ sourceId }: { sourceId: string }) => {
+ sourceId: string
+ }
resetCustomPropertyForm: (values?: CustomPropertyFormValues) => {
values?: CustomPropertyFormValues
}
+ runsLoadFailed: ({ sourceId }: { sourceId: string }) => {
+ sourceId: string
+ }
+ runsLoaded: ({ sourceId, runs }: { runs: CustomPropertySyncRunApi[]; sourceId: string }) => {
+ runs: CustomPropertySyncRunApi[]
+ sourceId: string
+ }
setCustomPropertyFormManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -343,6 +374,12 @@ export interface customPropertyDefinitionsLogicActions {
touchCustomPropertyFormField: (key: string) => {
key: string
}
+ triggerBackfill: ({ sourceId }: { sourceId: string }) => {
+ sourceId: string
+ }
+ triggerSync: ({ sourceId }: { sourceId: string }) => {
+ sourceId: string
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -396,6 +433,24 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
openEditModal: (definition: CustomPropertyDefinitionApi) => ({ definition }),
closeModal: true,
setEditingDefinition: (definition: CustomPropertyDefinitionApi) => ({ definition }),
+ // Person sources only. triggerSync re-runs the underlying warehouse sync; triggerBackfill
+ // starts a full-table backfill. add/removeTriggeringSource drive the per-row double-submit
+ // guard, keyed by source so triggering one row never re-enables another's in-flight button.
+ triggerSync: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
+ triggerBackfill: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
+ addTriggeringSource: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
+ removeTriggeringSource: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
+ // Run history per source (lazy on row-expand), driven by explicit actions so loading state is
+ // tracked per source rather than one shared loader boolean.
+ loadRuns: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
+ runsLoaded: ({ sourceId, runs }: { sourceId: string; runs: CustomPropertySyncRunApi[] }) => ({
+ sourceId,
+ runs,
+ }),
+ runsLoadFailed: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
+ // Poll definitions/runs after a trigger until the source's run settles, so the buttons and
+ // status stop reflecting a stale 'running' state without a manual page refresh.
+ pollRunsStatus: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
}),
reducers({
modalVisible: [
@@ -415,6 +470,32 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
closeModal: () => null,
},
],
+ // The sources whose sync/backfill trigger is in flight, for the per-row loading/disabled guard.
+ // Keyed per source (not a single scalar) so a second row's trigger can't unblock the first's
+ // still-in-flight button.
+ triggeringSourceIds: [
+ [] as string[],
+ {
+ addTriggeringSource: (state, { sourceId }) => (state.includes(sourceId) ? state : [...state, sourceId]),
+ removeTriggeringSource: (state, { sourceId }) => state.filter((id) => id !== sourceId),
+ },
+ ],
+ // Sync/backfill run history per person source, loaded lazily when a row is expanded.
+ runsBySourceId: [
+ {} as Record<string, CustomPropertySyncRunApi[]>,
+ {
+ runsLoaded: (state, { sourceId, runs }) => ({ ...state, [sourceId]: runs }),
+ },
+ ],
+ // Per-source loading flag so expanding one row's history doesn't spin every expanded row.
+ runsLoadingBySourceId: [
+ {} as Record<string, boolean>,
+ {
+ loadRuns: (state, { sourceId }) => ({ ...state, [sourceId]: true }),
+ runsLoaded: (state, { sourceId }) => ({ ...state, [sourceId]: false }),
+ runsLoadFailed: (state, { sourceId }) => ({ ...state, [sourceId]: false }),
+ },
+ ],
}),
loaders(({ actions, values }) => ({
definitions: [
@@ -662,7 +743,7 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
},
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
openCreateModal: ({ targetType }) => {
actions.resetCustomPropertyForm()
if (targetType) {
@@ -782,6 +863,89 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.loadWarehouseTables' })
lemonToast.error('Failed to load data warehouse tables')
},
+ triggerSync: async ({ sourceId }) => {
+ actions.addTriggeringSource({ sourceId })
+ try {
+ await customPropertySourcesSyncCreate(String(values.currentProjectId), sourceId)
+ lemonToast.success('Sync triggered — it may take a few minutes to run')
+ actions.loadDefinitions()
+ actions.pollRunsStatus({ sourceId })
+ } catch (error) {
+ posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.triggerSync' })
+ lemonToast.error('Could not trigger a sync for this property')
+ } finally {
+ actions.removeTriggeringSource({ sourceId })
+ }
+ },
+ triggerBackfill: async ({ sourceId }) => {
+ actions.addTriggeringSource({ sourceId })
+ try {
+ const response = await customPropertySourcesBackfillCreate(String(values.currentProjectId), sourceId)
+ const alreadyRunning = (response as { already_running?: boolean } | undefined)?.already_running
+ lemonToast.success(
+ alreadyRunning
+ ? 'A backfill is already running for this table'
+ : 'Backfill started — it may take a few minutes to run'
+ )
+ actions.loadRuns({ sourceId })
+ actions.loadDefinitions()
+ actions.pollRunsStatus({ sourceId })
+ } catch (error) {
+ posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.triggerBackfill' })
+ lemonToast.error('Could not start a backfill for this property')
+ } finally {
+ actions.removeTriggeringSource({ sourceId })
+ }
+ },
+ loadRuns: async ({ sourceId }) => {
+ try {
+ const response = await customPropertySourcesRunsList(String(values.currentProjectId), sourceId)
+ actions.runsLoaded({ sourceId, runs: response.results })
+ } catch (error) {
+ posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.loadRuns' })
+ actions.runsLoadFailed({ sourceId })
+ lemonToast.error('Failed to load run history')
+ }
+ },
+ pollRunsStatus: ({ sourceId }) => {
+ cache.pollSourceIds = cache.pollSourceIds ?? new Set<string>()
+ cache.pollAttempts = cache.pollAttempts ?? {}
+ cache.pollSourceIds.add(sourceId)
+ cache.pollAttempts[sourceId] = 0
+ cache.disposables.add(() => {
+ const timeoutId = setTimeout(() => actions.loadDefinitions(), RUNS_POLL_INTERVAL_MS)
+ return () => clearTimeout(timeoutId)
+ }, 'runsPoll')
+ },
+ loadDefinitionsSuccess: () => {
+ // Reschedule the trigger poll until each polled source's run settles (or attempts run out),
+ // so the buttons/status reflect completion without a manual refresh (see pollRunsStatus).
+ const pollSourceIds: Set<string> | undefined = cache.pollSourceIds
+ if (!pollSourceIds || pollSourceIds.size === 0) {
+ return
+ }
+ // Build the next round rather than mutating the set while iterating it.
+ const stillPolling = new Set<string>()
+ pollSourceIds.forEach((sourceId) => {
+ const definition = values.definitions.find((d) => d.source?.id === sourceId)
+ const stillRunning = definition?.source?.latest_run?.status === 'running'
+ const attempts = (cache.pollAttempts[sourceId] ?? 0) + 1
+ cache.pollAttempts[sourceId] = attempts
+ actions.loadRuns({ sourceId })
+ if (stillRunning && attempts < RUNS_POLL_MAX_ATTEMPTS) {
+ stillPolling.add(sourceId)
+ }
+ })
+ cache.pollSourceIds = stillPolling
+ if (stillPolling.size === 0) {
+ cache.disposables.dispose('runsPoll')
+ return
+ }
+ cache.disposables.add(() => {
+ const timeoutId = setTimeout(() => actions.loadDefinitions(), RUNS_POLL_INTERVAL_MS)
+ return () => clearTimeout(timeoutId)
+ }, 'runsPoll')
+ },
})),
afterMount(({ actions }) => {
actions.loadDefinitions()
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index d879d1777f1d..ac87c00b35eb 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -467,6 +467,9 @@ tools:
custom-property-definitions-values-retrieve:
operation: custom_property_definitions_values_retrieve
enabled: false
+ custom-property-sources-backfill-create:
+ operation: custom_property_sources_backfill_create
+ enabled: false
custom-property-sources-create:
operation: custom_property_sources_create
enabled: false
@@ -482,6 +485,12 @@ tools:
custom-property-sources-retrieve:
operation: custom_property_sources_retrieve
enabled: false
+ custom-property-sources-runs-list:
+ operation: custom_property_sources_runs_list
+ enabled: false
+ custom-property-sources-sync-create:
+ operation: custom_property_sources_sync_create
+ enabled: false
custom-property-sources-update:
operation: custom_property_sources_update
enabled: false
diff --git a/products/warehouse_sources/backend/facade/hooks.py b/products/warehouse_sources/backend/facade/hooks.py
index c204842305c4..b7cb7847402a 100644
--- a/products/warehouse_sources/backend/facade/hooks.py
+++ b/products/warehouse_sources/backend/facade/hooks.py
@@ -11,11 +11,13 @@ on the startup path does not drag the whole pipeline onto every process boot.
from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
EmitSignalsActivityInputs,
PersonPropertySourceProjection,
+ PersonPropertySyncRunRecord,
PersonPropertySyncSource,
person_property_projection_for,
register_emit_signals_gate,
register_engineering_analytics_view_sync,
register_person_property_projection,
+ register_person_property_sync_recorder,
register_person_property_sync_sources,
register_revenue_view_sync,
)
@@ -23,11 +25,13 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_h
__all__ = [
"EmitSignalsActivityInputs",
"PersonPropertySourceProjection",
+ "PersonPropertySyncRunRecord",
"PersonPropertySyncSource",
"person_property_projection_for",
"register_emit_signals_gate",
"register_engineering_analytics_view_sync",
"register_person_property_projection",
+ "register_person_property_sync_recorder",
"register_person_property_sync_sources",
"register_revenue_view_sync",
]
diff --git a/products/warehouse_sources/backend/facade/temporal.py b/products/warehouse_sources/backend/facade/temporal.py
index 8af56b0d0a43..517cb4ad1bc0 100644
--- a/products/warehouse_sources/backend/facade/temporal.py
+++ b/products/warehouse_sources/backend/facade/temporal.py
@@ -16,10 +16,19 @@ self-registers with ``SourceRegistry`` — both re-exported here as the registra
so the bootstrap never reaches into the source/settings internals directly.
"""
+from products.warehouse_sources.backend.temporal.data_imports.person_property_backfill_job import (
+ PERSON_PROPERTY_BACKFILL_ACTIVITIES,
+ PERSON_PROPERTY_BACKFILL_WORKFLOWS,
+)
from products.warehouse_sources.backend.temporal.data_imports.person_property_sync_job import (
PERSON_PROPERTY_SYNC_ACTIVITIES,
PERSON_PROPERTY_SYNC_WORKFLOWS,
)
+from products.warehouse_sources.backend.temporal.data_imports.person_property_triggers import (
+ ExternalDataSchemaSyncPausedError,
+ start_person_property_backfill,
+ trigger_schema_sync,
+)
from products.warehouse_sources.backend.temporal.data_imports.settings import ACTIVITIES, WORKFLOWS
from products.warehouse_sources.backend.temporal.data_imports.sources import load_all_sources
from products.warehouse_sources.backend.temporal.data_imports.table_metadata_settings import (
@@ -32,9 +41,14 @@ __all__ = [
"ACTIVITIES",
"METADATA_ACTIVITIES",
"METADATA_WORKFLOWS",
+ "PERSON_PROPERTY_BACKFILL_ACTIVITIES",
+ "PERSON_PROPERTY_BACKFILL_WORKFLOWS",
"PERSON_PROPERTY_SYNC_ACTIVITIES",
"PERSON_PROPERTY_SYNC_WORKFLOWS",
"WORKFLOWS",
+ "ExternalDataSchemaSyncPausedError",
"load_all_sources",
"prepare_s3_files_for_querying",
+ "start_person_property_backfill",
+ "trigger_schema_sync",
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index b2cb25c897bb..8ccdbf620144 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -583,17 +583,26 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
# Fire-and-forget, started by name because it runs on a different task queue (see
# person_property_sync_job.py). Gated up front (like signals) to avoid a no-op child per sync.
if source_type is not None and schema_name is not None and person_property_sync_enabled:
+ person_property_sync_inputs = PersonPropertySyncActivityInputs(
+ team_id=inputs.team_id,
+ schema_id=inputs.external_data_schema_id,
+ source_id=inputs.external_data_source_id,
+ job_id=job_id,
+ source_type=source_type,
+ schema_name=schema_name,
+ last_synced_at=last_synced_at,
+ )
+ # Keyed per job (not per schema): each sync stages its changed rows under a job-scoped
+ # S3 prefix that only its own child consumes. A per-schema id would coalesce a
+ # concurrent job's child (WorkflowAlreadyStartedError) and silently drop that job's
+ # staged delta — swept as abandoned days later, so those person-property updates were
+ # lost. Per-job children can safely run concurrently for one schema: the folder-based
+ # snapshot (_write_snapshot_hashes) is concurrency-safe by design. Gated by the
+ # person_property_sync_enabled activity field (defaults False for old histories),
+ # matching the emit-signals sibling above.
await workflow.start_child_workflow(
"sync-warehouse-person-properties",
- PersonPropertySyncActivityInputs(
- team_id=inputs.team_id,
- schema_id=inputs.external_data_schema_id,
- source_id=inputs.external_data_source_id,
- job_id=job_id,
- source_type=source_type,
- schema_name=schema_name,
- last_synced_at=last_synced_at,
- ),
+ person_property_sync_inputs,
id=f"sync-warehouse-person-properties-{job_id}",
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py
index d03e6e86178f..ec298d3256e4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py
@@ -196,3 +196,76 @@ class PersonPropertySyncActivityInputs:
"source_type": self.source_type,
"schema_name": self.schema_name,
}
+
+
+# --- Person-property backfill trigger contract ----------------------------------------
+# A backfill reads a warehouse table's full Delta data from S3 (rather than the incrementally
+# staged rows) to populate historical rows a new/changed person mapping never saw. It is keyed by
+# schema, not source: one backfill workflow reads the table once and upserts every enabled person
+# source on it.
+
+
[email protected](frozen=True)
+class PersonPropertyBackfillActivityInputs:
+ """Payload for the person-property backfill workflow (see person_property_backfill_job.py)."""
+
+ team_id: int
+ schema_id: uuid.UUID
+ source_type: str
+ schema_name: str
+ # "backfill" (auto on create/enable) or "manual" (a user asked to re-run). Recorded on the run.
+ trigger: str
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {
+ "team_id": self.team_id,
+ "schema_id": str(self.schema_id),
+ "source_type": self.source_type,
+ "schema_name": self.schema_name,
+ "trigger": self.trigger,
+ }
+
+
+# --- Person-property sync run recorder ------------------------------------------------
+# The sync/backfill activities (owned by warehouse_sources) persist each run's funnel counts so the
+# customer_analytics UI can show run history and affected-person counts. Recording is inverted the
+# same way as the resolvers above: customer_analytics registers a recorder at app-ready that writes
+# the CustomPropertySyncRun row (and updates the source's status fields); when nothing is registered
+# this is a no-op, so warehouse_sources stays importable and a bookkeeping failure never blocks a sync.
+
+
[email protected](frozen=True)
+class PersonPropertySyncRunRecord:
+ """One source's run outcome. Timestamps are ISO strings so the record crosses the hook boundary
+ without timezone/serialization surprises."""
+
+ team_id: int
+ schema_id: str
+ source_id: str
+ job_id: str | None
+ trigger: str
+ status: str
+ started_at: str
+ finished_at: str
+ rows_read: int
+ changed: int
+ existing: int
+ produced: int
+ skipped_missing_person: int
+ error: str | None
+
+
+PersonPropertySyncRecorder = Callable[[PersonPropertySyncRunRecord], None]
+_person_property_sync_recorder: Optional[PersonPropertySyncRecorder] = None
+
+
+def register_person_property_sync_recorder(fn: PersonPropertySyncRecorder) -> None:
+ global _person_property_sync_recorder
+ _person_property_sync_recorder = fn
+
+
+def record_person_property_sync_run(record: PersonPropertySyncRunRecord) -> None:
+ if _person_property_sync_recorder is None:
+ return
+ _person_property_sync_recorder(record)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py
new file mode 100644
index 000000000000..3dae4320fff4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py
@@ -0,0 +1,125 @@
+"""Temporal workflow that backfills person properties from a warehouse table's full Delta data.
+
+Unlike the incremental sync (which reads only the rows a sync staged), this reads the whole table's
+parquet from S3 so a newly-created or changed person mapping populates historical rows it never saw.
+It is keyed by schema, not source: one workflow reads the table once and upserts every enabled person
+source on it, so mapping several properties from one table runs a single backfill.
+
+Started from the customer_analytics facade (auto on mapping create/enable, or a manual "backfill"
+button) with a per-``{team, schema}`` workflow id so concurrent triggers for the same table coalesce.
+Runs on the DATA_WAREHOUSE_METADATA_TASK_QUEUE alongside the incremental sync so post-sync processing
+never competes with the sync workers. The snapshot diff still skips unchanged values, so a re-run is
+cheap and idempotent.
+"""
+
+import json
+import time
+import dataclasses
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import structlog
+from prometheus_client import Counter, Histogram
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+
+from posthog.exceptions_capture import capture_exception
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
+
+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
+ PersonPropertyBackfillActivityInputs,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.person_property_sync import (
+ record_completed_runs,
+ record_failed_runs,
+ run_person_property_backfill,
+)
+
+logger = structlog.get_logger(__name__)
+
+PERSON_PROPERTY_BACKFILL_TOTAL = Counter(
+ "warehouse_person_property_backfill_total",
+ "Person-property backfill activity attempts by outcome",
+ labelnames=["team_id", "outcome"],
+)
+
+PERSON_PROPERTY_BACKFILL_DURATION_SECONDS = Histogram(
+ "warehouse_person_property_backfill_duration_seconds",
+ "Duration of one person-property backfill activity run",
+ buckets=(0.5, 1.0, 2.5, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0, 3600.0),
+)
+
+
+async def backfill_warehouse_person_properties_activity(inputs: PersonPropertyBackfillActivityInputs) -> dict[str, Any]:
+ """Read the table's full Delta data and upsert every enabled person source onto person properties."""
+ log = logger.bind(**inputs.properties_to_log)
+ log.info(f"Starting person-property backfill for {inputs.source_type}/{inputs.schema_name}")
+ start = time.monotonic()
+ started_at = datetime.now(UTC).isoformat()
+ try:
+ async with Heartbeater():
+ result = await run_person_property_backfill(
+ team_id=inputs.team_id, schema_id=str(inputs.schema_id), trigger=inputs.trigger
+ )
+ except Exception as e:
+ PERSON_PROPERTY_BACKFILL_TOTAL.labels(team_id=str(inputs.team_id), outcome="failed").inc()
+ log.exception("Person-property backfill failed")
+ capture_exception(e)
+ await record_failed_runs(
+ team_id=inputs.team_id,
+ schema_id=str(inputs.schema_id),
+ job_id=None,
+ trigger=inputs.trigger,
+ started_at=started_at,
+ finished_at=datetime.now(UTC).isoformat(),
+ error=str(e),
+ )
+ raise
+
+ await record_completed_runs(
+ team_id=inputs.team_id,
+ schema_id=str(inputs.schema_id),
+ job_id=None,
+ trigger=inputs.trigger,
+ started_at=started_at,
+ finished_at=datetime.now(UTC).isoformat(),
+ result=result,
+ )
+ PERSON_PROPERTY_BACKFILL_TOTAL.labels(team_id=str(inputs.team_id), outcome="completed").inc()
+ PERSON_PROPERTY_BACKFILL_DURATION_SECONDS.observe(time.monotonic() - start)
+
+ log.info(
+ "Person-property backfill finished",
+ sources=result.sources,
+ rows_read=result.rows_read,
+ changed=result.changed,
+ existing=result.existing,
+ produced=result.produced,
+ skipped_missing_person=result.skipped_missing_person,
+ )
+ return dataclasses.asdict(result)
+
+
[email protected](name="backfill-warehouse-person-properties")
+class BackfillWarehousePersonPropertiesWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> PersonPropertyBackfillActivityInputs:
+ loaded = json.loads(inputs[0])
+ return PersonPropertyBackfillActivityInputs(**loaded)
+
+ @workflow.run
+ async def run(self, inputs: PersonPropertyBackfillActivityInputs) -> None:
+ await workflow.execute_activity(
+ backfill_warehouse_person_properties_activity,
+ inputs,
+ start_to_close_timeout=timedelta(hours=6),
+ heartbeat_timeout=timedelta(minutes=5),
+ # A one-off full-table read: don't silently re-scan the whole table on a transient error.
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+
+
+PERSON_PROPERTY_BACKFILL_WORKFLOWS = [BackfillWarehousePersonPropertiesWorkflow]
+PERSON_PROPERTY_BACKFILL_ACTIVITIES = [backfill_warehouse_person_properties_activity]
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.py
index acdc47c8e769..50b7c54a1a28 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
@@ -15,7 +15,7 @@ Every terminal failure is captured to error tracking and counted in the metrics
import json
import time
import dataclasses
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any
import structlog
@@ -31,6 +31,8 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_h
PersonPropertySyncActivityInputs,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.person_property_sync import (
+ record_completed_runs,
+ record_failed_runs,
run_person_property_sync,
)
@@ -64,6 +66,7 @@ async def sync_warehouse_person_properties_activity(inputs: PersonPropertySyncAc
log = logger.bind(**inputs.properties_to_log)
log.info(f"Starting person-property sync for {inputs.source_type}/{inputs.schema_name}")
start = time.monotonic()
+ started_at = datetime.now(UTC).isoformat()
try:
async with Heartbeater():
result = await run_person_property_sync(
@@ -75,8 +78,26 @@ async def sync_warehouse_person_properties_activity(inputs: PersonPropertySyncAc
PERSON_PROPERTY_SYNC_TOTAL.labels(team_id=str(inputs.team_id), outcome="failed").inc()
log.exception("Person-property sync failed")
capture_exception(e)
+ await record_failed_runs(
+ team_id=inputs.team_id,
+ schema_id=str(inputs.schema_id),
+ job_id=inputs.job_id,
+ trigger="scheduled",
+ started_at=started_at,
+ finished_at=datetime.now(UTC).isoformat(),
+ error=str(e),
+ )
raise
+ await record_completed_runs(
+ team_id=inputs.team_id,
+ schema_id=str(inputs.schema_id),
+ job_id=inputs.job_id,
+ trigger="scheduled",
+ started_at=started_at,
+ finished_at=datetime.now(UTC).isoformat(),
+ result=result,
+ )
PERSON_PROPERTY_SYNC_TOTAL.labels(team_id=str(inputs.team_id), outcome="completed").inc()
PERSON_PROPERTY_SYNC_DURATION_SECONDS.observe(time.monotonic() - start)
for stage, count in (
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py
new file mode 100644
index 000000000000..d9eaf1c3bbf3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py
@@ -0,0 +1,114 @@
+"""Temporal trigger seams for the person-property feature, exposed through the warehouse_sources
+facade so customer_analytics (which can't import data_warehouse) can start these from a DRF request.
+
+Both open a Temporal client, so this module must stay off the ``django.setup()`` path — it's reached
+only from the facade on a request, never from an AppConfig or model.
+"""
+
+from django.conf import settings
+
+import structlog
+from asgiref.sync import async_to_sync
+from temporalio.client import Client
+from temporalio.common import WorkflowIDReusePolicy
+from temporalio.exceptions import WorkflowAlreadyStartedError
+
+from posthog.exceptions_capture import capture_exception
+from posthog.temporal.common.client import async_connect, sync_connect
+from posthog.temporal.common.schedule import trigger_schedule
+
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
+ PersonPropertyBackfillActivityInputs,
+)
+
+logger = structlog.get_logger(__name__)
+
+BACKFILL_WORKFLOW_NAME = "backfill-warehouse-person-properties"
+
+# The canonical warehouse schema reload/resync endpoints reject a manual sync with this message when
+# the team's syncing is paused (monthly limit reached); reused so person-property "sync now" matches.
+SYNC_PAUSED_MESSAGE = "Monthly sync limit reached. Please increase your billing limit to resume syncing."
+
+
+class ExternalDataSchemaSyncPausedError(Exception):
+ """Raised by ``trigger_schema_sync`` when the team's warehouse syncing is paused, so a manual
+ person-property sync can't be used to run billable imports past the monthly limit."""
+
+
+def trigger_schema_sync(*, team_id: int, schema_id: str) -> None:
+ """Trigger the underlying warehouse schema's Temporal schedule — a real, billable sync. The normal
+ incremental person-property child runs off it, so this doubles as person-property "sync now".
+ Honors the team's sync pause the same way the canonical reload/resync endpoints do."""
+ # Resolved lazily: the data_warehouse facade is PEP 562 lazy-loaded (heavy deps + an import cycle
+ # with warehouse_sources), so a module-top ``from`` import would eagerly pull that chain in.
+ from products.data_warehouse.backend.facade.api import is_any_external_data_schema_paused # noqa: PLC0415
+
+ log = logger.bind(team_id=team_id, schema_id=str(schema_id))
+ if is_any_external_data_schema_paused(team_id):
+ log.info("person-property sync-now rejected: team's warehouse syncing is paused")
+ raise ExternalDataSchemaSyncPausedError(SYNC_PAUSED_MESSAGE)
+ try:
+ temporal = sync_connect()
+ trigger_schedule(temporal, schedule_id=str(schema_id))
+ except Exception as e:
+ # Surfaces to the caller as a 500, but capture with context so a failing "sync now" is
+ # diagnosable rather than an opaque Temporal client error in the request log.
+ log.exception("Failed to trigger warehouse schema sync for person-property sync-now")
+ capture_exception(e, {"team_id": team_id, "schema_id": str(schema_id)})
+ raise
+ log.info("Triggered warehouse schema sync for person-property sync-now")
+
+
+def start_person_property_backfill(*, team_id: int, schema_id: str, trigger: str) -> bool:
+ """Start the per-table backfill workflow. One workflow per ``{team, schema}`` (id-keyed), so
+ concurrent triggers for the same table coalesce: returns False (does not raise) when one is
+ already running. Also returns False when the schema no longer exists."""
+ log = logger.bind(team_id=team_id, schema_id=str(schema_id), trigger=trigger)
+ # exclude(deleted=True): a soft-deleted schema (its source removed) must not kick off a backfill.
+ schema = (
+ ExternalDataSchema.objects.exclude(deleted=True)
+ .filter(id=schema_id, team_id=team_id)
+ .select_related("source")
+ .first()
+ )
+ if schema is None:
+ log.warning("person-property backfill not started: schema no longer exists")
+ return False
+ inputs = PersonPropertyBackfillActivityInputs(
+ team_id=team_id,
+ schema_id=schema.id,
+ source_type=schema.source.source_type,
+ schema_name=schema.name,
+ trigger=trigger,
+ )
+ workflow_id = f"{BACKFILL_WORKFLOW_NAME}-{team_id}-{schema_id}"
+ return _start_backfill_workflow(inputs, workflow_id)
+
+
+@async_to_sync
+async def _start_backfill_workflow(inputs: PersonPropertyBackfillActivityInputs, workflow_id: str) -> bool:
+ log = logger.bind(workflow_id=workflow_id, **inputs.properties_to_log)
+ try:
+ client: Client = await async_connect()
+ # ALLOW_DUPLICATE so a manual re-backfill is allowed after a prior run closes; a run currently
+ # in flight for the same id raises WorkflowAlreadyStartedError, which we swallow to coalesce.
+ await client.start_workflow(
+ BACKFILL_WORKFLOW_NAME,
+ inputs,
+ id=workflow_id,
+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ )
+ log.info("Started person-property backfill workflow")
+ return True
+ except WorkflowAlreadyStartedError:
+ # Expected: a backfill for this table is already in flight, so this trigger coalesces into it.
+ log.info("person-property backfill already running for schema, coalescing")
+ return False
+ except Exception as e:
+ # A real failure to reach Temporal — capture it; the caller (facade) treats a raise as
+ # "start failed" and the placeholder running row is reconciled to failed by the next run.
+ log.exception("Failed to start person-property backfill workflow")
+ capture_exception(e, {**inputs.properties_to_log, "workflow_id": workflow_id})
+ raise
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers_test.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers_test.py
new file mode 100644
index 000000000000..e2968f54c0bc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers_test.py
@@ -0,0 +1,29 @@
+import pytest
+from unittest.mock import patch
+
+from products.warehouse_sources.backend.temporal.data_imports import person_property_triggers
+from products.warehouse_sources.backend.temporal.data_imports.person_property_triggers import (
+ ExternalDataSchemaSyncPausedError,
+ trigger_schema_sync,
+)
+
+# is_any_external_data_schema_paused is imported lazily inside trigger_schema_sync from the
+# data_warehouse facade, so patch it at that (lazy) resolution point rather than on this module.
+_PAUSE_CHECK = "products.data_warehouse.backend.facade.api.is_any_external_data_schema_paused"
+
+
[email protected](person_property_triggers, "sync_connect")
+@patch(_PAUSE_CHECK, return_value=True)
+def test_trigger_schema_sync_blocked_when_paused(_paused, mock_connect):
+ with pytest.raises(ExternalDataSchemaSyncPausedError):
+ trigger_schema_sync(team_id=1, schema_id="abc")
+ # Never opens a Temporal client / triggers the schedule when syncing is paused.
+ mock_connect.assert_not_called()
+
+
[email protected](person_property_triggers, "trigger_schedule")
[email protected](person_property_triggers, "sync_connect")
+@patch(_PAUSE_CHECK, return_value=False)
+def test_trigger_schema_sync_triggers_when_not_paused(_paused, _connect, mock_trigger_schedule):
+ trigger_schema_sync(team_id=1, schema_id="abc")
+ mock_trigger_schedule.assert_called_once()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
index 06d00e6c90a8..3ebc2429798e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
@@ -185,6 +185,46 @@ def _first_per_pk_table(
return pa_table.take(kept_indices)
+def delta_storage_options() -> dict[str, str]:
+ """delta-rs storage options for the data-warehouse bucket, independent of any import job — so a
+ read path (e.g. the person-property backfill) can open a Delta table without constructing a full
+ ``DeltaTableHelper`` (which carries caching, first-sync mutation, and corruption-repair)."""
+ if settings.USE_LOCAL_SETUP:
+ if (
+ not settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY
+ or not settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET
+ or not settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION
+ ):
+ raise KeyError(
+ "Missing env vars for data warehouse. Required vars: DATAWAREHOUSE_LOCAL_ACCESS_KEY, DATAWAREHOUSE_LOCAL_ACCESS_SECRET, DATAWAREHOUSE_LOCAL_BUCKET_REGION"
+ )
+
+ ensure_bucket_exists(
+ settings.BUCKET_URL,
+ settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,
+ settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,
+ settings.OBJECT_STORAGE_ENDPOINT,
+ )
+
+ options = {
+ "aws_access_key_id": settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,
+ "aws_secret_access_key": settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,
+ "endpoint_url": settings.OBJECT_STORAGE_ENDPOINT,
+ "region_name": settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION,
+ "AWS_DEFAULT_REGION": settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION,
+ "AWS_ALLOW_HTTP": "true",
+ }
+ else:
+ options = {}
+
+ # Conditional puts make a clashing concurrent commit fail loudly instead of
+ # clobbering _delta_log; set explicitly so a library default change can't undo it.
+ options["conditional_put"] = "etag"
+ if settings.DATA_WAREHOUSE_DELTA_S3_ALLOW_UNSAFE_RENAME:
+ options["AWS_S3_ALLOW_UNSAFE_RENAME"] = "true"
+ return options
+
+
class DeltaTableHelper:
_resource_name: str
_job: ExternalDataJob
@@ -204,40 +244,7 @@ class DeltaTableHelper:
return self._is_first_sync
def _get_credentials(self):
- if settings.USE_LOCAL_SETUP:
- if (
- not settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY
- or not settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET
- or not settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION
- ):
- raise KeyError(
- "Missing env vars for data warehouse. Required vars: DATAWAREHOUSE_LOCAL_ACCESS_KEY, DATAWAREHOUSE_LOCAL_ACCESS_SECRET, DATAWAREHOUSE_LOCAL_BUCKET_REGION"
- )
-
- ensure_bucket_exists(
- settings.BUCKET_URL,
- settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,
- settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,
- settings.OBJECT_STORAGE_ENDPOINT,
- )
-
- options = {
- "aws_access_key_id": settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,
- "aws_secret_access_key": settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,
- "endpoint_url": settings.OBJECT_STORAGE_ENDPOINT,
- "region_name": settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION,
- "AWS_DEFAULT_REGION": settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION,
- "AWS_ALLOW_HTTP": "true",
- }
- else:
- options = {}
-
- # Conditional puts make a clashing concurrent commit fail loudly instead of
- # clobbering _delta_log; set explicitly so a library default change can't undo it.
- options["conditional_put"] = "etag"
- if settings.DATA_WAREHOUSE_DELTA_S3_ALLOW_UNSAFE_RENAME:
- options["AWS_S3_ALLOW_UNSAFE_RENAME"] = "true"
- return options
+ return delta_storage_options()
async def _get_delta_table_uri(self) -> str:
normalized_resource_name = NamingConvention.normalize_identifier(self._resource_name)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
index 6c92017635bd..56cf954a3e47 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
@@ -28,6 +28,7 @@ from django.conf import settings
import structlog
import pyarrow.parquet as pq
+from posthog.exceptions_capture import capture_exception
from posthog.kafka_client.routing import producer_scope
from posthog.kafka_client.topics import KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES
from posthog.models import PropertyDefinition, Team
@@ -35,9 +36,16 @@ from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.sync import database_sync_to_async
from products.data_warehouse.backend.facade.api import aget_s3_client
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
+ PersonPropertySyncRunRecord,
PersonPropertySyncSource,
person_property_sync_sources_for,
+ record_person_property_sync_run,
+)
+from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import (
+ delta_storage_options,
)
logger = structlog.get_logger(__name__)
@@ -45,6 +53,18 @@ logger = structlog.get_logger(__name__)
EVENT_SOURCE = "customer_analytics_person_property_sync"
+class PerSourceResult:
+ """One source's funnel counts within a run, so the recorder can persist a run row per source."""
+
+ source_id: str
+ rows_read: int = 0
+ changed: int = 0
+ existing: int = 0
+ produced: int = 0
+ skipped_missing_person: int = 0
+
+
@dataclasses.dataclass
class SyncResult:
sources: int = 0
@@ -55,6 +75,7 @@ class SyncResult:
# Changed rows dropped because their distinct_id resolved to no existing person. The most
# common "why didn't my property update" answer, so it's tracked and reported explicitly.
skipped_missing_person: int = 0
+ per_source: list[PerSourceResult] = dataclasses.field(default_factory=list)
# --- pure core ---------------------------------------------------------------------------
@@ -114,8 +135,12 @@ def _staged_prefix(team_id: int, schema_id: str, job_id: str) -> str:
return f"{settings.DATAWAREHOUSE_BUCKET}/person_property_sync/{team_id}/{schema_id}/{job_id}"
-def _snapshot_path(team_id: int, schema_id: str, source_id: str) -> str:
- return f"{settings.DATAWAREHOUSE_BUCKET}/person_property_snapshot/{team_id}/{source_id}/{schema_id}.parquet"
+def _snapshot_prefix(team_id: int, schema_id: str, source_id: str) -> str:
+ # A folder, not a single file: each run drops a uniquely-named parquet of the hashes it produced,
+ # and the reader unions every file in the folder. Two writers (a scheduled sync and a backfill)
+ # for the same source can't clobber each other, since they write different filenames. Growth is
+ # bounded by _write_snapshot_hashes, which compacts the folder back down as it writes.
+ return f"{settings.DATAWAREHOUSE_BUCKET}/person_property_snapshot/{team_id}/{source_id}/{schema_id}"
async def _read_staged_rows(team_id: int, schema_id: str, job_id: str) -> list[dict]:
@@ -125,6 +150,8 @@ async def _read_staged_rows(team_id: int, schema_id: str, job_id: str) -> list[d
try:
listing = await s3_client._ls(f"s3://{prefix}/", detail=True)
except FileNotFoundError:
+ # No staged folder — the sync staged nothing for this run (common on a no-change sync).
+ logger.debug("person-property sync: no staged rows folder", team_id=team_id, schema_id=schema_id)
return []
values = listing.values() if isinstance(listing, dict) else listing
files = [f["Key"] for f in values if f.get("type") != "directory"]
@@ -146,26 +173,90 @@ def _decode_parquet_rows(data: bytes) -> list[dict]:
return pq.read_table(_bytes_reader(data)).to_pylist()
+def _snapshot_file_order(entry: dict) -> tuple:
+ # Oldest first, so a newer run's hashes win for a repeated distinct_id. Order by the file's
+ # last-modified time (the run that wrote it), falling back to the key when a store omits the
+ # timestamp. The (is-missing, time, key) shape keeps None timestamps sorting first without ever
+ # comparing None to a datetime.
+ last_modified = entry.get("LastModified")
+ return (last_modified is None, last_modified, entry["Key"])
+
+
+def _s3_uri(key: str) -> str:
+ return key if key.startswith("s3://") else f"s3://{key}"
+
+
+def _s3_key(key: str) -> str:
+ # Normalize an ``_ls`` key or a path we built for equality checks: drop any scheme and leading slash.
+ return key.removeprefix("s3://").lstrip("/")
+
+
+async def _list_snapshot_files(s3_client, prefix: str) -> list[str]:
+ """S3 keys of the source's snapshot files, oldest first (see ``_snapshot_file_order``). Empty when
+ the folder doesn't exist yet."""
+ try:
+ listing = await s3_client._ls(f"s3://{prefix}/", detail=True)
+ except FileNotFoundError:
+ return []
+ values = listing.values() if isinstance(listing, dict) else listing
+ files = sorted((f for f in values if f.get("type") != "directory"), key=_snapshot_file_order)
+ return [f["Key"] for f in files]
+
+
+async def _merge_snapshot_files(s3_client, file_keys: list[str]) -> dict[str, str]:
+ """Union the given snapshot files into {distinct_id: sent_hash}, later files winning (callers pass
+ them oldest-first). Decodes off the event loop so a large parquet can't starve the heartbeater."""
+ hashes: dict[str, str] = {}
+ for key in file_keys:
+ data = await s3_client._cat_file(_s3_uri(key))
+ for record in await asyncio.to_thread(_decode_parquet_rows, data):
+ hashes[record["distinct_id"]] = record["sent_hash"]
+ return hashes
+
+
async def _read_snapshot_hashes(team_id: int, schema_id: str, source_id: str) -> dict[str, str]:
- path = _snapshot_path(team_id, schema_id, source_id)
+ """Union every parquet file in the source's snapshot folder into {distinct_id: sent_hash}, reading
+ oldest file first so a newer run's hash wins for a repeated distinct_id (a stale hash would only
+ cost an idempotent re-send, but newest-wins avoids even that). Ordering never affects correctness."""
+ prefix = _snapshot_prefix(team_id, schema_id, source_id)
async with aget_s3_client() as s3_client:
- try:
- data = await s3_client._cat_file(f"s3://{path}")
- except FileNotFoundError:
- return {}
- records = await asyncio.to_thread(_decode_parquet_rows, data)
- return {r["distinct_id"]: r["sent_hash"] for r in records}
+ return await _merge_snapshot_files(s3_client, await _list_snapshot_files(s3_client, prefix))
-async def _write_snapshot_hashes(team_id: int, schema_id: str, source_id: str, hashes: dict[str, str]) -> None:
+async def _write_snapshot_hashes(
+ team_id: int, schema_id: str, source_id: str, run_token: str, hashes: dict[str, str]
+) -> None:
+ """Persist this run's produced ``hashes`` and compact the source's snapshot folder in one pass.
+ Writes the union of every existing snapshot file and ``hashes`` into ``{run_token}.parquet`` (this
+ run's values winning), then deletes the other files it merged. Compacting on the write path bounds
+ the folder to roughly one file per run instead of one more file every run — otherwise the reader
+ would download and decode the whole unbounded history on every later run, and a warehouse editor
+ could grow it (by repeatedly changing rows and syncing) until a metadata activity exhausts S3
+ requests, memory, or its timeout. Concurrency-safe: a file a concurrent writer adds after this
+ listing isn't in the merge set, so it's neither merged-away nor deleted, and its rows still surface
+ through the reader's union; the two files collapse on the next run. Write-then-delete keeps a crash
+ between the two harmless — the reader unions both the new file and the not-yet-deleted old ones."""
import pyarrow as pa # noqa: PLC0415
- path = _snapshot_path(team_id, schema_id, source_id)
- table = pa.table({"distinct_id": list(hashes.keys()), "sent_hash": list(hashes.values())})
- buffer = pa.BufferOutputStream()
- pq.write_table(table, buffer, compression="zstd")
+ prefix = _snapshot_prefix(team_id, schema_id, source_id)
+ write_path = f"{prefix}/{run_token}.parquet"
async with aget_s3_client() as s3_client:
- await s3_client._pipe_file(f"s3://{path}", buffer.getvalue().to_pybytes())
+ existing_keys = await _list_snapshot_files(s3_client, prefix)
+ merged = await _merge_snapshot_files(s3_client, existing_keys)
+ merged.update(hashes)
+
+ table = pa.table({"distinct_id": list(merged.keys()), "sent_hash": list(merged.values())})
+ buffer = pa.BufferOutputStream()
+ pq.write_table(table, buffer, compression="zstd")
+ await s3_client._pipe_file(_s3_uri(write_path), buffer.getvalue().to_pybytes())
+
+ # Delete the files we merged, except the one we just wrote (the backfill token reuses its name).
+ stale = [key for key in existing_keys if _s3_key(key) != _s3_key(write_path)]
+ if stale:
+ try:
+ await s3_client._rm([_s3_uri(key) for key in stale])
+ except FileNotFoundError:
+ pass
async def _clear_staged(team_id: int, schema_id: str, job_id: str) -> None:
@@ -177,6 +268,18 @@ async def _clear_staged(team_id: int, schema_id: str, job_id: str) -> None:
pass
+def _get_schema(team_id: int, schema_id: str) -> ExternalDataSchema | None:
+ # select_related the source so folder_path() (which reads source.source_type) doesn't lazy-load.
+ # exclude(deleted=True) matches the rest of the codebase's schema lookups — a soft-deleted schema
+ # (source removed) must not be backfilled against.
+ return (
+ ExternalDataSchema.objects.exclude(deleted=True)
+ .filter(id=schema_id, team_id=team_id)
+ .select_related("source")
+ .first()
+ )
+
+
def _filter_existing_persons(team_id: int, distinct_ids: list[str]) -> set[str]:
if not distinct_ids:
return set()
@@ -223,66 +326,340 @@ def _stamp_provenance(
# --- orchestration -----------------------------------------------------------------------
+async def _process_source_bundles(
+ *,
+ team_id: int,
+ schema_id: str,
+ team_api_token: str,
+ source: PersonPropertySyncSource,
+ bundles: list[tuple[str, dict]],
+ rows_read: int,
+ run_token: str,
+) -> PerSourceResult:
+ """Diff one source's bundles against its snapshot, drop non-existing persons, produce $set intents,
+ stamp provenance, and advance the snapshot. Shared by the incremental sync and the backfill — they
+ differ only in how ``bundles`` are sourced (staged rows vs a full Delta read)."""
+ ps = PerSourceResult(source_id=str(source.source_id), rows_read=rows_read)
+ prior = await _read_snapshot_hashes(team_id, schema_id, str(source.source_id))
+ changed, new_hashes = select_changed(bundles, prior)
+ ps.changed = len(changed)
+ if not changed:
+ return ps
+
+ existing = await database_sync_to_async(_filter_existing_persons, thread_sensitive=False)(
+ team_id, [distinct_id for distinct_id, _ in changed]
+ )
+ to_send = [(distinct_id, bundle) for distinct_id, bundle in changed if distinct_id in existing]
+ ps.existing = len(to_send)
+ ps.skipped_missing_person = len(changed) - len(to_send)
+ if not to_send:
+ logger.info(
+ "person-property sync: no existing persons among changed rows for source",
+ team_id=team_id,
+ schema_id=schema_id,
+ source_id=str(source.source_id),
+ changed=len(changed),
+ )
+ return ps
+
+ produced = await asyncio.to_thread(_produce_intents, team_id, team_api_token, to_send)
+ ps.produced = produced
+
+ # Stamp provenance before advancing the snapshot: the snapshot is the checkpoint that makes
+ # these rows look unchanged on the next run, so anything that must accompany a produce has to
+ # happen first. Stamping is an idempotent update, safe to repeat if a retry re-produces.
+ await database_sync_to_async(_stamp_provenance, thread_sensitive=False)(
+ team_id, schema_id, source, list((source.column_property_map or {}).values())
+ )
+
+ # Record only the distinct_ids we actually produced, as this run's snapshot file.
+ sent_ids = {distinct_id for distinct_id, _ in to_send}
+ produced_hashes = {d: h for d, h in new_hashes.items() if d in sent_ids}
+ await _write_snapshot_hashes(team_id, schema_id, str(source.source_id), run_token, produced_hashes)
+
+ logger.info(
+ "person-property sync: source processed",
+ team_id=team_id,
+ schema_id=schema_id,
+ source_id=str(source.source_id),
+ bundles=len(bundles),
+ changed=len(changed),
+ existing=len(to_send),
+ produced=produced,
+ )
+ return ps
+
+
+def _accumulate(result: SyncResult, ps: PerSourceResult) -> None:
+ result.per_source.append(ps)
+ result.changed += ps.changed
+ result.existing += ps.existing
+ result.produced += ps.produced
+ result.skipped_missing_person += ps.skipped_missing_person
+
+
async def run_person_property_sync(*, team_id: int, schema_id: str, job_id: str) -> SyncResult:
result = SyncResult()
sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(team_id, schema_id)
if not sources:
+ logger.info(
+ "person-property sync: no enabled person sources for schema, nothing to do",
+ team_id=team_id,
+ schema_id=str(schema_id),
+ job_id=job_id,
+ )
return result
team = await database_sync_to_async(Team.objects.get, thread_sensitive=False)(id=team_id)
rows = await _read_staged_rows(team_id, str(schema_id), job_id)
result.sources = len(sources)
result.rows_read = len(rows)
+ logger.info(
+ "person-property sync: read staged rows",
+ team_id=team_id,
+ schema_id=str(schema_id),
+ job_id=job_id,
+ sources=len(sources),
+ rows_read=len(rows),
+ )
for source in sources:
bundles = build_bundles(rows, source.key_column, source.column_property_map or {})
- prior = await _read_snapshot_hashes(team_id, str(schema_id), str(source.source_id))
- changed, new_hashes = select_changed(bundles, prior)
- result.changed += len(changed)
- if not changed:
- continue
-
- existing = await database_sync_to_async(_filter_existing_persons, thread_sensitive=False)(
- team_id, [distinct_id for distinct_id, _ in changed]
+ ps = await _process_source_bundles(
+ team_id=team_id,
+ schema_id=str(schema_id),
+ team_api_token=team.api_token,
+ source=source,
+ bundles=bundles,
+ rows_read=len(rows),
+ run_token=job_id,
)
- to_send = [(distinct_id, bundle) for distinct_id, bundle in changed if distinct_id in existing]
- result.existing += len(to_send)
- result.skipped_missing_person += len(changed) - len(to_send)
- if not to_send:
- logger.info(
- "person-property sync: no existing persons among changed rows for source",
- team_id=team_id,
- schema_id=str(schema_id),
+ _accumulate(result, ps)
+
+ await _clear_staged(team_id, str(schema_id), job_id)
+ return result
+
+
+# --- backfill (full Delta read) ----------------------------------------------------------
+
+# Rows per streamed Delta batch. Batches are processed then discarded, so peak memory is one batch
+# plus the per-source {distinct_id: bundle} accumulator (bounded by distinct-person cardinality).
+BACKFILL_BATCH_SIZE = 50_000
+
+# Backfill runs share one snapshot filename per source (a full-table read replaces the whole set),
+# distinct from the incremental job-id filenames, so the two writers never collide.
+BACKFILL_RUN_TOKEN = "backfill"
+
+
+def _read_delta_bundles(
+ uri: str, storage_options: dict[str, str], sources: list[PersonPropertySyncSource]
+) -> tuple[dict[str, dict[str, dict]], int]:
+ """Stream the table's Delta files from S3 and accumulate {source_id: {distinct_id: bundle}}
+ (last-write-wins per distinct_id). Streams batches — never materializes the whole table — so peak
+ memory tracks distinct persons, not row count. Returns (accumulated, rows_read)."""
+ import deltalake # noqa: PLC0415 — keeps the heavy delta-rs/pandas stack off the import path
+
+ accumulated: dict[str, dict[str, dict]] = {str(source.source_id): {} for source in sources}
+ if not deltalake.DeltaTable.is_deltatable(uri, storage_options=storage_options):
+ # No Delta table at the expected URI yet (e.g. the source's first sync hasn't landed) — treat
+ # as an empty read rather than erroring, but log it since a persistent empty backfill is a
+ # likely "why didn't anything happen" answer.
+ logger.warning("person-property backfill: no Delta table at URI, reading 0 rows", uri=uri)
+ return accumulated, 0
+
+ dataset = deltalake.DeltaTable(uri, storage_options=storage_options).to_pyarrow_dataset()
+ available = set(dataset.schema.names)
+ wanted = {
+ column for source in sources for column in (source.key_column, *(source.column_property_map or {}).keys())
+ }
+ # Project only columns that exist — a misconfigured column drops out rather than erroring.
+ project = sorted(wanted & available)
+
+ # A source whose key column itself is missing produces zero bundles for the whole table, which is
+ # otherwise indistinguishable from a genuinely idle backfill. Log it so a misconfigured mapping
+ # (table dropped/renamed the identifier column) is diagnosable rather than silent.
+ for source in sources:
+ if source.key_column not in available:
+ logger.warning(
+ "person-property backfill: source key column missing from table, will produce nothing",
+ uri=uri,
source_id=str(source.source_id),
- changed=len(changed),
+ key_column=source.key_column,
)
- continue
- produced = await asyncio.to_thread(_produce_intents, team_id, team.api_token, to_send)
- result.produced += produced
+ rows_read = 0
+ for batch in dataset.to_batches(columns=project, batch_size=BACKFILL_BATCH_SIZE):
+ rows = batch.to_pylist()
+ rows_read += len(rows)
+ for source in sources:
+ bucket = accumulated[str(source.source_id)]
+ for distinct_id, bundle in build_bundles(rows, source.key_column, source.column_property_map or {}):
+ bucket[distinct_id] = bundle
+ return accumulated, rows_read
+
+
+async def run_person_property_backfill(*, team_id: int, schema_id: str, trigger: str) -> SyncResult:
+ """Populate person properties from a warehouse table's full Delta data (rather than the
+ incrementally staged rows) — for a new/changed mapping that never saw historical rows. Reads the
+ table once and upserts every enabled person source on the schema; the snapshot diff still skips
+ unchanged values, so re-running is cheap."""
+ result = SyncResult()
+ sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(team_id, schema_id)
+ if not sources:
+ logger.info(
+ "person-property backfill: no enabled person sources for schema, nothing to do",
+ team_id=team_id,
+ schema_id=str(schema_id),
+ trigger=trigger,
+ )
+ return result
- # Stamp provenance before advancing the snapshot: the snapshot is the checkpoint that makes
- # these rows look unchanged on the next run, so anything that must accompany a produce has to
- # happen first. Stamping is an idempotent update, safe to repeat if a retry re-produces.
- await database_sync_to_async(_stamp_provenance, thread_sensitive=False)(
- team_id, str(schema_id), source, list((source.column_property_map or {}).values())
+ schema = await database_sync_to_async(_get_schema, thread_sensitive=False)(team_id, schema_id)
+ if schema is None:
+ logger.warning(
+ "person-property backfill: schema no longer exists, nothing to do",
+ team_id=team_id,
+ schema_id=str(schema_id),
+ trigger=trigger,
)
+ return result
- # Only advance the snapshot for distinct_ids we actually produced.
- sent_ids = {distinct_id for distinct_id, _ in to_send}
- merged = {**prior, **{d: h for d, h in new_hashes.items() if d in sent_ids}}
- await _write_snapshot_hashes(team_id, str(schema_id), str(source.source_id), merged)
+ team = await database_sync_to_async(Team.objects.get, thread_sensitive=False)(id=team_id)
+ # Resolve the Delta folder leaf the same way the loader wrote it: `resolved_s3_folder_name`
+ # (or the schema name) normalized, never `normalized_name`. For schema-qualified/migration-pinned
+ # sources (e.g. Postgres `public.users` → folder `users`) these diverge, and `normalized_name`
+ # would point at a prefix with no Delta log — a silent 0-row no-op.
+ folder_leaf = NamingConvention.normalize_identifier(schema.resolved_s3_folder_name or schema.name)
+ uri = f"{settings.BUCKET_URL}/{schema.folder_path()}/{folder_leaf}"
+ accumulated, rows_read = await asyncio.to_thread(_read_delta_bundles, uri, delta_storage_options(), sources)
+ result.sources = len(sources)
+ result.rows_read = rows_read
+ logger.info(
+ "person-property backfill: read full Delta table",
+ team_id=team_id,
+ schema_id=str(schema_id),
+ trigger=trigger,
+ sources=len(sources),
+ rows_read=rows_read,
+ )
- logger.info(
- "person-property sync: source processed",
+ for source in sources:
+ bundles = list(accumulated[str(source.source_id)].items())
+ ps = await _process_source_bundles(
team_id=team_id,
schema_id=str(schema_id),
- source_id=str(source.source_id),
- bundles=len(bundles),
- changed=len(changed),
- existing=len(to_send),
- produced=produced,
+ team_api_token=team.api_token,
+ source=source,
+ bundles=bundles,
+ rows_read=rows_read,
+ run_token=BACKFILL_RUN_TOKEN,
)
+ _accumulate(result, ps)
- await _clear_staged(team_id, str(schema_id), job_id)
return result
+
+
+# --- run recording (persisted history) ---------------------------------------------------
+
+
+def _record(
+ *,
+ team_id: int,
+ schema_id: str,
+ job_id: str | None,
+ trigger: str,
+ status: str,
+ started_at: str,
+ finished_at: str,
+ ps: PerSourceResult,
+ error: str | None,
+) -> None:
+ record_person_property_sync_run(
+ PersonPropertySyncRunRecord(
+ team_id=team_id,
+ schema_id=schema_id,
+ source_id=ps.source_id,
+ job_id=job_id,
+ trigger=trigger,
+ status=status,
+ started_at=started_at,
+ finished_at=finished_at,
+ rows_read=ps.rows_read,
+ changed=ps.changed,
+ existing=ps.existing,
+ produced=ps.produced,
+ skipped_missing_person=ps.skipped_missing_person,
+ error=error,
+ )
+ )
+
+
+async def record_completed_runs(
+ *,
+ team_id: int,
+ schema_id: str,
+ job_id: str | None,
+ trigger: str,
+ started_at: str,
+ finished_at: str,
+ result: SyncResult,
+) -> None:
+ """Persist one completed run row per source. Never raises — the recorder swallows its own errors,
+ and we still guard here so run bookkeeping can't fail the sync/backfill that produced it (which
+ would otherwise trigger a wasteful Temporal retry of an already-successful, produced run)."""
+ try:
+ for ps in result.per_source:
+ await database_sync_to_async(_record, thread_sensitive=False)(
+ team_id=team_id,
+ schema_id=schema_id,
+ job_id=job_id,
+ trigger=trigger,
+ status="completed",
+ started_at=started_at,
+ finished_at=finished_at,
+ ps=ps,
+ error=None,
+ )
+ except Exception as e:
+ logger.exception(
+ "person-property run: failed to record completed 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_failed_runs(
+ *, team_id: int, schema_id: str, job_id: str | None, trigger: str, started_at: str, finished_at: str, error: str
+) -> None:
+ """Persist a failed run row per source the schema feeds, so a failure is visible in the UI (not
+ only in error tracking). Never raises — this runs on the already-failing path, so any error here
+ (a bad DB state while resolving sources, or the record write itself) is captured, not propagated,
+ to avoid masking the original failure that Temporal needs to see."""
+ 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="failed",
+ started_at=started_at,
+ finished_at=finished_at,
+ ps=PerSourceResult(source_id=str(source.source_id)),
+ error=error,
+ )
+ except Exception as e:
+ logger.exception(
+ "person-property run: failed to record failed 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})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
index 227cac0e95fa..d8aa8f5ac59d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
@@ -106,9 +106,15 @@ class TestRunOrchestration:
assert sorted(d for d, _ in produced_items) == ["a", "b"]
assert result.produced == 2
- # snapshot advanced only for produced ids.
+ # one per-source result is recorded for the recorder to persist.
+ assert [ps.source_id for ps in result.per_source] == ["source-1"]
+ assert result.per_source[0].produced == 2
+ assert result.per_source[0].existing == 2
+
+ # snapshot advanced only for produced ids (args: team, schema, source, run_token, hashes).
assert write_snapshot.await_args is not None
- written = write_snapshot.await_args.args[3]
+ assert write_snapshot.await_args.args[3] == "job-1"
+ written = write_snapshot.await_args.args[4]
assert set(written) == {"a", "b"}
existing.assert_called_once()
@@ -127,3 +133,180 @@ class TestRunOrchestration:
assert result.sources == 0
read.assert_not_awaited()
clear.assert_not_awaited()
+
+
+class TestReadDeltaBundles:
+ """The backfill's Delta reader accumulates last-write-wins per source, scoped to each source's map."""
+
+ def _dataset(self, rows, columns):
+ import pyarrow as pa # local import, mirrors the module's optional-dep handling
+
+ batch = pa.RecordBatch.from_pylist(rows)
+ dataset = MagicMock()
+ dataset.schema.names = columns
+ dataset.to_batches.return_value = [batch]
+ return dataset
+
+ def test_accumulates_per_source_last_write_wins(self):
+ rows = [
+ {"distinct_id": "a", "plan": "free"},
+ {"distinct_id": "a", "plan": "pro"}, # later row wins
+ {"distinct_id": "b", "plan": "team"},
+ ]
+ sources = [
+ PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"}),
+ PersonPropertySyncSource("s2", "d2", "distinct_id", {"plan": "tier"}),
+ ]
+ fake_dt = MagicMock()
+ fake_dt.to_pyarrow_dataset.return_value = self._dataset(rows, ["distinct_id", "plan"])
+ with patch("deltalake.DeltaTable") as dt_cls:
+ dt_cls.is_deltatable.return_value = True
+ dt_cls.return_value = fake_dt
+ accumulated, rows_read = pps._read_delta_bundles("s3://uri", {}, sources)
+
+ assert rows_read == 3
+ assert accumulated["s1"] == {"a": {"plan_tier": "pro"}, "b": {"plan_tier": "team"}}
+ assert accumulated["s2"] == {"a": {"tier": "pro"}, "b": {"tier": "team"}}
+
+ def test_missing_table_returns_empty(self):
+ sources = [PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"})]
+ with patch("deltalake.DeltaTable") as dt_cls:
+ dt_cls.is_deltatable.return_value = False
+ accumulated, rows_read = pps._read_delta_bundles("s3://uri", {}, sources)
+ assert accumulated == {"s1": {}} and rows_read == 0
+
+
+class TestBackfillOrchestration:
+ """One backfill reads the table once and upserts every enabled person source on the schema."""
+
+ @pytest.mark.asyncio
+ async def test_reads_once_and_produces_per_source(self):
+ team = MagicMock(api_token="tok")
+ schema = MagicMock()
+ schema.folder_path.return_value = "team_1_stripe_schema-1"
+ # The backfill resolves the Delta folder from the loader's actual folder name, not normalized_name.
+ schema.resolved_s3_folder_name = "charges"
+ schema.name = "charges"
+ sources = [
+ PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"}),
+ PersonPropertySyncSource("s2", "d2", "distinct_id", {"plan": "tier"}),
+ ]
+ accumulated = {"s1": {"a": {"plan_tier": "pro"}}, "s2": {"a": {"tier": "pro"}}}
+ with (
+ patch(f"{_MODULE}.person_property_sync_sources_for", return_value=sources),
+ patch(f"{_MODULE}._get_schema", return_value=schema),
+ patch(f"{_MODULE}.Team") as team_cls,
+ patch(f"{_MODULE}.delta_storage_options", return_value={}),
+ patch(f"{_MODULE}._read_delta_bundles", return_value=(accumulated, 5)) as read_delta,
+ patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),
+ patch(f"{_MODULE}._filter_existing_persons", return_value={"a"}),
+ patch(f"{_MODULE}._produce_intents", return_value=1) as produce,
+ patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()) as write_snapshot,
+ patch(f"{_MODULE}._stamp_provenance"),
+ ):
+ team_cls.objects.get.return_value = team
+ result = await pps.run_person_property_backfill(team_id=1, schema_id="schema-1", trigger="manual")
+
+ # The table is read exactly once, though two sources map it.
+ read_delta.assert_called_once()
+ assert result.sources == 2
+ assert result.rows_read == 5
+ assert result.produced == 2 # one produced per source
+ assert sorted(ps.source_id for ps in result.per_source) == ["s1", "s2"]
+ # Both sources write a snapshot file under the shared backfill run token.
+ assert write_snapshot.await_count == 2
+ assert all(call.args[3] == pps.BACKFILL_RUN_TOKEN for call in write_snapshot.await_args_list)
+ assert produce.call_count == 2
+
+ @pytest.mark.asyncio
+ async def test_missing_schema_is_a_noop(self):
+ sources = [PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"})]
+ with (
+ patch(f"{_MODULE}.person_property_sync_sources_for", return_value=sources),
+ patch(f"{_MODULE}._get_schema", return_value=None),
+ patch(f"{_MODULE}._read_delta_bundles") as read_delta,
+ ):
+ result = await pps.run_person_property_backfill(team_id=1, schema_id="schema-1", trigger="backfill")
+
+ assert result.sources == 0
+ read_delta.assert_not_called()
+
+
+class _FakeS3:
+ """Minimal in-memory stand-in for the async s3fs client the snapshot helpers use — enough to store
+ real parquet bytes and list/read/delete them. A monotonic counter stamps LastModified so ordering
+ is deterministic without a real clock."""
+
+ def __init__(self):
+ self.store: dict[str, bytes] = {}
+ self.times: dict[str, int] = {}
+ self._clock = 0
+
+ async def _ls(self, path, detail=True):
+ prefix = pps._s3_key(path).rstrip("/") + "/"
+ entries = [
+ {"Key": key, "type": "file", "LastModified": self.times[key]}
+ for key in self.store
+ if key.startswith(prefix)
+ ]
+ if not entries:
+ raise FileNotFoundError(path)
+ return entries
+
+ async def _cat_file(self, path):
+ return self.store[pps._s3_key(path)]
+
+ async def _pipe_file(self, path, data):
+ self._clock += 1
+ key = pps._s3_key(path)
+ self.store[key] = data
+ self.times[key] = self._clock
+
+ async def _rm(self, paths, recursive=False):
+ for path in [paths] if isinstance(paths, str) else paths:
+ key = pps._s3_key(path)
+ self.store.pop(key, None)
+ self.times.pop(key, None)
+
+
+def _fake_s3_patch(fake):
+ import contextlib
+
+ @contextlib.asynccontextmanager
+ async def _cm():
+ yield fake
+
+ return patch(f"{_MODULE}.aget_s3_client", lambda: _cm())
+
+
+class TestSnapshotCompaction:
+ """_write_snapshot_hashes compacts the snapshot folder as it writes, so its history can't grow one
+ file per run (which the reader would then download in full on every later run)."""
+
+ @pytest.mark.asyncio
+ async def test_write_compacts_prior_files_and_preserves_union(self):
+ fake = _FakeS3()
+ with _fake_s3_patch(fake):
+ await pps._write_snapshot_hashes(1, "s", "src", "job-1", {"a": "h1", "b": "h1"})
+ await pps._write_snapshot_hashes(1, "s", "src", "job-2", {"b": "h2", "c": "h2"})
+
+ keys = await pps._list_snapshot_files(fake, pps._snapshot_prefix(1, "s", "src"))
+ hashes = await pps._read_snapshot_hashes(1, "s", "src")
+
+ # Two producing runs collapse to a single file whose union is newest-wins (b came from job-2).
+ assert len(keys) == 1
+ assert hashes == {"a": "h1", "b": "h2", "c": "h2"}
+
+ @pytest.mark.asyncio
+ async def test_repeated_run_token_overwrites_its_own_file(self):
+ fake = _FakeS3()
+ with _fake_s3_patch(fake):
+ # Backfills share one filename; the second write must overwrite it, not delete it as "stale".
+ await pps._write_snapshot_hashes(1, "s", "src", pps.BACKFILL_RUN_TOKEN, {"a": "h1"})
+ await pps._write_snapshot_hashes(1, "s", "src", pps.BACKFILL_RUN_TOKEN, {"a": "h2", "b": "h2"})
+
+ keys = await pps._list_snapshot_files(fake, pps._snapshot_prefix(1, "s", "src"))
+ hashes = await pps._read_snapshot_hashes(1, "s", "src")
+
+ assert len(keys) == 1
+ assert hashes == {"a": "h2", "b": "h2"}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e4c9ffef90e7..8190adf54a66 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16515,6 +16515,45 @@ export namespace Schemas {
color: CustomPropertyOptionColorEnum;
}
+ /**
+ * One person-property sync or backfill run. Read-only: runs are created by the sync/backfill
+ * pipeline, never through the API.
+ */
+ export interface CustomPropertySyncRun {
+ readonly id: string;
+ /** What started the run: 'scheduled' (rode a warehouse sync), 'manual', or 'backfill'. */
+ readonly trigger: string;
+ /** Run status: 'running', 'completed', or 'failed'. */
+ readonly status: string;
+ /**
+ * When the run began.
+ * @nullable
+ */
+ readonly started_at: string | null;
+ /**
+ * When the run ended, or null while running.
+ * @nullable
+ */
+ readonly finished_at: string | null;
+ /** Warehouse rows scanned this run. */
+ readonly rows_read: number;
+ /** Rows whose mapped values changed since the last run. */
+ readonly changed: number;
+ /** Person profiles updated (changed rows that matched an existing person). */
+ readonly existing: number;
+ /** Property-update intents produced to the ingestion pipeline. */
+ readonly produced: number;
+ /** Changed rows dropped because no existing person matched the distinct id. */
+ readonly skipped_missing_person: number;
+ /**
+ * Error summary if the run failed, else null.
+ * @nullable
+ */
+ readonly error: string | null;
+ /** When the run row was recorded. */
+ readonly created_at: string;
+ }
+
/**
* Binds a materialized data-warehouse view column to a custom property definition; the view's
* values are synced onto matching accounts on each materialization.
@@ -16565,6 +16604,18 @@ export namespace Schemas {
readonly created_by: number | null;
/** @nullable */
readonly updated_at: string | null;
+ /**
+ * Person sources only: how often the underlying warehouse schema syncs, in seconds. Null for account sources or when unavailable.
+ * @nullable
+ */
+ readonly sync_frequency_interval_seconds: number | null;
+ /**
+ * Person sources only: approximate time of the next scheduled sync (last synced + interval). Approximate — drifts if the schedule was paused. Null for account sources or if never synced.
+ * @nullable
+ */
+ readonly next_sync_at: string | null;
+ /** Person sources only: the most recent sync/backfill run, or null if none yet. */
+ readonly latest_run: CustomPropertySyncRun | null;
}
/**
@@ -40996,6 +41047,15 @@ export namespace Schemas {
results: CustomPropertySource[];
}
+ export interface PaginatedCustomPropertySyncRunList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: CustomPropertySyncRun[];
+ }
+
export interface PaginatedCustomerJourneyList {
count: number;
/** @nullable */
@@ -73209,6 +73269,21 @@ export namespace Schemas {
offset?: number;
};
+ export type CustomPropertySourcesBackfillCreate202 = { [key: string]: unknown };
+
+ export type CustomPropertySourcesRunsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type CustomPropertySourcesSyncCreate202 = { [key: string]: unknown };
+
export type CustomerJourneysListParams = {
/**
* Number of results to return per page.