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(groups): return 400 when a concurrent group create loses the race (#118819)

Phil Haackf15c6987d31d
diff --git a/posthog/models/group/test_util.py b/posthog/models/group/test_util.py
index d542a179c464..4ff02fd8678a 100644
--- a/posthog/models/group/test_util.py
+++ b/posthog/models/group/test_util.py
@@ -1,3 +1,4 @@
+from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -176,7 +177,10 @@ class TestCreateGroup(SimpleTestCase):
@patch(_CONVERTER_PATCH)
@patch(_CLIENT_PATCH)
def test_builds_request_converts_response_and_writes_clickhouse(self, mock_get_client, mock_convert, mock_ch):
- proto_group = _make_proto_group(id=42, team_id=self.team_id, group_key=self.group_key)
+ timestamp = datetime(2026, 1, 2, 3, 4, 5, 678000, tzinfo=UTC)
+ proto_group = _make_proto_group(
+ id=42, team_id=self.team_id, group_key=self.group_key, created_at=int(timestamp.timestamp() * 1000)
+ )
mock_client = MagicMock()
mock_client.create_group.return_value = MagicMock(group=proto_group)
mock_get_client.return_value = mock_client
@@ -188,6 +192,7 @@ class TestCreateGroup(SimpleTestCase):
group_type_index=self.group_type_index,
group_key=self.group_key,
properties=self.properties,
+ timestamp=timestamp,
)
assert result is fake_model
diff --git a/posthog/models/group/util.py b/posthog/models/group/util.py
index 1d135972c111..e4e882d76422 100644
--- a/posthog/models/group/util.py
+++ b/posthog/models/group/util.py
@@ -19,6 +19,10 @@ from posthog.models.group.sql import INSERT_GROUP_SQL
logger = structlog.get_logger(__name__)
+class GroupAlreadyExistsError(Exception):
+ pass
+
+
def raw_create_group_ch(
team_id: int,
group_type_index: GroupTypeIndex,
@@ -77,22 +81,30 @@ def create_group(
from posthog.personhog_client.converters import proto_group_to_model
from posthog.personhog_client.proto import CreateGroupRequest
+ created_at_ms = int(timestamp.timestamp() * 1000)
client = require_personhog_client()
- return personhog_call(
+ group = personhog_call(
"create_group",
- lambda: proto_group_to_model(
+ lambda: (
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),
+ created_at=created_at_ms,
)
).group
),
caller_tag="group/create_group",
)
+ # Personhog returns the stored group when the key already exists. A retry of this call sends the
+ # same created_at. A different created_at means that another request created the group first.
+ if group.created_at != created_at_ms:
+ raise GroupAlreadyExistsError(
+ f"group_key={group_key!r} group_type_index={group_type_index} already exists for team_id={team_id}"
+ )
+ return proto_group_to_model(group)
def save_group(group: Group, *, operation: str = "group_save") -> None:
diff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.py
index 0c3e30f6b242..49e3f24e0e1b 100644
--- a/posthog/personhog_client/fake_client.py
+++ b/posthog/personhog_client/fake_client.py
@@ -495,6 +495,10 @@ class FakePersonHogClient:
def create_group(self, request: group_pb2.CreateGroupRequest) -> group_pb2.CreateGroupResponse:
self.calls.append(_Call("create_group", request))
+ key = (request.team_id, request.group_type_index, request.group_key)
+ existing = self._groups.get(key)
+ if existing is not None:
+ return group_pb2.CreateGroupResponse(group=existing)
next_id = max((g.id for g in self._groups.values()), default=0) + 1
group = group_pb2.Group(
id=next_id,
@@ -505,7 +509,7 @@ class FakePersonHogClient:
created_at=request.created_at,
version=0,
)
- self._groups[(request.team_id, request.group_type_index, request.group_key)] = group
+ self._groups[key] = group
response = group_pb2.CreateGroupResponse(group=group)
return response
diff --git a/posthog/personhog_client/test_fake_client.py b/posthog/personhog_client/test_fake_client.py
index 4a822ed579e2..b4e78d20a0f4 100644
--- a/posthog/personhog_client/test_fake_client.py
+++ b/posthog/personhog_client/test_fake_client.py
@@ -251,6 +251,17 @@ class TestFakePersonHogClientGroupWrites:
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_returns_existing_group_on_duplicate_key(self):
+ existing = self.client.get_group(group_pb2.GetGroupRequest(team_id=1, group_type_index=0, group_key="org:1"))
+
+ resp = self.client.create_group(
+ group_pb2.CreateGroupRequest(
+ team_id=1, group_type_index=0, group_key="org:1", group_properties=b'{"name": "Other"}'
+ )
+ )
+
+ assert resp.group == existing.group
+
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"))
diff --git a/products/groups/backend/presentation/views.py b/products/groups/backend/presentation/views.py
index 9b0196d9f7b2..f80abb13955a 100644
--- a/products/groups/backend/presentation/views.py
+++ b/products/groups/backend/presentation/views.py
@@ -34,7 +34,14 @@ from posthog.models.activity_logging.activity_log import Change, Detail, load_ac
from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params
from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.group import Group
-from posthog.models.group.util import create_group, get_group_by_key, list_groups, raw_create_group_ch, save_group
+from posthog.models.group.util import (
+ GroupAlreadyExistsError,
+ create_group,
+ get_group_by_key,
+ list_groups,
+ raw_create_group_ch,
+ save_group,
+)
from posthog.models.group_type_mapping import (
GROUP_TYPE_MAPPING_SERIALIZER_FIELDS,
GroupTypeMapping,
@@ -499,8 +506,8 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
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.
+ # create_group writes ClickHouse before personhog reports a duplicate. Reject a known
+ # duplicate here so that it never reaches that write.
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"})
@@ -512,13 +519,8 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
team_id=self.team.pk,
timestamp=timezone.now(),
)
- except IntegrityError as exc:
- # Check for both constraint names: Django model name and actual database constraint name
- if "unique team_id/group_key/group_type_index combo" in str(
- exc
- ) or "unique_team_group_key_group_type" in str(exc):
- raise ValidationError({"detail": "A group with this key already exists"})
- raise
+ except GroupAlreadyExistsError:
+ raise ValidationError({"detail": "A group with this key already exists"})
try:
self.trigger_group_identify(group=group, operation="group create")
diff --git a/products/groups/backend/tests/test_clickhouse_groups.py b/products/groups/backend/tests/test_clickhouse_groups.py
index f8969e58b60e..205da471333d 100644
--- a/products/groups/backend/tests/test_clickhouse_groups.py
+++ b/products/groups/backend/tests/test_clickhouse_groups.py
@@ -1,5 +1,6 @@
import json
import base64
+import contextlib
from typing import Any, cast
from uuid import UUID, uuid4
@@ -20,6 +21,7 @@ from django.db import IntegrityError
from django.utils.timezone import now
import orjson
+from parameterized import parameterized
from rest_framework import status
from posthog.hogql import ast
@@ -531,39 +533,40 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
mock_capture.assert_not_called()
+ @parameterized.expand(
+ [
+ ("found_by_pre_check", False, 0),
+ ("created_after_pre_check", True, 1),
+ ]
+ )
@mock.patch("products.groups.backend.presentation.views.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."""
-
- group_type_mapping = create_group_type_mapping_without_created_at(
+ def test_create_group_duplicated_group_key_via_personhog(
+ self, _name, raced_past_pre_check, expected_create_calls, mock_capture
+ ):
+ 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"
+ pre_check = (
+ mock.patch("products.groups.backend.presentation.views.get_group_by_key", return_value=None)
+ if raced_past_pre_check
+ else contextlib.nullcontext()
+ )
- 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,
- )
+ with fake_personhog_client() as fake, pre_check:
+ fake.add_group(team_id=self.team.pk, group_type_index=0, group_key="dup-key-ph", id=1)
response = self.client.post(
f"/api/projects/{self.team.id}/groups",
- {
- "group_key": group_key,
- "group_type_index": 0,
- "group_properties": {},
- },
+ {"group_key": "dup-key-ph", "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")
+ self.assertEqual(len(create_calls), expected_create_calls)
mock_capture.assert_not_called()
@mock.patch("products.groups.backend.presentation.views.capture_internal")