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-target custom property config (#69979)

Tom Owerse2a7f263287f
diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
index ad2e83d259d4..8a4397354cfc 100644
--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
@@ -1359,6 +1359,7 @@
"posthog_propertydefinition"."property_type",
"posthog_propertydefinition"."type",
"posthog_propertydefinition"."group_type_index",
+ "posthog_propertydefinition"."warehouse_origin",
"posthog_propertydefinition"."property_type_format",
"posthog_propertydefinition"."volume_30_day",
"posthog_propertydefinition"."query_usage_30_day"
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index b4fc249eba14..4b2ae35d4af6 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -575,11 +575,18 @@ SPECTACULAR_SETTINGS = {
"UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES",
"BatchExportRunStatusEnum": "products.batch_exports.backend.models.batch_export.BatchExportRun.Status",
"HeatmapType": "products.web_analytics.backend.models.heatmap_saved.SavedHeatmap.Type",
+ # Pin the subscriptions target enum to its existing name so adding customer_analytics'
+ # `target_type` (below, inline-list category) doesn't auto-rename this shared-basename enum
+ # and churn subscriptions' generated types.
+ "TargetTypeEnum": "products.exports.backend.models.subscription.Subscription.SubscriptionTarget",
# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---
"PropertyGroupOperator": ["AND", "OR"],
# ReviewHog findings expose the same priority set on two fields (effective_priority +
# reviewer_priority); pin one shared name for the choice set.
"ReviewIssuePriorityEnum": ["must_fix", "should_fix", "consider"],
+ # Pin the customer_analytics custom-property target so it doesn't auto-collide with the
+ # subscriptions `target_type` enum (which would rename subscriptions' generated type).
+ "CustomPropertyDefinitionTargetType": ["account", "person"],
# The metrics query's OTel metric-type filter; without a pinned name it
# collides with the experiments MetricTypeEnum (funnel/ratio/...).
"OtelMetricTypeEnum": ["gauge", "sum", "histogram", "exponential_histogram", "summary"],
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index d9a13e9bf215..cdd7ad2e4030 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -59,6 +59,7 @@ from products.customer_analytics.backend.models import (
CustomPropertyDefinition,
CustomPropertySource,
DisplayType,
+ TargetType,
)
from products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties
from products.notebooks.backend.facade import (
@@ -780,6 +781,7 @@ def _to_custom_property_definition_view(
name=definition.name,
description=definition.description,
display_type=definition.display_type,
+ target_type=definition.target_type,
is_big_number=definition.is_big_number,
created_at=definition.created_at,
created_by=definition.created_by_id,
@@ -884,6 +886,7 @@ def create_custom_property_definition(
display_type: str,
is_big_number: bool,
options: list[dict[str, Any]] | None = None,
+ target_type: str = TargetType.ACCOUNT.value,
organization_id,
user: "User",
was_impersonated: bool,
@@ -895,6 +898,7 @@ def create_custom_property_definition(
name=name,
description=description,
display_type=display_type,
+ target_type=target_type,
is_big_number=coerce_is_big_number(display_type, is_big_number),
options=normalize_options(DisplayType(display_type), options),
)
@@ -1003,8 +1007,10 @@ def _to_custom_property_source_view(source: CustomPropertySource) -> contracts.C
id=source.id,
definition=source.definition_id,
saved_query=source.saved_query_id,
+ external_data_schema=source.external_data_schema_id,
source_column=source.source_column,
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,
@@ -1022,6 +1028,25 @@ def _saved_query_belongs_to_team(team_id: int, saved_query_id) -> bool:
return saved_query_model.objects.filter(id=saved_query_id, team_id=team_id).exclude(deleted=True).exists()
+def _external_data_schema_belongs_to_team(team_id: int, schema_id) -> bool:
+ """Whether the warehouse schema (raw synced table) exists for this team. ``apps.get_model`` keeps
+ customer_analytics from importing warehouse_sources internals (isolation)."""
+ schema_model = apps.get_model("warehouse_sources", "ExternalDataSchema")
+ return schema_model.objects.filter(id=schema_id, team_id=team_id).exists()
+
+
+def _validate_column_property_map(column_property_map: Any) -> dict[str, str]:
+ """A person-source's column->property map must be a non-empty {str: non-empty str} object."""
+ if not isinstance(column_property_map, dict) or not column_property_map:
+ raise CustomPropertySourceValidationError("column_property_map must be a non-empty object.")
+ for column, property_name in column_property_map.items():
+ if not isinstance(column, str) or not column:
+ raise CustomPropertySourceValidationError("column_property_map keys must be non-empty column names.")
+ if not isinstance(property_name, str) or not property_name:
+ raise CustomPropertySourceValidationError("column_property_map values must be non-empty property names.")
+ return column_property_map
+
+
def _enqueue_custom_property_sync(team_id: int, saved_query_id: str) -> None:
"""Dispatch the sync task by name. Enqueue failure must not fail the originating write, so it's swallowed."""
try:
@@ -1061,26 +1086,55 @@ def create_custom_property_source(
*,
team_id: int,
definition_id: str | UUID,
- saved_query_id: str | UUID,
- source_column: str,
key_column: str,
is_enabled: bool,
user: "User",
+ saved_query_id: str | UUID | None = None,
+ source_column: str | None = None,
+ external_data_schema_id: str | UUID | None = None,
+ column_property_map: dict | None = None,
) -> contracts.CustomPropertySourceView:
- if not _saved_query_belongs_to_team(team_id, saved_query_id):
- raise CustomPropertySourceValidationError("Saved query not found for this team.")
- if _get_team_scoped(CustomPropertyDefinition, team_id, definition_id) is None:
+ definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ if definition is None:
raise CustomPropertySourceValidationError("Custom property definition not found for this team.")
+
+ # The definition's target decides which binding is valid: account sources read a saved query
+ # column; person sources read a raw incremental schema and map columns onto person properties.
+ create_kwargs: dict[str, Any] = {
+ "team_id": team_id,
+ "created_by": user,
+ "definition_id": definition_id,
+ "key_column": key_column,
+ "is_enabled": is_enabled,
+ }
+ if definition.target_type == TargetType.PERSON.value:
+ if external_data_schema_id is None:
+ raise CustomPropertySourceValidationError("A person property source needs an external_data_schema.")
+ if saved_query_id is not None or source_column:
+ raise CustomPropertySourceValidationError(
+ "A person property source uses external_data_schema + column_property_map, not saved_query."
+ )
+ # Validate the map shape in memory before the DB lookup below.
+ 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.")
+ create_kwargs["external_data_schema_id"] = external_data_schema_id
+ else:
+ if saved_query_id is None or not source_column:
+ raise CustomPropertySourceValidationError(
+ "An account property source needs a saved_query and source_column."
+ )
+ if external_data_schema_id is not None or column_property_map is not None:
+ raise CustomPropertySourceValidationError(
+ "An account property source uses saved_query + source_column, not external_data_schema."
+ )
+ if not _saved_query_belongs_to_team(team_id, saved_query_id):
+ raise CustomPropertySourceValidationError("Saved query not found for this team.")
+ create_kwargs["saved_query_id"] = saved_query_id
+ create_kwargs["source_column"] = source_column
+
try:
- source = CustomPropertySource.objects.for_team(team_id).create(
- team_id=team_id,
- created_by=user,
- definition_id=definition_id,
- saved_query_id=saved_query_id,
- source_column=source_column,
- key_column=key_column,
- is_enabled=is_enabled,
- )
+ source = CustomPropertySource.objects.for_team(team_id).create(**create_kwargs)
except IntegrityError as exc:
# Both FKs are team-validated above, so the only expected violation is the definition's
# one-to-one uniqueness; re-raise anything else instead of mislabeling it as a duplicate.
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 28bfbbba641b..a53879658068 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -309,6 +309,7 @@ class CustomPropertyDefinitionView:
name: str = ""
description: str | None = None
display_type: str = "text"
+ target_type: str = "account"
is_big_number: bool = False
created_at: datetime | None = None
created_by: int | None = None
@@ -325,15 +326,18 @@ class CustomPropertySourceView:
``definition`` / ``saved_query`` are ids (the definition this feeds, and the data-warehouse
saved query read from). ``last_sync_error`` is null when the last run succeeded or hasn't run.
- Defaults exist so the wrapping serializer can parse partial request bodies (see
- :class:`AccountView`).
+ Account-target sources set ``saved_query`` + ``source_column``; person-target sources set
+ ``external_data_schema`` + ``column_property_map`` instead. Defaults exist so the wrapping
+ serializer can parse partial request bodies (see :class:`AccountView`).
"""
id: UUID | None = None
definition: UUID | None = None
saved_query: UUID | None = None
- source_column: str = ""
+ external_data_schema: UUID | None = None
+ source_column: str | None = ""
key_column: str = ""
+ column_property_map: dict | None = None
is_enabled: bool = True
consecutive_failures: int = 0
last_synced_at: datetime | None = None
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
new file mode 100644
index 000000000000..dc467e31ce89
--- /dev/null
+++ b/products/customer_analytics/backend/facade/custom_property_source_person_test.py
@@ -0,0 +1,137 @@
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+
+from products.customer_analytics.backend.facade import api
+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
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+
+class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.person_def = create_custom_property_definition(
+ team_id=self.team.id, name="Plan tier", target_type=TargetType.PERSON.value
+ )
+ self.account_def = create_custom_property_definition(
+ team_id=self.team.id, name="MRR", target_type=TargetType.ACCOUNT.value
+ )
+ source = ExternalDataSource.objects.create(
+ 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")
+
+ def _create(self, **overrides):
+ kwargs: dict = {
+ "team_id": self.team.id,
+ "definition_id": self.person_def.id,
+ "key_column": "distinct_id",
+ "is_enabled": True,
+ "user": self.user,
+ "external_data_schema_id": self.schema.id,
+ "column_property_map": {"plan": "plan_tier"},
+ }
+ kwargs.update(overrides)
+ return api.create_custom_property_source(**kwargs)
+
+ def test_create_person_source_round_trips(self):
+ view = self._create(column_property_map={"plan": "plan_tier", "seats": "seat_count"})
+
+ assert view.external_data_schema == self.schema.id
+ assert view.column_property_map == {"plan": "plan_tier", "seats": "seat_count"}
+ assert view.key_column == "distinct_id"
+ assert view.saved_query is None
+ assert not view.source_column
+
+ row = CustomPropertySource.objects.unscoped().get(id=view.id)
+ assert row.external_data_schema_id == self.schema.id
+ assert row.column_property_map == {"plan": "plan_tier", "seats": "seat_count"}
+ assert row.saved_query_id is None
+
+ @parameterized.expand(
+ [
+ (
+ "person_without_schema",
+ {"external_data_schema_id": None},
+ "needs an external_data_schema",
+ ),
+ (
+ "person_with_saved_query_binding",
+ {"saved_query_id": uuid4()},
+ "not saved_query",
+ ),
+ (
+ "person_with_source_column_binding",
+ {"source_column": "plan"},
+ "not saved_query",
+ ),
+ (
+ "person_empty_map",
+ {"column_property_map": {}},
+ "non-empty object",
+ ),
+ (
+ "person_blank_property_name",
+ {"column_property_map": {"plan": ""}},
+ "non-empty property names",
+ ),
+ (
+ "person_blank_column_name",
+ {"column_property_map": {"": "plan_tier"}},
+ "non-empty column names",
+ ),
+ ]
+ )
+ def test_person_source_validation(self, _name, overrides, expected_message):
+ with self.assertRaises(api.CustomPropertySourceValidationError) as ctx:
+ self._create(**overrides)
+ assert expected_message in str(ctx.exception)
+
+ def test_person_source_rejects_schema_from_another_team(self):
+ other_team_source = ExternalDataSource.objects.create(
+ team=self.organization.teams.create(name="other"),
+ source_id="s2",
+ connection_id="c2",
+ status="Running",
+ source_type="Stripe",
+ )
+ foreign_schema = ExternalDataSchema.objects.create(
+ team=other_team_source.team, source=other_team_source, name="users"
+ )
+ with self.assertRaises(api.CustomPropertySourceValidationError) as ctx:
+ self._create(external_data_schema_id=foreign_schema.id)
+ assert "not found for this team" in str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ (
+ "account_with_schema_binding",
+ {"saved_query_id": uuid4(), "source_column": "c", "external_data_schema_id": uuid4()},
+ "not external_data_schema",
+ ),
+ (
+ "account_with_column_map_binding",
+ {"saved_query_id": uuid4(), "source_column": "c", "column_property_map": {"a": "b"}},
+ "not external_data_schema",
+ ),
+ (
+ "account_without_saved_query",
+ {
+ "saved_query_id": None,
+ "source_column": None,
+ "external_data_schema_id": None,
+ "column_property_map": None,
+ },
+ "needs a saved_query",
+ ),
+ ]
+ )
+ def test_account_source_validation(self, _name, overrides, expected_message):
+ with self.assertRaises(api.CustomPropertySourceValidationError) as ctx:
+ self._create(definition_id=self.account_def.id, **overrides)
+ assert expected_message in str(ctx.exception)
diff --git a/products/customer_analytics/backend/logic/custom_property_sync.py b/products/customer_analytics/backend/logic/custom_property_sync.py
index c658ee76c298..8e0d4586a33e 100644
--- a/products/customer_analytics/backend/logic/custom_property_sync.py
+++ b/products/customer_analytics/backend/logic/custom_property_sync.py
@@ -68,12 +68,15 @@ def sync_custom_property_values(*, team_id: int, saved_query_id: str | UUID) ->
usable: list[CustomPropertySource] = []
selected_columns: set[str] = set()
for source in sources:
- missing = [column for column in (source.key_column, source.source_column) if column not in available_columns]
+ source_column = source.source_column
+ if source_column is None:
+ continue # only account sources (which always set source_column) reach this saved-query sync
+ missing = [column for column in (source.key_column, source_column) if column not in available_columns]
if missing:
result.source_errors[str(source.id)] = f"View {saved_query.name} has no column(s): {', '.join(missing)}"
continue
usable.append(source)
- selected_columns.update((source.key_column, source.source_column))
+ selected_columns.update((source.key_column, source_column))
if not usable:
return result
@@ -91,7 +94,10 @@ def sync_custom_property_values(*, team_id: int, saved_query_id: str | UUID) ->
unmatched: set[Any] = set()
for source in usable:
- key_index, value_index = column_index[source.key_column], column_index[source.source_column]
+ source_column = source.source_column
+ if source_column is None:
+ continue
+ key_index, value_index = column_index[source.key_column], column_index[source_column]
for row in rows_by_key_column[source.key_column]:
key = row[key_index]
if key is None:
diff --git a/products/customer_analytics/backend/migrations/0015_person_target_custom_properties.py b/products/customer_analytics/backend/migrations/0015_person_target_custom_properties.py
new file mode 100644
index 000000000000..32b0fc31a150
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0015_person_target_custom_properties.py
@@ -0,0 +1,48 @@
+# Generated by Django 5.2.14 on 2026-07-10 12:18
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import products.customer_analytics.backend.models.custom_property_definition
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0014_relationships_validate_fks"),
+ ("warehouse_sources", "0061_alter_externaldatasource_source_type_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="custompropertydefinition",
+ name="target_type",
+ field=models.CharField(
+ choices=[("account", "account"), ("person", "person")],
+ default=products.customer_analytics.backend.models.custom_property_definition.TargetType["ACCOUNT"],
+ help_text="What entity this property is attached to: an account (default) or a person.",
+ max_length=20,
+ ),
+ ),
+ migrations.AddField(
+ model_name="custompropertysource",
+ name="column_property_map",
+ field=models.JSONField(blank=True, default=None, null=True),
+ ),
+ migrations.AddField(
+ model_name="custompropertysource",
+ name="external_data_schema",
+ field=models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="warehouse_sources.externaldataschema",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="custompropertysource",
+ name="source_column",
+ field=models.CharField(blank=True, max_length=400, null=True),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index 47be7ee44677..ece1e7773f3e 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0014_relationships_validate_fks
+0015_person_target_custom_properties
diff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.py
index f848326742c1..5e2d07643131 100644
--- a/products/customer_analytics/backend/models/__init__.py
+++ b/products/customer_analytics/backend/models/__init__.py
@@ -1,5 +1,11 @@
from .account import Account
-from .custom_property_definition import DATA_TYPE_BY_DISPLAY_TYPE, CustomPropertyDefinition, DataType, DisplayType
+from .custom_property_definition import (
+ DATA_TYPE_BY_DISPLAY_TYPE,
+ CustomPropertyDefinition,
+ DataType,
+ DisplayType,
+ TargetType,
+)
from .custom_property_source import CustomPropertySource
from .custom_property_value import CustomPropertyValue
from .customer_journey import CustomerJourney
@@ -20,5 +26,6 @@ __all__ = [
"DataType",
"DisplayType",
"RelationshipDefinition",
+ "TargetType",
"TeamCustomerAnalyticsConfig",
]
diff --git a/products/customer_analytics/backend/models/custom_property_definition.py b/products/customer_analytics/backend/models/custom_property_definition.py
index 511388c3e5ca..ea8011901f76 100644
--- a/products/customer_analytics/backend/models/custom_property_definition.py
+++ b/products/customer_analytics/backend/models/custom_property_definition.py
@@ -17,6 +17,11 @@ class DisplayType(StrEnum):
SELECT = "select"
+class TargetType(StrEnum):
+ ACCOUNT = "account"
+ PERSON = "person"
+
+
class DataType(StrEnum):
STRING = "string"
NUMERIC = "numeric"
@@ -43,6 +48,12 @@ NUMERIC_DISPLAY_TYPES = [
class CustomPropertyDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+ target_type = models.CharField(
+ choices=[(t.value, t.value) for t in TargetType],
+ default=TargetType.ACCOUNT,
+ max_length=20,
+ help_text="What entity this property is attached to: an account (default) or a person.",
+ )
name = models.CharField(max_length=400)
description = models.TextField(null=True)
display_type = models.CharField(
diff --git a/products/customer_analytics/backend/models/custom_property_source.py b/products/customer_analytics/backend/models/custom_property_source.py
index 0c306a6c9862..f6ebbc4bffb0 100644
--- a/products/customer_analytics/backend/models/custom_property_source.py
+++ b/products/customer_analytics/backend/models/custom_property_source.py
@@ -13,12 +13,26 @@ class CustomPropertySource(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, Up
definition = models.OneToOneField(
"customer_analytics.CustomPropertyDefinition", on_delete=models.CASCADE, related_name="source"
)
+ # Account-target sources read from a materialized view (saved_query); person-target sources
+ # bind to a raw incremental warehouse table (external_data_schema). Exactly one is set — the
+ # facade enforces this, so no DB check constraint.
saved_query = models.ForeignKey(
"data_modeling.DataWarehouseSavedQuery", on_delete=models.SET_NULL, null=True, related_name="+"
)
+ external_data_schema = models.ForeignKey(
+ "warehouse_sources.ExternalDataSchema",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ db_constraint=False,
+ )
- source_column = models.CharField(max_length=400)
+ # Account path: single view column -> the definition's value.
+ source_column = models.CharField(max_length=400, null=True, blank=True)
key_column = models.CharField(max_length=400)
+ # Person path: {warehouse_column: person_property_name} for the columns this source maps.
+ column_property_map = models.JSONField(null=True, blank=True, default=None)
is_enabled = models.BooleanField(default=True)
consecutive_failures = models.PositiveIntegerField(default=0)
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 19f1990c2489..7fcfcc3060d3 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -315,13 +315,41 @@ class CustomPropertySourceSerializer(DataclassSerializer):
help_text="UUID of the custom property definition this source feeds. One source per definition."
)
saved_query = serializers.UUIDField(
- help_text="UUID of the data-warehouse saved query (materialized view) to read values from."
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Account sources only: UUID of the data-warehouse saved query (materialized view) to read "
+ "values from. Mutually exclusive with external_data_schema."
+ ),
+ )
+ external_data_schema = serializers.UUIDField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Person sources only: UUID of the warehouse schema (raw incremental table) to read from. "
+ "Mutually exclusive with saved_query."
+ ),
)
source_column = serializers.CharField(
- max_length=400, help_text="Column in the view whose value is written to the property."
+ max_length=400,
+ required=False,
+ allow_null=True,
+ help_text="Account sources only: column in the view whose value is written to the property.",
+ )
+ column_property_map = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Person sources only: {warehouse_column: person_property_name} mapping the columns this "
+ "source writes onto the person."
+ ),
)
key_column = serializers.CharField(
- max_length=400, help_text="Column in the view whose value matches an account's external_id."
+ max_length=400,
+ help_text=(
+ "Column whose value identifies the target: an account's external_id for account sources, "
+ "or the person's distinct_id for person sources."
+ ),
)
is_enabled = serializers.BooleanField(
required=False,
@@ -351,7 +379,9 @@ class CustomPropertySourceSerializer(DataclassSerializer):
"id",
"definition",
"saved_query",
+ "external_data_schema",
"source_column",
+ "column_property_map",
"key_column",
"is_enabled",
"consecutive_failures",
@@ -414,6 +444,16 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
"'percent', 'date', 'datetime', 'boolean', or 'select'."
),
)
+ target_type = serializers.ChoiceField(
+ choices=[("account", "account"), ("person", "person")],
+ required=False,
+ default="account",
+ help_text=(
+ "What entity this property is attached to: 'account' (default) or 'person'. Person "
+ "properties are populated from a warehouse schema and become usable like any other "
+ "person property (feature flags, cohorts, insights)."
+ ),
+ )
is_big_number = serializers.BooleanField(
required=False,
default=False,
@@ -450,6 +490,7 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
"name",
"description",
"display_type",
+ "target_type",
"is_big_number",
"options",
"source",
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index a955af943ab3..e73c266a0905 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -262,6 +262,7 @@ class CustomPropertyDefinitionViewSet(
display_type=data.display_type,
is_big_number=data.is_big_number,
options=_custom_property_option_dicts(data.options),
+ target_type=data.target_type,
organization_id=self.organization.id,
user=cast(User, request.user),
was_impersonated=is_impersonated(request),
@@ -446,6 +447,8 @@ class CustomPropertySourceViewSet(
definition_id=data.definition,
saved_query_id=data.saved_query,
source_column=data.source_column,
+ external_data_schema_id=data.external_data_schema,
+ column_property_map=data.column_property_map,
key_column=data.key_column,
is_enabled=data.is_enabled,
user=cast(User, request.user),
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index f2b521403703..a6a6a9fcf94a 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -28,11 +28,14 @@ from products.customer_analytics.backend.models import (
CustomPropertyDefinition,
CustomPropertySource,
DisplayType,
+ TargetType,
)
from products.customer_analytics.backend.models.account import AccountAssignment
from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
from products.notebooks.backend.models import Notebook, ResourceNotebook
from products.product_analytics.backend.models.insight import Insight
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from ee.models.rbac.access_control import AccessControl
@@ -1961,6 +1964,51 @@ class TestCustomPropertySourceViewSet(APIBaseTest):
assert toggled.status_code == status.HTTP_200_OK
assert toggled.json()["is_enabled"] is False
+ def _person_definition_and_schema(self):
+ 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")
+ return definition, schema
+
+ def test_create_person_source_round_trip(self):
+ # Wiring guard: the viewset routes a person-target source through serializer + facade.
+ definition, schema = self._person_definition_and_schema()
+
+ created = self.client.post(
+ self.endpoint,
+ {
+ "definition": str(definition.id),
+ "external_data_schema": str(schema.id),
+ "column_property_map": {"plan": "plan_tier"},
+ "key_column": "distinct_id",
+ },
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.content
+ body = created.json()
+ assert body["external_data_schema"] == str(schema.id)
+ assert body["column_property_map"] == {"plan": "plan_tier"}
+ assert body["saved_query"] is None
+
+ def test_create_person_source_with_account_binding_is_rejected(self):
+ definition, _schema = self._person_definition_and_schema()
+
+ response = self.client.post(
+ self.endpoint,
+ {
+ "definition": str(definition.id),
+ "saved_query": str(self.view.id),
+ "source_column": "mrr",
+ "key_column": "distinct_id",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+
class TestAccountNotesViewSet(APIBaseTest):
def setUp(self):
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index a1c1cc8abeff..e436f3ff6454 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -410,6 +410,18 @@ export const CustomPropertyDisplayTypeEnumApi = {
Select: 'select',
} as const
+/**
+ * * `account` - account
+ * * `person` - person
+ */
+export type CustomPropertyDefinitionTargetTypeApi =
+ (typeof CustomPropertyDefinitionTargetTypeApi)[keyof typeof CustomPropertyDefinitionTargetTypeApi]
+
+export const CustomPropertyDefinitionTargetTypeApi = {
+ Account: 'account',
+ Person: 'person',
+} as const
+
/**
* * `preset-1` - preset-1
* * `preset-2` - preset-2
@@ -475,15 +487,26 @@ export interface CustomPropertySourceApi {
readonly id: string
/** UUID of the custom property definition this source feeds. One source per definition. */
definition: string
- /** UUID of the data-warehouse saved query (materialized view) to read values from. */
- saved_query: string
/**
- * Column in the view whose value is written to the property.
+ * Account sources only: UUID of the data-warehouse saved query (materialized view) to read values from. Mutually exclusive with external_data_schema.
+ * @nullable
+ */
+ saved_query?: string | null
+ /**
+ * Person sources only: UUID of the warehouse schema (raw incremental table) to read from. Mutually exclusive with saved_query.
+ * @nullable
+ */
+ external_data_schema?: string | null
+ /**
+ * Account sources only: column in the view whose value is written to the property.
* @maxLength 400
+ * @nullable
*/
- source_column: string
+ source_column?: string | null
+ /** Person sources only: {warehouse_column: person_property_name} mapping the columns this source writes onto the person. */
+ column_property_map?: unknown
/**
- * Column in the view whose value matches an account's external_id.
+ * Column whose value identifies the target: an account's external_id for account sources, or the person's distinct_id for person sources.
* @maxLength 400
*/
key_column: string
@@ -551,6 +574,11 @@ export interface CustomPropertyDefinitionApi {
* * `boolean` - boolean
* * `select` - select */
display_type: CustomPropertyDisplayTypeEnumApi
+ /** What entity this property is attached to: 'account' (default) or 'person'. Person properties are populated from a warehouse schema and become usable like any other person property (feature flags, cohorts, insights).
+ *
+ * * `account` - account
+ * * `person` - person */
+ target_type?: CustomPropertyDefinitionTargetTypeApi
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean
/**
@@ -607,6 +635,11 @@ export interface PatchedCustomPropertyDefinitionApi {
* * `boolean` - boolean
* * `select` - select */
display_type?: CustomPropertyDisplayTypeEnumApi
+ /** What entity this property is attached to: 'account' (default) or 'person'. Person properties are populated from a warehouse schema and become usable like any other person property (feature flags, cohorts, insights).
+ *
+ * * `account` - account
+ * * `person` - person */
+ target_type?: CustomPropertyDefinitionTargetTypeApi
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean
/**
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index b18b5f1452bb..f56904498282 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -278,6 +278,7 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod
export const customPropertyDefinitionsCreateBodyNameMax = 400
+export const customPropertyDefinitionsCreateBodyTargetTypeDefault = `account`
export const customPropertyDefinitionsCreateBodyIsBigNumberDefault = false
export const customPropertyDefinitionsCreateBodyOptionsItemLabelMax = 400
@@ -296,6 +297,13 @@ export const CustomPropertyDefinitionsCreateBody = /* @__PURE__ */ zod
.describe(
"How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', 'boolean', or 'select'.\n\n\* `text` - text\n\* `number` - number\n\* `currency` - currency\n\* `percent` - percent\n\* `date` - date\n\* `datetime` - datetime\n\* `boolean` - boolean\n\* `select` - select"
),
+ target_type: zod
+ .enum(['account', 'person'])
+ .describe('\* `account` - account\n\* `person` - person')
+ .default(customPropertyDefinitionsCreateBodyTargetTypeDefault)
+ .describe(
+ "What entity this property is attached to: 'account' (default) or 'person'. Person properties are populated from a warehouse schema and become usable like any other person property (feature flags, cohorts, insights).\n\n\* `account` - account\n\* `person` - person"
+ ),
is_big_number: zod
.boolean()
.default(customPropertyDefinitionsCreateBodyIsBigNumberDefault)
@@ -347,6 +355,7 @@ export const CustomPropertyDefinitionsCreateBody = /* @__PURE__ */ zod
export const customPropertyDefinitionsUpdateBodyNameMax = 400
+export const customPropertyDefinitionsUpdateBodyTargetTypeDefault = `account`
export const customPropertyDefinitionsUpdateBodyIsBigNumberDefault = false
export const customPropertyDefinitionsUpdateBodyOptionsItemLabelMax = 400
@@ -365,6 +374,13 @@ export const CustomPropertyDefinitionsUpdateBody = /* @__PURE__ */ zod
.describe(
"How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', 'boolean', or 'select'.\n\n\* `text` - text\n\* `number` - number\n\* `currency` - currency\n\* `percent` - percent\n\* `date` - date\n\* `datetime` - datetime\n\* `boolean` - boolean\n\* `select` - select"
),
+ target_type: zod
+ .enum(['account', 'person'])
+ .describe('\* `account` - account\n\* `person` - person')
+ .default(customPropertyDefinitionsUpdateBodyTargetTypeDefault)
+ .describe(
+ "What entity this property is attached to: 'account' (default) or 'person'. Person properties are populated from a warehouse schema and become usable like any other person property (feature flags, cohorts, insights).\n\n\* `account` - account\n\* `person` - person"
+ ),
is_big_number: zod
.boolean()
.default(customPropertyDefinitionsUpdateBodyIsBigNumberDefault)
@@ -416,6 +432,7 @@ export const CustomPropertyDefinitionsUpdateBody = /* @__PURE__ */ zod
export const customPropertyDefinitionsPartialUpdateBodyNameMax = 400
+export const customPropertyDefinitionsPartialUpdateBodyTargetTypeDefault = `account`
export const customPropertyDefinitionsPartialUpdateBodyIsBigNumberDefault = false
export const customPropertyDefinitionsPartialUpdateBodyOptionsItemLabelMax = 400
@@ -436,6 +453,13 @@ export const CustomPropertyDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
"How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', 'boolean', or 'select'.\n\n\* `text` - text\n\* `number` - number\n\* `currency` - currency\n\* `percent` - percent\n\* `date` - date\n\* `datetime` - datetime\n\* `boolean` - boolean\n\* `select` - select"
),
+ target_type: zod
+ .enum(['account', 'person'])
+ .describe('\* `account` - account\n\* `person` - person')
+ .default(customPropertyDefinitionsPartialUpdateBodyTargetTypeDefault)
+ .describe(
+ "What entity this property is attached to: 'account' (default) or 'person'. Person properties are populated from a warehouse schema and become usable like any other person property (feature flags, cohorts, insights).\n\n\* `account` - account\n\* `person` - person"
+ ),
is_big_number: zod
.boolean()
.default(customPropertyDefinitionsPartialUpdateBodyIsBigNumberDefault)
@@ -498,15 +522,33 @@ export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod
.describe('UUID of the custom property definition this source feeds. One source per definition.'),
saved_query: zod
.uuid()
- .describe('UUID of the data-warehouse saved query (materialized view) to read values from.'),
+ .nullish()
+ .describe(
+ 'Account sources only: UUID of the data-warehouse saved query (materialized view) to read values from. Mutually exclusive with external_data_schema.'
+ ),
+ external_data_schema: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'Person sources only: UUID of the warehouse schema (raw incremental table) to read from. Mutually exclusive with saved_query.'
+ ),
source_column: zod
.string()
.max(customPropertySourcesCreateBodySourceColumnMax)
- .describe('Column in the view whose value is written to the property.'),
+ .nullish()
+ .describe('Account sources only: column in the view whose value is written to the property.'),
+ column_property_map: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Person sources only: {warehouse_column: person_property_name} mapping the columns this source writes onto the person.'
+ ),
key_column: zod
.string()
.max(customPropertySourcesCreateBodyKeyColumnMax)
- .describe("Column in the view whose value matches an account's external_id."),
+ .describe(
+ "Column whose value identifies the target: an account's external_id for account sources, or the person's distinct_id for person sources."
+ ),
is_enabled: zod
.boolean()
.default(customPropertySourcesCreateBodyIsEnabledDefault)
diff --git a/products/event_definitions/backend/migrations/0010_propertydefinition_warehouse_origin.py b/products/event_definitions/backend/migrations/0010_propertydefinition_warehouse_origin.py
new file mode 100644
index 000000000000..c99785f8c2c5
--- /dev/null
+++ b/products/event_definitions/backend/migrations/0010_propertydefinition_warehouse_origin.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.14 on 2026-07-10 12:18
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("event_definitions", "0009_drop_eventproperty_proj_event_coalesce_idx"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="propertydefinition",
+ name="warehouse_origin",
+ field=models.JSONField(blank=True, default=None, null=True),
+ ),
+ ]
diff --git a/products/event_definitions/backend/migrations/max_migration.txt b/products/event_definitions/backend/migrations/max_migration.txt
index 119e82a2dac1..16e7cad7755f 100644
--- a/products/event_definitions/backend/migrations/max_migration.txt
+++ b/products/event_definitions/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0009_drop_eventproperty_proj_event_coalesce_idx
+0010_propertydefinition_warehouse_origin
diff --git a/products/event_definitions/backend/models/property_definition.py b/products/event_definitions/backend/models/property_definition.py
index 2e893e90aa04..b856cdded75a 100644
--- a/products/event_definitions/backend/models/property_definition.py
+++ b/products/event_definitions/backend/models/property_definition.py
@@ -62,6 +62,13 @@ class PropertyDefinition(UUIDTModel):
# Only populated for `Type.GROUP`
group_type_index = models.PositiveSmallIntegerField(null=True)
+ # Provenance for properties populated from a data warehouse source (Customer analytics
+ # warehouse -> person properties). Null for the vast majority of definitions. Written by
+ # Django only; the Rust property-defs upsert lists its columns explicitly and never touches
+ # this one. Shape: {source_id, schema_id, table_name, column, custom_property_source_id,
+ # last_synced_at}.
+ warehouse_origin = models.JSONField(null=True, blank=True, default=None)
+
# DEPRECATED
property_type_format = models.CharField(
max_length=50, choices=PropertyFormat, blank=True, null=True
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9b0a95bab19f..a93ccf595172 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14918,6 +14918,18 @@ export namespace Schemas {
Select: 'select',
} as const;
+ /**
+ * * `account` - account
+ * * `person` - person
+ */
+ export type CustomPropertyDefinitionTargetType = typeof CustomPropertyDefinitionTargetType[keyof typeof CustomPropertyDefinitionTargetType];
+
+
+ export const CustomPropertyDefinitionTargetType = {
+ Account: 'account',
+ Person: 'person',
+ } as const;
+
/**
* * `preset-1` - preset-1
* * `preset-2` - preset-2
@@ -14983,15 +14995,26 @@ export namespace Schemas {
readonly id: string;
/** UUID of the custom property definition this source feeds. One source per definition. */
definition: string;
- /** UUID of the data-warehouse saved query (materialized view) to read values from. */
- saved_query: string;
/**
- * Column in the view whose value is written to the property.
+ * Account sources only: UUID of the data-warehouse saved query (materialized view) to read values from. Mutually exclusive with external_data_schema.
+ * @nullable
+ */
+ saved_query?: string | null;
+ /**
+ * Person sources only: UUID of the warehouse schema (raw incremental table) to read from. Mutually exclusive with saved_query.
+ * @nullable
+ */
+ external_data_schema?: string | null;
+ /**
+ * Account sources only: column in the view whose value is written to the property.
* @maxLength 400
+ * @nullable
*/
- source_column: string;
+ source_column?: string | null;
+ /** Person sources only: {warehouse_column: person_property_name} mapping the columns this source writes onto the person. */
+ column_property_map?: unknown;
/**
- * Column in the view whose value matches an account's external_id.
+ * Column whose value identifies the target: an account's external_id for account sources, or the person's distinct_id for person sources.
* @maxLength 400
*/
key_column: string;
@@ -15059,6 +15082,11 @@ export namespace Schemas {
* * `boolean` - boolean
* * `select` - select */
display_type: CustomPropertyDisplayTypeEnum;
+ /** What entity this property is attached to: 'account' (default) or 'person'. Person properties are populated from a warehouse schema and become usable like any other person property (feature flags, cohorts, insights).
+ *
+ * * `account` - account
+ * * `person` - person */
+ target_type?: CustomPropertyDefinitionTargetType;
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean;
/**
@@ -40353,6 +40381,11 @@ export namespace Schemas {
* * `boolean` - boolean
* * `select` - select */
display_type?: CustomPropertyDisplayTypeEnum;
+ /** What entity this property is attached to: 'account' (default) or 'person'. Person properties are populated from a warehouse schema and become usable like any other person property (feature flags, cohorts, insights).
+ *
+ * * `account` - account
+ * * `person` - person */
+ target_type?: CustomPropertyDefinitionTargetType;
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean;
/**
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 34f417a4fc4e..72be5c87ee64 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -433,6 +433,7 @@ export const CustomPropertyDefinitionsCreateParams = /* @__PURE__ */ zod.object(
export const customPropertyDefinitionsCreateBodyNameMax = 400
+export const customPropertyDefinitionsCreateBodyTargetTypeDefault = `account`
export const customPropertyDefinitionsCreateBodyIsBigNumberDefault = false
export const customPropertyDefinitionsCreateBodyOptionsItemLabelMax = 400
@@ -451,6 +452,13 @@ export const CustomPropertyDefinitionsCreateBody = /* @__PURE__ */ zod
.describe(
"How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', 'boolean', or 'select'.\n\n* `text` - text\n* `number` - number\n* `currency` - currency\n* `percent` - percent\n* `date` - date\n* `datetime` - datetime\n* `boolean` - boolean\n* `select` - select"
),
+ target_type: zod
+ .enum(['account', 'person'])
+ .describe('* `account` - account\n* `person` - person')
+ .default(customPropertyDefinitionsCreateBodyTargetTypeDefault)
+ .describe(
+ "What entity this property is attached to: 'account' (default) or 'person'. Person properties are populated from a warehouse schema and become usable like any other person property (feature flags, cohorts, insights).\n\n* `account` - account\n* `person` - person"
+ ),
is_big_number: zod
.boolean()
.default(customPropertyDefinitionsCreateBodyIsBigNumberDefault)
@@ -539,6 +547,13 @@ export const CustomPropertyDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
"How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', 'boolean', or 'select'.\n\n* `text` - text\n* `number` - number\n* `currency` - currency\n* `percent` - percent\n* `date` - date\n* `datetime` - datetime\n* `boolean` - boolean\n* `select` - select"
),
+ target_type: zod
+ .enum(['account', 'person'])
+ .describe('* `account` - account\n* `person` - person')
+ .optional()
+ .describe(
+ "What entity this property is attached to: 'account' (default) or 'person'. Person properties are populated from a warehouse schema and become usable like any other person property (feature flags, cohorts, insights).\n\n* `account` - account\n* `person` - person"
+ ),
is_big_number: zod
.boolean()
.optional()
diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.ts
index 8382a5b46919..022dfdeb46c5 100644
--- a/services/mcp/src/tools/generated/customer_analytics.ts
+++ b/services/mcp/src/tools/generated/customer_analytics.ts
@@ -523,6 +523,9 @@ const customPropertyDefinitionsCreate = (): ToolBase<
if (params.display_type !== undefined) {
body['display_type'] = params.display_type
}
+ if (params.target_type !== undefined) {
+ body['target_type'] = params.target_type
+ }
if (params.is_big_number !== undefined) {
body['is_big_number'] = params.is_big_number
}
@@ -597,6 +600,9 @@ const customPropertyDefinitionsPartialUpdate = (): ToolBase<
if (params.display_type !== undefined) {
body['display_type'] = params.display_type
}
+ if (params.target_type !== undefined) {
+ body['target_type'] = params.target_type
+ }
if (params.is_big_number !== undefined) {
body['is_big_number'] = params.is_big_number
}