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.

chore(django): GroupTypesViewSet list through personhog (#63147)

Nick Best497086c654cd
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.py
index 2caa5a794b11..0392329af8e3 100644
--- a/ee/clickhouse/views/groups.py
+++ b/ee/clickhouse/views/groups.py
@@ -37,10 +37,12 @@ from posthog.models.group_type_mapping import (
GROUP_TYPE_MAPPING_SERIALIZER_FIELDS,
GroupTypeMapping,
delete_group_type_mapping,
+ get_group_types_for_project,
invalidate_group_types_cache,
update_group_type_mapping_fields,
)
from posthog.models.user import User
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.personhog_client.converters import GroupTypeMappingResult
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
@@ -114,9 +116,25 @@ class GroupTypeSerializer(serializers.ModelSerializer, UserAccessControlSerializ
read_only_fields = ["group_type", "group_type_index"]
-class GroupsTypesViewSet(
- TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet
-):
+def _group_type_row_to_response(row: dict[str, Any]) -> dict[str, Any]:
+ """Shape a get_group_types_for_project row like GroupTypeSerializer output.
+
+ Cache entries written before the personhog converter aligned with the ORM
+ .values() shape carry the dashboard id under "detail_dashboard_id" — read
+ both keys until those entries age out.
+ """
+ return {
+ "group_type": row["group_type"],
+ "group_type_index": row["group_type_index"],
+ "name_singular": row.get("name_singular"),
+ "name_plural": row.get("name_plural"),
+ "detail_dashboard": row.get("detail_dashboard", row.get("detail_dashboard_id")),
+ "default_columns": row.get("default_columns"),
+ "created_at": row.get("created_at"),
+ }
+
+
+class GroupsTypesViewSet(TeamAndOrgViewSetMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
scope_object = "group"
serializer_class = GroupTypeSerializer
queryset = GroupTypeMapping.objects.all().order_by("group_type_index") # nosemgrep: no-direct-persons-db-orm
@@ -128,6 +146,13 @@ class GroupsTypesViewSet(
def safely_get_queryset(self, queryset):
return queryset.filter(project_id=self.team.project_id)
+ @extend_schema(responses={200: GroupTypeSerializer(many=True)})
+ def list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
+ # Served from the cached, personhog-routed helper instead of the persons DB
+ with personhog_caller_tag("groups/group-types-list"):
+ rows = get_group_types_for_project(self.team.project_id)
+ return response.Response([_group_type_row_to_response(row) for row in rows])
+
@action(detail=False, methods=["PATCH"], name="Update group types metadata")
def update_metadata(self, request: request.Request, *args, **kwargs):
for row in cast(list[dict], request.data):
@@ -265,8 +290,6 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
return group
def get_group_type_mapping_or_404(self, group_type_index: GroupTypeIndex) -> GroupTypeMappingResult:
- from posthog.models.group_type_mapping import get_group_types_for_project
-
for m in get_group_types_for_project(self.team.project_id):
if m["group_type_index"] == group_type_index:
return GroupTypeMappingResult(group_type=m["group_type"], group_type_index=m["group_type_index"])
diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.py
index b36cf4a3e2c2..45b999457b73 100644
--- a/ee/clickhouse/views/test/test_clickhouse_groups.py
+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py
@@ -1613,6 +1613,70 @@ class GroupsTypesViewSetTestCase(APIBaseTest):
cache.set(stale_cache_key, [{"stale": True}], 300)
return cache_key, stale_cache_key
+ def test_list_serves_from_group_types_cache(self):
+ # No GroupTypeMapping rows exist — a response can only come from the cached helper
+ cache_key = f"{GROUP_TYPES_CACHE_KEY_PREFIX}{self.team.project_id}"
+ cache.set(
+ cache_key,
+ [
+ {
+ "group_type": "organization",
+ "group_type_index": 0,
+ "name_singular": None,
+ "name_plural": None,
+ "detail_dashboard": 7,
+ "default_columns": ["name"],
+ "created_at": None,
+ }
+ ],
+ 300,
+ )
+
+ response = self.client.get(self.url)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json(),
+ [
+ {
+ "group_type": "organization",
+ "group_type_index": 0,
+ "name_singular": None,
+ "name_plural": None,
+ "detail_dashboard": 7,
+ "default_columns": ["name"],
+ "created_at": None,
+ }
+ ],
+ )
+
+ def test_list_normalizes_legacy_detail_dashboard_id_cache_key(self):
+ # Cache entries written before the personhog converter matched the ORM
+ # .values() shape carry "detail_dashboard_id" — the response must still
+ # expose "detail_dashboard"
+ cache_key = f"{GROUP_TYPES_CACHE_KEY_PREFIX}{self.team.project_id}"
+ cache.set(
+ cache_key,
+ [
+ {
+ "group_type": "organization",
+ "group_type_index": 0,
+ "name_singular": None,
+ "name_plural": None,
+ "detail_dashboard_id": 42,
+ "default_columns": None,
+ "created_at": None,
+ }
+ ],
+ 300,
+ )
+
+ response = self.client.get(self.url)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()[0]["detail_dashboard"], 42)
+ self.assertNotIn("detail_dashboard_id", response.json()[0])
+
def test_update_metadata_invalidates_cache(self):
GroupTypeMapping.objects.create(
team=self.team, project=self.project, group_type="organization", group_type_index=0
@@ -1625,8 +1689,9 @@ class GroupsTypesViewSetTestCase(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIsNone(cache.get(cache_key))
- self.assertIsNone(cache.get(stale_cache_key))
+ # update_metadata responds with the list, which re-populates both caches with fresh rows
+ self.assertEqual(cache.get(cache_key)[0]["name_singular"], "org")
+ self.assertEqual(cache.get(stale_cache_key)[0]["name_singular"], "org")
def test_destroy_invalidates_cache(self):
GroupTypeMapping.objects.create(
diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.py
index f8a7ee182734..5ed9ad2be295 100644
--- a/posthog/models/test/test_group_type_mapping.py
+++ b/posthog/models/test/test_group_type_mapping.py
@@ -1,3 +1,6 @@
+from datetime import UTC, datetime
+
+from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
@@ -8,6 +11,7 @@ from posthog.models.group_type_mapping import (
GROUP_TYPES_CACHE_KEY_PREFIX,
GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX,
GROUP_TYPES_STALE_CACHE_KEY_PREFIX,
+ GroupTypeMapping,
GroupTypesUnavailable,
_fetch_group_types_for_projects_via_personhog,
_record_group_types_fetch_failure,
@@ -22,8 +26,11 @@ from posthog.models.group_type_mapping import (
update_group_type_mapping_fields,
)
from posthog.person_db_router import PERSONS_DB_FOR_WRITE
+from posthog.personhog_client.fake_client import FakePersonHogClient
from posthog.utils import get_safe_cache, safe_cache_delete, safe_cache_set
+from products.dashboards.backend.models.dashboard import Dashboard
+
def _clear_cache(project_id: int) -> None:
safe_cache_delete(f"{GROUP_TYPES_CACHE_KEY_PREFIX}{project_id}")
@@ -36,7 +43,7 @@ PERSONHOG_SUCCESS_DATA = [
"group_type_index": 0,
"name_singular": "Organization",
"name_plural": "Organizations",
- "detail_dashboard_id": None,
+ "detail_dashboard": None,
"default_columns": ["name"],
"created_at": None,
},
@@ -45,7 +52,7 @@ PERSONHOG_SUCCESS_DATA = [
"group_type_index": 1,
"name_singular": None,
"name_plural": None,
- "detail_dashboard_id": None,
+ "detail_dashboard": None,
"default_columns": None,
"created_at": None,
},
@@ -57,7 +64,7 @@ ORM_DATA = [
"group_type_index": 0,
"name_singular": None,
"name_plural": None,
- "detail_dashboard_id": None,
+ "detail_dashboard": None,
"default_columns": None,
"created_at": None,
},
@@ -1323,3 +1330,71 @@ class TestProjectHasGroupTypesAuthoritatively(SimpleTestCase):
# A team adding its first group type must stop short-circuiting to False at once.
assert get_safe_cache(marker_key) is None
+
+
+class TestGroupTypesForProjectPathParity(BaseTest):
+ """The personhog and ORM paths of get_group_types_for_project must return identical rows.
+
+ The ORM path only runs as the fallback when personhog errors, so a shape or
+ value divergence would surface during incidents — compare the paths against
+ each other on the same data instead of against hand-written expectations.
+ Delete this test together with the ORM fallback.
+ """
+
+ def test_personhog_and_orm_paths_return_identical_rows(self):
+ # Exact-millisecond timestamp: the proto carries epoch ms, so a sub-ms
+ # value would diverge from the ORM no matter what the code does.
+ created_at = datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC)
+ dashboard = Dashboard.objects.create(team=self.team, name="orgs")
+
+ GroupTypeMapping.objects.create( # nosemgrep: no-direct-persons-db-orm
+ team=self.team,
+ project_id=self.team.project_id,
+ group_type="organization",
+ group_type_index=0,
+ name_singular="Organization",
+ name_plural="Organizations",
+ default_columns=["name"],
+ detail_dashboard=dashboard,
+ created_at=created_at,
+ )
+ minimal = GroupTypeMapping.objects.create( # nosemgrep: no-direct-persons-db-orm
+ team=self.team,
+ project_id=self.team.project_id,
+ group_type="company",
+ group_type_index=1,
+ )
+ # save() auto-fills created_at; NULL it to exercise the None case on both paths
+ GroupTypeMapping.objects.filter(pk=minimal.pk).update(created_at=None) # nosemgrep: no-direct-persons-db-orm
+
+ fake = FakePersonHogClient()
+ fake.add_group_type_mapping(
+ project_id=self.team.project_id,
+ team_id=self.team.id,
+ group_type="organization",
+ group_type_index=0,
+ name_singular="Organization",
+ name_plural="Organizations",
+ default_columns=["name"],
+ detail_dashboard_id=dashboard.id,
+ created_at=int(created_at.timestamp() * 1000),
+ )
+ fake.add_group_type_mapping(
+ project_id=self.team.project_id,
+ team_id=self.team.id,
+ group_type="company",
+ group_type_index=1,
+ )
+
+ with patch(_CLIENT_PATCH, return_value=fake):
+ _clear_cache(self.team.project_id)
+ personhog_rows = get_group_types_for_project(self.team.project_id)
+
+ with patch(_CLIENT_PATCH, return_value=None):
+ _clear_cache(self.team.project_id)
+ orm_rows = get_group_types_for_project(self.team.project_id)
+
+ # Guard against vacuous equality before comparing the paths
+ assert len(orm_rows) == 2
+ assert orm_rows[0]["detail_dashboard"] == dashboard.id
+ assert personhog_rows == orm_rows
diff --git a/posthog/personhog_client/converters.py b/posthog/personhog_client/converters.py
index 83dc85362e3e..94c96f162682 100644
--- a/posthog/personhog_client/converters.py
+++ b/posthog/personhog_client/converters.py
@@ -16,7 +16,8 @@ def proto_group_type_mapping_to_dict(mapping: group_pb2.GroupTypeMapping) -> dic
"""Convert a proto GroupTypeMapping to the same dict shape as
Django's GroupTypeMapping.objects.values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS).
- Django .values("detail_dashboard") on a ForeignKey produces key "detail_dashboard_id".
+ Django .values("detail_dashboard") aliases the FK column, so the key is
+ "detail_dashboard" (holding the dashboard id), not "detail_dashboard_id".
"""
default_columns: list[str] | None = None
if mapping.default_columns:
@@ -33,7 +34,7 @@ def proto_group_type_mapping_to_dict(mapping: group_pb2.GroupTypeMapping) -> dic
"group_type_index": mapping.group_type_index,
"name_singular": mapping.name_singular or None,
"name_plural": mapping.name_plural or None,
- "detail_dashboard_id": mapping.detail_dashboard_id or None,
+ "detail_dashboard": mapping.detail_dashboard_id or None,
"default_columns": default_columns,
"created_at": created_at,
}
diff --git a/posthog/personhog_client/test_converters.py b/posthog/personhog_client/test_converters.py
index bfa6f944ebe0..5e7e4a9fdb9f 100644
--- a/posthog/personhog_client/test_converters.py
+++ b/posthog/personhog_client/test_converters.py
@@ -55,7 +55,7 @@ class TestProtoGroupTypeMappingToDict:
"group_type_index": 0,
"name_singular": "Organization",
"name_plural": "Organizations",
- "detail_dashboard_id": 42,
+ "detail_dashboard": 42,
"default_columns": ["name", "industry"],
"created_at": datetime.fromtimestamp(1700000000, tz=UTC),
},
@@ -69,7 +69,7 @@ class TestProtoGroupTypeMappingToDict:
"group_type_index": 1,
"name_singular": None,
"name_plural": None,
- "detail_dashboard_id": None,
+ "detail_dashboard": None,
"default_columns": None,
"created_at": None,
},
@@ -90,7 +90,7 @@ class TestProtoGroupTypeMappingToDict:
"group_type_index": 2,
"name_singular": None,
"name_plural": None,
- "detail_dashboard_id": None,
+ "detail_dashboard": None,
"default_columns": None,
"created_at": None,
},
@@ -107,7 +107,7 @@ class TestProtoGroupTypeMappingToDict:
"group_type_index": 3,
"name_singular": None,
"name_plural": None,
- "detail_dashboard_id": None,
+ "detail_dashboard": None,
"default_columns": ["revenue", "size"],
"created_at": None,
},
@@ -336,14 +336,7 @@ class TestGroupTypeMappingDictKeysParity:
)
result = proto_group_type_mapping_to_dict(proto) # type: ignore[arg-type]
- expected_keys = set()
- for field in GROUP_TYPE_MAPPING_SERIALIZER_FIELDS:
- if field == "detail_dashboard":
- expected_keys.add("detail_dashboard_id")
- else:
- expected_keys.add(field)
-
- assert set(result.keys()) == expected_keys
+ assert set(result.keys()) == set(GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)
def test_converter_malformed_default_columns_raises(self):
proto = _make_proto_mapping(