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): support warehouse group properties (#72876)

Tom Owers98b53d4b00fd
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index d54edeffe505..9011cd8ab079 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -901,6 +901,7 @@ def _to_custom_property_definition_view(
description=definition.description,
display_type=definition.display_type,
target_type=definition.target_type,
+ group_type_index=definition.group_type_index,
is_big_number=definition.is_big_number,
created_at=definition.created_at,
created_by=definition.created_by_id,
@@ -969,13 +970,21 @@ def _definition_source_view(
def list_custom_property_definitions(
- team_id: int, offset: int, limit: int, *, user_access_control: "UserAccessControl"
+ team_id: int,
+ offset: int,
+ limit: int,
+ *,
+ user_access_control: "UserAccessControl",
+ exclude_group_targets: bool = False,
) -> tuple[list[contracts.CustomPropertyDefinitionView], int]:
"""Custom property definitions for the team, ordered by name. Returns ``(page, total_count)``.
``references`` (the workflows referencing each definition) is included only when the caller can
- read workflows — see ``_can_read_workflow_references``."""
+ read workflows — see ``_can_read_workflow_references``. ``exclude_group_targets`` hides group-target
+ definitions from callers without ``group`` read authorization."""
queryset = CustomPropertyDefinition.objects.filter(team_id=team_id).select_related("source").order_by("name")
+ if exclude_group_targets:
+ queryset = queryset.exclude(target_type=TargetType.GROUP.value)
total_count = queryset.count()
page = list(queryset[offset : offset + limit])
references = (
@@ -1027,6 +1036,7 @@ def create_custom_property_definition(
is_big_number: bool,
options: list[dict[str, Any]] | None = None,
target_type: str = TargetType.ACCOUNT.value,
+ group_type_index: int | None = None,
organization_id,
user: "User",
was_impersonated: bool,
@@ -1039,6 +1049,8 @@ def create_custom_property_definition(
description=description,
display_type=display_type,
target_type=target_type,
+ # Only group targets carry an index; force it null otherwise to satisfy the check constraint.
+ group_type_index=group_type_index if target_type == TargetType.GROUP.value else None,
is_big_number=coerce_is_big_number(display_type, is_big_number),
options=normalize_options(DisplayType(display_type), options),
)
@@ -1337,13 +1349,18 @@ def _enqueue_sync_if_enabled(source: CustomPropertySource) -> None:
transaction.on_commit(lambda: _enqueue_custom_property_sync(team_id, saved_query_id))
+# Targets fed by the warehouse staging/sync pipeline (person + group), as opposed to the account
+# materialized-view path. These share the sync-now / backfill / run-history machinery.
+_WAREHOUSE_PROFILE_TARGETS = (TargetType.PERSON.value, TargetType.GROUP.value)
+
+
def _create_running_runs(team_id: int, schema_id: str, trigger: str) -> list[Any]:
- """Insert a 'running' run for each enabled person source on the schema that isn't already running.
- The UI shows these as in-progress and disables the trigger while they exist; the backfill activity
- reconciles them to their terminal state (see record_sync_run). Skipping sources that already have a
- running run makes this a no-op when a backfill for the table is already in flight (coalesced).
- Returns the source ids a placeholder was created for, so the caller can reconcile them to FAILED if
- the workflow start never happens (see ``_fail_created_runs``)."""
+ """Insert a 'running' run for each enabled person/group source on the schema that isn't already
+ running. The UI shows these as in-progress and disables the trigger while they exist; the backfill
+ activity reconciles them to their terminal state (see record_sync_run). Skipping sources that
+ already have a running run makes this a no-op when a backfill for the table is already in flight
+ (coalesced). Returns the source ids a placeholder was created for, so the caller can reconcile them
+ to FAILED if the workflow start never happens (see ``_fail_created_runs``)."""
with transaction.atomic():
# Lock the candidate sources so a concurrent trigger for the same schema can't pass the
# "already running" check and insert a duplicate RUNNING row before this one commits.
@@ -1352,7 +1369,7 @@ def _create_running_runs(team_id: int, schema_id: str, trigger: str) -> list[Any
.filter(
external_data_schema_id=schema_id,
is_enabled=True,
- definition__target_type=TargetType.PERSON.value,
+ definition__target_type__in=_WAREHOUSE_PROFILE_TARGETS,
)
.select_for_update()
)
@@ -1419,8 +1436,8 @@ def _start_person_backfill_if_enabled(source: CustomPropertySource) -> None:
def _triggerable_person_schema_id(team_id: int, source_id: str) -> str | None:
- """The schema id to act on for a person-property trigger, or None when the source isn't a valid,
- flag-enabled person source (→ the view returns 400)."""
+ """The schema id to act on for a person/group-property trigger, or None when the source isn't a
+ valid, flag-enabled warehouse-profile source (→ the view returns 400)."""
source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).select_related("definition").first()
if source is None or source.external_data_schema_id is None:
return None
@@ -1429,7 +1446,7 @@ def _triggerable_person_schema_id(team_id: int, source_id: str) -> str | None:
# a mapping the system already turned off.
if not source.is_enabled:
return None
- if source.definition.target_type != TargetType.PERSON.value:
+ if source.definition.target_type not in _WAREHOUSE_PROFILE_TARGETS:
return None
if not person_properties_flag_enabled(team_id):
return None
@@ -1520,11 +1537,21 @@ def trigger_person_property_backfill(
def list_custom_property_sources(
- team_id: int, offset: int, limit: int, user_access_control: "UserAccessControl | None" = None
+ team_id: int,
+ offset: int,
+ limit: int,
+ user_access_control: "UserAccessControl | None" = None,
+ *,
+ exclude_group_targets: bool = False,
) -> tuple[list[contracts.CustomPropertySourceView], int]:
"""Custom-property sources for the team, newest first. Returns ``(page, total_count)``. Warehouse
- schedule/run enrichment per source is gated on the caller's warehouse-source viewer access."""
+ schedule/run enrichment per source is gated on the caller's warehouse-source viewer access.
+
+ ``exclude_group_targets`` hides sources feeding a group-target definition from callers without
+ ``group`` read authorization."""
queryset = CustomPropertySource.objects.for_team(team_id).order_by("-created_at")
+ if exclude_group_targets:
+ queryset = queryset.exclude(definition__target_type=TargetType.GROUP.value)
total_count = queryset.count()
page = list(queryset[offset : offset + limit])
enrichment = _batch_source_enrichment(team_id, page, user_access_control)
@@ -1567,12 +1594,12 @@ def create_custom_property_source(
"key_column": key_column,
"is_enabled": is_enabled,
}
- if definition.target_type == TargetType.PERSON.value:
+ if definition.target_type in _WAREHOUSE_PROFILE_TARGETS:
if external_data_schema_id is None:
- raise CustomPropertySourceValidationError("A person property source needs an external_data_schema.")
+ raise CustomPropertySourceValidationError("A person/group 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."
+ "A person/group 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)
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 2cadf620c1c6..3fd36a34f09a 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -347,6 +347,8 @@ class CustomPropertyDefinitionView:
description: str | None = None
display_type: str = "text"
target_type: str = "account"
+ # Only set for group targets: which group type (0-4) the property attaches to. Null otherwise.
+ group_type_index: int | None = None
is_big_number: bool = False
created_at: datetime | None = None
created_by: int | None = None
diff --git a/products/customer_analytics/backend/logic/person_property_projection.py b/products/customer_analytics/backend/logic/person_property_projection.py
index 66c6ab369fb4..62b2552723d2 100644
--- a/products/customer_analytics/backend/logic/person_property_projection.py
+++ b/products/customer_analytics/backend/logic/person_property_projection.py
@@ -47,25 +47,33 @@ def person_properties_flag_enabled(team_id: int) -> bool:
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.
+# Warehouse-backed profile targets (person or group). Account sources use the materialized-view
+# (saved_query) path, not the warehouse staging pipeline, so they're excluded here.
+_PROFILE_TARGETS = (TargetType.PERSON.value, TargetType.GROUP.value)
+
+
+def _enabled_profile_sources(team_id: int, schema_id: str | UUID) -> list[CustomPropertySource]:
+ # Sources without a key column are skipped: their rows have no identifier (person distinct_id or
+ # group key) to attach the properties to. select_related the definition so target_type /
+ # group_type_index don't lazy-load per source.
return [
source
- for source in CustomPropertySource.objects.for_team(team_id).filter(
+ for source in CustomPropertySource.objects.for_team(team_id)
+ .select_related("definition")
+ .filter(
external_data_schema_id=schema_id,
is_enabled=True,
- definition__target_type=TargetType.PERSON.value,
+ definition__target_type__in=_PROFILE_TARGETS,
)
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 = _enabled_person_sources(team_id, schema_id)
+ """One projection per enabled person/group-target source on the schema (its key column plus its
+ mapped columns), or None when the schema feeds no such properties (so the pipeline stages
+ nothing). The projection is target-agnostic — the group type is config, not a staged column."""
+ sources = _enabled_profile_sources(team_id, schema_id)
if not sources or not person_properties_flag_enabled(team_id):
return None
return [
@@ -78,9 +86,10 @@ def person_property_projection(team_id: int, schema_id: str | UUID) -> list[Pers
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)
+ """Full sync config per enabled person/group-target source on the schema, for the warehouse-owned
+ post-sync upsert job — or None when the schema feeds no such properties. Carries ``target`` and,
+ for group targets, ``group_type_index`` so the upsert can write the right entity."""
+ sources = _enabled_profile_sources(team_id, schema_id)
if not sources or not person_properties_flag_enabled(team_id):
return None
return [
@@ -89,6 +98,8 @@ def person_property_sync_sources(team_id: int, schema_id: str | UUID) -> list[Pe
definition_id=str(source.definition_id),
key_column=source.key_column,
column_property_map=dict(source.column_property_map or {}),
+ target=source.definition.target_type,
+ group_type_index=source.definition.group_type_index,
)
for source in sources
]
diff --git a/products/customer_analytics/backend/migrations/0020_custompropertydefinition_group_type_index_and_more.py b/products/customer_analytics/backend/migrations/0020_custompropertydefinition_group_type_index_and_more.py
new file mode 100644
index 000000000000..0290a419cbcc
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0020_custompropertydefinition_group_type_index_and_more.py
@@ -0,0 +1,51 @@
+# Generated by Django 5.2.14 on 2026-07-22 12:02
+
+from django.conf import settings
+from django.db import migrations, models
+
+import products.customer_analytics.backend.models.custom_property_definition
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0019_custompropertysyncrun_validate_fks"),
+ ("posthog", "1261_alter_personalapikey_scoped_organizations_and_more"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="custompropertydefinition",
+ name="group_type_index",
+ field=models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="For group targets only: the group type index (0-4). Null for account/person targets.",
+ null=True,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="custompropertydefinition",
+ name="target_type",
+ field=models.CharField(
+ choices=[
+ ("account", "account"),
+ ("person", "person"),
+ ("group", "group"),
+ ],
+ default=products.customer_analytics.backend.models.custom_property_definition.TargetType["ACCOUNT"],
+ help_text="What entity this property is attached to: an account (default), a person, or a group.",
+ max_length=20,
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="custompropertydefinition",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ models.Q(("target_type", "group"), _negated=True),
+ ("group_type_index__isnull", False),
+ _connector="OR",
+ ),
+ name="group_target_requires_group_type_index",
+ ),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index acf7c525badb..7ae5858c9b62 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0019_custompropertysyncrun_validate_fks
+0020_custompropertydefinition_group_type_index_and_more
diff --git a/products/customer_analytics/backend/models/custom_property_definition.py b/products/customer_analytics/backend/models/custom_property_definition.py
index ea8011901f76..4943433c7bed 100644
--- a/products/customer_analytics/backend/models/custom_property_definition.py
+++ b/products/customer_analytics/backend/models/custom_property_definition.py
@@ -20,6 +20,7 @@ class DisplayType(StrEnum):
class TargetType(StrEnum):
ACCOUNT = "account"
PERSON = "person"
+ GROUP = "group"
class DataType(StrEnum):
@@ -52,7 +53,14 @@ class CustomPropertyDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields
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.",
+ help_text="What entity this property is attached to: an account (default), a person, or a group.",
+ )
+ # Only set for group targets: which group type (0-4) the property attaches to. Groups are keyed by
+ # (group_type_index, group_key), so this pins the type; the source's key_column supplies the key.
+ group_type_index = models.PositiveSmallIntegerField(
+ null=True,
+ blank=True,
+ help_text="For group targets only: the group type index (0-4). Null for account/person targets.",
)
name = models.CharField(max_length=400)
description = models.TextField(null=True)
@@ -79,6 +87,10 @@ class CustomPropertyDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields
condition=models.Q(is_big_number=False) | models.Q(display_type__in=NUMERIC_DISPLAY_TYPES),
name="is_big_number_requires_numeric_display_type",
),
+ models.CheckConstraint(
+ condition=~models.Q(target_type=TargetType.GROUP.value) | models.Q(group_type_index__isnull=False),
+ name="group_target_requires_group_type_index",
+ ),
]
@property
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index fd1c00b69858..e60d01e92c83 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -535,13 +535,23 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
),
)
target_type = serializers.ChoiceField(
- choices=[("account", "account"), ("person", "person")],
+ choices=[("account", "account"), ("person", "person"), ("group", "group")],
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)."
+ "What entity this property is attached to: 'account' (default), 'person', or 'group'. "
+ "Person and group properties are populated from a warehouse schema and become usable like "
+ "any other person/group property (feature flags, cohorts, insights)."
+ ),
+ )
+ group_type_index = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=0,
+ max_value=4,
+ help_text=(
+ "For 'group' targets only: which group type (0-4) the property attaches to. Required when "
+ "target_type is 'group'; must be omitted otherwise. Create-only."
),
)
is_big_number = serializers.BooleanField(
@@ -572,6 +582,20 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
help_text="Workflows that use this property, resolved by definition id.",
)
+ def validate(self, attrs):
+ # target_type and group_type_index are create-only, so only enforce the group rule on create.
+ # (On a partial update DataclassSerializer fills unset fields with a sentinel, not None.)
+ if self.partial:
+ return attrs
+ # DataclassSerializer hands us the constructed dataclass (not a dict).
+ is_group = getattr(attrs, "target_type", None) == "group"
+ has_index = getattr(attrs, "group_type_index", None) is not None
+ if is_group and not has_index:
+ raise serializers.ValidationError({"group_type_index": "Required when target_type is 'group'."})
+ if not is_group and has_index:
+ raise serializers.ValidationError({"group_type_index": "Only valid when target_type is 'group'."})
+ return attrs
+
class Meta:
dataclass = CustomPropertyDefinitionView
ref_name = "CustomPropertyDefinition"
@@ -581,6 +605,7 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
"description",
"display_type",
"target_type",
+ "group_type_index",
"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 667dd1abda22..d6651c8ab134 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -145,6 +145,30 @@ def _object_required_level(request: Request, write: bool) -> str | None:
return _OBJECT_WRITE_LEVEL if write else _OBJECT_READ_LEVEL
+_GROUP_TARGET_TYPE = "group"
+
+
+def _has_group_scope(request: Request, *, write: bool) -> bool:
+ """Whether the caller may read (``write=False``) or write (``write=True``) the ``group`` resource.
+ Group-target custom properties read and modify group data, but these viewsets are scoped to
+ ``account`` — so a token/OAuth caller must additionally hold the matching ``group`` scope,
+ mirroring what the group API itself enforces. Session callers are governed by project membership
+ (same as the group API), and service auth is exempt."""
+ if is_service_auth(request):
+ return True
+ token_scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
+ if token_scopes is None:
+ return True # session / non-token auth — same footing as the group API
+ if "*" in token_scopes or "group:write" in token_scopes:
+ return True
+ return not write and "group:read" in token_scopes
+
+
+def _assert_group_scope(request: Request, *, write: bool) -> None:
+ if not _has_group_scope(request, write=write):
+ raise PermissionDenied(f"This action requires the `group:{'write' if write else 'read'}` API scope.")
+
+
class CustomerProfileConfigViewSet(
TeamAndOrgViewSetMixin,
_FacadePaginationMixin,
@@ -246,14 +270,23 @@ class CustomPropertyDefinitionViewSet(
viewsets.GenericViewSet,
):
scope_object = "account"
+ # ``values`` is a custom read action; without listing it here it carries no required scope and
+ # rejects token auth outright ("does not support personal API key access") before the group gate runs.
+ scope_object_read_actions = ["list", "retrieve", "values"]
serializer_class = CustomPropertyDefinitionSerializer
queryset = None # data is reached through the facade; declared for router/schema only
def list(self, request: Request, *args, **kwargs) -> Response:
+ # Callers without group read authorization don't see group-target definitions.
+ exclude_group_targets = not _has_group_scope(request, write=False)
return self._paginate_via_facade(
request,
lambda offset, limit: api.list_custom_property_definitions(
- self.team_id, offset=offset, limit=limit, user_access_control=_warehouse_scoped_uac(self)
+ self.team_id,
+ offset=offset,
+ limit=limit,
+ user_access_control=_warehouse_scoped_uac(self),
+ exclude_group_targets=exclude_group_targets,
),
CustomPropertyDefinitionSerializer,
)
@@ -262,7 +295,10 @@ class CustomPropertyDefinitionViewSet(
definition = api.get_custom_property_definition(
self.team_id, self.kwargs["pk"], user_access_control=_warehouse_scoped_uac(self)
)
- if definition is None:
+ # Hide group-target definitions from callers without group read authorization.
+ if definition is None or (
+ definition.target_type == _GROUP_TARGET_TYPE and not _has_group_scope(request, write=False)
+ ):
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(CustomPropertyDefinitionSerializer(instance=definition).data)
@@ -290,6 +326,18 @@ class CustomPropertyDefinitionViewSet(
key = request.GET.get("key")
if not key:
return Response({"results": [], "refreshing": False})
+ # Suggestions expose a group-target definition's option labels (and its existence), so gate them
+ # on group read authorization just like list/retrieve — an account-scoped caller without group
+ # read must not read group property configuration. Unknown keys keep the empty-envelope behavior.
+ definition = api.get_custom_property_definition(
+ self.team_id, key, user_access_control=_warehouse_scoped_uac(self)
+ )
+ if (
+ definition is not None
+ and definition.target_type == _GROUP_TARGET_TYPE
+ and not _has_group_scope(request, write=False)
+ ):
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
suggestions = api.list_custom_property_value_suggestions(self.team_id, key, request.GET.get("value"))
return Response({"results": [{"name": value} for value in suggestions], "refreshing": False})
@@ -297,8 +345,11 @@ 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."})
+ # Person and group targets are both gated behind the warehouse-person-properties rollout flag.
+ if data.target_type in ("person", "group") and not api.person_properties_flag_enabled(self.team_id):
+ raise ValidationError({"target_type": "Person/group properties from warehouse data are not enabled yet."})
+ if data.target_type == _GROUP_TARGET_TYPE:
+ _assert_group_scope(request, write=True)
try:
definition = api.create_custom_property_definition(
team_id=self.team_id,
@@ -308,6 +359,7 @@ class CustomPropertyDefinitionViewSet(
is_big_number=data.is_big_number,
options=_custom_property_option_dicts(data.options),
target_type=data.target_type,
+ group_type_index=data.group_type_index,
organization_id=self.organization.id,
user=cast(User, request.user),
was_impersonated=is_impersonated(request),
@@ -318,7 +370,16 @@ class CustomPropertyDefinitionViewSet(
raise ValidationError({"options": str(e)})
return Response(CustomPropertyDefinitionSerializer(instance=definition).data, status=status.HTTP_201_CREATED)
+ def _guard_group_definition(self, request: Request, definition_id) -> None:
+ # Group-target definitions gate the group-writing pipeline, so mutating one needs group scope.
+ definition = api.get_custom_property_definition(
+ self.team_id, definition_id, user_access_control=self.user_access_control
+ )
+ if definition is not None and definition.target_type == _GROUP_TARGET_TYPE:
+ _assert_group_scope(request, write=True)
+
def update(self, request: Request, *args, **kwargs) -> Response:
+ self._guard_group_definition(request, self.kwargs["pk"])
partial = kwargs.pop("partial", False)
serializer = CustomPropertyDefinitionSerializer(data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
@@ -345,6 +406,7 @@ class CustomPropertyDefinitionViewSet(
return self.update(request, *args, **kwargs)
def destroy(self, request: Request, *args, **kwargs) -> Response:
+ self._guard_group_definition(request, self.kwargs["pk"])
deleted = api.delete_custom_property_definition(
team_id=self.team_id,
definition_id=self.kwargs["pk"],
@@ -471,10 +533,16 @@ class CustomPropertySourceViewSet(
queryset = None # data is reached through the facade; declared for router/schema only
def list(self, request: Request, *args, **kwargs) -> Response:
+ # Callers without group read authorization don't see sources feeding group-target definitions.
+ exclude_group_targets = not _has_group_scope(request, write=False)
return self._paginate_via_facade(
request,
lambda offset, limit: api.list_custom_property_sources(
- self.team_id, offset=offset, limit=limit, user_access_control=_warehouse_scoped_uac(self)
+ self.team_id,
+ offset=offset,
+ limit=limit,
+ user_access_control=_warehouse_scoped_uac(self),
+ exclude_group_targets=exclude_group_targets,
),
CustomPropertySourceSerializer,
)
@@ -483,14 +551,34 @@ class CustomPropertySourceViewSet(
source = api.get_custom_property_source(
self.team_id, self.kwargs["pk"], user_access_control=_warehouse_scoped_uac(self)
)
- if source is None:
+ # Hide sources feeding a group-target definition from callers without group read authorization.
+ if source is None or (
+ self._definition_is_group(source.definition) and not _has_group_scope(request, write=False)
+ ):
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(CustomPropertySourceSerializer(instance=source).data)
+ def _definition_is_group(self, definition_id) -> bool:
+ if definition_id is None:
+ return False
+ definition = api.get_custom_property_definition(
+ self.team_id, str(definition_id), user_access_control=self.user_access_control
+ )
+ return definition is not None and definition.target_type == _GROUP_TARGET_TYPE
+
+ def _guard_group_source(self, request: Request, source_id, *, write: bool = True) -> None:
+ # A source feeding a group definition reads/activates the group-writing pipeline, so touching
+ # it needs group scope — an account-only token must not read or modify group properties.
+ source = api.get_custom_property_source(self.team_id, source_id)
+ if source is not None and self._definition_is_group(source.definition):
+ _assert_group_scope(request, write=write)
+
def create(self, request: Request, *args, **kwargs) -> Response:
serializer = CustomPropertySourceSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
data = serializer.validated_data
+ if self._definition_is_group(data.definition):
+ _assert_group_scope(request, write=True)
try:
source = api.create_custom_property_source(
team_id=self.team_id,
@@ -512,6 +600,7 @@ class CustomPropertySourceViewSet(
@extend_schema(request=CustomPropertySourceUpdateSerializer)
def update(self, request: Request, *args, **kwargs) -> Response:
+ self._guard_group_source(request, self.kwargs["pk"])
write = CustomPropertySourceUpdateSerializer(data=request.data, partial=kwargs.pop("partial", False))
write.is_valid(raise_exception=True)
try:
@@ -533,6 +622,7 @@ class CustomPropertySourceViewSet(
return self.update(request, *args, **kwargs)
def destroy(self, request: Request, *args, **kwargs) -> Response:
+ self._guard_group_source(request, self.kwargs["pk"])
try:
deleted = api.delete_custom_property_source(
team_id=self.team_id,
@@ -554,6 +644,7 @@ class CustomPropertySourceViewSet(
def sync(self, request: Request, *args, **kwargs) -> Response:
"""Person sources only: trigger the underlying warehouse schema's sync now. This re-runs a
real (billable) warehouse sync; the incremental person-property update runs off it."""
+ self._guard_group_source(request, self.kwargs["pk"])
try:
triggered = api.trigger_person_property_sync(
team_id=self.team_id, source_id=self.kwargs["pk"], user_access_control=_warehouse_scoped_uac(self)
@@ -575,6 +666,7 @@ class CustomPropertySourceViewSet(
def backfill(self, request: Request, *args, **kwargs) -> Response:
"""Person sources only: start a backfill that reads the whole warehouse table and populates
person properties for historical rows. Coalesces if one is already running for the table."""
+ self._guard_group_source(request, self.kwargs["pk"])
try:
started = api.trigger_person_property_backfill(
team_id=self.team_id,
@@ -599,6 +691,14 @@ class CustomPropertySourceViewSet(
def runs(self, request: Request, *args, **kwargs) -> Response:
"""Person sources only: the source's sync/backfill run history, newest first. Gated on the
caller's warehouse-source viewer access, since the runs expose its row counts and sync errors."""
+ # Hide the run history of a group-target source from callers without group read authorization.
+ source = api.get_custom_property_source(self.team_id, self.kwargs["pk"])
+ if (
+ source is not None
+ and self._definition_is_group(source.definition)
+ and not _has_group_scope(request, write=False)
+ ):
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
try:
return self._paginate_via_facade(
request,
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 69f8c686ed86..b044cb93497d 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -15,8 +15,10 @@ from posthog.constants import AvailableFeature
from posthog.models import Tag, TaggedItem
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import OrganizationMembership
+from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.customer_analytics.backend.logic import relationships as relationships_logic
from products.customer_analytics.backend.models import (
@@ -2055,6 +2057,214 @@ class TestCustomPropertySourceViewSet(APIBaseTest):
assert runs.status_code == status.HTTP_200_OK
assert any(run["status"] == "running" for run in runs.json()["results"])
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_create_group_definition_and_source_round_trip(self, _flag):
+ # Group support: a group definition carries a group_type_index, and its source binds the same
+ # warehouse way as a person source (external_data_schema + column_property_map + key_column).
+ definitions_endpoint = f"/api/projects/{self.team.id}/custom_property_definitions/"
+ definition = self.client.post(
+ definitions_endpoint,
+ {"name": "Plan tier", "display_type": "text", "target_type": "group", "group_type_index": 0},
+ format="json",
+ )
+ assert definition.status_code == status.HTTP_201_CREATED, definition.content
+ assert definition.json()["group_type_index"] == 0
+
+ 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="orgs")
+ created = self.client.post(
+ self.endpoint,
+ {
+ "definition": definition.json()["id"],
+ "external_data_schema": str(schema.id),
+ "column_property_map": {"plan": "plan_tier"},
+ "key_column": "org_id",
+ },
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.content
+ assert created.json()["external_data_schema"] == str(schema.id)
+
+ @parameterized.expand(
+ [
+ ("group_without_index", {"target_type": "group"}),
+ ("index_without_group", {"target_type": "person", "group_type_index": 0}),
+ ]
+ )
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_group_type_index_validation(self, _name, extra, _flag):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/custom_property_definitions/",
+ {"name": "X", "display_type": "text", **extra},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+
+
+class TestCustomPropertyGroupScope(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.definitions_endpoint = f"/api/projects/{self.team.id}/custom_property_definitions/"
+ self.sources_endpoint = f"/api/projects/{self.team.id}/custom_property_sources/"
+
+ def _token(self, scopes: list[str]) -> str:
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="scoped",
+ user=self.user,
+ secure_value=hash_key_value(value),
+ scopes=scopes,
+ scoped_teams=[],
+ scoped_organizations=[],
+ )
+ return value
+
+ @parameterized.expand(
+ [
+ ("account_only", ["account:write", "group:read"], status.HTTP_403_FORBIDDEN),
+ ("with_group_write", ["account:write", "group:write"], status.HTTP_201_CREATED),
+ ]
+ )
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_group_definition_create_requires_group_write_scope(self, _name, scopes, expected, _flag):
+ # Group-target definitions write group properties, so an account-scoped token must also carry
+ # group:write — a regression that drops this guard would let an account-only key configure the
+ # group-writing pipeline.
+ token = self._token(scopes)
+ response = self.client.post(
+ self.definitions_endpoint,
+ {"name": "Plan tier", "display_type": "text", "target_type": "group", "group_type_index": 0},
+ format="json",
+ headers={"authorization": f"Bearer {token}"},
+ )
+ assert response.status_code == expected, response.content
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_group_source_mutation_requires_group_write_scope(self, _flag):
+ # An account-only token must not be able to enable/mutate a source feeding a group definition.
+ # The group def + source are set up as an admin session, which the scope check exempts.
+ definition = self.client.post(
+ self.definitions_endpoint,
+ {"name": "Plan tier", "display_type": "text", "target_type": "group", "group_type_index": 0},
+ format="json",
+ )
+ assert definition.status_code == status.HTTP_201_CREATED, definition.content
+ 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="orgs")
+ created = self.client.post(
+ self.sources_endpoint,
+ {
+ "definition": definition.json()["id"],
+ "external_data_schema": str(schema.id),
+ "column_property_map": {"plan": "plan_tier"},
+ "key_column": "org_id",
+ },
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.content
+ source_id = created.json()["id"]
+
+ token = self._token(["account:write", "group:read"])
+ patched = self.client.patch(
+ f"{self.sources_endpoint}{source_id}/",
+ {"is_enabled": False},
+ format="json",
+ headers={"authorization": f"Bearer {token}"},
+ )
+ assert patched.status_code == status.HTTP_403_FORBIDDEN, patched.content
+
+ def _create_group_definition_and_source(self):
+ definition = self.client.post(
+ self.definitions_endpoint,
+ {"name": "Plan tier", "display_type": "text", "target_type": "group", "group_type_index": 0},
+ format="json",
+ )
+ assert definition.status_code == status.HTTP_201_CREATED, definition.content
+ 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="orgs")
+ created = self.client.post(
+ self.sources_endpoint,
+ {
+ "definition": definition.json()["id"],
+ "external_data_schema": str(schema.id),
+ "column_property_map": {"plan": "plan_tier"},
+ "key_column": "org_id",
+ },
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.content
+ return definition.json()["id"], created.json()["id"]
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_group_definition_reads_require_group_read_scope(self, _flag):
+ # A token without group read must not see group-target definitions in the list or detail;
+ # group:read makes them visible again.
+ def_id, _ = self._create_group_definition_and_source()
+
+ account_token = self._token(["account:read"])
+ listed = self.client.get(self.definitions_endpoint, headers={"authorization": f"Bearer {account_token}"})
+ assert listed.status_code == status.HTTP_200_OK, listed.content
+ assert def_id not in [d["id"] for d in listed.json()["results"]]
+ detail = self.client.get(
+ f"{self.definitions_endpoint}{def_id}/", headers={"authorization": f"Bearer {account_token}"}
+ )
+ assert detail.status_code == status.HTTP_404_NOT_FOUND, detail.content
+
+ group_token = self._token(["account:read", "group:read"])
+ listed2 = self.client.get(self.definitions_endpoint, headers={"authorization": f"Bearer {group_token}"})
+ assert def_id in [d["id"] for d in listed2.json()["results"]]
+ detail2 = self.client.get(
+ f"{self.definitions_endpoint}{def_id}/", headers={"authorization": f"Bearer {group_token}"}
+ )
+ assert detail2.status_code == status.HTTP_200_OK, detail2.content
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_group_source_reads_require_group_read_scope(self, _flag):
+ # Sources feeding a group definition are hidden from list and detail without group read.
+ # (The runs action rejects personal API keys outright, so it isn't reachable via a token.)
+ _, source_id = self._create_group_definition_and_source()
+
+ account_token = self._token(["account:read"])
+ listed = self.client.get(self.sources_endpoint, headers={"authorization": f"Bearer {account_token}"})
+ assert listed.status_code == status.HTTP_200_OK, listed.content
+ assert source_id not in [s["id"] for s in listed.json()["results"]]
+ detail = self.client.get(
+ f"{self.sources_endpoint}{source_id}/", headers={"authorization": f"Bearer {account_token}"}
+ )
+ assert detail.status_code == status.HTTP_404_NOT_FOUND, detail.content
+
+ group_token = self._token(["account:read", "group:read"])
+ detail2 = self.client.get(
+ f"{self.sources_endpoint}{source_id}/", headers={"authorization": f"Bearer {group_token}"}
+ )
+ assert detail2.status_code == status.HTTP_200_OK, detail2.content
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_group_definition_value_suggestions_require_group_read_scope(self, _flag):
+ # The values action loads a definition by id, so it must apply the same group-read gate as
+ # list/detail — an account-only token must not read a group-target definition's suggestions.
+ def_id, _ = self._create_group_definition_and_source()
+
+ account_token = self._token(["account:read"])
+ denied = self.client.get(
+ f"{self.definitions_endpoint}values/?key={def_id}",
+ headers={"authorization": f"Bearer {account_token}"},
+ )
+ assert denied.status_code == status.HTTP_404_NOT_FOUND, denied.content
+
+ group_token = self._token(["account:read", "group:read"])
+ allowed = self.client.get(
+ f"{self.definitions_endpoint}values/?key={def_id}",
+ headers={"authorization": f"Bearer {group_token}"},
+ )
+ assert allowed.status_code == status.HTTP_200_OK, allowed.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 02b2201998b7..2dcb18978a33 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -575,13 +575,15 @@ export const CustomPropertyDisplayTypeEnumApi = {
/**
* * `account` - account
* * `person` - person
+ * * `group` - group
*/
-export type CustomPropertyDefinitionTargetTypeApi =
- (typeof CustomPropertyDefinitionTargetTypeApi)[keyof typeof CustomPropertyDefinitionTargetTypeApi]
+export type CustomPropertyDefinitionTargetTypeEnumApi =
+ (typeof CustomPropertyDefinitionTargetTypeEnumApi)[keyof typeof CustomPropertyDefinitionTargetTypeEnumApi]
-export const CustomPropertyDefinitionTargetTypeApi = {
+export const CustomPropertyDefinitionTargetTypeEnumApi = {
Account: 'account',
Person: 'person',
+ Group: 'group',
} as const
/**
@@ -787,11 +789,19 @@ 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).
+ /** What entity this property is attached to: 'account' (default), 'person', or 'group'. Person and group properties are populated from a warehouse schema and become usable like any other person/group property (feature flags, cohorts, insights).
*
* * `account` - account
- * * `person` - person */
- target_type?: CustomPropertyDefinitionTargetTypeApi
+ * * `person` - person
+ * * `group` - group */
+ target_type?: CustomPropertyDefinitionTargetTypeEnumApi
+ /**
+ * For 'group' targets only: which group type (0-4) the property attaches to. Required when target_type is 'group'; must be omitted otherwise. Create-only.
+ * @minimum 0
+ * @maximum 4
+ * @nullable
+ */
+ group_type_index?: number | null
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean
/**
@@ -848,11 +858,19 @@ 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).
+ /** What entity this property is attached to: 'account' (default), 'person', or 'group'. Person and group properties are populated from a warehouse schema and become usable like any other person/group property (feature flags, cohorts, insights).
*
* * `account` - account
- * * `person` - person */
- target_type?: CustomPropertyDefinitionTargetTypeApi
+ * * `person` - person
+ * * `group` - group */
+ target_type?: CustomPropertyDefinitionTargetTypeEnumApi
+ /**
+ * For 'group' targets only: which group type (0-4) the property attaches to. Required when target_type is 'group'; must be omitted otherwise. Create-only.
+ * @minimum 0
+ * @maximum 4
+ * @nullable
+ */
+ group_type_index?: number | null
/** 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 5cec5bd74a62..a3d7064eab9a 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -288,6 +288,9 @@ export const AnnouncementsCreateBody = /* @__PURE__ */ zod.object({
export const customPropertyDefinitionsCreateBodyNameMax = 400
export const customPropertyDefinitionsCreateBodyTargetTypeDefault = `account`
+export const customPropertyDefinitionsCreateBodyGroupTypeIndexMin = 0
+export const customPropertyDefinitionsCreateBodyGroupTypeIndexMax = 4
+
export const customPropertyDefinitionsCreateBodyIsBigNumberDefault = false
export const customPropertyDefinitionsCreateBodyOptionsItemLabelMax = 400
@@ -307,11 +310,19 @@ export const CustomPropertyDefinitionsCreateBody = /* @__PURE__ */ zod
"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')
+ .enum(['account', 'person', 'group'])
+ .describe('\* `account` - account\n\* `person` - person\n\* `group` - group')
.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"
+ "What entity this property is attached to: 'account' (default), 'person', or 'group'. Person and group properties are populated from a warehouse schema and become usable like any other person\/group property (feature flags, cohorts, insights).\n\n\* `account` - account\n\* `person` - person\n\* `group` - group"
+ ),
+ group_type_index: zod
+ .number()
+ .min(customPropertyDefinitionsCreateBodyGroupTypeIndexMin)
+ .max(customPropertyDefinitionsCreateBodyGroupTypeIndexMax)
+ .nullish()
+ .describe(
+ "For 'group' targets only: which group type (0-4) the property attaches to. Required when target_type is 'group'; must be omitted otherwise. Create-only."
),
is_big_number: zod
.boolean()
@@ -365,6 +376,9 @@ export const CustomPropertyDefinitionsCreateBody = /* @__PURE__ */ zod
export const customPropertyDefinitionsUpdateBodyNameMax = 400
export const customPropertyDefinitionsUpdateBodyTargetTypeDefault = `account`
+export const customPropertyDefinitionsUpdateBodyGroupTypeIndexMin = 0
+export const customPropertyDefinitionsUpdateBodyGroupTypeIndexMax = 4
+
export const customPropertyDefinitionsUpdateBodyIsBigNumberDefault = false
export const customPropertyDefinitionsUpdateBodyOptionsItemLabelMax = 400
@@ -384,11 +398,19 @@ export const CustomPropertyDefinitionsUpdateBody = /* @__PURE__ */ zod
"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')
+ .enum(['account', 'person', 'group'])
+ .describe('\* `account` - account\n\* `person` - person\n\* `group` - group')
.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"
+ "What entity this property is attached to: 'account' (default), 'person', or 'group'. Person and group properties are populated from a warehouse schema and become usable like any other person\/group property (feature flags, cohorts, insights).\n\n\* `account` - account\n\* `person` - person\n\* `group` - group"
+ ),
+ group_type_index: zod
+ .number()
+ .min(customPropertyDefinitionsUpdateBodyGroupTypeIndexMin)
+ .max(customPropertyDefinitionsUpdateBodyGroupTypeIndexMax)
+ .nullish()
+ .describe(
+ "For 'group' targets only: which group type (0-4) the property attaches to. Required when target_type is 'group'; must be omitted otherwise. Create-only."
),
is_big_number: zod
.boolean()
@@ -442,6 +464,9 @@ export const CustomPropertyDefinitionsUpdateBody = /* @__PURE__ */ zod
export const customPropertyDefinitionsPartialUpdateBodyNameMax = 400
export const customPropertyDefinitionsPartialUpdateBodyTargetTypeDefault = `account`
+export const customPropertyDefinitionsPartialUpdateBodyGroupTypeIndexMin = 0
+export const customPropertyDefinitionsPartialUpdateBodyGroupTypeIndexMax = 4
+
export const customPropertyDefinitionsPartialUpdateBodyIsBigNumberDefault = false
export const customPropertyDefinitionsPartialUpdateBodyOptionsItemLabelMax = 400
@@ -463,11 +488,19 @@ export const CustomPropertyDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
"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')
+ .enum(['account', 'person', 'group'])
+ .describe('\* `account` - account\n\* `person` - person\n\* `group` - group')
.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"
+ "What entity this property is attached to: 'account' (default), 'person', or 'group'. Person and group properties are populated from a warehouse schema and become usable like any other person\/group property (feature flags, cohorts, insights).\n\n\* `account` - account\n\* `person` - person\n\* `group` - group"
+ ),
+ group_type_index: zod
+ .number()
+ .min(customPropertyDefinitionsPartialUpdateBodyGroupTypeIndexMin)
+ .max(customPropertyDefinitionsPartialUpdateBodyGroupTypeIndexMax)
+ .nullish()
+ .describe(
+ "For 'group' targets only: which group type (0-4) the property attaches to. Required when target_type is 'group'; must be omitted otherwise. Create-only."
),
is_big_number: zod
.boolean()
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
index 1d31f0c2f813..5687d72a2d8c 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
@@ -25,6 +25,8 @@ import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
+import { groupsModel } from '~/models/groupsModel'
+
import type { CustomPropertyOptionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
import {
@@ -48,11 +50,13 @@ const SOURCE_MODE_OPTIONS: { value: CustomPropertySourceMode; label: string }[]
const TARGET_TYPE_OPTIONS: { value: CustomPropertyTargetType; label: string }[] = [
{ value: 'account', label: 'Account' },
{ value: 'person', label: 'Person' },
+ { value: 'group', label: 'Group' },
]
-// Person-target editor: pick a synced warehouse table, the distinct_id column, and the
-// column → person-property mappings. The binding + mappings are create-only on the backend, so
-// they're read-only once a source exists (only the key column + enabled switch stay editable).
+// Warehouse-profile editor (person or group target): pick a synced warehouse table, the key column
+// (a person's distinct_id or a group's key), and the column → property mappings. For group targets it
+// also picks which group type. The binding + mappings are create-only on the backend, so they're
+// read-only once a source exists (only the key column + enabled switch stay editable).
function PersonSourceEditor(): JSX.Element {
const {
customPropertyForm,
@@ -64,12 +68,19 @@ function PersonSourceEditor(): JSX.Element {
selectedTableColumnsLoading,
} = useValues(customPropertyDefinitionsLogic)
const { setCustomPropertyFormValue, loadSelectedTableColumns } = useActions(customPropertyDefinitionsLogic)
+ const { groupTypes } = useValues(groupsModel)
+ const isGroup = customPropertyForm.targetType === 'group'
+ const entityLabel = isGroup ? 'group' : 'person'
const hasExistingSource = !!editingDefinition?.source
const noTables = !warehouseTablesLoading && warehouseTables.length === 0
const mappings = customPropertyForm.columnMappings
const setMappings = (next: typeof mappings): void => setCustomPropertyFormValue('columnMappings', next)
const columnOptions = selectedTableColumns.map((column) => ({ key: column, label: column }))
+ const groupTypeOptions = Array.from(groupTypes.values()).map((groupType) => ({
+ value: groupType.group_type_index,
+ label: groupType.name_singular || groupType.group_type,
+ }))
// Only block on missing tables while creating a source — an existing source still needs its
// key column and enabled switch editable even if its table was later deleted or filtered out.
@@ -84,16 +95,30 @@ function PersonSourceEditor(): JSX.Element {
return (
<>
+ {isGroup && !hasExistingSource && (
+ <LemonField name="groupTypeIndex" label="Group type" help="Which group type this property attaches to.">
+ {({ value, onChange }) => (
+ <LemonSelect
+ value={value}
+ onChange={onChange}
+ options={groupTypeOptions}
+ placeholder="Select a group type"
+ fullWidth
+ />
+ )}
+ </LemonField>
+ )}
{hasExistingSource ? (
<LemonBanner type="info">
The warehouse table and column mappings are fixed once a source is created. To change them, delete
- this property and create a new one. You can still update the distinct ID column and toggle syncing.
+ this property and create a new one. You can still update the {isGroup ? 'group key' : 'distinct ID'}{' '}
+ column and toggle syncing.
</LemonBanner>
) : (
<LemonField
name="warehouseTable"
label="Warehouse table"
- help="Rows from this synced table are upserted onto matching people."
+ help={`Rows from this synced table are upserted onto matching ${entityLabel}s.`}
>
{({ value, onChange }) => (
<LemonSearchableSelect
@@ -119,8 +144,10 @@ function PersonSourceEditor(): JSX.Element {
)}
<LemonField
name="keyColumn"
- label="Distinct ID column"
- help="The column holding each row's distinct ID — used to match the person to update."
+ label={isGroup ? 'Group key column' : 'Distinct ID column'}
+ help={`The column holding each row's ${
+ isGroup ? 'group key' : 'distinct ID'
+ } — used to match the ${entityLabel} to update.`}
>
{({ value, onChange }) => (
<LemonInputSelect
@@ -138,7 +165,7 @@ function PersonSourceEditor(): JSX.Element {
<div className="flex flex-col gap-2">
<LemonLabel>Column mappings</LemonLabel>
<span className="text-secondary text-xs">
- Map each warehouse column to the person property name it should set.
+ Map each warehouse column to the {entityLabel} property name it should set.
</span>
{mappings.map((mapping, index) => (
<div key={index} className="flex flex-col gap-1">
@@ -167,7 +194,7 @@ function PersonSourceEditor(): JSX.Element {
onChange={(property) =>
setMappings(mappings.map((m, i) => (i === index ? { ...m, property } : m)))
}
- placeholder="Person property"
+ placeholder={`${isGroup ? 'Group' : 'Person'} property`}
fullWidth
/>
</div>
@@ -289,9 +316,10 @@ export function CustomPropertyModal(): JSX.Element {
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
+ const isProfileTarget = targetType === 'person' || targetType === 'group'
+ // Person/group-target properties are gated behind the rollout flag; an existing profile property
// stays editable so a rollback doesn't strand its configuration.
- const personTargetAvailable = !!featureFlags[FEATURE_FLAGS.WAREHOUSE_PERSON_PROPERTIES] || targetType === 'person'
+ const profileTargetAvailable = !!featureFlags[FEATURE_FLAGS.WAREHOUSE_PERSON_PROPERTIES] || isProfileTarget
const hasExistingSource = !!editingDefinition?.source
const noViews = !savedQueriesLoading && materializedViews.length === 0
@@ -308,10 +336,10 @@ export function CustomPropertyModal(): JSX.Element {
: option
)
- // A new person source needs at least one complete column → property pair. The mapping rows
+ // A new person/group source needs at least one complete column → property pair. The mapping rows
// aren't LemonFields, so this gates the submit button rather than showing a per-field error.
const missingPersonMapping =
- targetType === 'person' &&
+ isProfileTarget &&
!hasExistingSource &&
!customPropertyForm.columnMappings.some((mapping) => mapping.column.trim() && mapping.property.trim())
@@ -363,7 +391,7 @@ export function CustomPropertyModal(): JSX.Element {
<LemonField name="description" label="Description">
<LemonTextArea placeholder="Optional description" minRows={2} />
</LemonField>
- {personTargetAvailable && (
+ {profileTargetAvailable && (
<LemonField
name="targetType"
label="Attach to"
@@ -406,7 +434,7 @@ export function CustomPropertyModal(): JSX.Element {
{customPropertyForm.displayType === 'select' && <CustomPropertyOptionsEditor />}
</>
)}
- {targetType === 'person' && <PersonSourceEditor />}
+ {isProfileTarget && <PersonSourceEditor />}
{targetType === 'account' && (
<>
<LemonField name="sourceMode" label="Source">
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
index 6adfa57dfc77..db8e18269130 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
@@ -133,6 +133,7 @@ describe('customPropertyDefinitionsLogic', () => {
isBigNumber: true,
options: [],
targetType: 'account',
+ groupTypeIndex: null,
sourceMode: 'data_warehouse',
savedQuery: 'view-1',
sourceColumn: 'mrr',
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
index f4a08936fe27..619884c11af5 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
@@ -35,7 +35,7 @@ import type {
import { NEW_OPTION_ID_PREFIX, isNumericDisplayType, optionLabelError } from './customPropertyTypes'
export type CustomPropertySourceMode = 'manual' | 'data_warehouse' | 'workflow'
-export type CustomPropertyTargetType = 'account' | 'person'
+export type CustomPropertyTargetType = 'account' | 'person' | 'group'
// After triggering a sync/backfill, poll until the source's run settles so the UI reflects
// completion without a manual refresh. Bounded so a stuck run can't poll forever.
@@ -58,11 +58,13 @@ export interface CustomPropertyFormValues {
// 'account' feeds an account (group) property from a saved query; 'person' upserts warehouse
// columns onto person properties (usable in flags/cohorts/insights) from a raw synced table.
targetType: CustomPropertyTargetType
+ // Group target only: which group type (0-4) the property attaches to.
+ groupTypeIndex: number | null
sourceMode: CustomPropertySourceMode
savedQuery: string | null
sourceColumn: string | null
keyColumn: string | null
- // Person target: the warehouse table (its schema id backs the source) + the column mappings.
+ // Person/group target: the warehouse table (its schema id backs the source) + the column mappings.
warehouseTable: string | null
columnMappings: ColumnPropertyMapping[]
isEnabled: boolean
@@ -75,6 +77,7 @@ const DEFAULT_FORM_VALUES: CustomPropertyFormValues = {
isBigNumber: false,
options: [],
targetType: 'account',
+ groupTypeIndex: null,
sourceMode: 'manual',
savedQuery: null,
sourceColumn: null,
@@ -91,27 +94,31 @@ const serializeDefinition = ({
isBigNumber,
options,
targetType,
+ groupTypeIndex,
}: CustomPropertyFormValues): {
name: string
description: string | null
display_type: CustomPropertyDisplayTypeEnumApi
target_type: CustomPropertyTargetType
+ group_type_index?: number | null
is_big_number: boolean
options?: CustomPropertyOptionApi[]
} => {
- // display_type/is_big_number/options only drive how an account property renders — a person
- // property is written as a raw $set value, so those fields are hidden and forced to defaults.
- const isPerson = targetType === 'person'
+ // display_type/is_big_number/options only drive how an account property renders — person and
+ // group properties are written as raw $set / $group_set values, so those are hidden and defaulted.
+ const isProfile = targetType === 'person' || targetType === 'group'
return {
name: name.trim(),
description: description?.trim() || null,
- display_type: isPerson ? 'text' : displayType,
+ display_type: isProfile ? 'text' : displayType,
// Create-only on the backend; a definition's target doesn't change after creation.
target_type: targetType,
+ // The group type is create-only too; sent only for group targets, omitted otherwise.
+ ...(targetType === 'group' ? { group_type_index: groupTypeIndex } : {}),
// The switch is hidden for non-numeric types, so never send a stale flag for them.
- is_big_number: !isPerson && isNumericDisplayType(displayType) ? isBigNumber : false,
+ is_big_number: !isProfile && isNumericDisplayType(displayType) ? isBigNumber : false,
// Options only apply to select; the backend clears them for other types.
- ...(!isPerson && displayType === 'select'
+ ...(!isProfile && displayType === 'select'
? {
options: options.map(({ id, label, color }) => ({
...(id && !id.startsWith(NEW_OPTION_ID_PREFIX) ? { id } : {}),
@@ -588,28 +595,32 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
displayType,
options,
targetType,
+ groupTypeIndex,
sourceMode,
savedQuery,
sourceColumn,
keyColumn,
warehouseTable,
}: CustomPropertyFormValues) => {
- const isPerson = targetType === 'person'
- const isAccountWarehouse = !isPerson && sourceMode === 'data_warehouse'
+ // Person and group both feed from a warehouse table; account can also via a view.
+ const isProfile = targetType === 'person' || targetType === 'group'
+ const isAccountWarehouse = !isProfile && sourceMode === 'data_warehouse'
// The table + column map are create-only, so only require them when creating a new
- // person source — an existing source keeps only key_column and enabled editable.
- const isNewPersonSource = isPerson && !values.editingDefinition?.source
+ // profile source — an existing source keeps only key_column and enabled editable.
+ const isNewProfileSource = isProfile && !values.editingDefinition?.source
return {
name: !name?.trim() ? 'Name is required' : undefined,
+ groupTypeIndex:
+ targetType === 'group' && groupTypeIndex == null ? 'Select a group type' : undefined,
options:
- !isPerson && displayType === 'select'
+ !isProfile && displayType === 'select'
? options.map((_, index) => ({ label: optionLabelError(options, index) }))
: undefined,
savedQuery: isAccountWarehouse && !savedQuery ? 'Select a view' : undefined,
sourceColumn: isAccountWarehouse && !sourceColumn ? 'Select the value column' : undefined,
keyColumn:
- (isAccountWarehouse || isPerson) && !keyColumn?.trim() ? 'Enter the key column' : undefined,
- warehouseTable: isNewPersonSource && !warehouseTable ? 'Select a warehouse table' : undefined,
+ (isAccountWarehouse || isProfile) && !keyColumn?.trim() ? 'Enter the key column' : undefined,
+ warehouseTable: isNewProfileSource && !warehouseTable ? 'Select a warehouse table' : undefined,
}
},
submit: async (formValues: CustomPropertyFormValues) => {
@@ -628,7 +639,8 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
try {
const { targetType, sourceMode, savedQuery, sourceColumn, keyColumn, isEnabled } = formValues
const existingSource = editing?.source ?? null
- if (targetType === 'person') {
+ // Person and group sources share the same warehouse binding (schema + column map).
+ if (targetType === 'person' || targetType === 'group') {
const schemaId = values.selectedWarehouseSchemaId
if (existingSource) {
// The binding + column map are create-only on the backend; only key_column
@@ -759,14 +771,19 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
actions.loadSavedQueries()
actions.loadWarehouseTables()
actions.loadPersonPropertyDefinitions()
- const isPerson = definition.target_type === 'person'
+ const targetType: CustomPropertyTargetType =
+ definition.target_type === 'person' || definition.target_type === 'group'
+ ? definition.target_type
+ : 'account'
+ const isProfile = targetType === 'person' || targetType === 'group'
actions.setCustomPropertyFormValues({
name: definition.name,
description: definition.description ?? '',
displayType: definition.display_type,
isBigNumber: definition.is_big_number ?? false,
options: definition.options ?? [],
- targetType: isPerson ? 'person' : 'account',
+ targetType,
+ groupTypeIndex: definition.group_type_index ?? null,
sourceMode: definition.source
? 'data_warehouse'
: definition.references?.length
@@ -778,7 +795,7 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
// The warehouse-table binding is create-only, so on edit we surface the existing map
// (read-only in the modal) rather than resolving the table back for the picker.
warehouseTable: null,
- columnMappings: isPerson
+ columnMappings: isProfile
? parseColumnPropertyMap(definition.source?.column_property_map)
: [{ column: '', property: '' }],
isEnabled: definition.source?.is_enabled ?? true,
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 ec298d3256e4..8e7e5d1f01ff 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
@@ -145,16 +145,19 @@ def person_property_sync_enabled_for(team_id: int, schema_id: "uuid.UUID") -> bo
@dataclasses.dataclass(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."""
+ """One enabled person- or group-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 identifier (a person's distinct_id, or a group's key) and ``column_property_map`` maps
+ warehouse column -> property name. ``target`` is "person" or "group"; ``group_type_index`` is the
+ group type (0-4) for group targets, else None."""
source_id: str
definition_id: str
key_column: str
column_property_map: dict[str, str]
+ target: str = "person"
+ group_type_index: int | None = None
PersonPropertySyncSourcesResolver = Callable[[int, "str | uuid.UUID"], Optional[list[PersonPropertySyncSource]]]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py
index 513aa6fe01d8..c298b8aeba08 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py
@@ -107,8 +107,9 @@ register_policy(_RATE_DOMAIN, _rate_policy)
def build_capture_kwargs(payload: dict[str, Any]) -> dict[str, Any]:
- """Map a topic message to capture_internal kwargs. Raises InvalidPersonPropertyMessage for a
- shape that can never succeed (missing token/distinct_id, or no properties)."""
+ """Map a topic message to capture_internal kwargs. Person messages become a `$set`; group messages
+ (``kind == "group"``) become a `$groupidentify` carrying `$group_type`/`$group_key`/`$group_set`.
+ Raises InvalidPersonPropertyMessage for a shape that can never succeed."""
token = payload.get("token")
distinct_id = payload.get("distinct_id")
properties = payload.get("properties")
@@ -123,10 +124,27 @@ def build_capture_kwargs(payload: dict[str, Any]) -> dict[str, Any]:
json.dumps(properties, allow_nan=False)
except ValueError as exc:
raise InvalidPersonPropertyMessage("message has non-finite property values") from exc
+
+ event_source = payload.get("event_source") or EVENT_SOURCE
+ if payload.get("kind") == "group":
+ group_type = payload.get("group_type")
+ group_key = payload.get("group_key")
+ if not group_type or not group_key:
+ raise InvalidPersonPropertyMessage("group message missing group_type or group_key")
+ # Mirror the canonical group-identify write (ee/clickhouse/views/groups.py::trigger_group_identify):
+ # distinct_id is the team-uuid placeholder, group type is the name, process_person_profile=False.
+ return {
+ "token": token,
+ "event_name": "$groupidentify",
+ "event_source": event_source,
+ "distinct_id": str(distinct_id),
+ "properties": {"$group_type": group_type, "$group_key": str(group_key), "$group_set": properties},
+ "process_person_profile": False,
+ }
return {
"token": token,
"event_name": "$set",
- "event_source": payload.get("event_source") or EVENT_SOURCE,
+ "event_source": event_source,
"distinct_id": str(distinct_id),
"properties": {"$set": properties},
"process_person_profile": True,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer_test.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer_test.py
index 3be65221352f..c9bdb5448ecd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer_test.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer_test.py
@@ -11,6 +11,7 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.person_property_update_consumer import (
_DEFAULT_RATE_PER_SEC,
DLQ,
+ EVENT_SOURCE,
RETRY,
SENT,
InvalidPersonPropertyMessage,
@@ -38,6 +39,29 @@ class TestBuildCaptureKwargs:
"process_person_profile": True,
}
+ def test_group_message_maps_to_groupidentify(self):
+ # Regression: a group message must become a $groupidentify with $group_type/$group_key/$group_set
+ # and process_person_profile=False, mirroring the canonical group-identify write.
+ kwargs = build_capture_kwargs(
+ {
+ "token": "tok",
+ "kind": "group",
+ "distinct_id": "team-uuid",
+ "group_type": "organization",
+ "group_type_index": 0,
+ "group_key": "acme",
+ "properties": {"plan_tier": "pro"},
+ }
+ )
+ assert kwargs == {
+ "token": "tok",
+ "event_name": "$groupidentify",
+ "event_source": EVENT_SOURCE,
+ "distinct_id": "team-uuid",
+ "properties": {"$group_type": "organization", "$group_key": "acme", "$group_set": {"plan_tier": "pro"}},
+ "process_person_profile": False,
+ }
+
@parameterized.expand(
[
("missing_token", {"distinct_id": "a", "properties": {"p": 1}}),
@@ -47,6 +71,14 @@ class TestBuildCaptureKwargs:
("nan_value", {"token": "t", "distinct_id": "a", "properties": {"p": float("nan")}}),
("inf_value", {"token": "t", "distinct_id": "a", "properties": {"p": float("inf")}}),
("nested_inf_value", {"token": "t", "distinct_id": "a", "properties": {"p": {"q": float("-inf")}}}),
+ (
+ "group_missing_group_type",
+ {"token": "t", "distinct_id": "a", "kind": "group", "group_key": "k", "properties": {"p": 1}},
+ ),
+ (
+ "group_missing_group_key",
+ {"token": "t", "distinct_id": "a", "kind": "group", "group_type": "org", "properties": {"p": 1}},
+ ),
]
)
def test_rejects_unusable_messages(self, _name, payload):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
index 56cf954a3e47..3311ae56e118 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
@@ -32,6 +32,8 @@ from posthog.exceptions_capture import capture_exception
from posthog.kafka_client.routing import producer_scope
from posthog.kafka_client.topics import KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES
from posthog.models import PropertyDefinition, Team
+from posthog.models.group.util import get_groups_by_identifiers
+from posthog.models.group_type_mapping import get_group_types_for_team
from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.sync import database_sync_to_async
@@ -52,6 +54,10 @@ logger = structlog.get_logger(__name__)
EVENT_SOURCE = "customer_analytics_person_property_sync"
+# target_type value for group sources (kept as a literal so this module doesn't import the
+# customer_analytics config models, matching the isolation the hooks already preserve).
+_GROUP_TARGET = "group"
+
@dataclasses.dataclass
class PerSourceResult:
@@ -280,29 +286,67 @@ def _get_schema(team_id: int, schema_id: str) -> ExternalDataSchema | None:
)
-def _filter_existing_persons(team_id: int, distinct_ids: list[str]) -> set[str]:
- if not distinct_ids:
+def _filter_existing_ids(team_id: int, source: PersonPropertySyncSource, ids: list[str]) -> set[str]:
+ """The subset of ``ids`` that resolve to an existing person (or group, for group targets). We only
+ enrich entities that already exist — the same rule for both, just a different lookup."""
+ if not ids:
return set()
- return set(get_persons_mapped_by_distinct_id(team_id, distinct_ids).keys())
+ if source.target == _GROUP_TARGET:
+ if source.group_type_index is None:
+ return set()
+ return {group.group_key for group in get_groups_by_identifiers(team_id, source.group_type_index, ids)}
+ return set(get_persons_mapped_by_distinct_id(team_id, ids).keys())
+
+
+def _group_type_name(team_id: int, group_type_index: int) -> str | None:
+ # $groupidentify carries the group-type *name*; the config stores the index, so resolve it.
+ for group_type in get_group_types_for_team(team_id):
+ if group_type.get("group_type_index") == group_type_index:
+ return group_type.get("group_type")
+ return None
-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."""
+def _produce_intents(
+ team_id: int,
+ token: str,
+ source: PersonPropertySyncSource,
+ items: list[tuple[str, dict]],
+ *,
+ team_uuid: str,
+ group_type_name: str | None,
+) -> int:
+ """Produce one property-update intent per entity to Kafka. Person intents map to a `$set` keyed
+ by team:distinct_id; group intents map to a `$groupidentify` keyed by team:group_type:group_key so
+ per-group ordering is preserved. The consumer branches on ``kind``. Returns the count produced."""
+ is_group = source.target == _GROUP_TARGET
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={
+ for key, bundle in items:
+ if is_group:
+ data = {
"team_id": team_id,
"token": token,
- "distinct_id": distinct_id,
+ "kind": "group",
+ # $groupidentify isn't tied to a person; capture uses the team uuid as distinct_id.
+ "distinct_id": team_uuid,
+ "group_type": group_type_name,
+ "group_type_index": source.group_type_index,
+ "group_key": key,
"properties": bundle,
"event_source": EVENT_SOURCE,
- },
- key=f"{team_id}:{distinct_id}",
- )
+ }
+ kafka_key = f"{team_id}:{source.group_type_index}:{key}"
+ else:
+ data = {
+ "team_id": team_id,
+ "token": token,
+ "kind": "person",
+ "distinct_id": key,
+ "properties": bundle,
+ "event_source": EVENT_SOURCE,
+ }
+ kafka_key = f"{team_id}:{key}"
+ producer.produce(topic=KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES, data=data, key=kafka_key)
produced += 1
return produced
@@ -310,17 +354,21 @@ def _produce_intents(team_id: int, token: str, items: list[tuple[str, dict]]) ->
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.
+ # UPDATE-only on purpose: definitions are created by ingestion's propdef upsert when the $set /
+ # $groupidentify 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)
+ query = PropertyDefinition.objects.filter(team_id=team_id, name__in=property_names)
+ if source.target == _GROUP_TARGET:
+ # Group propdefs are keyed per group type, so the index predicate is mandatory.
+ query = query.filter(type=PropertyDefinition.Type.GROUP, group_type_index=source.group_type_index)
+ else:
+ query = query.filter(type=PropertyDefinition.Type.PERSON)
+ query.update(warehouse_origin=origin)
# --- orchestration -----------------------------------------------------------------------
@@ -331,14 +379,16 @@ async def _process_source_bundles(
team_id: int,
schema_id: str,
team_api_token: str,
+ team_uuid: str,
source: PersonPropertySyncSource,
bundles: list[tuple[str, dict]],
rows_read: int,
run_token: str,
) -> PerSourceResult:
- """Diff one source's bundles against its snapshot, drop non-existing persons, produce $set intents,
- stamp provenance, and advance the snapshot. Shared by the incremental sync and the backfill — they
- differ only in how ``bundles`` are sourced (staged rows vs a full Delta read)."""
+ """Diff one source's bundles against its snapshot, drop entities that don't exist, produce update
+ intents (person `$set` or group `$groupidentify`), stamp provenance, and advance the snapshot.
+ Shared by the incremental sync and the backfill — they differ only in how ``bundles`` are sourced
+ (staged rows vs a full Delta read)."""
ps = PerSourceResult(source_id=str(source.source_id), rows_read=rows_read)
prior = await _read_snapshot_hashes(team_id, schema_id, str(source.source_id))
changed, new_hashes = select_changed(bundles, prior)
@@ -346,23 +396,42 @@ async def _process_source_bundles(
if not changed:
return ps
- existing = await database_sync_to_async(_filter_existing_persons, thread_sensitive=False)(
- team_id, [distinct_id for distinct_id, _ in changed]
+ existing = await database_sync_to_async(_filter_existing_ids, thread_sensitive=False)(
+ team_id, source, [key for key, _ in changed]
)
- to_send = [(distinct_id, bundle) for distinct_id, bundle in changed if distinct_id in existing]
+ to_send = [(key, bundle) for key, bundle in changed if key in existing]
ps.existing = len(to_send)
ps.skipped_missing_person = len(changed) - len(to_send)
if not to_send:
logger.info(
- "person-property sync: no existing persons among changed rows for source",
+ "person-property sync: no existing entities among changed rows for source",
team_id=team_id,
schema_id=schema_id,
source_id=str(source.source_id),
+ target=source.target,
changed=len(changed),
)
return ps
- produced = await asyncio.to_thread(_produce_intents, team_id, team_api_token, to_send)
+ group_type_name = None
+ if source.target == _GROUP_TARGET and source.group_type_index is not None:
+ group_type_name = await database_sync_to_async(_group_type_name, thread_sensitive=False)(
+ team_id, source.group_type_index
+ )
+ if group_type_name is None:
+ # Without the group-type name the consumer can't build a valid $groupidentify and would
+ # DLQ every message — skip the source instead of producing intents doomed to fail.
+ logger.warning(
+ "person-property sync: group type not found, skipping source",
+ team_id=team_id,
+ schema_id=schema_id,
+ source_id=str(source.source_id),
+ group_type_index=source.group_type_index,
+ )
+ return ps
+ produced = await asyncio.to_thread(
+ _produce_intents, team_id, team_api_token, source, to_send, team_uuid=team_uuid, group_type_name=group_type_name
+ )
ps.produced = produced
# Stamp provenance before advancing the snapshot: the snapshot is the checkpoint that makes
@@ -429,6 +498,7 @@ async def run_person_property_sync(*, team_id: int, schema_id: str, job_id: str)
team_id=team_id,
schema_id=str(schema_id),
team_api_token=team.api_token,
+ team_uuid=str(team.uuid),
source=source,
bundles=bundles,
rows_read=len(rows),
@@ -549,6 +619,7 @@ async def run_person_property_backfill(*, team_id: int, schema_id: str, trigger:
team_id=team_id,
schema_id=str(schema_id),
team_api_token=team.api_token,
+ team_uuid=str(team.uuid),
source=source,
bundles=bundles,
rows_read=rows_read,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
index d8aa8f5ac59d..672bf6be96bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
@@ -92,7 +92,7 @@ class TestRunOrchestration:
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}._filter_existing_ids", 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,
@@ -102,7 +102,7 @@ class TestRunOrchestration:
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]
+ produced_items = produce.call_args.args[3]
assert sorted(d for d, _ in produced_items) == ["a", "b"]
assert result.produced == 2
@@ -199,7 +199,7 @@ class TestBackfillOrchestration:
patch(f"{_MODULE}.delta_storage_options", return_value={}),
patch(f"{_MODULE}._read_delta_bundles", return_value=(accumulated, 5)) as read_delta,
patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),
- patch(f"{_MODULE}._filter_existing_persons", return_value={"a"}),
+ patch(f"{_MODULE}._filter_existing_ids", return_value={"a"}),
patch(f"{_MODULE}._produce_intents", return_value=1) as produce,
patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()) as write_snapshot,
patch(f"{_MODULE}._stamp_provenance"),
@@ -310,3 +310,68 @@ class TestSnapshotCompaction:
assert len(keys) == 1
assert hashes == {"a": "h2", "b": "h2"}
+
+
+class TestGroupTarget:
+ """The group branch: a group source produces a $groupidentify-shaped intent and checks group
+ existence, keyed per group type."""
+
+ def _group_source(self):
+ return PersonPropertySyncSource("s1", "d1", "group_key", {"plan": "tier"}, target="group", group_type_index=0)
+
+ def test_produce_intents_group_payload(self):
+ captured: list[dict] = []
+ producer = MagicMock()
+ producer.produce.side_effect = lambda **kw: captured.append(kw)
+ with patch(f"{_MODULE}.producer_scope") as producer_scope:
+ producer_scope.return_value.__enter__.return_value = producer
+ produced = pps._produce_intents(
+ 1,
+ "tok",
+ self._group_source(),
+ [("acme", {"tier": "pro"})],
+ team_uuid="team-uuid",
+ group_type_name="organization",
+ )
+ assert produced == 1
+ data = captured[0]["data"]
+ assert data["kind"] == "group"
+ assert data["group_type"] == "organization"
+ assert data["group_key"] == "acme"
+ assert data["distinct_id"] == "team-uuid" # $groupidentify placeholder
+ assert data["properties"] == {"tier": "pro"}
+ # keyed per (team, group_type_index, group_key) so per-group ordering is preserved
+ assert captured[0]["key"] == "1:0:acme"
+
+ def test_filter_existing_ids_uses_group_lookup(self):
+ group = MagicMock(group_key="acme")
+ with patch(f"{_MODULE}.get_groups_by_identifiers", return_value=[group]) as lookup:
+ result = pps._filter_existing_ids(9, self._group_source(), ["acme", "ghost"])
+ lookup.assert_called_once_with(9, 0, ["acme", "ghost"])
+ assert result == {"acme"} # ghost dropped: no existing group
+
+ @pytest.mark.asyncio
+ async def test_unresolved_group_type_skips_producing(self):
+ # If the group type can't be resolved (deleted/misconfigured), the consumer would DLQ every
+ # $groupidentify missing a group_type — so the source must be skipped, not produced.
+ team = MagicMock(api_token="tok", uuid="team-uuid")
+ rows = [{"group_key": "acme", "plan": "pro"}]
+ with (
+ patch(f"{_MODULE}.person_property_sync_sources_for", return_value=[self._group_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_ids", return_value={"acme"}),
+ patch(f"{_MODULE}._group_type_name", return_value=None),
+ patch(f"{_MODULE}._produce_intents", return_value=1) as produce,
+ patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()) as write_snapshot,
+ patch(f"{_MODULE}._stamp_provenance") as stamp,
+ patch(f"{_MODULE}._clear_staged", new=AsyncMock()),
+ ):
+ 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")
+
+ produce.assert_not_called()
+ stamp.assert_not_called()
+ write_snapshot.assert_not_awaited()
+ assert result.produced == 0
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 68f01aa6504e..c8fd8405f6f5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16449,13 +16449,15 @@ export namespace Schemas {
/**
* * `account` - account
* * `person` - person
+ * * `group` - group
*/
- export type CustomPropertyDefinitionTargetType = typeof CustomPropertyDefinitionTargetType[keyof typeof CustomPropertyDefinitionTargetType];
+ export type CustomPropertyDefinitionTargetTypeEnum = typeof CustomPropertyDefinitionTargetTypeEnum[keyof typeof CustomPropertyDefinitionTargetTypeEnum];
- export const CustomPropertyDefinitionTargetType = {
+ export const CustomPropertyDefinitionTargetTypeEnum = {
Account: 'account',
Person: 'person',
+ Group: 'group',
} as const;
/**
@@ -16661,11 +16663,19 @@ 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).
+ /** What entity this property is attached to: 'account' (default), 'person', or 'group'. Person and group properties are populated from a warehouse schema and become usable like any other person/group property (feature flags, cohorts, insights).
*
* * `account` - account
- * * `person` - person */
- target_type?: CustomPropertyDefinitionTargetType;
+ * * `person` - person
+ * * `group` - group */
+ target_type?: CustomPropertyDefinitionTargetTypeEnum;
+ /**
+ * For 'group' targets only: which group type (0-4) the property attaches to. Required when target_type is 'group'; must be omitted otherwise. Create-only.
+ * @minimum 0
+ * @maximum 4
+ * @nullable
+ */
+ group_type_index?: number | null;
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean;
/**
@@ -47091,11 +47101,19 @@ 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).
+ /** What entity this property is attached to: 'account' (default), 'person', or 'group'. Person and group properties are populated from a warehouse schema and become usable like any other person/group property (feature flags, cohorts, insights).
*
* * `account` - account
- * * `person` - person */
- target_type?: CustomPropertyDefinitionTargetType;
+ * * `person` - person
+ * * `group` - group */
+ target_type?: CustomPropertyDefinitionTargetTypeEnum;
+ /**
+ * For 'group' targets only: which group type (0-4) the property attaches to. Required when target_type is 'group'; must be omitted otherwise. Create-only.
+ * @minimum 0
+ * @maximum 4
+ * @nullable
+ */
+ group_type_index?: number | null;
/** 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 eda8b6dc39b2..1ca0e36b2d12 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -434,6 +434,9 @@ export const CustomPropertyDefinitionsCreateParams = /* @__PURE__ */ zod.object(
export const customPropertyDefinitionsCreateBodyNameMax = 400
export const customPropertyDefinitionsCreateBodyTargetTypeDefault = `account`
+export const customPropertyDefinitionsCreateBodyGroupTypeIndexMin = 0
+export const customPropertyDefinitionsCreateBodyGroupTypeIndexMax = 4
+
export const customPropertyDefinitionsCreateBodyIsBigNumberDefault = false
export const customPropertyDefinitionsCreateBodyOptionsItemLabelMax = 400
@@ -453,11 +456,19 @@ export const CustomPropertyDefinitionsCreateBody = /* @__PURE__ */ zod
"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')
+ .enum(['account', 'person', 'group'])
+ .describe('* `account` - account\n* `person` - person\n* `group` - group')
.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"
+ "What entity this property is attached to: 'account' (default), 'person', or 'group'. Person and group properties are populated from a warehouse schema and become usable like any other person/group property (feature flags, cohorts, insights).\n\n* `account` - account\n* `person` - person\n* `group` - group"
+ ),
+ group_type_index: zod
+ .number()
+ .min(customPropertyDefinitionsCreateBodyGroupTypeIndexMin)
+ .max(customPropertyDefinitionsCreateBodyGroupTypeIndexMax)
+ .nullish()
+ .describe(
+ "For 'group' targets only: which group type (0-4) the property attaches to. Required when target_type is 'group'; must be omitted otherwise. Create-only."
),
is_big_number: zod
.boolean()
@@ -528,6 +539,9 @@ export const CustomPropertyDefinitionsPartialUpdateParams = /* @__PURE__ */ zod.
export const customPropertyDefinitionsPartialUpdateBodyNameMax = 400
+export const customPropertyDefinitionsPartialUpdateBodyGroupTypeIndexMin = 0
+export const customPropertyDefinitionsPartialUpdateBodyGroupTypeIndexMax = 4
+
export const customPropertyDefinitionsPartialUpdateBodyOptionsItemLabelMax = 400
export const CustomPropertyDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
@@ -548,11 +562,19 @@ export const CustomPropertyDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
"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')
+ .enum(['account', 'person', 'group'])
+ .describe('* `account` - account\n* `person` - person\n* `group` - group')
.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"
+ "What entity this property is attached to: 'account' (default), 'person', or 'group'. Person and group properties are populated from a warehouse schema and become usable like any other person/group property (feature flags, cohorts, insights).\n\n* `account` - account\n* `person` - person\n* `group` - group"
+ ),
+ group_type_index: zod
+ .number()
+ .min(customPropertyDefinitionsPartialUpdateBodyGroupTypeIndexMin)
+ .max(customPropertyDefinitionsPartialUpdateBodyGroupTypeIndexMax)
+ .nullish()
+ .describe(
+ "For 'group' targets only: which group type (0-4) the property attaches to. Required when target_type is 'group'; must be omitted otherwise. Create-only."
),
is_big_number: zod
.boolean()
diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.ts
index 96fc6c3b7c15..f0de9e101c00 100644
--- a/services/mcp/src/tools/generated/customer_analytics.ts
+++ b/services/mcp/src/tools/generated/customer_analytics.ts
@@ -536,6 +536,9 @@ const customPropertyDefinitionsCreate = (): ToolBase<
if (params.target_type !== undefined) {
body['target_type'] = params.target_type
}
+ if (params.group_type_index !== undefined) {
+ body['group_type_index'] = params.group_type_index
+ }
if (params.is_big_number !== undefined) {
body['is_big_number'] = params.is_big_number
}
@@ -613,6 +616,9 @@ const customPropertyDefinitionsPartialUpdate = (): ToolBase<
if (params.target_type !== undefined) {
body['target_type'] = params.target_type
}
+ if (params.group_type_index !== undefined) {
+ body['group_type_index'] = params.group_type_index
+ }
if (params.is_big_number !== undefined) {
body['is_big_number'] = params.is_big_number
}