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): group type moves to phog (#64169)

Nick Beste396625cc3bf
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.py
index bbb9a7bd9c56..935626ef81a0 100644
--- a/ee/clickhouse/views/groups.py
+++ b/ee/clickhouse/views/groups.py
@@ -37,12 +37,12 @@ from posthog.models.group_type_mapping import (
GROUP_TYPE_MAPPING_SERIALIZER_FIELDS,
GroupTypeMapping,
delete_group_type_mapping,
+ get_group_type_mapping_instance,
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
from posthog.utils import str_to_bool
@@ -140,33 +140,31 @@ def _group_type_row_to_response(row: dict[str, Any]) -> dict[str, Any]:
}
-class GroupsTypesViewSet(TeamAndOrgViewSetMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
+class GroupsTypesViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
scope_object = "group"
serializer_class = GroupTypeSerializer
- queryset = GroupTypeMapping.objects.all().order_by("group_type_index") # nosemgrep: no-direct-persons-db-orm
+ # DRF requires a queryset for model resolution, but all actions are overridden
+ # to read via personhog-routed helpers — this queryset is never evaluated.
+ queryset = GroupTypeMapping.objects.none() # nosemgrep: no-direct-persons-db-orm
pagination_class = None
sharing_enabled_actions = ["list"]
lookup_field = "group_type_index"
- filter_rewrite_rules = {"project_id": "project_id"}
-
- 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)
+ rows = get_group_types_for_project(self.team.project_id, caller_tag="groups/list")
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):
- instance = GroupTypeMapping.objects.get( # nosemgrep: no-direct-persons-db-orm
- project_id=self.team.project_id, group_type_index=row["group_type_index"]
+ instance = get_group_type_mapping_instance(
+ self.team.project_id,
+ row["group_type_index"],
+ team=self.team,
+ consistency="strong",
+ caller_tag="groups/update-metadata",
)
- # Pre-populate the team FK cache so serializer access control checks
- instance.team = self.team
serializer = self.get_serializer(instance, data=row)
serializer.is_valid(raise_exception=True)
fields: dict[str, Any] = {}
@@ -175,7 +173,7 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, mixins.DestroyModelMixin, views
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")
+ update_group_type_mapping_fields(instance, fields=fields, caller_tag="groups/update-metadata")
invalidate_group_types_cache(self.team.project_id)
return self.list(request, *args, **kwargs)
@@ -183,8 +181,12 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, mixins.DestroyModelMixin, views
@action(methods=["PUT"], detail=False)
def create_detail_dashboard(self, request: request.Request, **kw):
try:
- group_type_mapping = GroupTypeMapping.objects.get( # nosemgrep: no-direct-persons-db-orm
- project_id=self.team.project_id, group_type_index=request.data["group_type_index"]
+ group_type_mapping = get_group_type_mapping_instance(
+ self.team.project_id,
+ request.data["group_type_index"],
+ team=self.team,
+ consistency="strong",
+ caller_tag="groups/create-detail-dashboard",
)
except GroupTypeMapping.DoesNotExist:
raise NotFound(detail="Group type not found")
@@ -199,21 +201,36 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, mixins.DestroyModelMixin, views
update_group_type_mapping_fields(
group_type_mapping,
fields={"detail_dashboard_id": dashboard.id},
- operation="group_type_create_detail_dashboard",
+ caller_tag="groups/create-detail-dashboard",
)
- group_type_mapping.detail_dashboard_id = dashboard.id
invalidate_group_types_cache(self.team.project_id)
return response.Response(self.get_serializer(group_type_mapping).data)
- def perform_destroy(self, instance):
- delete_group_type_mapping(instance)
+ def destroy(self, request: request.Request, *args, **kwargs):
+ group_type_index = int(kwargs[self.lookup_field])
+ try:
+ instance = get_group_type_mapping_instance(
+ self.team.project_id,
+ group_type_index,
+ team=self.team,
+ consistency="strong",
+ caller_tag="groups/destroy",
+ )
+ except GroupTypeMapping.DoesNotExist:
+ raise NotFound(detail="Group type not found")
+ delete_group_type_mapping(instance, caller_tag="groups/destroy")
invalidate_group_types_cache(self.team.project_id)
+ return response.Response(status=status.HTTP_204_NO_CONTENT)
@action(methods=["PUT"], detail=False)
def set_default_columns(self, request: request.Request, **kw):
try:
- group_type_mapping = GroupTypeMapping.objects.get( # nosemgrep: no-direct-persons-db-orm
- project_id=self.team.project_id, group_type_index=request.data["group_type_index"]
+ group_type_mapping = get_group_type_mapping_instance(
+ self.team.project_id,
+ request.data["group_type_index"],
+ team=self.team,
+ consistency="strong",
+ caller_tag="groups/set-default-columns",
)
except GroupTypeMapping.DoesNotExist:
raise NotFound(detail="Group type not found")
@@ -221,9 +238,8 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, mixins.DestroyModelMixin, views
update_group_type_mapping_fields(
group_type_mapping,
fields={"default_columns": request.data["default_columns"]},
- operation="group_type_set_default_columns",
+ caller_tag="groups/set-default-columns",
)
- group_type_mapping.default_columns = request.data["default_columns"]
invalidate_group_types_cache(self.team.project_id)
return response.Response(self.get_serializer(group_type_mapping).data)
@@ -296,7 +312,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
return group
def get_group_type_mapping_or_404(self, group_type_index: GroupTypeIndex) -> GroupTypeMappingResult:
- for m in get_group_types_for_project(self.team.project_id):
+ for m in get_group_types_for_project(self.team.project_id, caller_tag="groups/group-type-lookup"):
if m["group_type_index"] == group_type_index:
return GroupTypeMappingResult(group_type=m["group_type"], group_type_index=m["group_type_index"])
raise NotFound()
diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.py
index 477271c1bbd2..3c7e54844859 100644
--- a/ee/clickhouse/views/test/test_clickhouse_groups.py
+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py
@@ -1616,6 +1616,11 @@ class GroupsTypesViewSetTestCase(APIBaseTest):
self.assertEqual(list_response.status_code, status.HTTP_200_OK)
self.assertEqual(len(list_response.json()), 0)
+ def test_delete_nonexistent(self):
+ response = self.client.delete(self.url + "/99")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
def test_create_detail_dashboard(self):
GroupTypeMapping.objects.create(
team=self.team, project=self.project, group_type="organization", group_type_index=0
@@ -1630,11 +1635,20 @@ class GroupsTypesViewSetTestCase(APIBaseTest):
self.assertIsNotNone(data["detail_dashboard"])
def _seed_cache(self):
- """Populate both cache keys so we can verify invalidation clears both."""
+ """Populate both cache keys with well-formed but stale data so we can verify invalidation."""
cache_key = f"{GROUP_TYPES_CACHE_KEY_PREFIX}{self.team.project_id}"
stale_cache_key = f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{self.team.project_id}"
- cache.set(cache_key, [{"stale": True}], 300)
- cache.set(stale_cache_key, [{"stale": True}], 300)
+ stale_row = {
+ "group_type": "organization",
+ "group_type_index": 0,
+ "name_singular": None,
+ "name_plural": None,
+ "detail_dashboard": None,
+ "default_columns": None,
+ "created_at": None,
+ }
+ cache.set(cache_key, [stale_row], 300)
+ cache.set(stale_cache_key, [stale_row], 300)
return cache_key, stale_cache_key
def test_list_serves_from_group_types_cache(self):
diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.py
index eccdcf95d76a..31ec428af5f0 100644
--- a/posthog/models/group_type_mapping.py
+++ b/posthog/models/group_type_mapping.py
@@ -1,9 +1,11 @@
from __future__ import annotations
import json
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, TypeVar
if TYPE_CHECKING:
+ from collections.abc import Callable
+
from posthog.models.project import Project
from posthog.models.team.team import Team
from posthog.personhog_client.client import PersonHogClient
@@ -19,6 +21,8 @@ from prometheus_client import Counter
from posthog.models.utils import RootTeamMixin
from posthog.person_db_router import PERSONS_DB_FOR_WRITE
+from posthog.personhog_client import ReadConsistency, consistency_to_read_options
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name
from posthog.rbac.decorators import field_access_control
from posthog.storage.hypercache import HyperCacheDependencyUnavailable
@@ -26,6 +30,8 @@ from posthog.utils import capture_exception_throttled, get_safe_cache, safe_cach
logger = structlog.get_logger(__name__)
+_T = TypeVar("_T")
+
GROUP_TYPES_CACHE_TTL = 60 * 5 # 5 minutes
GROUP_TYPES_STALE_CACHE_TTL = 60 * 60 * 24 # 24 hours — last-known-good fallback during outages
GROUP_TYPES_NEGATIVE_CACHE_TTL = 30 # seconds — short so we detect DB recovery quickly
@@ -84,6 +90,44 @@ def _record_group_types_fetch_failure(*, operation: str, log_event: str, exc: Ba
)
+def _personhog_routed(
+ operation: str,
+ personhog_fn: Callable[[PersonHogClient], _T],
+ orm_fn: Callable[[], _T],
+ *,
+ caller_tag: str | None = None,
+ **log_fields: Any,
+) -> _T:
+ """Try personhog first, fall back to ORM on failure or when disabled.
+
+ ``operation`` is the RPC being performed (used in metrics).
+ ``caller_tag`` is the granular calling context (used in personhog caller
+ tagging for observability). Defaults to ``operation`` when not given.
+
+ ORM exceptions are NOT caught — callers handle their own DatabaseError
+ recovery (stale cache, fail-closed, etc.).
+ """
+ from posthog.personhog_client.client import get_personhog_client
+
+ tag = caller_tag or operation
+
+ client = get_personhog_client()
+ if client is not None:
+ try:
+ with personhog_caller_tag(f"group_type_mapping/{tag}"):
+ result = personhog_fn(client)
+ PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="personhog", client_name=get_client_name()).inc()
+ return result
+ except Exception:
+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
+ operation=operation, source="personhog", error_type="grpc_error", client_name=get_client_name()
+ ).inc()
+ logger.warning("personhog_%s_failure", operation, **log_fields, exc_info=True)
+
+ PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="django_orm", client_name=get_client_name()).inc()
+ return orm_fn()
+
+
# Defined here for reuse between OS and EE
GROUP_TYPE_MAPPING_SERIALIZER_FIELDS = [
"group_type",
@@ -178,10 +222,8 @@ def _fetch_group_types_via_personhog(client: PersonHogClient, project_id: int) -
return result
-def get_group_types_for_project(project_id: int) -> list[dict[str, Any]]:
+def get_group_types_for_project(project_id: int, *, caller_tag: str | None = None) -> list[dict[str, Any]]:
"""Fetch group types from cache, falling back to personhog then ORM, then stale cache, then empty list."""
- from posthog.personhog_client.client import get_personhog_client
-
cache_key = f"{GROUP_TYPES_CACHE_KEY_PREFIX}{project_id}"
stale_cache_key = f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{project_id}"
@@ -189,37 +231,18 @@ def get_group_types_for_project(project_id: int) -> list[dict[str, Any]]:
if cached is not None:
return cached
- client = get_personhog_client()
- if client is not None:
- try:
- result = _fetch_group_types_via_personhog(client, project_id)
- PERSONHOG_ROUTING_TOTAL.labels(
- operation="get_group_types_for_project", source="personhog", client_name=get_client_name()
- ).inc()
- safe_cache_set(cache_key, result, GROUP_TYPES_CACHE_TTL)
- _write_project_stale_if_non_empty(project_id, result)
- return result
- except Exception:
- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
- operation="get_group_types_for_project",
- source="personhog",
- error_type="grpc_error",
- client_name=get_client_name(),
- ).inc()
- logger.warning("personhog_group_types_failure", project_id=project_id, exc_info=True)
-
try:
- result = list(
- GroupTypeMapping.objects.filter(project_id=project_id) # nosemgrep: no-direct-persons-db-orm
- .order_by("group_type_index")
- .values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)
+ result = _personhog_routed(
+ "get_group_types_for_project",
+ lambda client: _fetch_group_types_via_personhog(client, project_id),
+ lambda: list(
+ GroupTypeMapping.objects.filter(project_id=project_id) # nosemgrep: no-direct-persons-db-orm
+ .order_by("group_type_index")
+ .values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)
+ ),
+ caller_tag=caller_tag,
+ project_id=project_id,
)
- PERSONHOG_ROUTING_TOTAL.labels(
- operation="get_group_types_for_project", source="django_orm", client_name=get_client_name()
- ).inc()
- safe_cache_set(cache_key, result, GROUP_TYPES_CACHE_TTL)
- _write_project_stale_if_non_empty(project_id, result)
- return result
except DatabaseError as exc:
_record_group_types_fetch_failure(
operation="get_group_types_for_project",
@@ -234,6 +257,10 @@ def get_group_types_for_project(project_id: int) -> list[dict[str, Any]]:
safe_cache_set(cache_key, [], GROUP_TYPES_NEGATIVE_CACHE_TTL)
return []
+ safe_cache_set(cache_key, result, GROUP_TYPES_CACHE_TTL)
+ _write_project_stale_if_non_empty(project_id, result)
+ return result
+
def _fetch_group_types_for_team_via_personhog(client: PersonHogClient, team_id: int) -> list[dict[str, Any]]:
from posthog.personhog_client.converters import proto_group_type_mapping_to_dict
@@ -245,35 +272,19 @@ def _fetch_group_types_for_team_via_personhog(client: PersonHogClient, team_id:
return result
-def get_group_types_for_team(team_id: int) -> list[dict[str, Any]]:
+def get_group_types_for_team(team_id: int, *, caller_tag: str | None = None) -> list[dict[str, Any]]:
"""Fetch group types for a team via personhog, falling back to ORM on error."""
- from posthog.personhog_client.client import get_personhog_client
-
- client = get_personhog_client()
- if client is not None:
- try:
- result = _fetch_group_types_for_team_via_personhog(client, team_id)
- PERSONHOG_ROUTING_TOTAL.labels(
- operation="get_group_types_for_team", source="personhog", client_name=get_client_name()
- ).inc()
- return result
- except Exception:
- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
- operation="get_group_types_for_team",
- source="personhog",
- error_type="grpc_error",
- client_name=get_client_name(),
- ).inc()
- logger.warning("personhog_group_types_for_team_failure", team_id=team_id, exc_info=True)
-
- PERSONHOG_ROUTING_TOTAL.labels(
- operation="get_group_types_for_team", source="django_orm", client_name=get_client_name()
- ).inc()
try:
- return list(
- GroupTypeMapping.objects.filter(team_id=team_id) # nosemgrep: no-direct-persons-db-orm
- .order_by("group_type_index")
- .values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)
+ return _personhog_routed(
+ "get_group_types_for_team",
+ lambda client: _fetch_group_types_for_team_via_personhog(client, team_id),
+ lambda: list(
+ GroupTypeMapping.objects.filter(team_id=team_id) # nosemgrep: no-direct-persons-db-orm
+ .order_by("group_type_index")
+ .values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)
+ ),
+ caller_tag=caller_tag,
+ team_id=team_id,
)
except DatabaseError as exc:
_record_group_types_fetch_failure(
@@ -382,7 +393,9 @@ def _recover_projects_from_stale_or_fail(project_ids: list[int], exc: DatabaseEr
return recovered
-def get_group_types_for_projects(project_ids: list[int]) -> dict[int, list[dict[str, Any]]]:
+def get_group_types_for_projects(
+ project_ids: list[int], *, caller_tag: str | None = None
+) -> dict[int, list[dict[str, Any]]]:
"""Batch fetch group types for multiple projects via personhog, falling back to
ORM, then to the per-project stale cache on a DB failure.
@@ -390,33 +403,15 @@ def get_group_types_for_projects(project_ids: list[int]) -> dict[int, list[dict[
project has no cached last-known-good, rather than returning an all-empty
mapping. Callers must handle that case.
"""
- from posthog.personhog_client.client import get_personhog_client
- client = get_personhog_client()
- if client is not None:
- try:
- result = _fetch_group_types_for_projects_via_personhog(client, project_ids)
- for pid in project_ids:
- result.setdefault(pid, [])
- PERSONHOG_ROUTING_TOTAL.labels(
- operation="get_group_types_for_projects", source="personhog", client_name=get_client_name()
- ).inc()
- _populate_projects_stale_cache(result)
- return result
- except Exception:
- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
- operation="get_group_types_for_projects",
- source="personhog",
- error_type="grpc_error",
- client_name=get_client_name(),
- ).inc()
- logger.warning("personhog_group_types_for_projects_failure", project_ids=project_ids, exc_info=True)
+ def _personhog_fn(client: PersonHogClient) -> dict[int, list[dict[str, Any]]]:
+ result = _fetch_group_types_for_projects_via_personhog(client, project_ids)
+ for pid in project_ids:
+ result.setdefault(pid, [])
+ return result
- PERSONHOG_ROUTING_TOTAL.labels(
- operation="get_group_types_for_projects", source="django_orm", client_name=get_client_name()
- ).inc()
- result = {pid: [] for pid in project_ids}
- try:
+ def _orm_fn() -> dict[int, list[dict[str, Any]]]:
+ result: dict[int, list[dict[str, Any]]] = {pid: [] for pid in project_ids}
for row in (
GroupTypeMapping.objects.filter(project_id__in=project_ids) # nosemgrep: no-direct-persons-db-orm
.order_by("group_type_index")
@@ -424,6 +419,12 @@ def get_group_types_for_projects(project_ids: list[int]) -> dict[int, list[dict[
):
pid = row.pop("project_id")
result.setdefault(pid, []).append(row)
+ return result
+
+ try:
+ result = _personhog_routed(
+ "get_group_types_for_projects", _personhog_fn, _orm_fn, caller_tag=caller_tag, project_ids=project_ids
+ )
except DatabaseError as exc:
return _recover_projects_from_stale_or_fail(project_ids, exc)
@@ -431,36 +432,23 @@ def get_group_types_for_projects(project_ids: list[int]) -> dict[int, list[dict[
return result
-def count_group_type_mappings_per_team() -> list[dict[str, int]]:
+def count_group_type_mappings_per_team(*, caller_tag: str | None = None) -> list[dict[str, int]]:
"""Count group type mappings per team via personhog, falling back to ORM."""
- from posthog.personhog_client.client import get_personhog_client
from posthog.personhog_client.proto import CountGroupTypeMappingsRequest
- client = get_personhog_client()
- if client is not None:
- try:
- resp = client.count_group_type_mappings(CountGroupTypeMappingsRequest())
- PERSONHOG_ROUTING_TOTAL.labels(
- operation="count_group_type_mappings_per_team", source="personhog", client_name=get_client_name()
- ).inc()
- return [{"team_id": c.team_id, "total": c.count} for c in resp.counts]
- except Exception:
- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
- operation="count_group_type_mappings_per_team",
- source="personhog",
- error_type="grpc_error",
- client_name=get_client_name(),
- ).inc()
- logger.warning("personhog_count_group_type_mappings_failure", exc_info=True)
-
- PERSONHOG_ROUTING_TOTAL.labels(
- operation="count_group_type_mappings_per_team", source="django_orm", client_name=get_client_name()
- ).inc()
try:
- return list(
- GroupTypeMapping.objects.values("team_id") # nosemgrep: no-direct-persons-db-orm
- .annotate(total=Count("id"))
- .order_by("team_id") # nosemgrep: no-direct-persons-db-orm
+ return _personhog_routed(
+ "count_group_type_mappings_per_team",
+ lambda client: [
+ {"team_id": c.team_id, "total": c.count}
+ for c in client.count_group_type_mappings(CountGroupTypeMappingsRequest()).counts
+ ],
+ lambda: list(
+ GroupTypeMapping.objects.values("team_id") # nosemgrep: no-direct-persons-db-orm
+ .annotate(total=Count("id"))
+ .order_by("team_id") # nosemgrep: no-direct-persons-db-orm
+ ),
+ caller_tag=caller_tag,
)
except DatabaseError:
logger.warning("count_group_type_mappings_orm_failure", exc_info=True)
@@ -468,18 +456,16 @@ def count_group_type_mappings_per_team() -> list[dict[str, int]]:
def project_has_group_types_authoritatively(project_id: int) -> bool:
- """True if the project has group types per the persons-DB primary, or if that
+ """True if the project has group types per a strong-consistency read, or if that
cannot be confirmed (fail closed).
The local-eval empty-mapping guard uses this when its cheap last-known-good signal
(the per-project stale key) is absent, so a write that would empty a populated
mapping is only allowed when the project is *confirmed* to have no group types.
- Reads the primary (PERSONS_DB_FOR_WRITE) on purpose: the normal fetch already
- returned the suspect empty (possibly from personhog or a lagging replica), so this
- independent check must hit the source of truth rather than route through personhog
- again. On a DB error it returns True — the caller must not treat an unconfirmable
- state as safe to empty.
+ Uses _fetch_group_types_for_project_direct with "strong" consistency so the read
+ hits the primary, not a lagging replica. On any error it returns True — the caller
+ must not treat an unconfirmable state as safe to empty.
A short-lived "confirmed empty" marker caches the authoritative False so a team
that has never had group types — the common case, where this fires on every
@@ -490,27 +476,135 @@ def project_has_group_types_authoritatively(project_id: int) -> bool:
confirmed_empty_key = f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{project_id}"
if get_safe_cache(confirmed_empty_key):
return False
+
try:
has_group_types = (
- GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE) # nosemgrep: no-direct-persons-db-orm
- .filter(project_id=project_id)
- .exists()
+ len(_fetch_group_types_for_project_direct(project_id, "strong", caller_tag="flags/has-group-types")) > 0
)
except DatabaseError:
logger.warning("group_types_primary_confirmation_failed", project_id=project_id, exc_info=True)
return True
+
if not has_group_types:
- # Only cache the negative. A True must keep hitting the DB so a later deletion
- # is seen promptly, and the DB-error branch above must never be cached.
safe_cache_set(confirmed_empty_key, True, GROUP_TYPES_CONFIRMED_EMPTY_CACHE_TTL)
return has_group_types
+def _dict_to_group_type_mapping_model(
+ row: dict[str, Any],
+ *,
+ project_id: int,
+ team: Team | None = None,
+) -> GroupTypeMapping:
+ """Build an unsaved GroupTypeMapping from a get_group_types_for_project dict.
+
+ The instance is NOT database-backed — it carries data in memory so serializers
+ and attribute access work without a round-trip. Mark _state.adding = False so
+ Django treats it as "existing" for serializer context, but note that save() will
+ not work — writes go through update_group_type_mapping_fields instead.
+ """
+ detail_dashboard_id = row.get("detail_dashboard", row.get("detail_dashboard_id"))
+ obj = GroupTypeMapping(
+ project_id=project_id,
+ team=team,
+ 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_id=detail_dashboard_id,
+ default_columns=row.get("default_columns"),
+ created_at=row.get("created_at"),
+ )
+ obj._state.adding = False
+ return obj
+
+
+def _fetch_group_types_for_project_direct(
+ project_id: int,
+ consistency: ReadConsistency,
+ *,
+ caller_tag: str | None = None,
+) -> list[dict[str, Any]]:
+ """Cache-bypassing read at the requested consistency level."""
+ from posthog.personhog_client.converters import proto_group_type_mapping_to_dict
+ from posthog.personhog_client.proto import GetGroupTypeMappingsByProjectIdRequest
+
+ db_alias = PERSONS_DB_FOR_WRITE if consistency == "strong" else "default"
+
+ return _personhog_routed(
+ "get_group_types_for_project_direct",
+ lambda client: sorted(
+ [
+ proto_group_type_mapping_to_dict(m)
+ for m in client.get_group_type_mappings_by_project_id(
+ GetGroupTypeMappingsByProjectIdRequest(
+ project_id=project_id,
+ read_options=consistency_to_read_options(consistency),
+ )
+ ).mappings
+ ],
+ key=lambda d: d["group_type_index"],
+ ),
+ lambda: list(
+ GroupTypeMapping.objects.using(db_alias) # nosemgrep: no-direct-persons-db-orm
+ .filter(project_id=project_id)
+ .order_by("group_type_index")
+ .values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)
+ ),
+ caller_tag=caller_tag,
+ project_id=project_id,
+ )
+
+
+def get_group_type_mapping_instance(
+ project_id: int,
+ group_type_index: int,
+ *,
+ team: Team | None = None,
+ consistency: ReadConsistency | None = None,
+ caller_tag: str | None = None,
+) -> GroupTypeMapping:
+ """Fetch a single GroupTypeMapping by (project_id, group_type_index) via personhog.
+
+ When consistency is None (default), uses the cached get_group_types_for_project
+ helper. If the mapping isn't in the cached results, invalidates the cache and
+ retries once before raising GroupTypeMapping.DoesNotExist.
+
+ When consistency is set (e.g. "strong"), skips the cache and does a direct read
+ at the requested consistency level — use "strong" before writes to avoid acting
+ on stale data.
+ """
+ if consistency is not None:
+ rows = _fetch_group_types_for_project_direct(project_id, consistency, caller_tag=caller_tag)
+ for row in rows:
+ if row["group_type_index"] == group_type_index:
+ return _dict_to_group_type_mapping_model(row, project_id=project_id, team=team)
+ raise GroupTypeMapping.DoesNotExist(
+ f"GroupTypeMapping matching query does not exist: project_id={project_id}, group_type_index={group_type_index}"
+ )
+
+ rows = get_group_types_for_project(project_id, caller_tag=caller_tag)
+ for row in rows:
+ if row["group_type_index"] == group_type_index:
+ return _dict_to_group_type_mapping_model(row, project_id=project_id, team=team)
+
+ # Cache may be stale — bust it and retry once via the full personhog/ORM chain.
+ invalidate_group_types_cache(project_id)
+ rows = get_group_types_for_project(project_id, caller_tag=caller_tag)
+ for row in rows:
+ if row["group_type_index"] == group_type_index:
+ return _dict_to_group_type_mapping_model(row, project_id=project_id, team=team)
+
+ raise GroupTypeMapping.DoesNotExist(
+ f"GroupTypeMapping matching query does not exist: project_id={project_id}, group_type_index={group_type_index}"
+ )
+
+
def update_group_type_mapping_fields(
instance: GroupTypeMapping,
*,
fields: dict[str, Any],
- operation: str = "group_type_update",
+ caller_tag: str | None = None,
) -> None:
"""Update specific fields on a GroupTypeMapping via personhog, falling back to ORM.
@@ -518,139 +612,105 @@ def update_group_type_mapping_fields(
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()
+ def _personhog_fn(client: PersonHogClient) -> None:
+ 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))
+
+ def _orm_fn() -> None:
+ GroupTypeMapping.objects.filter( # nosemgrep: no-direct-persons-db-orm
+ project_id=instance.project_id,
+ group_type_index=instance.group_type_index,
+ ).update(**fields)
+
+ _personhog_routed(
+ "update_group_type_mapping_fields",
+ _personhog_fn,
+ _orm_fn,
+ caller_tag=caller_tag,
+ project_id=instance.project_id,
+ group_type_index=instance.group_type_index,
+ )
for field_name, value in fields.items():
setattr(instance, field_name, value)
- instance.save()
-def delete_group_type_mapping(instance: GroupTypeMapping) -> None:
+def delete_group_type_mapping(instance: GroupTypeMapping, *, caller_tag: str | None = None) -> 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",
+ _personhog_routed(
+ "delete_group_type_mapping",
+ lambda client: client.delete_group_type_mapping(
+ DeleteGroupTypeMappingRequest(
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()
+ ),
+ lambda: GroupTypeMapping.objects.filter( # nosemgrep: no-direct-persons-db-orm
+ project_id=instance.project_id,
+ group_type_index=instance.group_type_index,
+ ).delete(),
+ caller_tag=caller_tag,
+ project_id=instance.project_id,
+ group_type_index=instance.group_type_index,
+ )
-def clear_dashboard_from_group_type_mapping(team_id: int, dashboard_id: int, project_id: int | None = None) -> None:
+def clear_dashboard_from_group_type_mapping(
+ team_id: int, dashboard_id: int, project_id: int | None = None, *, caller_tag: str | 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"],
- )
+ def _personhog_fn(client: PersonHogClient) -> None:
+ 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,
)
+ invalidate_group_types_cache(resp.mapping.project_id)
- 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
+ def _orm_fn() -> None:
+ 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)
+
+ _personhog_routed(
+ "clear_dashboard_from_group_type_mapping",
+ _personhog_fn,
+ _orm_fn,
+ caller_tag=caller_tag,
+ team_id=team_id,
+ dashboard_id=dashboard_id,
)
- if project_id is not None:
- invalidate_group_types_cache(project_id)
diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.py
index 5ed9ad2be295..43eece14583c 100644
--- a/posthog/models/test/test_group_type_mapping.py
+++ b/posthog/models/test/test_group_type_mapping.py
@@ -13,11 +13,13 @@ from posthog.models.group_type_mapping import (
GROUP_TYPES_STALE_CACHE_KEY_PREFIX,
GroupTypeMapping,
GroupTypesUnavailable,
+ _dict_to_group_type_mapping_model,
_fetch_group_types_for_projects_via_personhog,
_record_group_types_fetch_failure,
clear_dashboard_from_group_type_mapping,
count_group_type_mappings_per_team,
delete_group_type_mapping,
+ get_group_type_mapping_instance,
get_group_types_for_project,
get_group_types_for_projects,
get_group_types_for_team,
@@ -25,7 +27,6 @@ from posthog.models.group_type_mapping import (
project_has_group_types_authoritatively,
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
@@ -788,13 +789,22 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):
instance.group_type_index = 0
return instance
+ def _mock_objects_filter(self):
+ """Patch GroupTypeMapping.objects.filter so the ORM fallback doesn't hit a real DB."""
+ patcher = patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
+ mock_objects = patcher.start()
+ self.addCleanup(patcher.stop)
+ return mock_objects
+
@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):
+ def test_personhog_success_does_not_call_orm(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
+ mock_objects = self._mock_objects_filter()
+
instance = self._make_instance()
update_group_type_mapping_fields(instance, fields={"name_singular": "Org", "name_plural": "Orgs"})
@@ -805,22 +815,24 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):
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_objects.filter.assert_not_called()
mock_routing_counter.labels.assert_called_with(
- operation="group_type_update", source="personhog", client_name="posthog-django"
+ operation="update_group_type_mapping_fields", 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):
+ def test_client_none_falls_back_to_orm_update(self, mock_get_client, mock_routing_counter):
mock_get_client.return_value = None
+ mock_objects = self._mock_objects_filter()
instance = self._make_instance()
update_group_type_mapping_fields(instance, fields={"name_singular": "Org"})
- instance.save.assert_called_once()
+ mock_objects.filter.assert_called_once_with(project_id=1, group_type_index=0)
+ mock_objects.filter.return_value.update.assert_called_once_with(name_singular="Org")
mock_routing_counter.labels.assert_called_with(
- operation="group_type_update", source="django_orm", client_name="posthog-django"
+ operation="update_group_type_mapping_fields", source="django_orm", client_name="posthog-django"
)
@parameterized.expand(
@@ -839,12 +851,15 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):
mock_client.update_group_type_mapping.side_effect = exception
mock_get_client.return_value = mock_client
+ mock_objects = self._mock_objects_filter()
+
instance = self._make_instance()
update_group_type_mapping_fields(instance, fields={"name_singular": "Org"})
- instance.save.assert_called_once()
+ mock_objects.filter.assert_called_once_with(project_id=1, group_type_index=0)
+ mock_objects.filter.return_value.update.assert_called_once_with(name_singular="Org")
mock_errors_counter.labels.assert_called_once_with(
- operation="group_type_update",
+ operation="update_group_type_mapping_fields",
source="personhog",
error_type="grpc_error",
client_name="posthog-django",
@@ -854,13 +869,13 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):
@patch(_CLIENT_PATCH)
def test_orm_fallback_sets_fields_on_instance(self, mock_get_client, mock_routing_counter):
mock_get_client.return_value = None
+ self._mock_objects_filter()
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)
@@ -931,24 +946,27 @@ class TestDeleteGroupTypeMapping(SimpleTestCase):
operation="delete_group_type_mapping", source="personhog", client_name="posthog-django"
)
+ @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_delete(self, mock_get_client, mock_routing_counter):
+ def test_client_none_falls_back_to_orm_delete(self, mock_get_client, mock_routing_counter, mock_objects):
mock_get_client.return_value = None
instance = self._make_instance()
delete_group_type_mapping(instance)
- instance.delete.assert_called_once()
+ mock_objects.filter.assert_called_once_with(project_id=1, group_type_index=0)
+ mock_objects.filter.return_value.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.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_delete(
- self, mock_get_client, mock_routing_counter, mock_errors_counter
+ self, mock_get_client, mock_routing_counter, mock_errors_counter, mock_objects
):
mock_client = MagicMock()
mock_client.delete_group_type_mapping.side_effect = RuntimeError("grpc timeout")
@@ -957,7 +975,8 @@ class TestDeleteGroupTypeMapping(SimpleTestCase):
instance = self._make_instance()
delete_group_type_mapping(instance)
- instance.delete.assert_called_once()
+ mock_objects.filter.assert_called_once_with(project_id=1, group_type_index=0)
+ mock_objects.filter.return_value.delete.assert_called_once()
mock_errors_counter.labels.assert_called_once()
@@ -1266,6 +1285,16 @@ class TestRecordGroupTypesFetchFailureThrottle(SimpleTestCase):
class TestProjectHasGroupTypesAuthoritatively(SimpleTestCase):
_PROJECT_IDS = (123, 777, 888)
+ _DIRECT_PATCH = "posthog.models.group_type_mapping._fetch_group_types_for_project_direct"
+ _SAMPLE_ROW = {
+ "group_type": "organization",
+ "group_type_index": 0,
+ "name_singular": None,
+ "name_plural": None,
+ "detail_dashboard": None,
+ "default_columns": None,
+ "created_at": None,
+ }
def setUp(self):
self._clear_markers()
@@ -1277,50 +1306,42 @@ class TestProjectHasGroupTypesAuthoritatively(SimpleTestCase):
for project_id in self._PROJECT_IDS:
safe_cache_delete(f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{project_id}")
- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
- def test_returns_true_when_rows_exist(self, mock_objects):
- mock_objects.using.return_value.filter.return_value.exists.return_value = True
+ @patch(_DIRECT_PATCH)
+ def test_returns_true_when_rows_exist(self, mock_fetch):
+ mock_fetch.return_value = [self._SAMPLE_ROW]
assert project_has_group_types_authoritatively(123) is True
- # Reads the primary, not a replica, so a lagging read cannot fake a deletion.
- mock_objects.using.assert_called_once_with(PERSONS_DB_FOR_WRITE)
- mock_objects.using.return_value.filter.assert_called_once_with(project_id=123)
+ mock_fetch.assert_called_once_with(123, "strong", caller_tag="flags/has-group-types")
- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
- def test_returns_false_when_no_rows(self, mock_objects):
- mock_objects.using.return_value.filter.return_value.exists.return_value = False
+ @patch(_DIRECT_PATCH)
+ def test_returns_false_when_no_rows(self, mock_fetch):
+ mock_fetch.return_value = []
assert project_has_group_types_authoritatively(123) is False
- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
- def test_fails_closed_on_db_error(self, mock_objects):
+ @patch(_DIRECT_PATCH)
+ def test_fails_closed_on_db_error(self, mock_fetch):
from django.db import DatabaseError
- mock_objects.using.return_value.filter.return_value.exists.side_effect = DatabaseError("db down")
+ mock_fetch.side_effect = DatabaseError("db down")
- # Cannot confirm absence → assume present so the caller keeps the existing entry.
assert project_has_group_types_authoritatively(123) is True
- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
- def test_confirmed_empty_marker_short_circuits_second_call(self, mock_objects):
- exists_mock = mock_objects.using.return_value.filter.return_value.exists
- exists_mock.return_value = False
+ @patch(_DIRECT_PATCH)
+ def test_confirmed_empty_marker_short_circuits_second_call(self, mock_fetch):
+ mock_fetch.return_value = []
- # First call confirms empty against the DB and caches the marker.
assert project_has_group_types_authoritatively(777) is False
- # Second call reads the marker instead of probing the writer DB again.
assert project_has_group_types_authoritatively(777) is False
- exists_mock.assert_called_once()
+ mock_fetch.assert_called_once()
- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
- def test_present_result_is_not_cached(self, mock_objects):
- exists_mock = mock_objects.using.return_value.filter.return_value.exists
- exists_mock.return_value = True
+ @patch(_DIRECT_PATCH)
+ def test_present_result_is_not_cached(self, mock_fetch):
+ mock_fetch.return_value = [self._SAMPLE_ROW]
- # A True is never cached, so a later deletion is seen on the next call.
assert project_has_group_types_authoritatively(777) is True
assert project_has_group_types_authoritatively(777) is True
- assert exists_mock.call_count == 2
+ assert mock_fetch.call_count == 2
def test_invalidate_group_types_cache_clears_confirmed_empty_marker(self):
marker_key = f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}888"
@@ -1328,7 +1349,6 @@ class TestProjectHasGroupTypesAuthoritatively(SimpleTestCase):
invalidate_group_types_cache(888)
- # A team adding its first group type must stop short-circuiting to False at once.
assert get_safe_cache(marker_key) is None
@@ -1398,3 +1418,146 @@ class TestGroupTypesForProjectPathParity(BaseTest):
assert len(orm_rows) == 2
assert orm_rows[0]["detail_dashboard"] == dashboard.id
assert personhog_rows == orm_rows
+
+
+class TestDictToGroupTypeMappingModel(SimpleTestCase):
+ def test_builds_model_from_full_dict(self):
+ row = {
+ "group_type": "organization",
+ "group_type_index": 0,
+ "name_singular": "Organization",
+ "name_plural": "Organizations",
+ "detail_dashboard": 42,
+ "default_columns": ["name"],
+ "created_at": None,
+ }
+ obj = _dict_to_group_type_mapping_model(row, project_id=99)
+
+ assert obj.project_id == 99
+ assert obj.group_type == "organization"
+ assert obj.group_type_index == 0
+ assert obj.name_singular == "Organization"
+ assert obj.name_plural == "Organizations"
+ assert obj.detail_dashboard_id == 42
+ assert obj.default_columns == ["name"]
+ assert obj._state.adding is False
+
+ def test_builds_model_from_minimal_dict(self):
+ row = {"group_type": "company", "group_type_index": 1}
+ obj = _dict_to_group_type_mapping_model(row, project_id=99)
+
+ assert obj.group_type == "company"
+ assert obj.group_type_index == 1
+ assert obj.name_singular is None
+ assert obj.name_plural is None
+ assert obj.detail_dashboard_id is None
+ assert obj.default_columns is None
+ assert obj._state.adding is False
+
+ def test_accepts_detail_dashboard_id_key(self):
+ row = {"group_type": "org", "group_type_index": 0, "detail_dashboard_id": 7}
+ obj = _dict_to_group_type_mapping_model(row, project_id=99)
+
+ assert obj.detail_dashboard_id == 7
+
+ def test_team_none_by_default(self):
+ row = {"group_type": "org", "group_type_index": 0}
+ obj = _dict_to_group_type_mapping_model(row, project_id=99)
+
+ assert obj.team_id is None
+
+
+class TestGetGroupTypeMappingInstance(SimpleTestCase):
+ def setUp(self):
+ self.project_id = 777
+ _clear_cache(self.project_id)
+
+ def tearDown(self):
+ _clear_cache(self.project_id)
+
+ @patch("posthog.models.group_type_mapping.get_group_types_for_project")
+ def test_returns_matching_instance(self, mock_get):
+ mock_get.return_value = PERSONHOG_SUCCESS_DATA
+
+ result = get_group_type_mapping_instance(self.project_id, 0)
+
+ assert isinstance(result, GroupTypeMapping)
+ assert result.group_type == "organization"
+ assert result.group_type_index == 0
+ assert result.project_id == self.project_id
+ mock_get.assert_called_once_with(self.project_id, caller_tag=None)
+
+ @patch("posthog.models.group_type_mapping.get_group_types_for_project")
+ def test_returns_second_index(self, mock_get):
+ mock_get.return_value = PERSONHOG_SUCCESS_DATA
+
+ result = get_group_type_mapping_instance(self.project_id, 1)
+
+ assert result.group_type == "company"
+ assert result.group_type_index == 1
+
+ @patch("posthog.models.group_type_mapping.invalidate_group_types_cache")
+ @patch("posthog.models.group_type_mapping.get_group_types_for_project")
+ def test_cache_bust_retry_finds_mapping(self, mock_get, mock_invalidate):
+ fresh_data = [
+ *PERSONHOG_SUCCESS_DATA,
+ {
+ "group_type": "workspace",
+ "group_type_index": 2,
+ "name_singular": "Workspace",
+ "name_plural": "Workspaces",
+ "detail_dashboard": None,
+ "default_columns": None,
+ "created_at": None,
+ },
+ ]
+ mock_get.side_effect = [PERSONHOG_SUCCESS_DATA, fresh_data]
+
+ result = get_group_type_mapping_instance(self.project_id, 2)
+
+ assert result.group_type == "workspace"
+ assert result.group_type_index == 2
+ mock_invalidate.assert_called_once_with(self.project_id)
+ assert mock_get.call_count == 2
+
+ @patch("posthog.models.group_type_mapping.invalidate_group_types_cache")
+ @patch("posthog.models.group_type_mapping.get_group_types_for_project")
+ def test_raises_does_not_exist_after_retry(self, mock_get, mock_invalidate):
+ mock_get.return_value = PERSONHOG_SUCCESS_DATA
+
+ with self.assertRaises(GroupTypeMapping.DoesNotExist):
+ get_group_type_mapping_instance(self.project_id, 99)
+
+ mock_invalidate.assert_called_once_with(self.project_id)
+ assert mock_get.call_count == 2
+
+ @patch("posthog.models.group_type_mapping._dict_to_group_type_mapping_model")
+ @patch("posthog.models.group_type_mapping.get_group_types_for_project")
+ def test_passes_team_to_model_builder(self, mock_get, mock_builder):
+ mock_get.return_value = PERSONHOG_SUCCESS_DATA
+ mock_builder.return_value = MagicMock(spec=GroupTypeMapping)
+ team = MagicMock()
+
+ get_group_type_mapping_instance(self.project_id, 0, team=team)
+
+ mock_builder.assert_called_once_with(PERSONHOG_SUCCESS_DATA[0], project_id=self.project_id, team=team)
+
+ @patch("posthog.models.group_type_mapping._fetch_group_types_for_project_direct")
+ def test_consistency_strong_bypasses_cache(self, mock_fetch):
+ mock_fetch.return_value = PERSONHOG_SUCCESS_DATA
+ mock_builder_result = MagicMock(spec=GroupTypeMapping)
+
+ with patch(
+ "posthog.models.group_type_mapping._dict_to_group_type_mapping_model", return_value=mock_builder_result
+ ):
+ result = get_group_type_mapping_instance(self.project_id, 0, consistency="strong")
+
+ assert result is mock_builder_result
+ mock_fetch.assert_called_once()
+
+ @patch("posthog.models.group_type_mapping._fetch_group_types_for_project_direct")
+ def test_consistency_strong_raises_does_not_exist(self, mock_fetch):
+ mock_fetch.return_value = PERSONHOG_SUCCESS_DATA
+
+ with self.assertRaises(GroupTypeMapping.DoesNotExist):
+ get_group_type_mapping_instance(self.project_id, 99, consistency="strong")
diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.py
index 4fd23b6c1050..391f20787fd8 100644
--- a/products/feature_flags/backend/test/test_local_evaluation.py
+++ b/products/feature_flags/backend/test/test_local_evaluation.py
@@ -386,9 +386,11 @@ class TestUpdateFlagCachesGroupMappingGuards(BaseTest):
"products.feature_flags.backend.local_evaluation.get_group_types_for_projects",
return_value={self.team.project_id: []},
),
- patch("posthog.models.group_type_mapping.GroupTypeMapping.objects") as mock_objects,
+ patch(
+ "posthog.models.group_type_mapping._fetch_group_types_for_project_direct",
+ side_effect=DatabaseError("persons db down"),
+ ),
):
- mock_objects.using.return_value.filter.return_value.exists.side_effect = DatabaseError("persons db down")
with patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set:
update_flag_caches(self.team)
mock_set.assert_not_called()