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): sync staged rows to person properties via kafka (#70025)

Tom Owersce5e17687524
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 35efd3c79315..8251b6666106 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -516,6 +516,7 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_BOT_ANALYSIS: 'web-analytics-bot-analysis', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_CONVERSION_GOAL_PREAGG: 'web-analytics-conversion-goal-preagg', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_DRAG_TO_ZOOM: 'web-analytics-drag-to-zoom', // owner: @jordanm-posthog #team-web-analytics
+ WAREHOUSE_PERSON_PROPERTIES: 'warehouse-person-properties', // owner: @tomowers #team-warehouse-sources, gates warehouse -> person properties (person-target custom property sources)
WEB_ANALYTICS_EMPTY_ONBOARDING: 'web-analytics-empty-onboarding', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_FILTERS_V2: 'web-analytics-filters-v2', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_FOCUS_MODE: 'web-analytics-focus-mode', // owner: @jordanm-posthog #team-web-analytics
diff --git a/posthog/kafka_client/routing.py b/posthog/kafka_client/routing.py
index a60f50de0be0..dcc1db561c0f 100644
--- a/posthog/kafka_client/routing.py
+++ b/posthog/kafka_client/routing.py
@@ -50,6 +50,8 @@ from posthog.kafka_client.topics import (
KAFKA_PERSON,
KAFKA_PERSON_DISTINCT_ID,
KAFKA_SIGNALS_REPORT_COMPLETED,
+ KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES,
+ KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES_DLQ,
KAFKA_WAREHOUSE_SOURCE_WEBHOOKS,
KAFKA_WAREHOUSE_SOURCE_WEBHOOKS_DLQ,
KAFKA_WAREHOUSE_SOURCES_JOBS,
@@ -94,6 +96,8 @@ _DEFAULT_TOPIC_ROUTING: dict[str, KafkaClusterProfile] = {
KAFKA_WAREHOUSE_SOURCES_JOBS_DLQ: KafkaClusterProfile.WAREHOUSE_SOURCES,
KAFKA_WAREHOUSE_SOURCE_WEBHOOKS: KafkaClusterProfile.WAREHOUSE_SOURCES,
KAFKA_WAREHOUSE_SOURCE_WEBHOOKS_DLQ: KafkaClusterProfile.WAREHOUSE_SOURCES,
+ KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES: KafkaClusterProfile.WAREHOUSE_SOURCES,
+ KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES_DLQ: KafkaClusterProfile.WAREHOUSE_SOURCES,
# --- CYCLOTRON (Warpstream cyclotron) ---
KAFKA_CDP_INTERNAL_EVENTS: KafkaClusterProfile.CYCLOTRON,
KAFKA_DWH_CDP_RAW_TABLE: KafkaClusterProfile.CYCLOTRON,
diff --git a/posthog/kafka_client/topics.py b/posthog/kafka_client/topics.py
index 60cfb69c7ee5..d9e89e02d79d 100644
--- a/posthog/kafka_client/topics.py
+++ b/posthog/kafka_client/topics.py
@@ -90,3 +90,8 @@ KAFKA_SIGNALS_REPORT_COMPLETED = f"{KAFKA_PREFIX}signals_report_completed{SUFFIX
# concern — no Node-side mirror needed.
KAFKA_FLAGS_CACHE_INVALIDATION = f"{KAFKA_PREFIX}flags_cache_invalidation{SUFFIX}"
KAFKA_FLAGS_CACHE_INVALIDATION_DLQ = f"{KAFKA_PREFIX}flags_cache_invalidation_dlq{SUFFIX}"
+
+# Producer: customer_analytics person-property sync activity (warehouse -> person props).
+# Consumer: a dedicated throttling consumer that rate-limits $set events into capture-internal.
+KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES = f"{KAFKA_PREFIX}warehouse_person_property_updates{SUFFIX}"
+KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES_DLQ = f"{KAFKA_PREFIX}warehouse_person_property_updates_dlq{SUFFIX}"
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 8f941ad2c4ab..5b93e558b9c7 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -234,6 +234,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_SYNC_ACTIVITIES,
+ PERSON_PROPERTY_SYNC_WORKFLOWS,
WORKFLOWS as DATA_SYNC_WORKFLOWS,
load_all_sources,
)
@@ -267,8 +269,8 @@ _task_queue_specs = [
),
(
settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
- DATA_WAREHOUSE_METADATA_WORKFLOWS + SEMANTIC_ENRICHMENT_WORKFLOWS,
- DATA_WAREHOUSE_METADATA_ACTIVITIES + SEMANTIC_ENRICHMENT_ACTIVITIES,
+ DATA_WAREHOUSE_METADATA_WORKFLOWS + SEMANTIC_ENRICHMENT_WORKFLOWS + PERSON_PROPERTY_SYNC_WORKFLOWS,
+ DATA_WAREHOUSE_METADATA_ACTIVITIES + SEMANTIC_ENRICHMENT_ACTIVITIES + PERSON_PROPERTY_SYNC_ACTIVITIES,
),
(
settings.DATA_MODELING_TASK_QUEUE,
diff --git a/products/customer_analytics/backend/apps.py b/products/customer_analytics/backend/apps.py
index f559f4730ae8..afa5cebbbb87 100644
--- a/products/customer_analytics/backend/apps.py
+++ b/products/customer_analytics/backend/apps.py
@@ -7,23 +7,34 @@ class CustomerAnalyticsConfig(AppConfig):
label = "customer_analytics"
def ready(self) -> None:
- self._register_person_property_projection()
+ self._register_person_property_hooks()
- def _register_person_property_projection(self) -> None:
+ def _register_person_property_hooks(self) -> None:
"""Tell the data-import pipeline which columns to stage for a schema's person-property
- sources, without warehouse_sources importing this product. The impl is imported lazily so
- the models stay off the django.setup() path.
+ sources, and give its post-sync upsert job the full source configs — without
+ warehouse_sources importing this product. The impls are imported lazily so the models stay
+ off the django.setup() path.
"""
from products.warehouse_sources.backend.facade.hooks import (
PersonPropertySourceProjection,
+ PersonPropertySyncSource,
register_person_property_projection,
+ register_person_property_sync_sources,
)
- def _resolver(team_id: int, schema_id) -> list[PersonPropertySourceProjection] | None:
+ def _projection_resolver(team_id: int, schema_id) -> list[PersonPropertySourceProjection] | None:
from products.customer_analytics.backend.logic.person_property_projection import ( # noqa: PLC0415
person_property_projection,
)
return person_property_projection(team_id, schema_id)
- register_person_property_projection(_resolver)
+ def _sync_sources_resolver(team_id: int, schema_id) -> list[PersonPropertySyncSource] | None:
+ from products.customer_analytics.backend.logic.person_property_projection import ( # noqa: PLC0415
+ person_property_sync_sources,
+ )
+
+ return person_property_sync_sources(team_id, schema_id)
+
+ register_person_property_projection(_projection_resolver)
+ register_person_property_sync_sources(_sync_sources_resolver)
diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.py
index bf95beb5b649..c1526e4d11de 100644
--- a/products/customer_analytics/backend/constants.py
+++ b/products/customer_analytics/backend/constants.py
@@ -3,6 +3,11 @@ DEFAULT_ACTIVITY_EVENT = {"kind": "EventsNode", "event": "$pageview", "name": "$
# Mirrors frontend `FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP`.
CUSTOMER_ANALYTICS_CSP_FLAG = "customer-analytics-csp"
+# Mirrors frontend `FEATURE_FLAGS.WAREHOUSE_PERSON_PROPERTIES`. Gates the whole warehouse -> person
+# properties feature: creating person-target custom property sources (API + UI), staging rows during
+# syncs, and the post-sync upsert workflow.
+WAREHOUSE_PERSON_PROPERTIES_FLAG = "warehouse-person-properties"
+
# Account assignment roles, each assignable to a user. Shared by the external account API's
# request validation and the facade write path so the set is defined once.
ACCOUNT_ASSIGNMENT_ROLE_FIELDS = ("csm", "account_executive", "account_owner")
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index cdd7ad2e4030..25a7f0cb21b4 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -47,6 +47,9 @@ from products.customer_analytics.backend.logic.custom_property_definitions impor
coerce_is_big_number,
normalize_options,
)
+from products.customer_analytics.backend.logic.person_property_projection import (
+ person_properties_flag_enabled as person_properties_flag_enabled,
+)
from products.customer_analytics.backend.logic.usage_spike_notifications import (
notify_managers_of_usage_spike as notify_managers_of_usage_spike,
)
diff --git a/products/customer_analytics/backend/logic/person_property_projection.py b/products/customer_analytics/backend/logic/person_property_projection.py
index 54b9098bfca3..66c6ab369fb4 100644
--- a/products/customer_analytics/backend/logic/person_property_projection.py
+++ b/products/customer_analytics/backend/logic/person_property_projection.py
@@ -1,31 +1,94 @@
-"""Resolves which warehouse columns to stage for a schema's person-property sources.
+"""Resolves the person-property source configs the warehouse import pipeline asks for.
-Registered as the data-import pipeline's projection hook (see apps.ready). Called from the
-pipeline, outside request context, so it scopes explicitly with ``for_team``.
+Registered as the data-import pipeline's projection and sync-config hooks (see apps.ready).
+Called from the pipeline, outside request context, so it scopes explicitly with ``for_team``.
+
+Both resolvers are the feature's pipeline choke point: they return None when the
+``warehouse-person-properties`` rollout flag is off for the team's organization, which switches
+off staging, the post-sync workflow gate, and the upsert in one place. The flag is only evaluated
+once a schema is confirmed to have enabled person sources, so unconfigured schemas (the vast
+majority of syncs) never pay a flag-service call.
"""
from uuid import UUID
+import posthoganalytics
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team
+
+from products.customer_analytics.backend.constants import WAREHOUSE_PERSON_PROPERTIES_FLAG
from products.customer_analytics.backend.models import CustomPropertySource, TargetType
-from products.warehouse_sources.backend.facade.hooks import PersonPropertySourceProjection
+from products.warehouse_sources.backend.facade.hooks import PersonPropertySourceProjection, PersonPropertySyncSource
+
+
+def person_properties_flag_enabled(team_id: int) -> bool:
+ """Whether the warehouse -> person properties rollout flag is on for the team's organization.
+
+ Fails closed: an unknown team or a flag-service error disables the feature for that call
+ rather than letting an unvetted rollout through.
+ """
+ try:
+ organization_id = str(Team.objects.only("organization_id").get(id=team_id).organization_id)
+ except Team.DoesNotExist:
+ return False
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ WAREHOUSE_PERSON_PROPERTIES_FLAG,
+ organization_id,
+ groups={"organization": organization_id},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+
+def _enabled_person_sources(team_id: int, schema_id: str | UUID) -> list[CustomPropertySource]:
+ # Sources without a key column are skipped: their rows have no person identifier to attach
+ # the properties to.
+ return [
+ source
+ for source in CustomPropertySource.objects.for_team(team_id).filter(
+ external_data_schema_id=schema_id,
+ is_enabled=True,
+ definition__target_type=TargetType.PERSON.value,
+ )
+ if source.key_column
+ ]
def person_property_projection(team_id: int, schema_id: str | UUID) -> list[PersonPropertySourceProjection] | None:
"""One projection per enabled person-target source on the schema (its key column plus its
mapped columns), or None when the schema feeds no person properties (so the pipeline stages
- nothing). Sources without a key column are skipped: their rows have no person identifier to
- attach the properties to."""
- sources = CustomPropertySource.objects.for_team(team_id).filter(
- external_data_schema_id=schema_id,
- is_enabled=True,
- definition__target_type=TargetType.PERSON.value,
- )
- projections = [
+ nothing)."""
+ sources = _enabled_person_sources(team_id, schema_id)
+ if not sources or not person_properties_flag_enabled(team_id):
+ return None
+ return [
PersonPropertySourceProjection(
key_column=source.key_column,
columns=frozenset({source.key_column, *(source.column_property_map or {}).keys()}),
)
for source in sources
- if source.key_column
]
- return projections or None
+
+
+def person_property_sync_sources(team_id: int, schema_id: str | UUID) -> list[PersonPropertySyncSource] | None:
+ """Full sync config per enabled person-target source on the schema, for the warehouse-owned
+ post-sync upsert job — or None when the schema feeds no person properties."""
+ sources = _enabled_person_sources(team_id, schema_id)
+ if not sources or not person_properties_flag_enabled(team_id):
+ return None
+ return [
+ PersonPropertySyncSource(
+ source_id=str(source.id),
+ definition_id=str(source.definition_id),
+ key_column=source.key_column,
+ column_property_map=dict(source.column_property_map or {}),
+ )
+ for source in sources
+ ]
diff --git a/products/customer_analytics/backend/logic/person_property_projection_test.py b/products/customer_analytics/backend/logic/person_property_projection_test.py
index 88a19861d9c3..269506a3da2c 100644
--- a/products/customer_analytics/backend/logic/person_property_projection_test.py
+++ b/products/customer_analytics/backend/logic/person_property_projection_test.py
@@ -1,6 +1,10 @@
from posthog.test.base import BaseTest
+from unittest.mock import patch
-from products.customer_analytics.backend.logic.person_property_projection import person_property_projection
+from products.customer_analytics.backend.logic.person_property_projection import (
+ person_property_projection,
+ person_property_sync_sources,
+)
from products.customer_analytics.backend.models import CustomPropertySource, 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
@@ -15,6 +19,12 @@ class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):
team=self.team, source_id="s", connection_id="c", status="Running", source_type="Stripe"
)
self.schema = ExternalDataSchema.objects.create(team=self.team, source=source, name="users")
+ flag_patch = patch(
+ "products.customer_analytics.backend.logic.person_property_projection.person_properties_flag_enabled",
+ return_value=True,
+ )
+ flag_patch.start()
+ self.addCleanup(flag_patch.stop)
def _person_source(self, name, key_column, column_property_map, *, is_enabled=True, schema=None):
definition = create_custom_property_definition(
@@ -68,3 +78,31 @@ class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):
)
assert self._projected() == {"distinct_id": ["distinct_id", "plan"]}
+
+ def test_sync_sources_carry_full_config_for_the_upsert_job(self):
+ # The warehouse-owned sync job consumes these configs through the hook; a wrong field
+ # mapping here mis-stamps provenance or upserts the wrong columns.
+ source = self._person_source("A", "distinct_id", {"plan": "plan_tier"})
+
+ configs = person_property_sync_sources(self.team.id, self.schema.id)
+
+ assert configs is not None and len(configs) == 1
+ config = configs[0]
+ assert config.source_id == str(source.id)
+ assert config.definition_id == str(source.definition_id)
+ assert config.key_column == "distinct_id"
+ assert config.column_property_map == {"plan": "plan_tier"}
+
+ def test_sync_sources_none_when_no_person_sources(self):
+ assert person_property_sync_sources(self.team.id, self.schema.id) is None
+
+ def test_flag_off_disables_both_resolvers_despite_configured_sources(self):
+ # The resolvers are the pipeline choke point for the rollout flag: with the flag off,
+ # configured sources must not stage rows or start the sync workflow.
+ self._person_source("A", "distinct_id", {"plan": "plan_tier"})
+ with patch(
+ "products.customer_analytics.backend.logic.person_property_projection.person_properties_flag_enabled",
+ return_value=False,
+ ):
+ assert person_property_projection(self.team.id, self.schema.id) is None
+ assert person_property_sync_sources(self.team.id, self.schema.id) is None
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index e73c266a0905..c21b5112992b 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -254,6 +254,8 @@ class CustomPropertyDefinitionViewSet(
serializer = CustomPropertyDefinitionSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
data = serializer.validated_data
+ if data.target_type == "person" and not api.person_properties_flag_enabled(self.team_id):
+ raise ValidationError({"target_type": "Person properties from warehouse data are not enabled yet."})
try:
definition = api.create_custom_property_definition(
team_id=self.team_id,
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
index c6cdc4e49497..574b24040ff8 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
@@ -18,8 +18,10 @@ import {
} from '@posthog/lemon-ui'
import type { DataColorToken } from 'lib/colors'
+import { FEATURE_FLAGS } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
import type { CustomPropertyOptionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
@@ -244,8 +246,12 @@ export function CustomPropertyModal(): JSX.Element {
createWorkflowForProperty,
} = useActions(customPropertyDefinitionsLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
const showBigNumberSwitch = isNumericDisplayType(customPropertyForm.displayType)
const { sourceMode, targetType } = customPropertyForm
+ // Person-target properties are gated behind the rollout flag; an existing person property
+ // stays editable so a rollback doesn't strand its configuration.
+ const personTargetAvailable = !!featureFlags[FEATURE_FLAGS.WAREHOUSE_PERSON_PROPERTIES] || targetType === 'person'
const hasExistingSource = !!editingDefinition?.source
const noViews = !savedQueriesLoading && materializedViews.length === 0
@@ -313,25 +319,27 @@ export function CustomPropertyModal(): JSX.Element {
<LemonField name="description" label="Description">
<LemonTextArea placeholder="Optional description" minRows={2} />
</LemonField>
- <LemonField
- name="targetType"
- label="Attach to"
- help="Account properties describe a customer; person properties attach to individual people and are usable in feature flags, cohorts and insights."
- >
- {({ value, onChange }) => (
- <LemonSegmentedButton
- value={value}
- onChange={onChange}
- options={TARGET_TYPE_OPTIONS.map((option) => ({
- ...option,
- disabledReason: editingDefinition
- ? "A property's target can't change after it's created"
- : undefined,
- }))}
- fullWidth
- />
- )}
- </LemonField>
+ {personTargetAvailable && (
+ <LemonField
+ name="targetType"
+ label="Attach to"
+ help="Account properties describe a customer; person properties attach to individual people and are usable in feature flags, cohorts and insights."
+ >
+ {({ value, onChange }) => (
+ <LemonSegmentedButton
+ value={value}
+ onChange={onChange}
+ options={TARGET_TYPE_OPTIONS.map((option) => ({
+ ...option,
+ disabledReason: editingDefinition
+ ? "A property's target can't change after it's created"
+ : undefined,
+ }))}
+ fullWidth
+ />
+ )}
+ </LemonField>
+ )}
<LemonField name="displayType" label="Type">
<LemonSelect options={DISPLAY_TYPE_OPTIONS} fullWidth />
</LemonField>
diff --git a/products/warehouse_sources/backend/facade/hooks.py b/products/warehouse_sources/backend/facade/hooks.py
index 4b5019548209..c204842305c4 100644
--- a/products/warehouse_sources/backend/facade/hooks.py
+++ b/products/warehouse_sources/backend/facade/hooks.py
@@ -11,19 +11,23 @@ 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,
+ PersonPropertySyncSource,
person_property_projection_for,
register_emit_signals_gate,
register_engineering_analytics_view_sync,
register_person_property_projection,
+ register_person_property_sync_sources,
register_revenue_view_sync,
)
__all__ = [
"EmitSignalsActivityInputs",
"PersonPropertySourceProjection",
+ "PersonPropertySyncSource",
"person_property_projection_for",
"register_emit_signals_gate",
"register_engineering_analytics_view_sync",
"register_person_property_projection",
+ "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 87eb70bc719b..8af56b0d0a43 100644
--- a/products/warehouse_sources/backend/facade/temporal.py
+++ b/products/warehouse_sources/backend/facade/temporal.py
@@ -16,6 +16,10 @@ 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_sync_job import (
+ PERSON_PROPERTY_SYNC_ACTIVITIES,
+ PERSON_PROPERTY_SYNC_WORKFLOWS,
+)
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 (
@@ -28,6 +32,8 @@ __all__ = [
"ACTIVITIES",
"METADATA_ACTIVITIES",
"METADATA_WORKFLOWS",
+ "PERSON_PROPERTY_SYNC_ACTIVITIES",
+ "PERSON_PROPERTY_SYNC_WORKFLOWS",
"WORKFLOWS",
"load_all_sources",
"prepare_s3_files_for_querying",
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 be865e3a2e60..9257ae3de6dc 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
@@ -35,7 +35,10 @@ from products.data_warehouse.backend.facade.api import (
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, update_should_sync
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
-from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import EmitSignalsActivityInputs
+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
+ EmitSignalsActivityInputs,
+ PersonPropertySyncActivityInputs,
+)
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
get_data_import_finished_metric,
get_v3_lock_skipped_metric,
@@ -417,6 +420,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
schema_name, last_synced_at, emit_signals_enabled = None, None, False
enrichment_needed = False
statistics_needed = False
+ person_property_sync_enabled = False
else:
job_id = create_job_result.job_id
incremental_or_append = create_job_result.incremental_or_append
@@ -426,6 +430,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
emit_signals_enabled = create_job_result.emit_signals_enabled
enrichment_needed = create_job_result.enrichment_needed
statistics_needed = create_job_result.statistics_needed
+ person_property_sync_enabled = create_job_result.person_property_sync_enabled
update_inputs.job_id = str(job_id) if job_id is not None else None
# Check billing limits
@@ -569,6 +574,28 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
execution_timeout=dt.timedelta(hours=2),
)
+ # Upsert warehouse columns onto person properties for any enabled person-target source.
+ # 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:
+ 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,
+ ),
+ id=f"sync-warehouse-person-properties-{job_id}",
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
+ parent_close_policy=ParentClosePolicy.ABANDON,
+ execution_timeout=dt.timedelta(hours=6),
+ )
+
# Generate semantic descriptions for the synced table. Gated up front on actual need
# (feature flag + AI consent AND unannotated columns / missing table description, resolved in
# create_external_data_job_model_activity) so a steady-state sync — which re-fires every few
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 8b5d5964a7bd..d03e6e86178f 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
@@ -135,3 +135,64 @@ def person_property_projection_for(
if _person_property_projection_resolver is None:
return None
return _person_property_projection_resolver(team_id, schema_id)
+
+
+def person_property_sync_enabled_for(team_id: int, schema_id: "uuid.UUID") -> bool:
+ """Gate for starting the person-property sync child workflow: true when the schema feeds at
+ least one enabled person-target source (i.e. there are columns to stage/upsert)."""
+ return person_property_projection_for(team_id, schema_id) is not None
+
+
[email protected](frozen=True)
+class PersonPropertySyncSource:
+ """One enabled person-target source's sync config, resolved through the hook below so the
+ sync job (owned by warehouse_sources) never imports the customer_analytics config models.
+ ``source_id``/``definition_id`` identify the source for provenance stamping; ``key_column``
+ holds the person identifier and ``column_property_map`` maps warehouse column -> person
+ property name."""
+
+ source_id: str
+ definition_id: str
+ key_column: str
+ column_property_map: dict[str, str]
+
+
+PersonPropertySyncSourcesResolver = Callable[[int, "str | uuid.UUID"], Optional[list[PersonPropertySyncSource]]]
+_person_property_sync_sources_resolver: Optional[PersonPropertySyncSourcesResolver] = None
+
+
+def register_person_property_sync_sources(fn: PersonPropertySyncSourcesResolver) -> None:
+ global _person_property_sync_sources_resolver
+ _person_property_sync_sources_resolver = fn
+
+
+def person_property_sync_sources_for(
+ team_id: int, schema_id: "str | uuid.UUID"
+) -> Optional[list[PersonPropertySyncSource]]:
+ if _person_property_sync_sources_resolver is None:
+ return None
+ return _person_property_sync_sources_resolver(team_id, schema_id)
+
+
[email protected](frozen=True)
+class PersonPropertySyncActivityInputs:
+ """Payload the import workflow sends to the person-property sync child workflow."""
+
+ team_id: int
+ schema_id: uuid.UUID
+ source_id: uuid.UUID
+ job_id: str
+ source_type: str
+ schema_name: str
+ last_synced_at: str | None
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {
+ "team_id": self.team_id,
+ "schema_id": str(self.schema_id),
+ "source_id": str(self.source_id),
+ "job_id": self.job_id,
+ "source_type": self.source_type,
+ "schema_name": self.schema_name,
+ }
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
new file mode 100644
index 000000000000..acdc47c8e769
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py
@@ -0,0 +1,123 @@
+"""Post-sync Temporal workflow that upserts staged warehouse rows onto person properties.
+
+Started fire-and-forget by ``ExternalDataJobWorkflow`` after a sync when the schema feeds at least
+one enabled person-target Customer analytics source. Runs on the DATA_WAREHOUSE_METADATA_TASK_QUEUE
+(alongside semantic enrichment and column statistics) so a large first sync's post-processing never
+competes with the sync workers themselves; ``start_temporal_worker`` registers it via the facade's
+``PERSON_PROPERTY_SYNC_WORKFLOWS``/``PERSON_PROPERTY_SYNC_ACTIVITIES``.
+
+Failure semantics: the activity retries up to 3 times, then the (abandoned) child workflow fails
+without affecting the sync. Nothing is lost — staged files are only cleared on success and the
+dedup snapshot only advances per produced person, so the next sync's run re-reads and re-diffs.
+Every terminal failure is captured to error tracking and counted in the metrics below.
+"""
+
+import json
+import time
+import dataclasses
+from datetime import 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 (
+ PersonPropertySyncActivityInputs,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.person_property_sync import (
+ run_person_property_sync,
+)
+
+logger = structlog.get_logger(__name__)
+
+PERSON_PROPERTY_SYNC_TOTAL = Counter(
+ "warehouse_person_property_sync_total",
+ "Person-property sync activity attempts by outcome",
+ labelnames=["team_id", "outcome"],
+)
+
+# Funnel stages: rows_read -> changed (survived the snapshot diff) -> existing (distinct_id
+# resolved to a person) -> produced (intent on Kafka). A stage dropping to zero pinpoints where
+# updates are going missing (nothing staged / nothing changed / no matching persons / produce).
+PERSON_PROPERTY_SYNC_ROWS_TOTAL = Counter(
+ "warehouse_person_property_sync_rows_total",
+ "Rows flowing through each stage of the person-property sync funnel",
+ labelnames=["team_id", "stage"],
+)
+
+PERSON_PROPERTY_SYNC_DURATION_SECONDS = Histogram(
+ "warehouse_person_property_sync_duration_seconds",
+ "Duration of one person-property sync 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),
+)
+
+
+async def sync_warehouse_person_properties_activity(inputs: PersonPropertySyncActivityInputs) -> dict[str, Any]:
+ """Read the rows a sync staged and upsert them onto person properties via Kafka."""
+ log = logger.bind(**inputs.properties_to_log)
+ log.info(f"Starting person-property sync for {inputs.source_type}/{inputs.schema_name}")
+ start = time.monotonic()
+ try:
+ async with Heartbeater():
+ result = await run_person_property_sync(
+ team_id=inputs.team_id, schema_id=str(inputs.schema_id), job_id=inputs.job_id
+ )
+ except Exception as e:
+ # Re-raised so Temporal retries; captured so a terminal failure is visible in error
+ # tracking rather than dying silently in an abandoned child workflow.
+ PERSON_PROPERTY_SYNC_TOTAL.labels(team_id=str(inputs.team_id), outcome="failed").inc()
+ log.exception("Person-property sync failed")
+ capture_exception(e)
+ raise
+
+ 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 (
+ ("read", result.rows_read),
+ ("changed", result.changed),
+ ("existing", result.existing),
+ ("produced", result.produced),
+ ("skipped_missing_person", result.skipped_missing_person),
+ ):
+ if count:
+ PERSON_PROPERTY_SYNC_ROWS_TOTAL.labels(team_id=str(inputs.team_id), stage=stage).inc(count)
+
+ log.info(
+ "Person-property sync 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="sync-warehouse-person-properties")
+class SyncWarehousePersonPropertiesWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> PersonPropertySyncActivityInputs:
+ loaded = json.loads(inputs[0])
+ return PersonPropertySyncActivityInputs(**loaded)
+
+ @workflow.run
+ async def run(self, inputs: PersonPropertySyncActivityInputs) -> None:
+ await workflow.execute_activity(
+ sync_warehouse_person_properties_activity,
+ inputs,
+ start_to_close_timeout=timedelta(hours=6),
+ heartbeat_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+
+PERSON_PROPERTY_SYNC_WORKFLOWS = [SyncWarehousePersonPropertiesWorkflow]
+PERSON_PROPERTY_SYNC_ACTIVITIES = [sync_warehouse_person_properties_activity]
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
new file mode 100644
index 000000000000..6c92017635bd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
@@ -0,0 +1,288 @@
+"""Upsert warehouse columns onto person properties from the rows a sync staged to S3.
+
+Runs in a post-sync Temporal activity (see data_imports/person_property_sync_job.py). Per enabled
+person-target source for the schema it:
+
+1. reads the staged parquet (already just this run's changed rows),
+2. builds each row's {property: value} bundle keyed by distinct_id,
+3. diffs against the source's last-sent snapshot (S3) so unchanged values are skipped even on a
+ full refresh,
+4. drops distinct_ids that don't resolve to an existing person (personhog),
+5. produces one $set intent per survivor to Kafka (a throttling consumer sends them to capture),
+6. updates the snapshot, stamps provenance on the person PropertyDefinitions, and clears the staged
+ files.
+
+The source configs (key column + column -> property map) are resolved through the
+``person_property_sync_sources_for`` hook so this module never imports the customer_analytics
+config models. The pure functions (bundle building, hashing, diff) are unit-tested directly; the
+S3/personhog/Kafka helpers are the boundaries and are mocked in the orchestration test.
+"""
+
+import json
+import asyncio
+import hashlib
+import dataclasses
+
+from django.conf import settings
+
+import structlog
+import pyarrow.parquet as pq
+
+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
+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.temporal.data_imports.external_product_hooks import (
+ PersonPropertySyncSource,
+ person_property_sync_sources_for,
+)
+
+logger = structlog.get_logger(__name__)
+
+EVENT_SOURCE = "customer_analytics_person_property_sync"
+
+
+class SyncResult:
+ sources: int = 0
+ rows_read: int = 0
+ changed: int = 0
+ existing: int = 0
+ produced: int = 0
+ # 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
+
+
+# --- pure core ---------------------------------------------------------------------------
+
+
+def bundle_hash(bundle: dict) -> str:
+ """Stable hash of a {property: value} bundle. sort_keys + default=str so re-ordering or
+ non-JSON scalars (datetimes) don't spuriously look changed.
+
+ The hash covers the source's whole bundle (all of its mapped properties for one person), not
+ each property individually — one changed column re-sends every property the source maps for
+ that person. That's deliberately coarse: re-`$set`ting an unchanged value is a no-op, and one
+ hash per (source, distinct_id) keeps the snapshot a flat two-column parquet."""
+ return hashlib.sha256(json.dumps(bundle, sort_keys=True, default=str).encode("utf-8")).hexdigest()
+
+
+def build_bundles(rows: list[dict], key_column: str, column_property_map: dict[str, str]) -> list[tuple[str, dict]]:
+ """(distinct_id, {person_property: value}) for each row with a non-null key and at least one
+ non-null mapped value. Missing columns are simply absent (a misconfigured source degrades to
+ fewer properties rather than erroring)."""
+ bundles: list[tuple[str, dict]] = []
+ for row in rows:
+ key = row.get(key_column)
+ if key is None:
+ continue
+ bundle = {prop: row[col] for col, prop in column_property_map.items() if row.get(col) is not None}
+ if bundle:
+ bundles.append((str(key), bundle))
+ return bundles
+
+
+def select_changed(
+ bundles: list[tuple[str, dict]], prior_hashes: dict[str, str]
+) -> tuple[list[tuple[str, dict]], dict[str, str]]:
+ """Keep only bundles whose hash differs from the snapshot. Returns (changed, hashes-for-changed).
+ Last write wins when a distinct_id appears twice in one run."""
+ changed: list[tuple[str, dict]] = []
+ new_hashes: dict[str, str] = {}
+ seen: set[str] = set()
+ for distinct_id, bundle in bundles:
+ current = bundle_hash(bundle)
+ if prior_hashes.get(distinct_id) == current and distinct_id not in new_hashes:
+ continue
+ if distinct_id in seen:
+ # replace the earlier bundle for this run with the later one
+ changed = [(d, b) for d, b in changed if d != distinct_id]
+ changed.append((distinct_id, bundle))
+ new_hashes[distinct_id] = current
+ seen.add(distinct_id)
+ return changed, new_hashes
+
+
+# --- S3 / Kafka / personhog boundaries (mocked in tests) ---------------------------------
+
+
+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"
+
+
+async def _read_staged_rows(team_id: int, schema_id: str, job_id: str) -> list[dict]:
+ prefix = _staged_prefix(team_id, schema_id, job_id)
+ rows: list[dict] = []
+ async with aget_s3_client() as s3_client:
+ try:
+ listing = await s3_client._ls(f"s3://{prefix}/", detail=True)
+ except FileNotFoundError:
+ return []
+ values = listing.values() if isinstance(listing, dict) else listing
+ files = [f["Key"] for f in values if f.get("type") != "directory"]
+ for file_path in files:
+ data = await s3_client._cat_file(f"s3://{file_path}" if not file_path.startswith("s3://") else file_path)
+ # Decode off the event loop: a large parquet chunk would otherwise block the async
+ # activity long enough to starve the heartbeater and trip its timeout.
+ rows.extend(await asyncio.to_thread(_decode_parquet_rows, data))
+ return rows
+
+
+def _bytes_reader(data: bytes):
+ import io # noqa: PLC0415 — local to keep the module import light
+
+ return io.BytesIO(data)
+
+
+def _decode_parquet_rows(data: bytes) -> list[dict]:
+ return pq.read_table(_bytes_reader(data)).to_pylist()
+
+
+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)
+ 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}
+
+
+async def _write_snapshot_hashes(team_id: int, schema_id: str, source_id: str, hashes: dict[str, str]) -> None:
+ 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")
+ async with aget_s3_client() as s3_client:
+ await s3_client._pipe_file(f"s3://{path}", buffer.getvalue().to_pybytes())
+
+
+async def _clear_staged(team_id: int, schema_id: str, job_id: str) -> None:
+ prefix = _staged_prefix(team_id, schema_id, job_id)
+ async with aget_s3_client() as s3_client:
+ try:
+ await s3_client._rm(f"s3://{prefix}/", recursive=True)
+ except FileNotFoundError:
+ pass
+
+
+def _filter_existing_persons(team_id: int, distinct_ids: list[str]) -> set[str]:
+ if not distinct_ids:
+ return set()
+ return set(get_persons_mapped_by_distinct_id(team_id, distinct_ids).keys())
+
+
+def _produce_intents(team_id: int, token: str, items: list[tuple[str, dict]]) -> int:
+ """Produce one $set intent per person to Kafka, keyed by team:distinct_id so the consumer can
+ throttle per team and preserve per-person ordering. Returns the count produced."""
+ produced = 0
+ with producer_scope(topic=KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES) as producer:
+ for distinct_id, bundle in items:
+ producer.produce(
+ topic=KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES,
+ data={
+ "team_id": team_id,
+ "token": token,
+ "distinct_id": distinct_id,
+ "properties": bundle,
+ "event_source": EVENT_SOURCE,
+ },
+ key=f"{team_id}:{distinct_id}",
+ )
+ produced += 1
+ return produced
+
+
+def _stamp_provenance(
+ team_id: int, schema_id: str, source: PersonPropertySyncSource, property_names: list[str]
+) -> None:
+ # UPDATE-only on purpose: definitions are created by ingestion's propdef upsert when the $set
+ # lands, so a brand-new property may not have a row yet on the first sync — the next sync's
+ # stamp catches it. Never inserting means this can't race that upsert.
+ origin = {
+ "source_id": str(source.definition_id),
+ "schema_id": str(schema_id),
+ "custom_property_source_id": str(source.source_id),
+ }
+ PropertyDefinition.objects.filter(
+ team_id=team_id, type=PropertyDefinition.Type.PERSON, name__in=property_names
+ ).update(warehouse_origin=origin)
+
+
+# --- orchestration -----------------------------------------------------------------------
+
+
+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:
+ 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)
+
+ 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]
+ )
+ 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),
+ source_id=str(source.source_id),
+ changed=len(changed),
+ )
+ continue
+
+ produced = await asyncio.to_thread(_produce_intents, team_id, team.api_token, to_send)
+ result.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, str(schema_id), source, list((source.column_property_map or {}).values())
+ )
+
+ # 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)
+
+ logger.info(
+ "person-property sync: source processed",
+ 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,
+ )
+
+ await _clear_staged(team_id, str(schema_id), job_id)
+ return result
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
new file mode 100644
index 000000000000..227cac0e95fa
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
@@ -0,0 +1,129 @@
+from datetime import datetime
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import PersonPropertySyncSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline import person_property_sync as pps
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.person_property_sync"
+
+
+class TestBuildBundles:
+ def test_maps_columns_and_stringifies_key(self):
+ rows = [{"distinct_id": 123, "plan": "pro", "seats": 5}]
+ bundles = pps.build_bundles(rows, "distinct_id", {"plan": "plan_tier", "seats": "seat_count"})
+ assert bundles == [("123", {"plan_tier": "pro", "seat_count": 5})]
+
+ @parameterized.expand(
+ [
+ ("null_key", [{"distinct_id": None, "plan": "pro"}], []),
+ ("null_value_excluded", [{"distinct_id": "a", "plan": None}], []),
+ ("missing_column_excluded", [{"distinct_id": "a"}], []),
+ ]
+ )
+ def test_rows_without_usable_data_are_skipped(self, _name, rows, expected):
+ assert pps.build_bundles(rows, "distinct_id", {"plan": "plan_tier"}) == expected
+
+ def test_partial_bundle_keeps_present_values(self):
+ rows = [{"distinct_id": "a", "plan": "pro", "seats": None}]
+ assert pps.build_bundles(rows, "distinct_id", {"plan": "plan_tier", "seats": "seat_count"}) == [
+ ("a", {"plan_tier": "pro"})
+ ]
+
+
+class TestBundleHash:
+ def test_is_order_independent(self):
+ assert pps.bundle_hash({"a": 1, "b": 2}) == pps.bundle_hash({"b": 2, "a": 1})
+
+ def test_handles_non_json_scalars(self):
+ # datetimes must hash without raising
+ assert isinstance(pps.bundle_hash({"t": datetime(2026, 1, 1)}), str)
+
+ def test_different_values_hash_differently(self):
+ assert pps.bundle_hash({"a": 1}) != pps.bundle_hash({"a": 2})
+
+
+class TestSelectChanged:
+ def test_skips_unchanged_and_keeps_changed_and_new(self):
+ unchanged_hash = pps.bundle_hash({"plan_tier": "pro"})
+ bundles = [
+ ("unchanged", {"plan_tier": "pro"}),
+ ("changed", {"plan_tier": "enterprise"}),
+ ("new", {"plan_tier": "free"}),
+ ]
+ prior = {"unchanged": unchanged_hash, "changed": pps.bundle_hash({"plan_tier": "starter"})}
+
+ changed, new_hashes = pps.select_changed(bundles, prior)
+
+ assert sorted(d for d, _ in changed) == ["changed", "new"]
+ assert set(new_hashes) == {"changed", "new"}
+
+ def test_last_write_wins_for_duplicate_distinct_id_in_run(self):
+ bundles = [("a", {"plan_tier": "old"}), ("a", {"plan_tier": "new"})]
+ changed, new_hashes = pps.select_changed(bundles, {})
+ assert changed == [("a", {"plan_tier": "new"})]
+ assert new_hashes["a"] == pps.bundle_hash({"plan_tier": "new"})
+
+
+class TestRunOrchestration:
+ """Orchestration control flow with all I/O boundaries (S3, personhog, Kafka, DB) mocked."""
+
+ def _source(self):
+ return PersonPropertySyncSource(
+ source_id="source-1",
+ definition_id="def-1",
+ key_column="distinct_id",
+ column_property_map={"plan": "plan_tier"},
+ )
+
+ @pytest.mark.asyncio
+ async def test_produces_only_changed_and_existing_persons_and_advances_snapshot(self):
+ team = MagicMock(api_token="tok", project_id=7)
+ rows = [
+ {"distinct_id": "a", "plan": "pro"},
+ {"distinct_id": "b", "plan": "free"},
+ {"distinct_id": "ghost", "plan": "x"},
+ ]
+ with (
+ patch(f"{_MODULE}.person_property_sync_sources_for", return_value=[self._source()]),
+ patch(f"{_MODULE}.Team") as team_cls,
+ patch(f"{_MODULE}._read_staged_rows", new=AsyncMock(return_value=rows)),
+ patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),
+ patch(f"{_MODULE}._filter_existing_persons", return_value={"a", "b"}) as existing,
+ patch(f"{_MODULE}._produce_intents", return_value=2) as produce,
+ patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()) as write_snapshot,
+ patch(f"{_MODULE}._stamp_provenance") as stamp,
+ patch(f"{_MODULE}._clear_staged", new=AsyncMock()) as clear,
+ ):
+ team_cls.objects.get.return_value = team
+ result = await pps.run_person_property_sync(team_id=1, schema_id="schema-1", job_id="job-1")
+
+ # ghost is filtered out; only a and b are produced.
+ produced_items = produce.call_args.args[2]
+ assert sorted(d for d, _ in produced_items) == ["a", "b"]
+ assert result.produced == 2
+
+ # snapshot advanced only for produced ids.
+ assert write_snapshot.await_args is not None
+ written = write_snapshot.await_args.args[3]
+ assert set(written) == {"a", "b"}
+
+ existing.assert_called_once()
+ stamp.assert_called_once()
+ clear.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_no_sources_is_a_noop(self):
+ with (
+ patch(f"{_MODULE}.person_property_sync_sources_for", return_value=None),
+ patch(f"{_MODULE}._read_staged_rows", new=AsyncMock()) as read,
+ patch(f"{_MODULE}._clear_staged", new=AsyncMock()) as clear,
+ ):
+ result = await pps.run_person_property_sync(team_id=1, schema_id="schema-1", job_id="job-1")
+
+ assert result.sources == 0
+ read.assert_not_awaited()
+ clear.assert_not_awaited()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index e5d994fe7e42..9bcbf53fc4d9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -22,7 +22,10 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import HIDDEN_COLUMNS, DataWarehouseTable
-from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import emit_signals_enabled_for
+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
+ emit_signals_enabled_for,
+ person_property_sync_enabled_for,
+)
WAREHOUSE_PIPELINES_V3_FLAG = "warehouse-pipelines-v3"
@@ -156,6 +159,9 @@ class CreateExternalDataJobModelActivityOutputs:
enrichment_needed: bool = False
# True when statistics are permitted AND stale (no row yet, or older than the recompute interval).
statistics_needed: bool = False
+ # True when the schema feeds at least one enabled person-target Customer analytics source, so the
+ # workflow should start the person-property sync child. Gated up front to avoid a no-op child per sync.
+ person_property_sync_enabled: bool = False
@activity.defn
@@ -241,6 +247,10 @@ def create_external_data_job_model_activity(
enrichment_needed = enrichment_should_run and _enrichment_pending(inputs.team_id, table, schema)
statistics_needed = statistics_should_run and _statistics_stale(inputs.team_id, table)
+ # Whether this schema feeds any enabled person-target Customer analytics source (owned by
+ # customer_analytics via external_product_hooks; not imported here).
+ person_property_sync_enabled = person_property_sync_enabled_for(inputs.team_id, schema.id)
+
return CreateExternalDataJobModelActivityOutputs(
job_id=str(job.id),
incremental_or_append=schema.is_incremental or schema.is_append or schema.is_webhook,
@@ -252,6 +262,7 @@ def create_external_data_job_model_activity(
statistics_enabled=statistics_should_run,
enrichment_needed=enrichment_needed,
statistics_needed=statistics_needed,
+ person_property_sync_enabled=person_property_sync_enabled,
)
except Exception as e:
logger.exception(