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(django): migrate group/gtm orm writes to personhog (#57347)

Nick Bestc817793cb06c
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.py
index 11399aa9b578..80da628f76d8 100644
--- a/ee/clickhouse/views/groups.py
+++ b/ee/clickhouse/views/groups.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import Optional, cast
+from typing import Any, Optional, cast
from django.db import IntegrityError, transaction
from django.db.models import Q
@@ -33,11 +33,13 @@ from posthog.models.activity_logging.activity_log import Change, Detail, load_ac
from posthog.models.activity_logging.activity_page import activity_page_response
from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.group import Group
-from posthog.models.group.util import create_group, raw_create_group_ch
+from posthog.models.group.util import create_group, raw_create_group_ch, save_group
from posthog.models.group_type_mapping import (
GROUP_TYPE_MAPPING_SERIALIZER_FIELDS,
GroupTypeMapping,
+ delete_group_type_mapping,
invalidate_group_types_cache,
+ update_group_type_mapping_fields,
)
from posthog.models.user import User
from posthog.personhog_client.converters import GroupTypeMappingResult
@@ -121,7 +123,13 @@ class GroupsTypesViewSet(
instance.team = self.team
serializer = self.get_serializer(instance, data=row)
serializer.is_valid(raise_exception=True)
- serializer.save()
+ fields: dict[str, Any] = {}
+ if "name_singular" in serializer.validated_data:
+ fields["name_singular"] = serializer.validated_data["name_singular"]
+ if "name_plural" in serializer.validated_data:
+ fields["name_plural"] = serializer.validated_data["name_plural"]
+ if fields:
+ update_group_type_mapping_fields(instance, fields=fields, operation="group_type_update_metadata")
invalidate_group_types_cache(self.team.project_id)
return self.list(request, *args, **kwargs)
@@ -142,13 +150,17 @@ class GroupsTypesViewSet(
)
dashboard = create_group_type_mapping_detail_dashboard(group_type_mapping, request.user)
+ update_group_type_mapping_fields(
+ group_type_mapping,
+ fields={"detail_dashboard_id": dashboard.id},
+ operation="group_type_create_detail_dashboard",
+ )
group_type_mapping.detail_dashboard_id = dashboard.id
- group_type_mapping.save()
invalidate_group_types_cache(self.team.project_id)
return response.Response(self.get_serializer(group_type_mapping).data)
def perform_destroy(self, instance):
- super().perform_destroy(instance)
+ delete_group_type_mapping(instance)
invalidate_group_types_cache(self.team.project_id)
@action(methods=["PUT"], detail=False)
@@ -160,8 +172,12 @@ class GroupsTypesViewSet(
except GroupTypeMapping.DoesNotExist:
raise NotFound(detail="Group type not found")
+ update_group_type_mapping_fields(
+ group_type_mapping,
+ fields={"default_columns": request.data["default_columns"]},
+ operation="group_type_set_default_columns",
+ )
group_type_mapping.default_columns = request.data["default_columns"]
- group_type_mapping.save()
invalidate_group_types_cache(self.team.project_id)
return response.Response(self.get_serializer(group_type_mapping).data)
@@ -454,7 +470,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
create_or_update = "update" if property_key in group.group_properties else "create"
original_value = group.group_properties.get(property_key, None)
group.group_properties[property_key] = property_value
- group.save()
+ save_group(group, operation="group_update_property")
create_property_definition(
team_id=self.team.pk,
@@ -537,7 +553,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
group_type_mapping = self.get_group_type_mapping_or_404(cast(GroupTypeIndex, group.group_type_index))
original_value = group.group_properties[property_key]
del group.group_properties[property_key]
- group.save()
+ save_group(group, operation="group_delete_property")
# Need to update ClickHouse too
timestamp = timezone.now()
diff --git a/posthog/models/group/test_util.py b/posthog/models/group/test_util.py
index 348de9bd5b40..435ed610c8e9 100644
--- a/posthog/models/group/test_util.py
+++ b/posthog/models/group/test_util.py
@@ -7,7 +7,14 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from posthog.models.group.util import get_group_by_key, get_groups_by_identifiers, get_groups_by_type_indices
+from posthog.models.filters.utils import GroupTypeIndex
+from posthog.models.group.util import (
+ create_group,
+ get_group_by_key,
+ get_groups_by_identifiers,
+ get_groups_by_type_indices,
+ save_group,
+)
# Patched at source because util.py uses lazy `from X import Y` inside each function body —
# there is no module-level binding on util to patch. If these move to top-level imports, patch at call site instead.
@@ -611,3 +618,200 @@ class TestOrmDatabaseErrorHandling(SimpleTestCase):
result = get_groups_by_type_indices(10, {0, 1}, {"k1", "k2"})
assert result == []
+
+
+class TestCreateGroup(SimpleTestCase):
+ def setUp(self):
+ self.team_id = 10
+ self.group_type_index: GroupTypeIndex = 0
+ self.group_key = "org:123"
+ self.properties = {"name": "Acme"}
+
+ @patch("posthog.models.group.util.raw_create_group_ch")
+ @patch(_ROUTING_TOTAL_PATCH)
+ @patch(_CONVERTER_PATCH)
+ @patch(_CLIENT_PATCH)
+ def test_personhog_success_returns_converted_model(
+ self, mock_get_client, mock_convert, mock_routing_counter, mock_ch
+ ):
+ proto_group = _make_proto_group(id=42, team_id=self.team_id, group_key=self.group_key)
+ mock_response = MagicMock()
+ mock_response.group = proto_group
+ mock_client = MagicMock()
+ mock_client.create_group.return_value = mock_response
+ mock_get_client.return_value = mock_client
+
+ fake_model = MagicMock()
+ mock_convert.return_value = fake_model
+
+ result = create_group(
+ team_id=self.team_id,
+ group_type_index=self.group_type_index,
+ group_key=self.group_key,
+ properties=self.properties,
+ )
+
+ assert result is fake_model
+ mock_client.create_group.assert_called_once()
+ req = mock_client.create_group.call_args[0][0]
+ assert req.team_id == self.team_id
+ assert req.group_type_index == self.group_type_index
+ assert req.group_key == self.group_key
+ assert b'"name": "Acme"' in req.group_properties
+ mock_routing_counter.labels.assert_called_with(
+ operation="create_group", source="personhog", client_name="posthog-django"
+ )
+ mock_ch.assert_called_once()
+
+ @patch("posthog.models.group.util.raw_create_group_ch")
+ @patch(_ROUTING_TOTAL_PATCH)
+ @patch(_CLIENT_PATCH)
+ def test_personhog_client_none_falls_back_to_orm(self, mock_get_client, mock_routing_counter, mock_ch):
+ mock_get_client.return_value = None
+
+ from posthog.models.group.group import Group
+
+ with patch.object(Group, "objects") as mock_objects:
+ mock_group = MagicMock(spec=Group)
+ mock_objects.create.return_value = mock_group
+
+ result = create_group(
+ team_id=self.team_id,
+ group_type_index=self.group_type_index,
+ group_key=self.group_key,
+ properties=self.properties,
+ )
+
+ assert result is mock_group
+ mock_objects.create.assert_called_once()
+ mock_routing_counter.labels.assert_called_with(
+ operation="create_group", source="django_orm", client_name="posthog-django"
+ )
+
+ @parameterized.expand(
+ [
+ ("grpc_timeout", RuntimeError("grpc timeout")),
+ ("connection_error", ConnectionError("connection refused")),
+ ]
+ )
+ @patch("posthog.models.group.util.raw_create_group_ch")
+ @patch(_ROUTING_ERRORS_PATCH)
+ @patch(_ROUTING_TOTAL_PATCH)
+ @patch(_CLIENT_PATCH)
+ def test_personhog_exception_falls_back_to_orm(
+ self, _name, exception, mock_get_client, mock_routing_counter, mock_errors_counter, mock_ch
+ ):
+ mock_client = MagicMock()
+ mock_client.create_group.side_effect = exception
+ mock_get_client.return_value = mock_client
+
+ from posthog.models.group.group import Group
+
+ with patch.object(Group, "objects") as mock_objects:
+ mock_group = MagicMock(spec=Group)
+ mock_objects.create.return_value = mock_group
+
+ result = create_group(
+ team_id=self.team_id,
+ group_type_index=self.group_type_index,
+ group_key=self.group_key,
+ properties=self.properties,
+ )
+
+ assert result is mock_group
+ mock_errors_counter.labels.assert_called_once_with(
+ operation="create_group",
+ source="personhog",
+ error_type="grpc_error",
+ client_name="posthog-django",
+ )
+
+ @patch("posthog.models.group.util.raw_create_group_ch")
+ @patch(_ROUTING_TOTAL_PATCH)
+ @patch(_CLIENT_PATCH)
+ def test_clickhouse_write_always_happens(self, mock_get_client, mock_routing_counter, mock_ch):
+ mock_get_client.return_value = None
+
+ from posthog.models.group.group import Group
+
+ with patch.object(Group, "objects") as mock_objects:
+ mock_objects.create.return_value = MagicMock(spec=Group)
+ create_group(
+ team_id=self.team_id,
+ group_type_index=self.group_type_index,
+ group_key=self.group_key,
+ properties=self.properties,
+ )
+ mock_ch.assert_called_once()
+
+
+class TestSaveGroup(SimpleTestCase):
+ def _make_group_instance(self):
+ mock_group = MagicMock()
+ mock_group.team_id = 10
+ mock_group.group_type_index = 0
+ mock_group.group_key = "org:123"
+ mock_group.group_properties = {"name": "Acme"}
+ return mock_group
+
+ @patch(_ROUTING_TOTAL_PATCH)
+ @patch(_CLIENT_PATCH)
+ def test_personhog_success_does_not_call_orm_save(self, mock_get_client, mock_routing_counter):
+ mock_client = MagicMock()
+ mock_client.update_group.return_value = MagicMock()
+ mock_get_client.return_value = mock_client
+
+ group = self._make_group_instance()
+ save_group(group)
+
+ mock_client.update_group.assert_called_once()
+ req = mock_client.update_group.call_args[0][0]
+ assert req.team_id == 10
+ assert req.group_type_index == 0
+ assert req.group_key == "org:123"
+ assert req.update_mask == ["group_properties"]
+ assert b'"name": "Acme"' in req.group_properties
+ group.save.assert_not_called()
+ mock_routing_counter.labels.assert_called_with(
+ operation="group_save", source="personhog", client_name="posthog-django"
+ )
+
+ @patch(_ROUTING_TOTAL_PATCH)
+ @patch(_CLIENT_PATCH)
+ def test_client_none_falls_back_to_orm_save(self, mock_get_client, mock_routing_counter):
+ mock_get_client.return_value = None
+
+ group = self._make_group_instance()
+ save_group(group)
+
+ group.save.assert_called_once()
+ mock_routing_counter.labels.assert_called_with(
+ operation="group_save", source="django_orm", client_name="posthog-django"
+ )
+
+ @parameterized.expand(
+ [
+ ("grpc_timeout", RuntimeError("grpc timeout")),
+ ("connection_error", ConnectionError("connection refused")),
+ ]
+ )
+ @patch(_ROUTING_ERRORS_PATCH)
+ @patch(_ROUTING_TOTAL_PATCH)
+ @patch(_CLIENT_PATCH)
+ def test_personhog_exception_falls_back_to_orm_save(
+ self, _name, exception, mock_get_client, mock_routing_counter, mock_errors_counter
+ ):
+ mock_client = MagicMock()
+ mock_client.update_group.side_effect = exception
+ mock_get_client.return_value = mock_client
+
+ group = self._make_group_instance()
+ save_group(group)
+
+ group.save.assert_called_once()
+ mock_errors_counter.labels.assert_called_once_with(
+ operation="group_save",
+ source="personhog",
+ error_type="grpc_error",
+ client_name="posthog-django",
+ )
diff --git a/posthog/models/group/util.py b/posthog/models/group/util.py
index 407a278668e7..f8bd6cf3e5e8 100644
--- a/posthog/models/group/util.py
+++ b/posthog/models/group/util.py
@@ -72,6 +72,43 @@ def create_group(
timestamp,
timestamp=timestamp,
)
+
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.converters import proto_group_to_model
+ from posthog.personhog_client.proto import CreateGroupRequest
+
+ client = get_personhog_client()
+ if client is not None:
+ try:
+ resp = client.create_group(
+ CreateGroupRequest(
+ team_id=team_id,
+ group_type_index=group_type_index,
+ group_key=group_key,
+ group_properties=json.dumps(properties).encode(),
+ created_at=int(timestamp.timestamp() * 1000),
+ )
+ )
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="create_group", source="personhog", client_name=get_client_name()
+ ).inc()
+ return proto_group_to_model(resp.group)
+ except Exception:
+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
+ operation="create_group",
+ source="personhog",
+ error_type="grpc_error",
+ client_name=get_client_name(),
+ ).inc()
+ logger.warning(
+ "personhog_create_group_failure",
+ team_id=team_id,
+ group_type_index=group_type_index,
+ group_key=group_key,
+ exc_info=True,
+ )
+
+ PERSONHOG_ROUTING_TOTAL.labels(operation="create_group", source="django_orm", client_name=get_client_name()).inc()
group = Group.objects.create( # nosemgrep: no-direct-persons-db-orm
team_id=team_id,
group_type_index=group_type_index,
@@ -83,6 +120,49 @@ def create_group(
return group
+def save_group(group: Group, *, operation: str = "group_save") -> None:
+ """Save a Group's group_properties via personhog, falling back to ORM.
+
+ Only group_properties is synced on the personhog path. The ORM fallback
+ calls group.save() which persists all fields, but once the fallback is
+ removed this will only write group_properties.
+ """
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.proto import UpdateGroupRequest
+
+ client = get_personhog_client()
+ if client is not None:
+ try:
+ client.update_group(
+ UpdateGroupRequest(
+ team_id=group.team_id,
+ group_type_index=group.group_type_index,
+ group_key=group.group_key,
+ update_mask=["group_properties"],
+ group_properties=json.dumps(group.group_properties).encode(),
+ )
+ )
+ PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="personhog", client_name=get_client_name()).inc()
+ return
+ except Exception:
+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
+ operation=operation,
+ source="personhog",
+ error_type="grpc_error",
+ client_name=get_client_name(),
+ ).inc()
+ logger.warning(
+ "personhog_save_group_failure",
+ team_id=group.team_id,
+ group_type_index=group.group_type_index,
+ group_key=group.group_key,
+ exc_info=True,
+ )
+
+ PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="django_orm", client_name=get_client_name()).inc()
+ group.save()
+
+
def get_group_by_key(team_id: int, group_type_index: int, group_key: str) -> Group | None:
"""Fetch a single Group via personhog, falling back to ORM on error."""
from posthog.personhog_client.client import get_personhog_client
diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.py
index d133c856045f..243edc9b72e9 100644
--- a/posthog/models/group_type_mapping.py
+++ b/posthog/models/group_type_mapping.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import json
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
@@ -299,3 +300,155 @@ def get_group_types_for_projects(project_ids: list[int]) -> dict[int, list[dict[
except DatabaseError:
logger.warning("persons_db_group_types_for_projects_failure", project_ids=project_ids, exc_info=True)
return result
+
+
+def update_group_type_mapping_fields(
+ instance: GroupTypeMapping,
+ *,
+ fields: dict[str, Any],
+ operation: str = "group_type_update",
+) -> None:
+ """Update specific fields on a GroupTypeMapping via personhog, falling back to ORM.
+
+ `fields` maps model field names to values — e.g. {"name_singular": "Org", "name_plural": "Orgs"}.
+ For `detail_dashboard_id`, pass None to clear or an int to set.
+ For `default_columns`, pass a list[str] or None.
+ """
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.proto import UpdateGroupTypeMappingRequest
+
+ client = get_personhog_client()
+ if client is not None:
+ try:
+ update_mask: list[str] = list(fields.keys())
+ kwargs: dict[str, Any] = {
+ "project_id": instance.project_id,
+ "group_type_index": instance.group_type_index,
+ "update_mask": update_mask,
+ }
+ if "name_singular" in fields:
+ kwargs["name_singular"] = fields["name_singular"] or ""
+ if "name_plural" in fields:
+ kwargs["name_plural"] = fields["name_plural"] or ""
+ if "detail_dashboard_id" in fields:
+ if fields["detail_dashboard_id"] is not None:
+ kwargs["detail_dashboard_id"] = fields["detail_dashboard_id"]
+ if "default_columns" in fields:
+ if fields["default_columns"] is not None:
+ kwargs["default_columns"] = json.dumps(fields["default_columns"]).encode()
+
+ client.update_group_type_mapping(UpdateGroupTypeMappingRequest(**kwargs))
+ PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="personhog", client_name=get_client_name()).inc()
+ return
+ except Exception:
+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
+ operation=operation,
+ source="personhog",
+ error_type="grpc_error",
+ client_name=get_client_name(),
+ ).inc()
+ logger.warning(
+ "personhog_update_group_type_mapping_failure",
+ project_id=instance.project_id,
+ group_type_index=instance.group_type_index,
+ exc_info=True,
+ )
+
+ PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="django_orm", client_name=get_client_name()).inc()
+ for field_name, value in fields.items():
+ setattr(instance, field_name, value)
+ instance.save()
+
+
+def delete_group_type_mapping(instance: GroupTypeMapping) -> None:
+ """Delete a GroupTypeMapping via personhog, falling back to ORM."""
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.proto import DeleteGroupTypeMappingRequest
+
+ client = get_personhog_client()
+ if client is not None:
+ try:
+ client.delete_group_type_mapping(
+ DeleteGroupTypeMappingRequest(
+ project_id=instance.project_id,
+ group_type_index=instance.group_type_index,
+ )
+ )
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="delete_group_type_mapping", source="personhog", client_name=get_client_name()
+ ).inc()
+ return
+ except Exception:
+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
+ operation="delete_group_type_mapping",
+ source="personhog",
+ error_type="grpc_error",
+ client_name=get_client_name(),
+ ).inc()
+ logger.warning(
+ "personhog_delete_group_type_mapping_failure",
+ project_id=instance.project_id,
+ group_type_index=instance.group_type_index,
+ exc_info=True,
+ )
+
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="delete_group_type_mapping", source="django_orm", client_name=get_client_name()
+ ).inc()
+ instance.delete()
+
+
+def clear_dashboard_from_group_type_mapping(team_id: int, dashboard_id: int, project_id: int | None = None) -> None:
+ """Clear detail_dashboard_id from any GroupTypeMapping referencing this dashboard.
+
+ Uses GetGroupTypeMappingByDashboardId to find the mapping, then UpdateGroupTypeMapping to clear it.
+ Falls back to ORM filter/update.
+ """
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.proto import GetGroupTypeMappingByDashboardIdRequest, UpdateGroupTypeMappingRequest
+
+ client = get_personhog_client()
+ if client is not None:
+ try:
+ resp = client.get_group_type_mapping_by_dashboard_id(
+ GetGroupTypeMappingByDashboardIdRequest(team_id=team_id, dashboard_id=dashboard_id)
+ )
+ if resp.mapping and resp.mapping.group_type_index is not None:
+ client.update_group_type_mapping(
+ UpdateGroupTypeMappingRequest(
+ project_id=resp.mapping.project_id,
+ group_type_index=resp.mapping.group_type_index,
+ update_mask=["detail_dashboard_id"],
+ )
+ )
+ invalidate_group_types_cache(resp.mapping.project_id)
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="clear_dashboard_from_group_type_mapping", source="personhog", client_name=get_client_name()
+ ).inc()
+ return
+ except Exception:
+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
+ operation="clear_dashboard_from_group_type_mapping",
+ source="personhog",
+ error_type="grpc_error",
+ client_name=get_client_name(),
+ ).inc()
+ logger.warning(
+ "personhog_clear_dashboard_from_group_type_mapping_failure",
+ team_id=team_id,
+ dashboard_id=dashboard_id,
+ exc_info=True,
+ )
+
+ from posthog.person_db_router import PERSONS_DB_FOR_WRITE
+
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="clear_dashboard_from_group_type_mapping", source="django_orm", client_name=get_client_name()
+ ).inc()
+ GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE).filter( # nosemgrep: no-direct-persons-db-orm
+ detail_dashboard_id=dashboard_id
+ ).update( # nosemgrep: no-direct-persons-db-orm
+ detail_dashboard_id=None
+ )
+ if project_id is not None:
+ invalidate_group_types_cache(project_id)
diff --git a/posthog/models/team/test_util_deletion.py b/posthog/models/team/test_util_deletion.py
new file mode 100644
index 000000000000..168386ad19c0
--- /dev/null
+++ b/posthog/models/team/test_util_deletion.py
@@ -0,0 +1,147 @@
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from posthog.models.team.util import _delete_group_type_mappings_for_teams, _delete_groups_for_teams
+
+_CLIENT_PATCH = "posthog.personhog_client.client.get_personhog_client"
+
+
+class TestDeleteGroupsForTeams(SimpleTestCase):
+ @patch(_CLIENT_PATCH)
+ def test_deletes_via_personhog_per_team(self, mock_get_client):
+ mock_client = MagicMock()
+ resp = MagicMock()
+ resp.deleted_count = 0
+ mock_client.delete_groups_batch_for_team.return_value = resp
+ mock_get_client.return_value = mock_client
+
+ _delete_groups_for_teams([1, 2, 3])
+
+ assert mock_client.delete_groups_batch_for_team.call_count == 3
+
+ @patch(_CLIENT_PATCH)
+ def test_loops_until_zero_deleted(self, mock_get_client):
+ mock_client = MagicMock()
+ resp1 = MagicMock()
+ resp1.deleted_count = 10000
+ resp2 = MagicMock()
+ resp2.deleted_count = 500
+ resp3 = MagicMock()
+ resp3.deleted_count = 0
+ mock_client.delete_groups_batch_for_team.side_effect = [resp1, resp2, resp3]
+ mock_get_client.return_value = mock_client
+
+ _delete_groups_for_teams([42])
+
+ assert mock_client.delete_groups_batch_for_team.call_count == 3
+
+ @patch(_CLIENT_PATCH)
+ def test_uses_batch_size_10000(self, mock_get_client):
+ mock_client = MagicMock()
+ resp = MagicMock()
+ resp.deleted_count = 0
+ mock_client.delete_groups_batch_for_team.return_value = resp
+ mock_get_client.return_value = mock_client
+
+ _delete_groups_for_teams([42])
+
+ req = mock_client.delete_groups_batch_for_team.call_args[0][0]
+ assert req.batch_size == 10000
+ assert req.team_id == 42
+
+ @patch("posthog.models.team.util._raw_delete")
+ @patch(_CLIENT_PATCH)
+ def test_falls_back_to_orm_when_client_none(self, mock_get_client, mock_raw_delete):
+ mock_get_client.return_value = None
+
+ _delete_groups_for_teams([42])
+
+ mock_raw_delete.assert_called_once()
+
+ @patch("posthog.models.team.util._raw_delete")
+ @patch(_CLIENT_PATCH)
+ def test_falls_back_to_orm_on_error(self, mock_get_client, mock_raw_delete):
+ mock_client = MagicMock()
+ mock_client.delete_groups_batch_for_team.side_effect = Exception("rpc failed")
+ mock_get_client.return_value = mock_client
+
+ _delete_groups_for_teams([42])
+
+ mock_raw_delete.assert_called_once()
+
+ @patch(_CLIENT_PATCH)
+ def test_empty_list_does_nothing(self, mock_get_client):
+ _delete_groups_for_teams([])
+
+ mock_get_client.return_value.delete_groups_batch_for_team.assert_not_called()
+
+
+class TestDeleteGroupTypeMappingsForTeams(SimpleTestCase):
+ @patch(_CLIENT_PATCH)
+ def test_deletes_via_personhog_per_team(self, mock_get_client):
+ mock_client = MagicMock()
+ resp = MagicMock()
+ resp.deleted_count = 0
+ mock_client.delete_group_type_mappings_batch_for_team.return_value = resp
+ mock_get_client.return_value = mock_client
+
+ _delete_group_type_mappings_for_teams([1, 2, 3])
+
+ assert mock_client.delete_group_type_mappings_batch_for_team.call_count == 3
+
+ @patch(_CLIENT_PATCH)
+ def test_loops_until_zero_deleted(self, mock_get_client):
+ mock_client = MagicMock()
+ resp1 = MagicMock()
+ resp1.deleted_count = 5
+ resp2 = MagicMock()
+ resp2.deleted_count = 0
+ mock_client.delete_group_type_mappings_batch_for_team.side_effect = [resp1, resp2]
+ mock_get_client.return_value = mock_client
+
+ _delete_group_type_mappings_for_teams([42])
+
+ assert mock_client.delete_group_type_mappings_batch_for_team.call_count == 2
+
+ @patch(_CLIENT_PATCH)
+ def test_uses_batch_size_10000(self, mock_get_client):
+ mock_client = MagicMock()
+ resp = MagicMock()
+ resp.deleted_count = 0
+ mock_client.delete_group_type_mappings_batch_for_team.return_value = resp
+ mock_get_client.return_value = mock_client
+
+ _delete_group_type_mappings_for_teams([42])
+
+ req = mock_client.delete_group_type_mappings_batch_for_team.call_args[0][0]
+ assert req.batch_size == 10000
+ assert req.team_id == 42
+
+ @patch("posthog.models.team.util._raw_delete")
+ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
+ @patch(_CLIENT_PATCH)
+ def test_falls_back_to_orm_when_client_none(self, mock_get_client, mock_objects, mock_raw_delete):
+ mock_get_client.return_value = None
+
+ _delete_group_type_mappings_for_teams([42])
+
+ mock_raw_delete.assert_called_once()
+
+ @patch("posthog.models.team.util._raw_delete")
+ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
+ @patch(_CLIENT_PATCH)
+ def test_falls_back_to_orm_on_error(self, mock_get_client, mock_objects, mock_raw_delete):
+ mock_client = MagicMock()
+ mock_client.delete_group_type_mappings_batch_for_team.side_effect = Exception("rpc failed")
+ mock_get_client.return_value = mock_client
+
+ _delete_group_type_mappings_for_teams([42])
+
+ mock_raw_delete.assert_called_once()
+
+ @patch(_CLIENT_PATCH)
+ def test_empty_list_does_nothing(self, mock_get_client):
+ _delete_group_type_mappings_for_teams([])
+
+ mock_get_client.return_value.delete_group_type_mappings_batch_for_team.assert_not_called()
diff --git a/posthog/models/team/util.py b/posthog/models/team/util.py
index 8b5fd90734fb..bc56c076b154 100644
--- a/posthog/models/team/util.py
+++ b/posthog/models/team/util.py
@@ -27,8 +27,6 @@ def delete_bulky_postgres_data(team_ids: list[int]):
from posthog.models.cohort import Cohort, CohortPeople
from posthog.models.feature_flag.feature_flag import FeatureFlagHashKeyOverride
- from posthog.models.group.group import Group
- from posthog.models.group_type_mapping import GroupTypeMapping
from posthog.models.insight_caching_state import InsightCachingState
from posthog.models.person import PersonlessDistinctId
@@ -51,8 +49,8 @@ def delete_bulky_postgres_data(team_ids: list[int]):
_raw_delete(CohortPeople.objects.filter(cohort_id__in=cohort_ids)) # nosemgrep: no-direct-persons-db-orm
_raw_delete(FeatureFlagHashKeyOverride.objects.filter(team_id__in=team_ids)) # nosemgrep: no-direct-persons-db-orm
- _raw_delete(Group.objects.filter(team_id__in=team_ids)) # nosemgrep: no-direct-persons-db-orm
- _raw_delete(GroupTypeMapping.objects.filter(team_id__in=team_ids)) # nosemgrep: no-direct-persons-db-orm
+ _delete_groups_for_teams(team_ids)
+ _delete_group_type_mappings_for_teams(team_ids)
# Delete Person + PersonDistinctId via personhog RPC (handles both tables).
# Falls back to ORM batch deletion when personhog is not available.
@@ -102,6 +100,76 @@ def _delete_persons_for_team_via_orm(team_id: int) -> None:
_raw_delete_batch(Person.objects.filter(team_id=team_id)) # nosemgrep: no-direct-persons-db-orm
+def _delete_groups_for_teams(team_ids: list[int]) -> None:
+ from posthog.models.group.group import Group
+ from posthog.models.person.util import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.proto import DeleteGroupsBatchForTeamRequest
+
+ client = get_personhog_client()
+ for team_id in team_ids:
+ if client is not None:
+ try:
+ while True:
+ resp = client.delete_groups_batch_for_team(
+ DeleteGroupsBatchForTeamRequest(team_id=team_id, batch_size=10000)
+ )
+ if resp.deleted_count == 0:
+ break
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="delete_groups_for_team", source="personhog", client_name=get_client_name()
+ ).inc()
+ continue
+ except Exception:
+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
+ operation="delete_groups_for_team",
+ source="personhog",
+ error_type="grpc_error",
+ client_name=get_client_name(),
+ ).inc()
+ logger.warning("personhog_delete_groups_for_team_failure", team_id=team_id, exc_info=True)
+
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="delete_groups_for_team", source="django_orm", client_name=get_client_name()
+ ).inc()
+ _raw_delete(Group.objects.filter(team_id=team_id)) # nosemgrep: no-direct-persons-db-orm
+
+
+def _delete_group_type_mappings_for_teams(team_ids: list[int]) -> None:
+ from posthog.models.group_type_mapping import GroupTypeMapping
+ from posthog.models.person.util import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.proto import DeleteGroupTypeMappingsBatchForTeamRequest
+
+ client = get_personhog_client()
+ for team_id in team_ids:
+ if client is not None:
+ try:
+ while True:
+ resp = client.delete_group_type_mappings_batch_for_team(
+ DeleteGroupTypeMappingsBatchForTeamRequest(team_id=team_id, batch_size=10000)
+ )
+ if resp.deleted_count == 0:
+ break
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="delete_group_type_mappings_for_team", source="personhog", client_name=get_client_name()
+ ).inc()
+ continue
+ except Exception:
+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
+ operation="delete_group_type_mappings_for_team",
+ source="personhog",
+ error_type="grpc_error",
+ client_name=get_client_name(),
+ ).inc()
+ logger.warning("personhog_delete_group_type_mappings_for_team_failure", team_id=team_id, exc_info=True)
+
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="delete_group_type_mappings_for_team", source="django_orm", client_name=get_client_name()
+ ).inc()
+ _raw_delete(GroupTypeMapping.objects.filter(team_id=team_id)) # nosemgrep: no-direct-persons-db-orm
+
+
def _raw_delete(queryset: Any):
"Issues a single DELETE statement for the queryset"
from django.db import router
diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.py
index c295c5c79c88..64f2b5946c4c 100644
--- a/posthog/models/test/test_group_type_mapping.py
+++ b/posthog/models/test/test_group_type_mapping.py
@@ -7,9 +7,12 @@ from parameterized import parameterized
from posthog.models.group_type_mapping import (
GROUP_TYPES_CACHE_KEY_PREFIX,
GROUP_TYPES_STALE_CACHE_KEY_PREFIX,
+ clear_dashboard_from_group_type_mapping,
+ delete_group_type_mapping,
get_group_types_for_project,
get_group_types_for_projects,
get_group_types_for_team,
+ update_group_type_mapping_fields,
)
from posthog.utils import safe_cache_delete
@@ -590,3 +593,261 @@ class TestGetGroupTypesForProjectsEdgeCases(SimpleTestCase):
result = get_group_types_for_projects([10, 20])
assert result == {10: [], 20: []}
+
+
+# ── Write helper tests ─────────────────────────────────────────────
+
+
+class TestUpdateGroupTypeMappingFields(SimpleTestCase):
+ def _make_instance(self):
+ instance = MagicMock()
+ instance.project_id = 1
+ instance.group_type_index = 0
+ return instance
+
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_personhog_success_does_not_call_orm_save(self, mock_get_client, mock_routing_counter):
+ mock_client = MagicMock()
+ mock_client.update_group_type_mapping.return_value = MagicMock()
+ mock_get_client.return_value = mock_client
+
+ instance = self._make_instance()
+ update_group_type_mapping_fields(instance, fields={"name_singular": "Org", "name_plural": "Orgs"})
+
+ mock_client.update_group_type_mapping.assert_called_once()
+ req = mock_client.update_group_type_mapping.call_args[0][0]
+ assert req.project_id == 1
+ assert req.group_type_index == 0
+ assert set(req.update_mask) == {"name_singular", "name_plural"}
+ assert req.name_singular == "Org"
+ assert req.name_plural == "Orgs"
+ instance.save.assert_not_called()
+ mock_routing_counter.labels.assert_called_with(
+ operation="group_type_update", source="personhog", client_name="posthog-django"
+ )
+
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_client_none_falls_back_to_orm_save(self, mock_get_client, mock_routing_counter):
+ mock_get_client.return_value = None
+
+ instance = self._make_instance()
+ update_group_type_mapping_fields(instance, fields={"name_singular": "Org"})
+
+ instance.save.assert_called_once()
+ mock_routing_counter.labels.assert_called_with(
+ operation="group_type_update", source="django_orm", client_name="posthog-django"
+ )
+
+ @parameterized.expand(
+ [
+ ("grpc_timeout", RuntimeError("grpc timeout")),
+ ("connection_error", ConnectionError("connection refused")),
+ ]
+ )
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_personhog_exception_falls_back_to_orm(
+ self, _name, exception, mock_get_client, mock_routing_counter, mock_errors_counter
+ ):
+ mock_client = MagicMock()
+ mock_client.update_group_type_mapping.side_effect = exception
+ mock_get_client.return_value = mock_client
+
+ instance = self._make_instance()
+ update_group_type_mapping_fields(instance, fields={"name_singular": "Org"})
+
+ instance.save.assert_called_once()
+ mock_errors_counter.labels.assert_called_once_with(
+ operation="group_type_update",
+ source="personhog",
+ error_type="grpc_error",
+ client_name="posthog-django",
+ )
+
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_orm_fallback_sets_fields_on_instance(self, mock_get_client, mock_routing_counter):
+ mock_get_client.return_value = None
+
+ instance = self._make_instance()
+ update_group_type_mapping_fields(instance, fields={"name_singular": "Team", "default_columns": ["name"]})
+
+ assert instance.name_singular == "Team"
+ assert instance.default_columns == ["name"]
+ instance.save.assert_called_once()
+
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_detail_dashboard_id_sent_correctly(self, mock_get_client, mock_routing_counter):
+ mock_client = MagicMock()
+ mock_client.update_group_type_mapping.return_value = MagicMock()
+ mock_get_client.return_value = mock_client
+
+ instance = self._make_instance()
+ update_group_type_mapping_fields(instance, fields={"detail_dashboard_id": 42})
+
+ req = mock_client.update_group_type_mapping.call_args[0][0]
+ assert req.detail_dashboard_id == 42
+ assert "detail_dashboard_id" in req.update_mask
+
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_detail_dashboard_id_none_leaves_field_unset(self, mock_get_client, mock_routing_counter):
+ mock_client = MagicMock()
+ mock_client.update_group_type_mapping.return_value = MagicMock()
+ mock_get_client.return_value = mock_client
+
+ instance = self._make_instance()
+ update_group_type_mapping_fields(instance, fields={"detail_dashboard_id": None})
+
+ req = mock_client.update_group_type_mapping.call_args[0][0]
+ assert "detail_dashboard_id" in req.update_mask
+ assert req.detail_dashboard_id == 0
+
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_default_columns_json_encoded(self, mock_get_client, mock_routing_counter):
+ mock_client = MagicMock()
+ mock_client.update_group_type_mapping.return_value = MagicMock()
+ mock_get_client.return_value = mock_client
+
+ instance = self._make_instance()
+ update_group_type_mapping_fields(instance, fields={"default_columns": ["name", "email"]})
+
+ req = mock_client.update_group_type_mapping.call_args[0][0]
+ assert b'"name"' in req.default_columns
+ assert b'"email"' in req.default_columns
+
+
+class TestDeleteGroupTypeMapping(SimpleTestCase):
+ def _make_instance(self):
+ instance = MagicMock()
+ instance.project_id = 1
+ instance.group_type_index = 0
+ return instance
+
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_personhog_success_does_not_call_orm_delete(self, mock_get_client, mock_routing_counter):
+ mock_client = MagicMock()
+ mock_client.delete_group_type_mapping.return_value = MagicMock()
+ mock_get_client.return_value = mock_client
+
+ instance = self._make_instance()
+ delete_group_type_mapping(instance)
+
+ mock_client.delete_group_type_mapping.assert_called_once()
+ req = mock_client.delete_group_type_mapping.call_args[0][0]
+ assert req.project_id == 1
+ assert req.group_type_index == 0
+ instance.delete.assert_not_called()
+ mock_routing_counter.labels.assert_called_with(
+ operation="delete_group_type_mapping", source="personhog", client_name="posthog-django"
+ )
+
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_client_none_falls_back_to_orm_delete(self, mock_get_client, mock_routing_counter):
+ mock_get_client.return_value = None
+
+ instance = self._make_instance()
+ delete_group_type_mapping(instance)
+
+ instance.delete.assert_called_once()
+ mock_routing_counter.labels.assert_called_with(
+ operation="delete_group_type_mapping", source="django_orm", client_name="posthog-django"
+ )
+
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_personhog_exception_falls_back_to_orm_delete(
+ self, mock_get_client, mock_routing_counter, mock_errors_counter
+ ):
+ mock_client = MagicMock()
+ mock_client.delete_group_type_mapping.side_effect = RuntimeError("grpc timeout")
+ mock_get_client.return_value = mock_client
+
+ instance = self._make_instance()
+ delete_group_type_mapping(instance)
+
+ instance.delete.assert_called_once()
+ mock_errors_counter.labels.assert_called_once()
+
+
+class TestClearDashboardFromGroupTypeMapping(SimpleTestCase):
+ @patch("posthog.models.group_type_mapping.invalidate_group_types_cache")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_personhog_success_reads_then_updates(self, mock_get_client, mock_routing_counter, mock_invalidate):
+ mock_mapping = MagicMock()
+ mock_mapping.project_id = 1
+ mock_mapping.group_type_index = 0
+ mock_resp = MagicMock()
+ mock_resp.mapping = mock_mapping
+
+ mock_client = MagicMock()
+ mock_client.get_group_type_mapping_by_dashboard_id.return_value = mock_resp
+ mock_client.update_group_type_mapping.return_value = MagicMock()
+ mock_get_client.return_value = mock_client
+
+ clear_dashboard_from_group_type_mapping(team_id=10, dashboard_id=42)
+
+ mock_client.get_group_type_mapping_by_dashboard_id.assert_called_once()
+ mock_client.update_group_type_mapping.assert_called_once()
+ update_req = mock_client.update_group_type_mapping.call_args[0][0]
+ assert update_req.project_id == 1
+ assert update_req.group_type_index == 0
+ assert "detail_dashboard_id" in update_req.update_mask
+ assert update_req.detail_dashboard_id == 0
+ mock_invalidate.assert_called_once_with(1)
+
+ @patch("posthog.models.group_type_mapping.invalidate_group_types_cache")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_personhog_no_matching_mapping_skips_update(self, mock_get_client, mock_routing_counter, mock_invalidate):
+ mock_resp = MagicMock()
+ mock_resp.mapping = None
+
+ mock_client = MagicMock()
+ mock_client.get_group_type_mapping_by_dashboard_id.return_value = mock_resp
+ mock_get_client.return_value = mock_client
+
+ clear_dashboard_from_group_type_mapping(team_id=10, dashboard_id=999)
+
+ mock_client.update_group_type_mapping.assert_not_called()
+ mock_invalidate.assert_not_called()
+
+ @patch("posthog.models.group_type_mapping.invalidate_group_types_cache")
+ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_client_none_falls_back_to_orm(self, mock_get_client, mock_routing_counter, mock_objects, mock_invalidate):
+ mock_get_client.return_value = None
+
+ clear_dashboard_from_group_type_mapping(team_id=10, dashboard_id=42, project_id=1)
+
+ mock_objects.using.assert_called_once()
+ mock_invalidate.assert_called_once_with(1)
+ mock_routing_counter.labels.assert_called_with(
+ operation="clear_dashboard_from_group_type_mapping", source="django_orm", client_name="posthog-django"
+ )
+
+ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch(_CLIENT_PATCH)
+ def test_personhog_exception_falls_back_to_orm(
+ self, mock_get_client, mock_routing_counter, mock_errors_counter, mock_objects
+ ):
+ mock_client = MagicMock()
+ mock_client.get_group_type_mapping_by_dashboard_id.side_effect = RuntimeError("grpc timeout")
+ mock_get_client.return_value = mock_client
+
+ clear_dashboard_from_group_type_mapping(team_id=10, dashboard_id=42, project_id=1)
+
+ mock_objects.using.assert_called_once()
+ mock_errors_counter.labels.assert_called_once()
diff --git a/posthog/personhog_client/client.py b/posthog/personhog_client/client.py
index bdcac34a03db..e74b0918909d 100644
--- a/posthog/personhog_client/client.py
+++ b/posthog/personhog_client/client.py
@@ -16,10 +16,18 @@ from posthog.personhog_client.proto import (
CohortMembershipResponse,
CountCohortMembersRequest,
CountCohortMembersResponse,
+ CreateGroupRequest,
+ CreateGroupResponse,
DeleteCohortMemberRequest,
DeleteCohortMemberResponse,
DeleteCohortMembersBulkRequest,
DeleteCohortMembersBulkResponse,
+ DeleteGroupsBatchForTeamRequest,
+ DeleteGroupsBatchForTeamResponse,
+ DeleteGroupTypeMappingRequest,
+ DeleteGroupTypeMappingResponse,
+ DeleteGroupTypeMappingsBatchForTeamRequest,
+ DeleteGroupTypeMappingsBatchForTeamResponse,
DeletePersonsBatchForTeamRequest,
DeletePersonsBatchForTeamResponse,
DeletePersonsRequest,
@@ -33,6 +41,8 @@ from posthog.personhog_client.proto import (
GetGroupsBatchRequest,
GetGroupsBatchResponse,
GetGroupsRequest,
+ GetGroupTypeMappingByDashboardIdRequest,
+ GetGroupTypeMappingByDashboardIdResponse,
GetGroupTypeMappingsByProjectIdRequest,
GetGroupTypeMappingsByProjectIdsRequest,
GetGroupTypeMappingsByTeamIdRequest,
@@ -54,6 +64,10 @@ from posthog.personhog_client.proto import (
PersonHogServiceStub,
PersonsByDistinctIdsInTeamResponse,
PersonsResponse,
+ UpdateGroupRequest,
+ UpdateGroupResponse,
+ UpdateGroupTypeMappingRequest,
+ UpdateGroupTypeMappingResponse,
)
logger = structlog.get_logger(__name__)
@@ -243,6 +257,17 @@ class PersonHogClient:
def get_groups_batch(self, request: GetGroupsBatchRequest) -> GetGroupsBatchResponse:
return self._stub.GetGroupsBatch(request, timeout=self._timeout)
+ def create_group(self, request: CreateGroupRequest) -> CreateGroupResponse:
+ return self._stub.CreateGroup(request, timeout=self._timeout)
+
+ def update_group(self, request: UpdateGroupRequest) -> UpdateGroupResponse:
+ return self._stub.UpdateGroup(request, timeout=self._timeout)
+
+ def delete_groups_batch_for_team(
+ self, request: DeleteGroupsBatchForTeamRequest, timeout: float | None = None
+ ) -> DeleteGroupsBatchForTeamResponse:
+ return self._stub.DeleteGroupsBatchForTeam(request, timeout=timeout or self._timeout)
+
# -- Group type mappings --
def get_group_type_mappings_by_team_id(
@@ -265,6 +290,22 @@ class PersonHogClient:
) -> GroupTypeMappingsBatchResponse:
return self._stub.GetGroupTypeMappingsByProjectIds(request, timeout=self._timeout)
+ def get_group_type_mapping_by_dashboard_id(
+ self, request: GetGroupTypeMappingByDashboardIdRequest
+ ) -> GetGroupTypeMappingByDashboardIdResponse:
+ return self._stub.GetGroupTypeMappingByDashboardId(request, timeout=self._timeout)
+
+ def update_group_type_mapping(self, request: UpdateGroupTypeMappingRequest) -> UpdateGroupTypeMappingResponse:
+ return self._stub.UpdateGroupTypeMapping(request, timeout=self._timeout)
+
+ def delete_group_type_mapping(self, request: DeleteGroupTypeMappingRequest) -> DeleteGroupTypeMappingResponse:
+ return self._stub.DeleteGroupTypeMapping(request, timeout=self._timeout)
+
+ def delete_group_type_mappings_batch_for_team(
+ self, request: DeleteGroupTypeMappingsBatchForTeamRequest, timeout: float | None = None
+ ) -> DeleteGroupTypeMappingsBatchForTeamResponse:
+ return self._stub.DeleteGroupTypeMappingsBatchForTeam(request, timeout=timeout or self._timeout)
+
_client: Optional[PersonHogClient] = None
_lock = threading.Lock()
diff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.py
index f47b05ad980e..b3d51e219a15 100644
--- a/posthog/personhog_client/fake_client.py
+++ b/posthog/personhog_client/fake_client.py
@@ -382,6 +382,120 @@ class FakePersonHogClient:
results.append(group_pb2.GroupTypeMappingsByKey(key=pid, mappings=mappings))
return group_pb2.GroupTypeMappingsBatchResponse(results=results)
+ # ── Group writes ─────────────────────────────────────────────────
+
+ def create_group(self, request: group_pb2.CreateGroupRequest) -> group_pb2.CreateGroupResponse:
+ self.calls.append(_Call("create_group", request))
+ next_id = max((g.id for g in self._groups.values()), default=0) + 1
+ group = group_pb2.Group(
+ id=next_id,
+ team_id=request.team_id,
+ group_type_index=request.group_type_index,
+ group_key=request.group_key,
+ group_properties=request.group_properties,
+ created_at=request.created_at,
+ version=0,
+ )
+ self._groups[(request.team_id, request.group_type_index, request.group_key)] = group
+ response = group_pb2.CreateGroupResponse(group=group)
+ return response
+
+ def update_group(self, request: group_pb2.UpdateGroupRequest) -> group_pb2.UpdateGroupResponse:
+ self.calls.append(_Call("update_group", request))
+ key = (request.team_id, request.group_type_index, request.group_key)
+ group = self._groups.get(key)
+ if group is None:
+ import grpc
+
+ raise grpc.RpcError()
+ for field in request.update_mask:
+ if field == "group_properties":
+ group.group_properties = request.group_properties
+ elif field == "properties_last_updated_at":
+ group.properties_last_updated_at = request.properties_last_updated_at
+ elif field == "properties_last_operation":
+ group.properties_last_operation = request.properties_last_operation
+ elif field == "created_at":
+ group.created_at = request.created_at
+ group.version += 1
+ self._groups[key] = group
+ return group_pb2.UpdateGroupResponse(group=group, updated=True)
+
+ def delete_groups_batch_for_team(
+ self, request: group_pb2.DeleteGroupsBatchForTeamRequest, timeout: float | None = None
+ ) -> group_pb2.DeleteGroupsBatchForTeamResponse:
+ self.calls.append(_Call("delete_groups_batch_for_team", request))
+ to_delete = [k for k in self._groups if k[0] == request.team_id][: request.batch_size]
+ for key in to_delete:
+ del self._groups[key]
+ return group_pb2.DeleteGroupsBatchForTeamResponse(deleted_count=len(to_delete))
+
+ # ── Group type mapping writes ───────────────────────────────────
+
+ def get_group_type_mapping_by_dashboard_id(
+ self, request: group_pb2.GetGroupTypeMappingByDashboardIdRequest
+ ) -> group_pb2.GetGroupTypeMappingByDashboardIdResponse:
+ self.calls.append(_Call("get_group_type_mapping_by_dashboard_id", request))
+ for mappings in self._group_type_mappings_by_project.values():
+ for m in mappings:
+ if m.detail_dashboard_id == request.dashboard_id and m.team_id == request.team_id:
+ return group_pb2.GetGroupTypeMappingByDashboardIdResponse(mapping=m)
+ return group_pb2.GetGroupTypeMappingByDashboardIdResponse()
+
+ def update_group_type_mapping(
+ self, request: group_pb2.UpdateGroupTypeMappingRequest
+ ) -> group_pb2.UpdateGroupTypeMappingResponse:
+ self.calls.append(_Call("update_group_type_mapping", request))
+ mappings = self._group_type_mappings_by_project.get(request.project_id, [])
+ for m in mappings:
+ if m.group_type_index == request.group_type_index:
+ for field in request.update_mask:
+ if field == "name_singular":
+ m.name_singular = request.name_singular
+ elif field == "name_plural":
+ m.name_plural = request.name_plural
+ elif field == "detail_dashboard_id":
+ m.detail_dashboard_id = request.detail_dashboard_id
+ elif field == "default_columns":
+ m.default_columns = request.default_columns
+ return group_pb2.UpdateGroupTypeMappingResponse(mapping=m)
+ import grpc
+
+ raise grpc.RpcError()
+
+ def delete_group_type_mapping(
+ self, request: group_pb2.DeleteGroupTypeMappingRequest
+ ) -> group_pb2.DeleteGroupTypeMappingResponse:
+ self.calls.append(_Call("delete_group_type_mapping", request))
+ mappings = self._group_type_mappings_by_project.get(request.project_id, [])
+ original_len = len(mappings)
+ self._group_type_mappings_by_project[request.project_id] = [
+ m for m in mappings if m.group_type_index != request.group_type_index
+ ]
+ deleted = len(self._group_type_mappings_by_project[request.project_id]) < original_len
+ for tid in list(self._group_type_mappings_by_team):
+ self._group_type_mappings_by_team[tid] = [
+ m
+ for m in self._group_type_mappings_by_team[tid]
+ if not (m.project_id == request.project_id and m.group_type_index == request.group_type_index)
+ ]
+ return group_pb2.DeleteGroupTypeMappingResponse(deleted=deleted)
+
+ def delete_group_type_mappings_batch_for_team(
+ self, request: group_pb2.DeleteGroupTypeMappingsBatchForTeamRequest, timeout: float | None = None
+ ) -> group_pb2.DeleteGroupTypeMappingsBatchForTeamResponse:
+ self.calls.append(_Call("delete_group_type_mappings_batch_for_team", request))
+ deleted = 0
+ for pid in list(self._group_type_mappings_by_project):
+ before = len(self._group_type_mappings_by_project[pid])
+ self._group_type_mappings_by_project[pid] = [
+ m for m in self._group_type_mappings_by_project[pid] if m.team_id != request.team_id
+ ]
+ deleted += before - len(self._group_type_mappings_by_project[pid])
+ if deleted >= request.batch_size:
+ break
+ return group_pb2.DeleteGroupTypeMappingsBatchForTeamResponse(deleted_count=deleted)
+
# ── Person deletes ────────────────────────────────────────────────
def delete_persons(
diff --git a/posthog/personhog_client/proto/__init__.py b/posthog/personhog_client/proto/__init__.py
index 288a1cdbbdbd..01351d8cc85a 100644
--- a/posthog/personhog_client/proto/__init__.py
+++ b/posthog/personhog_client/proto/__init__.py
@@ -26,11 +26,21 @@ from posthog.personhog_client.proto.generated.personhog.types.v1.cohort_pb2 impo
ListCohortMemberIdsResponse,
)
from posthog.personhog_client.proto.generated.personhog.types.v1.group_pb2 import (
+ CreateGroupRequest,
+ CreateGroupResponse,
+ DeleteGroupsBatchForTeamRequest,
+ DeleteGroupsBatchForTeamResponse,
+ DeleteGroupTypeMappingRequest,
+ DeleteGroupTypeMappingResponse,
+ DeleteGroupTypeMappingsBatchForTeamRequest,
+ DeleteGroupTypeMappingsBatchForTeamResponse,
GetGroupRequest,
GetGroupResponse,
GetGroupsBatchRequest,
GetGroupsBatchResponse,
GetGroupsRequest,
+ GetGroupTypeMappingByDashboardIdRequest,
+ GetGroupTypeMappingByDashboardIdResponse,
GetGroupTypeMappingsByProjectIdRequest,
GetGroupTypeMappingsByProjectIdsRequest,
GetGroupTypeMappingsByTeamIdRequest,
@@ -41,6 +51,10 @@ from posthog.personhog_client.proto.generated.personhog.types.v1.group_pb2 impor
GroupTypeMappingsBatchResponse,
GroupTypeMappingsResponse,
GroupWithKey,
+ UpdateGroupRequest,
+ UpdateGroupResponse,
+ UpdateGroupTypeMappingRequest,
+ UpdateGroupTypeMappingResponse,
)
from posthog.personhog_client.proto.generated.personhog.types.v1.person_pb2 import (
DeletePersonsBatchForTeamRequest,
diff --git a/posthog/personhog_client/test_fake_client.py b/posthog/personhog_client/test_fake_client.py
index 2bd53f544a8f..4bc12a7951a7 100644
--- a/posthog/personhog_client/test_fake_client.py
+++ b/posthog/personhog_client/test_fake_client.py
@@ -211,6 +211,239 @@ class TestCallTracking:
client.assert_not_called("get_person")
+class TestFakePersonHogClientGroupWrites:
+ def setup_method(self):
+ self.client = FakePersonHogClient()
+ self.client.add_group(team_id=1, group_type_index=0, group_key="org:1", group_properties={"name": "Acme"})
+
+ def test_create_group(self):
+ resp = self.client.create_group(
+ group_pb2.CreateGroupRequest(
+ team_id=1,
+ group_type_index=0,
+ group_key="org:new",
+ group_properties=b'{"foo": "bar"}',
+ created_at=1000,
+ )
+ )
+ assert resp.group.id > 0
+ assert resp.group.group_key == "org:new"
+ assert resp.group.team_id == 1
+ assert resp.group.created_at == 1000
+ assert resp.group.version == 0
+ fetched = self.client.get_group(group_pb2.GetGroupRequest(team_id=1, group_type_index=0, group_key="org:new"))
+ assert fetched.group.id == resp.group.id
+
+ def test_create_group_auto_increment_id(self):
+ resp1 = self.client.create_group(group_pb2.CreateGroupRequest(team_id=1, group_type_index=1, group_key="k1"))
+ resp2 = self.client.create_group(group_pb2.CreateGroupRequest(team_id=1, group_type_index=2, group_key="k2"))
+ assert resp2.group.id > resp1.group.id
+
+ def test_update_group_properties(self):
+ self.client.update_group(
+ group_pb2.UpdateGroupRequest(
+ team_id=1,
+ group_type_index=0,
+ group_key="org:1",
+ update_mask=["group_properties"],
+ group_properties=b'{"name": "Updated"}',
+ )
+ )
+ fetched = self.client.get_group(group_pb2.GetGroupRequest(team_id=1, group_type_index=0, group_key="org:1"))
+ assert json.loads(fetched.group.group_properties) == {"name": "Updated"}
+ assert fetched.group.version == 1
+
+ def test_update_group_not_found_raises(self):
+ import grpc
+
+ with pytest.raises(grpc.RpcError):
+ self.client.update_group(
+ group_pb2.UpdateGroupRequest(
+ team_id=1,
+ group_type_index=0,
+ group_key="nonexistent",
+ update_mask=["group_properties"],
+ )
+ )
+
+ def test_update_group_increments_version(self):
+ self.client.update_group(
+ group_pb2.UpdateGroupRequest(
+ team_id=1,
+ group_type_index=0,
+ group_key="org:1",
+ update_mask=["group_properties"],
+ group_properties=b"{}",
+ )
+ )
+ self.client.update_group(
+ group_pb2.UpdateGroupRequest(
+ team_id=1,
+ group_type_index=0,
+ group_key="org:1",
+ update_mask=["group_properties"],
+ group_properties=b"{}",
+ )
+ )
+ fetched = self.client.get_group(group_pb2.GetGroupRequest(team_id=1, group_type_index=0, group_key="org:1"))
+ assert fetched.group.version == 2
+
+ def test_delete_groups_batch_for_team(self):
+ self.client.add_group(team_id=1, group_type_index=0, group_key="org:2")
+ resp = self.client.delete_groups_batch_for_team(
+ group_pb2.DeleteGroupsBatchForTeamRequest(team_id=1, batch_size=10)
+ )
+ assert resp.deleted_count == 2
+ fetched = self.client.get_group(group_pb2.GetGroupRequest(team_id=1, group_type_index=0, group_key="org:1"))
+ assert not fetched.HasField("group")
+
+ def test_delete_groups_batch_respects_batch_size(self):
+ self.client.add_group(team_id=1, group_type_index=0, group_key="org:2")
+ self.client.add_group(team_id=1, group_type_index=0, group_key="org:3")
+ resp = self.client.delete_groups_batch_for_team(
+ group_pb2.DeleteGroupsBatchForTeamRequest(team_id=1, batch_size=2)
+ )
+ assert resp.deleted_count == 2
+ remaining = self.client.get_groups(
+ group_pb2.GetGroupsRequest(
+ team_id=1,
+ group_identifiers=[
+ common_pb2.GroupIdentifier(group_type_index=0, group_key="org:1"),
+ common_pb2.GroupIdentifier(group_type_index=0, group_key="org:2"),
+ common_pb2.GroupIdentifier(group_type_index=0, group_key="org:3"),
+ ],
+ )
+ )
+ assert len(remaining.groups) == 1
+
+ def test_delete_groups_batch_wrong_team(self):
+ resp = self.client.delete_groups_batch_for_team(
+ group_pb2.DeleteGroupsBatchForTeamRequest(team_id=999, batch_size=10)
+ )
+ assert resp.deleted_count == 0
+ fetched = self.client.get_group(group_pb2.GetGroupRequest(team_id=1, group_type_index=0, group_key="org:1"))
+ assert fetched.group.group_key == "org:1"
+
+
+class TestFakePersonHogClientGroupTypeMappingWrites:
+ def setup_method(self):
+ self.client = FakePersonHogClient()
+ self.client.add_group_type_mapping(
+ project_id=100,
+ team_id=1,
+ group_type="organization",
+ group_type_index=0,
+ name_singular="Organization",
+ detail_dashboard_id=42,
+ )
+ self.client.add_group_type_mapping(project_id=100, team_id=1, group_type="company", group_type_index=1)
+
+ def test_get_group_type_mapping_by_dashboard_id_found(self):
+ resp = self.client.get_group_type_mapping_by_dashboard_id(
+ group_pb2.GetGroupTypeMappingByDashboardIdRequest(team_id=1, dashboard_id=42)
+ )
+ assert resp.mapping.group_type == "organization"
+
+ def test_get_group_type_mapping_by_dashboard_id_not_found(self):
+ resp = self.client.get_group_type_mapping_by_dashboard_id(
+ group_pb2.GetGroupTypeMappingByDashboardIdRequest(team_id=1, dashboard_id=999)
+ )
+ assert not resp.HasField("mapping")
+
+ def test_get_group_type_mapping_by_dashboard_id_wrong_team(self):
+ resp = self.client.get_group_type_mapping_by_dashboard_id(
+ group_pb2.GetGroupTypeMappingByDashboardIdRequest(team_id=99, dashboard_id=42)
+ )
+ assert not resp.HasField("mapping")
+
+ def test_update_group_type_mapping_name(self):
+ self.client.update_group_type_mapping(
+ group_pb2.UpdateGroupTypeMappingRequest(
+ project_id=100,
+ group_type_index=0,
+ update_mask=["name_singular", "name_plural"],
+ name_singular="Org",
+ name_plural="Orgs",
+ )
+ )
+ resp = self.client.get_group_type_mappings_by_project_id(
+ group_pb2.GetGroupTypeMappingsByProjectIdRequest(project_id=100)
+ )
+ org_mapping = next(m for m in resp.mappings if m.group_type_index == 0)
+ assert org_mapping.name_singular == "Org"
+ assert org_mapping.name_plural == "Orgs"
+
+ def test_update_group_type_mapping_dashboard_id(self):
+ self.client.update_group_type_mapping(
+ group_pb2.UpdateGroupTypeMappingRequest(
+ project_id=100,
+ group_type_index=0,
+ update_mask=["detail_dashboard_id"],
+ detail_dashboard_id=99,
+ )
+ )
+ resp = self.client.get_group_type_mapping_by_dashboard_id(
+ group_pb2.GetGroupTypeMappingByDashboardIdRequest(team_id=1, dashboard_id=99)
+ )
+ assert resp.mapping.group_type == "organization"
+
+ def test_update_group_type_mapping_not_found_raises(self):
+ import grpc
+
+ with pytest.raises(grpc.RpcError):
+ self.client.update_group_type_mapping(
+ group_pb2.UpdateGroupTypeMappingRequest(
+ project_id=100,
+ group_type_index=99,
+ update_mask=["name_singular"],
+ name_singular="X",
+ )
+ )
+
+ def test_delete_group_type_mapping(self):
+ resp = self.client.delete_group_type_mapping(
+ group_pb2.DeleteGroupTypeMappingRequest(project_id=100, group_type_index=0)
+ )
+ assert resp.deleted is True
+ remaining = self.client.get_group_type_mappings_by_project_id(
+ group_pb2.GetGroupTypeMappingsByProjectIdRequest(project_id=100)
+ )
+ assert len(remaining.mappings) == 1
+ assert remaining.mappings[0].group_type == "company"
+
+ def test_delete_group_type_mapping_not_found(self):
+ resp = self.client.delete_group_type_mapping(
+ group_pb2.DeleteGroupTypeMappingRequest(project_id=100, group_type_index=99)
+ )
+ assert resp.deleted is False
+
+ def test_delete_group_type_mapping_removes_from_team_index(self):
+ self.client.delete_group_type_mapping(
+ group_pb2.DeleteGroupTypeMappingRequest(project_id=100, group_type_index=0)
+ )
+ by_team = self.client.get_group_type_mappings_by_team_id(
+ group_pb2.GetGroupTypeMappingsByTeamIdRequest(team_id=1)
+ )
+ assert len(by_team.mappings) == 1
+ assert by_team.mappings[0].group_type == "company"
+
+ def test_delete_group_type_mappings_batch_for_team(self):
+ resp = self.client.delete_group_type_mappings_batch_for_team(
+ group_pb2.DeleteGroupTypeMappingsBatchForTeamRequest(team_id=1, batch_size=10)
+ )
+ assert resp.deleted_count == 2
+ remaining = self.client.get_group_type_mappings_by_project_id(
+ group_pb2.GetGroupTypeMappingsByProjectIdRequest(project_id=100)
+ )
+ assert len(remaining.mappings) == 0
+
+ def test_delete_group_type_mappings_batch_wrong_team(self):
+ resp = self.client.delete_group_type_mappings_batch_for_team(
+ group_pb2.DeleteGroupTypeMappingsBatchForTeamRequest(team_id=999, batch_size=10)
+ )
+ assert resp.deleted_count == 0
+
+
class TestFakePersonhogClientContextManager:
def test_patches_get_personhog_client(self):
with fake_personhog_client() as fake:
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 57be4dcdb34f..804d61d9d45d 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -60,7 +60,6 @@ from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models import Insight
from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
from posthog.models.alert import AlertConfiguration
-from posthog.models.group_type_mapping import GroupTypeMapping, invalidate_group_types_cache
from posthog.models.insight_variable import InsightVariable
from posthog.models.quick_filter import QuickFilter
from posthog.models.signals import model_activity_signal, mutable_receiver
@@ -684,14 +683,11 @@ class DashboardSerializer(DashboardMetadataSerializer):
primary_dashboard=instance,
id=instance.team_id,
).update(primary_dashboard=None)
- # Will be migrated with the personhog write path
- group_type_mapping = GroupTypeMapping.objects.filter( # nosemgrep: no-direct-persons-db-orm
- team=instance.team, project_id=instance.team.project_id, detail_dashboard_id=instance.id
- ).first()
- if group_type_mapping:
- group_type_mapping.detail_dashboard_id = None
- group_type_mapping.save()
- invalidate_group_types_cache(instance.team.project_id)
+ from posthog.models.group_type_mapping import clear_dashboard_from_group_type_mapping
+
+ clear_dashboard_from_group_type_mapping(
+ team_id=instance.team_id, dashboard_id=instance.id, project_id=instance.team.project_id
+ )
request_filters = initial_data.get("filters")
if request_filters:
diff --git a/products/dashboards/backend/models/dashboard.py b/products/dashboards/backend/models/dashboard.py
index 56b8b01cba5a..69c751ff1022 100644
--- a/products/dashboards/backend/models/dashboard.py
+++ b/products/dashboards/backend/models/dashboard.py
@@ -8,7 +8,6 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
from posthog.models.utils import RootTeamManager, RootTeamMixin, sane_repr
-from posthog.person_db_router import PERSONS_DB_FOR_WRITE
from posthog.utils import absolute_uri
if TYPE_CHECKING:
@@ -111,14 +110,10 @@ class Dashboard(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.M
return self.name or str(self.id)
def delete(self, *args, **kwargs):
- from posthog.models.group_type_mapping import GroupTypeMapping
-
- # Handle SET_NULL for GroupTypeMapping.detail_dashboard in persons database
- # This is needed because GroupTypeMapping is in the persons database
- GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE).filter( # nosemgrep: no-direct-persons-db-orm
- detail_dashboard_id=self.id
- ).update( # nosemgrep: no-direct-persons-db-orm
- detail_dashboard_id=None
+ from posthog.models.group_type_mapping import clear_dashboard_from_group_type_mapping
+
+ clear_dashboard_from_group_type_mapping(
+ team_id=self.team_id, dashboard_id=self.id, project_id=self.team.project_id
)
return super().delete(*args, **kwargs)