Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(django): couple personhog behavioural fixes (#65577)

Nick Best804e2894e0b8
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.py
index cfd54c5397eb..7ef4ee19578e 100644
--- a/ee/clickhouse/views/groups.py
+++ b/ee/clickhouse/views/groups.py
@@ -441,10 +441,18 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
request_data = CreateGroupSerializer(data=request.data)
request_data.is_valid(raise_exception=True)
+ group_key = request_data.validated_data["group_key"]
+ group_type_index = request_data.validated_data["group_type_index"]
+
+ # Personhog upserts on duplicate (team, group_type_index, group_key) instead
+ # of raising, so reject duplicates up front to preserve the 400 contract.
+ if get_group_by_key(self.team.pk, group_type_index, group_key) is not None:
+ raise ValidationError({"detail": "A group with this key already exists"})
+
try:
group = create_group(
- group_key=request_data.validated_data["group_key"],
- group_type_index=request_data.validated_data["group_type_index"],
+ group_key=group_key,
+ group_type_index=group_type_index,
properties=request_data.validated_data["group_properties"],
team_id=self.team.pk,
timestamp=timezone.now(),
diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.py
index 4e0cc8d7afda..c5d9021acd73 100644
--- a/ee/clickhouse/views/test/test_clickhouse_groups.py
+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py
@@ -485,6 +485,42 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
mock_capture.assert_not_called()
+ @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ def test_create_group_duplicated_group_key_via_personhog(self, mock_capture):
+ """Personhog upserts on duplicate so the pre-check must catch it."""
+ from posthog.personhog_client.fake_client import fake_personhog_client
+
+ group_type_mapping = create_group_type_mapping_without_created_at(
+ team=self.team,
+ project_id=self.team.project_id,
+ group_type_index=0,
+ group_type="organization",
+ )
+ group_key = "dup-key-ph"
+
+ with fake_personhog_client() as fake:
+ fake.add_group(
+ team_id=self.team.pk,
+ group_type_index=group_type_mapping.group_type_index,
+ group_key=group_key,
+ id=1,
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/groups",
+ {
+ "group_key": group_key,
+ "group_type_index": 0,
+ "group_properties": {},
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["detail"], "A group with this key already exists")
+ create_calls = [c for c in fake.calls if c.method == "create_group"]
+ self.assertEqual(len(create_calls), 0, "create_group should not be called for duplicates")
+ mock_capture.assert_not_called()
+
@mock.patch("ee.clickhouse.views.groups.capture_internal")
def test_create_group_missing_group_key(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.py
index c53c2c8f33fc..cd653f0ee433 100644
--- a/posthog/models/group_type_mapping.py
+++ b/posthog/models/group_type_mapping.py
@@ -687,7 +687,7 @@ def clear_dashboard_from_group_type_mapping(
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:
+ if resp.HasField("mapping"):
client.update_group_type_mapping(
UpdateGroupTypeMappingRequest(
project_id=resp.mapping.project_id,
diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.py
index 43eece14583c..f979fda08260 100644
--- a/posthog/models/test/test_group_type_mapping.py
+++ b/posthog/models/test/test_group_type_mapping.py
@@ -1007,12 +1007,37 @@ class TestClearDashboardFromGroupTypeMapping(SimpleTestCase):
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_group_type_index_zero_still_clears(self, mock_get_client, mock_routing_counter, mock_invalidate):
+ """group_type_index=0 is falsy but valid — HasField must not skip it."""
+ mock_mapping = MagicMock(spec=["project_id", "group_type_index"])
+ mock_mapping.project_id = 1
+ mock_mapping.group_type_index = 0
+
+ mock_resp = MagicMock()
+ mock_resp.HasField.return_value = True
+ 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.update_group_type_mapping.assert_called_once()
+ update_req = mock_client.update_group_type_mapping.call_args[0][0]
+ assert update_req.group_type_index == 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_resp.HasField.return_value = False
mock_client = MagicMock()
mock_client.get_group_type_mapping_by_dashboard_id.return_value = mock_resp