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.

fix(taxonomy): key group upserts and property cleanup on the project (#112915)

Eli Reisman26126e16d62a
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.py
index 41b68aa3fd6d..10d51b83ea23 100644
--- a/ee/clickhouse/views/groups.py
+++ b/ee/clickhouse/views/groups.py
@@ -49,7 +49,7 @@ from posthog.ph_client import feature_enabled_or_false
from posthog.utils import str_to_bool
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
-from products.event_definitions.backend.models.property_definition import PropertyType
+from products.event_definitions.backend.models import PropertyType, effective_project_id_expr, group_type_index_key_expr
from products.notebooks.backend.facade import api as notebooks
from products.notebooks.backend.facade.content import (
build_markdown_notebook_content,
@@ -103,20 +103,32 @@ def detect_group_property_type(value):
return PropertyType.String
-def create_property_definition(team_id: int, group_type_index: int, property_name: str, property_value):
+def create_property_definition(
+ team_id: int, project_id: int, group_type_index: int, property_name: str, property_value
+):
"""Create or update PostgreSQL PropertyDefinition for group property"""
property_type = detect_group_property_type(property_value)
is_numerical = property_type == PropertyType.Numeric
- PropertyDefinition.objects.update_or_create(
- team_id=team_id,
+ # Match on the key of posthog_propdef_proj_uniq. Then the lookup is a single index seek, and it finds a
+ # definition that another environment of the project created, so the insert cannot violate that constraint.
+ PropertyDefinition.objects.alias(
+ effective_project_id=effective_project_id_expr(),
+ group_type_index_key=group_type_index_key_expr(),
+ ).filter(effective_project_id=project_id, group_type_index_key=group_type_index).update_or_create(
name=property_name,
type=PropertyDefinition.Type.GROUP,
- group_type_index=group_type_index,
defaults={
"property_type": property_type.value,
"is_numerical": is_numerical,
},
+ create_defaults={
+ "team_id": team_id,
+ "project_id": project_id,
+ "group_type_index": group_type_index,
+ "property_type": property_type.value,
+ "is_numerical": is_numerical,
+ },
)
@@ -523,6 +535,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
for prop_name, prop_value in group.group_properties.items():
create_property_definition(
team_id=self.team.pk,
+ project_id=self.team.project_id,
group_type_index=group.group_type_index,
property_name=prop_name,
property_value=prop_value,
@@ -641,6 +654,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
create_property_definition(
team_id=self.team.pk,
+ project_id=self.team.project_id,
group_type_index=group.group_type_index,
property_name=property_key,
property_value=property_value,
diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.py
index ae5daa3b76db..7cf93d596f85 100644
--- a/ee/clickhouse/views/test/test_clickhouse_groups.py
+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py
@@ -784,6 +784,45 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["before"], "finance")
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["after"], "technology")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ def test_group_property_update_reuses_definition_from_another_environment(self, mock_capture):
+ group_type_mapping = create_group_type_mapping_without_created_at(
+ team=self.team,
+ project_id=self.team.project_id,
+ group_type_index=0,
+ group_type="organization",
+ )
+ create_group(
+ team_id=self.team.pk,
+ group_type_index=typed_group_type_index(group_type_mapping.group_type_index),
+ group_key="org:5",
+ properties={"industry": "finance"},
+ )
+ sibling_team = Team.objects.create(organization=self.organization, project=self.team.project)
+ existing = PropertyDefinition.objects.create(
+ team=sibling_team,
+ project=self.team.project,
+ name="industry",
+ type=PropertyDefinition.Type.GROUP,
+ group_type_index=0,
+ property_type="Numeric",
+ is_numerical=True,
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/groups/update_property?group_key=org:5&group_type_index=0",
+ {"key": "industry", "value": "technology"},
+ )
+
+ self.assertEqual(response.status_code, 200)
+ definitions = PropertyDefinition.objects.filter(
+ project=self.team.project, name="industry", type=PropertyDefinition.Type.GROUP
+ )
+ self.assertEqual(
+ [(d.pk, d.team_id, d.group_type_index, d.property_type, d.is_numerical) for d in definitions],
+ [(existing.pk, sibling_team.pk, 0, "String", False)],
+ )
+
@time_machine.travel("2021-05-02", tick=False)
def test_group_property_crud_update_missing_key(self):
group_type_mapping = create_group_type_mapping_without_created_at(
diff --git a/posthog/temporal/cleanup_property_definitions/activities.py b/posthog/temporal/cleanup_property_definitions/activities.py
index 07463f516c6f..8d2af4ec70f2 100644
--- a/posthog/temporal/cleanup_property_definitions/activities.py
+++ b/posthog/temporal/cleanup_property_definitions/activities.py
@@ -2,6 +2,7 @@ from uuid import uuid4
from django.conf import settings
from django.db import transaction
+from django.db.models import F, QuerySet
from structlog.contextvars import bind_contextvars
from temporalio import activity
@@ -17,11 +18,42 @@ from posthog.temporal.cleanup_property_definitions.types import (
from posthog.temporal.common.clickhouse import get_client
from posthog.temporal.common.logger import get_write_only_logger
+from products.event_definitions.backend.models import effective_project_id_expr, group_type_index_key_expr
from products.event_definitions.backend.models.event_property import EventProperty
LOGGER = get_write_only_logger()
+def _project_id_for_team(team_id: int) -> int:
+ project_id = Team.objects.filter(id=team_id).values_list("project_id", flat=True).first()
+ if project_id is None:
+ raise CleanupPropertyDefinitionsError(f"Team {team_id} not found")
+ return project_id
+
+
+def _project_definitions(project_id: int, property_type: int) -> QuerySet[PropertyDefinition]:
+ return PropertyDefinition.objects.alias(
+ effective_project_id=effective_project_id_expr(),
+ group_type_index_key=group_type_index_key_expr(),
+ ).filter(effective_project_id=project_id, type=property_type)
+
+
+def _definitions_matching(project_id: int, property_type: int, pattern: str) -> QuerySet[PropertyDefinition]:
+ # The order is the key of index_property_def_query_proj, so Postgres reads that index in order and stops at
+ # the slice limit. Without an order, Postgres plans a Seq Scan of the whole table for the largest projects.
+ return (
+ _project_definitions(project_id, property_type)
+ .filter(name__regex=pattern)
+ .order_by(
+ "effective_project_id",
+ "type",
+ "group_type_index_key",
+ F("query_usage_30_day").desc(nulls_last=True),
+ "name",
+ )
+ )
+
+
@activity.defn(name="delete-property-definitions-from-postgres")
async def delete_property_definitions_from_postgres(
input: DeletePostgresPropertyDefinitionsInput,
@@ -39,26 +71,21 @@ async def delete_property_definitions_from_postgres(
@database_sync_to_async
def delete_batch() -> dict:
- if not Team.objects.filter(id=input.team_id).exists():
- raise CleanupPropertyDefinitionsError(f"Team {input.team_id} not found")
+ project_id = _project_id_for_team(input.team_id)
# Select a batch of matching property names to coordinate deletes across tables
batch_names = list(
- PropertyDefinition.objects.filter(
- team_id=input.team_id,
- type=input.property_type,
- name__regex=input.pattern,
- ).values_list("name", flat=True)[: input.batch_size]
+ _definitions_matching(project_id, input.property_type, input.pattern).values_list("name", flat=True)[
+ : input.batch_size
+ ]
)
if not batch_names:
return {"property_definitions_deleted": 0, "event_properties_deleted": 0}
with transaction.atomic():
- property_definitions_deleted, _ = PropertyDefinition.objects.filter(
- team_id=input.team_id,
- type=input.property_type,
- name__in=batch_names,
- ).delete()
+ property_definitions_deleted, _ = (
+ _project_definitions(project_id, input.property_type).filter(name__in=batch_names).delete()
+ )
event_properties_deleted, _ = EventProperty.objects.filter(
team_id=input.team_id,
@@ -127,14 +154,9 @@ async def preview_property_definitions(input: PreviewPropertyDefinitionsInput) -
@database_sync_to_async
def get_matching_definitions() -> dict:
- if not Team.objects.filter(id=input.team_id).exists():
- raise CleanupPropertyDefinitionsError(f"Team {input.team_id} not found")
+ project_id = _project_id_for_team(input.team_id)
- queryset = PropertyDefinition.objects.filter(
- team_id=input.team_id,
- type=input.property_type,
- name__regex=input.pattern,
- )
+ queryset = _definitions_matching(project_id, input.property_type, input.pattern)
total_count = queryset.count()
names = list(queryset.values_list("name", flat=True)[: input.limit])
return {"total_count": total_count, "names": names, "truncated": total_count > input.limit}
diff --git a/posthog/temporal/tests/cleanup_property_definitions/test_activities.py b/posthog/temporal/tests/cleanup_property_definitions/test_activities.py
index 7689c52a7ca7..c7a5fd5917a8 100644
--- a/posthog/temporal/tests/cleanup_property_definitions/test_activities.py
+++ b/posthog/temporal/tests/cleanup_property_definitions/test_activities.py
@@ -5,7 +5,7 @@ import pytest
from asgiref.sync import sync_to_async
from parameterized import parameterized_class
-from posthog.models import PropertyDefinition
+from posthog.models import Project, PropertyDefinition, Team
from posthog.temporal.cleanup_property_definitions.activities import (
delete_property_definitions_from_clickhouse,
delete_property_definitions_from_postgres,
@@ -24,12 +24,14 @@ from posthog.temporal.tests.cleanup_property_definitions.conftest import (
from products.event_definitions.backend.models.event_property import EventProperty
-def create_property_definition(team, name: str, property_type: int) -> PropertyDefinition:
+def create_property_definition(
+ team, name: str, property_type: int, project: Project | None = None
+) -> PropertyDefinition:
"""Create a PropertyDefinition with the correct fields for the given type.
GROUP type requires group_type_index to be set due to database constraint.
"""
- kwargs = {"team": team, "name": name, "type": property_type}
+ kwargs = {"team": team, "name": name, "type": property_type, "project": project}
if property_type == PropertyDefinition.Type.GROUP:
kwargs["group_type_index"] = 0
return PropertyDefinition.objects.create(**kwargs)
@@ -214,6 +216,37 @@ class TestDeletePropertyDefinitionsFromPostgres:
await cleanup()
+ @pytest.mark.asyncio
+ async def test_deletes_definition_another_environment_of_the_project_recorded(self, organization):
+ prop_name = f"{self.prefix}_sibling_prop"
+
+ @sync_to_async
+ def create_sibling_definition():
+ sibling_team = Team.objects.create(organization=organization, project=self.team.project, name="Sibling")
+ create_property_definition(sibling_team, prop_name, self.property_type, project=self.team.project)
+ return sibling_team
+
+ sibling_team = await create_sibling_definition()
+
+ result = await self.activity_environment.run(
+ delete_property_definitions_from_postgres,
+ DeletePostgresPropertyDefinitionsInput(
+ team_id=self.team.id,
+ pattern=f"^{self.prefix}_.*",
+ property_type=self.property_type,
+ ),
+ )
+
+ @sync_to_async
+ def sibling_definition_exists_then_cleanup():
+ exists = PropertyDefinition.objects.filter(team=sibling_team, name=prop_name).exists()
+ sibling_team.delete()
+ return exists
+
+ sibling_definition_exists = await sibling_definition_exists_then_cleanup()
+ assert result["property_definitions_deleted"] == 1
+ assert not sibling_definition_exists
+
@pytest.mark.asyncio
async def test_deletes_in_batches(self):
prop_names = [f"{self.prefix}_batch_prop_{i}" for i in range(5)]
diff --git a/products/event_definitions/backend/models/__init__.py b/products/event_definitions/backend/models/__init__.py
index 2d8a575cd55f..673a82561809 100644
--- a/products/event_definitions/backend/models/__init__.py
+++ b/products/event_definitions/backend/models/__init__.py
@@ -7,6 +7,7 @@ from .property_definition import (
PropertyFormat,
PropertyType,
effective_project_id_expr,
+ group_type_index_key_expr,
)
from .schema import EventSchema, SchemaPropertyGroup, SchemaPropertyGroupProperty, SchemaPropertyType
@@ -24,4 +25,5 @@ __all__ = [
"PROPERTY_DEFINITIONS_TABLE_SQL",
"DROP_PROPERTY_DEFINITIONS_TABLE_SQL",
"effective_project_id_expr",
+ "group_type_index_key_expr",
]
diff --git a/products/event_definitions/backend/models/property_definition.py b/products/event_definitions/backend/models/property_definition.py
index 845e5eaccc4e..67f08c6f6252 100644
--- a/products/event_definitions/backend/models/property_definition.py
+++ b/products/event_definitions/backend/models/property_definition.py
@@ -36,6 +36,15 @@ def effective_project_id_expr() -> Coalesce:
return Coalesce(F("project_id"), F("team_id"), output_field=models.BigIntegerField())
+def group_type_index_key_expr() -> Coalesce:
+ """
+ `group_type_index` as `posthog_propdef_proj_uniq` and `index_property_def_query_proj` store it, with -1 for no group.
+
+ A filter or an ordering must use this exact expression, or Postgres cannot use those index columns for it.
+ """
+ return Coalesce(F("group_type_index"), -1, output_field=models.IntegerField())
+
+
class PropertyFormat(models.TextChoices):
UnixTimestamp = "unix_timestamp", "Unix Timestamp in seconds"
UnixTimestampMilliseconds = (