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): mv usage report to use personhog for gtm (#61492)

Nick Bestf0132c47276a
diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.py
index b443f9171dbc..eb8fac9e0047 100644
--- a/posthog/models/group_type_mapping.py
+++ b/posthog/models/group_type_mapping.py
@@ -10,6 +10,7 @@ if TYPE_CHECKING:
from django.contrib.postgres.fields import ArrayField
from django.db import DatabaseError, models
+from django.db.models import Count
from django.utils import timezone
import structlog
@@ -428,6 +429,42 @@ 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]]:
+ """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
+ )
+ except DatabaseError:
+ logger.warning("count_group_type_mappings_orm_failure", exc_info=True)
+ return []
+
+
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
cannot be confirmed (fail closed).
diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.py
index 5383c7e85019..7344d93c77cc 100644
--- a/posthog/models/test/test_group_type_mapping.py
+++ b/posthog/models/test/test_group_type_mapping.py
@@ -11,6 +11,7 @@ from posthog.models.group_type_mapping import (
GroupTypesUnavailable,
_record_group_types_fetch_failure,
clear_dashboard_from_group_type_mapping,
+ count_group_type_mappings_per_team,
delete_group_type_mapping,
get_group_types_for_project,
get_group_types_for_projects,
@@ -635,6 +636,123 @@ class TestGetGroupTypesForProjectsEdgeCases(SimpleTestCase):
assert set(ctx.exception.project_ids) == {10, 20}
+class TestCountGroupTypeMappingsPerTeam(SimpleTestCase):
+ def setUp(self):
+ self._mock_client = MagicMock()
+ self._client_patcher = patch(_CLIENT_PATCH, return_value=self._mock_client)
+ self._client_patcher.start()
+
+ def tearDown(self):
+ self._client_patcher.stop()
+
+ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")
+ def test_personhog_success_returns_converted_counts(
+ self,
+ mock_errors_counter,
+ mock_routing_counter,
+ mock_objects,
+ ):
+ mock_count_1 = MagicMock()
+ mock_count_1.team_id = 1
+ mock_count_1.count = 3
+ mock_count_2 = MagicMock()
+ mock_count_2.team_id = 2
+ mock_count_2.count = 5
+
+ mock_resp = MagicMock()
+ mock_resp.counts = [mock_count_1, mock_count_2]
+ self._mock_client.count_group_type_mappings.return_value = mock_resp
+
+ result = count_group_type_mappings_per_team()
+
+ assert result == [{"team_id": 1, "total": 3}, {"team_id": 2, "total": 5}]
+ mock_objects.values.assert_not_called()
+ mock_routing_counter.labels.assert_called_with(
+ operation="count_group_type_mappings_per_team", source="personhog", client_name="posthog-django"
+ )
+ mock_errors_counter.labels.assert_not_called()
+
+ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")
+ def test_personhog_failure_falls_back_to_orm(
+ self,
+ mock_errors_counter,
+ mock_routing_counter,
+ mock_objects,
+ ):
+ self._mock_client.count_group_type_mappings.side_effect = RuntimeError("grpc timeout")
+
+ orm_data = [{"team_id": 1, "total": 3}]
+ mock_qs = MagicMock()
+ mock_qs.annotate.return_value.order_by.return_value = orm_data
+ mock_objects.values.return_value = mock_qs
+
+ result = count_group_type_mappings_per_team()
+
+ assert result == orm_data
+ mock_errors_counter.labels.assert_called_once_with(
+ operation="count_group_type_mappings_per_team",
+ source="personhog",
+ error_type="grpc_error",
+ client_name="posthog-django",
+ )
+
+ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")
+ def test_no_client_uses_orm_directly(
+ self,
+ mock_errors_counter,
+ mock_routing_counter,
+ mock_objects,
+ ):
+ self._client_patcher.stop()
+ no_client_patcher = patch(_CLIENT_PATCH, return_value=None)
+ no_client_patcher.start()
+
+ orm_data = [{"team_id": 10, "total": 2}]
+ mock_qs = MagicMock()
+ mock_qs.annotate.return_value.order_by.return_value = orm_data
+ mock_objects.values.return_value = mock_qs
+
+ result = count_group_type_mappings_per_team()
+
+ assert result == orm_data
+ mock_routing_counter.labels.assert_called_with(
+ operation="count_group_type_mappings_per_team", source="django_orm", client_name="posthog-django"
+ )
+ mock_errors_counter.labels.assert_not_called()
+
+ no_client_patcher.stop()
+ self._mock_client = MagicMock()
+ self._client_patcher = patch(_CLIENT_PATCH, return_value=self._mock_client)
+ self._client_patcher.start()
+
+ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")
+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")
+ def test_both_paths_fail_returns_empty_list(
+ self,
+ mock_errors_counter,
+ mock_routing_counter,
+ mock_objects,
+ ):
+ from django.db import DatabaseError
+
+ self._mock_client.count_group_type_mappings.side_effect = RuntimeError("grpc timeout")
+
+ mock_qs = MagicMock()
+ mock_qs.annotate.return_value.order_by.side_effect = DatabaseError("db is down")
+ mock_objects.values.return_value = mock_qs
+
+ result = count_group_type_mappings_per_team()
+
+ assert result == []
+
+
# ── Write helper tests ─────────────────────────────────────────────
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 99f8ebdf14c9..94d75779360d 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -32,8 +32,8 @@ from posthog.cloud_utils import get_cached_instance_license
from posthog.constants import FlagRequestType
from posthog.exceptions_capture import capture_exception
from posthog.logging.timing import timed_log
-from posthog.models import GroupTypeMapping, OrganizationMembership, User
-from posthog.models.group_type_mapping import get_group_types_for_team
+from posthog.models import OrganizationMembership, User
+from posthog.models.group_type_mapping import count_group_type_mappings_per_team, get_group_types_for_team
from posthog.models.organization import Organization
from posthog.models.property.util import get_property_string_expr
from posthog.models.team.team import Team
@@ -2089,11 +2089,7 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st
"teams_with_local_evaluation_requests_count_in_period": get_teams_with_feature_flag_requests_count_in_period(
period_start, period_end, FlagRequestType.LOCAL_EVALUATION
),
- "teams_with_group_types_total": 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
- ),
+ "teams_with_group_types_total": count_group_type_mappings_per_team(),
"teams_with_dashboard_count": list(
Dashboard.objects.values("team_id").annotate(total=Count("id")).order_by("team_id")
),
diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.py
index 0f67d8461423..aaebeba90d15 100644
--- a/posthog/temporal/usage_report/queries.py
+++ b/posthog/temporal/usage_report/queries.py
@@ -46,7 +46,7 @@ from typing import Any, Literal
from django.db.models import Count
from posthog.constants import FlagRequestType
-from posthog.models import GroupTypeMapping
+from posthog.models.group_type_mapping import count_group_type_mappings_per_team
from posthog.tasks.usage_report import (
get_all_event_metrics_in_period,
get_teams_with_active_batch_exports_in_period,
@@ -97,11 +97,7 @@ from products.surveys.backend.models import Survey
def _group_types_total() -> list[dict[str, int]]:
- 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 count_group_type_mappings_per_team()
def _dashboard_count() -> list[dict[str, int]]: