: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(django): move list groups search to clickhouse (#63313)
Zach Brown236387c03940
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.pyindex aa375ce1865e..bbb9a7bd9c56 100644--- a/ee/clickhouse/views/groups.py+++ b/ee/clickhouse/views/groups.py@@ -63,20 +63,25 @@ logger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)-def _encode_groups_cursor(created_at_us: int, group_id: int) -> str:- return base64.urlsafe_b64encode(_json.dumps({"c": created_at_us, "i": group_id}).encode()).decode()+def _encode_groups_cursor(created_at_us: int, group_key: str) -> str:+ return base64.urlsafe_b64encode(_json.dumps({"c": created_at_us, "k": group_key}).encode()).decode()-def _decode_groups_cursor(cursor: str) -> tuple[int, int]:+def _decode_groups_cursor(cursor: str) -> tuple[int, str]:try:data = _json.loads(base64.urlsafe_b64decode(cursor))+ # Pre-deploy cursors keyed the tiebreaker on the PG id ("i") instead of group_key ("k").+ # The new keyset can't honor that boundary (different column, no id in ClickHouse), so treat+ # an old-format cursor as no cursor — restart from the first page, like any invalid cursor.+ if "k" not in data:+ return 0, ""raw_ts = int(data.get("c", 0))- group_id = int(data.get("i", 0))+ group_key = str(data.get("k", ""))if 0 < raw_ts < 1e15:raw_ts *= 1000- return raw_ts, group_id+ return raw_ts, group_keyexcept Exception:- return 0, 0+ return 0, ""def detect_group_property_type(value):@@ -387,10 +392,10 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Creategroup_key = self.request.GET.get("group_key", "")cursor_created_at_us = 0- cursor_id = 0+ cursor_group_key = ""cursor_param = self.request.GET.get("cursor")if cursor_param:- cursor_created_at_us, cursor_id = _decode_groups_cursor(cursor_param)+ cursor_created_at_us, cursor_group_key = _decode_groups_cursor(cursor_param)result = list_groups(team_id=self.team.pk,@@ -398,7 +403,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Creategroup_key_contains=group_key,search=group_search,cursor_created_at_us=cursor_created_at_us,- cursor_id=cursor_id,+ cursor_group_key=cursor_group_key,)serializer = self.get_serializer(result.groups, many=True)@@ -406,7 +411,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Createnext_url = Noneif result.has_more and result.groups:last = result.groups[-1]- cursor = _encode_groups_cursor(int(last.created_at.timestamp() * 1_000_000), last.id)+ cursor = _encode_groups_cursor(int(last.created_at.timestamp() * 1_000_000), last.group_key)params: dict[str, str | int] = {"group_type_index": group_type_index, "cursor": cursor}if group_search:params["search"] = group_searchdiff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.pyindex 7cc3d77fc233..477271c1bbd2 100644--- a/ee/clickhouse/views/test/test_clickhouse_groups.py+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py@@ -1,4 +1,5 @@import json+import base64from typing import Any, castfrom uuid import UUID@@ -6,10 +7,11 @@ import pytestfrom freezegun.api import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, snapshot_clickhouse_queriesfrom unittest import mock-from unittest.mock import MagicMock, patch+from unittest.mock import patchfrom django.core.cache import cachefrom django.db import IntegrityError+from django.utils.timezone import nowimport orjsonfrom rest_framework import status@@ -21,7 +23,8 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboardfrom posthog.models import GroupTypeMapping, GroupUsageMetric, Person, PropertyDefinitionfrom posthog.models.filters.utils import GroupTypeIndex-from posthog.models.group.util import create_group, list_groups+from posthog.models.group.group import Group+from posthog.models.group.util import ListGroupsResult, create_group, list_groups, raw_create_group_chfrom posthog.models.group_type_mapping import GROUP_TYPES_CACHE_KEY_PREFIX, GROUP_TYPES_STALE_CACHE_KEY_PREFIXfrom posthog.models.organization import Organizationfrom posthog.models.sharing_configuration import SharingConfiguration@@ -2408,7 +2411,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):team_id=self.team.pk,group_type_index=0,cursor_created_at_us=int(last.created_at.timestamp() * 1_000_000),- cursor_id=last.id,+ cursor_group_key=last.group_key,limit=2,)@@ -2416,6 +2419,44 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):assert page2.groups[0].group_key == "org:1"assert page2.has_more is False+ @freeze_time("2021-05-04")+ def test_pagination_cursor_breaks_created_at_ties_on_group_key(self):+ # Three groups created at the same instant: keyset pagination must fall back to the+ # group_key tiebreaker (descending) and neither skip nor duplicate a row across pages.+ with freeze_time("2021-05-01"):+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:a", properties={})+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:b", properties={})+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:c", properties={})++ page1 = list_groups(team_id=self.team.pk, group_type_index=0, limit=2)+ assert [g.group_key for g in page1.groups] == ["org:c", "org:b"]+ assert page1.has_more is True++ last = page1.groups[-1]+ page2 = list_groups(+ team_id=self.team.pk,+ group_type_index=0,+ cursor_created_at_us=int(last.created_at.timestamp() * 1_000_000),+ cursor_group_key=last.group_key,+ limit=2,+ )+ assert [g.group_key for g in page2.groups] == ["org:a"]+ assert page2.has_more is False++ @freeze_time("2021-05-03")+ def test_search_escapes_like_wildcards(self):+ # A literal "%" in the search term must match literally, not act as a wildcard.+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={"name": "50% off"})+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:2", properties={"name": "discount"})++ matched = list_groups(team_id=self.team.pk, group_type_index=0, search="50%")+ assert [g.group_key for g in matched.groups] == ["org:1"]++ # A bare "%" would match every group if treated as a wildcard; escaped, it matches only the+ # group whose properties contain a literal "%" (org:1's "50% off"), proving the escape works.+ literal = list_groups(team_id=self.team.pk, group_type_index=0, search="%")+ assert [g.group_key for g in literal.groups] == ["org:1"]+@freeze_time("2021-05-03")def test_search_filters_by_properties(self):create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={"name": "Acme Corp"})@@ -2464,83 +2505,85 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):assert result.has_more is False@freeze_time("2021-05-03")- def test_personhog_fallback_on_error(self):- create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={"name": "Test"})-- mock_client = MagicMock()- mock_client.list_groups.side_effect = Exception("gRPC error")- with patch("posthog.personhog_client.client.get_personhog_client", return_value=mock_client):- result = list_groups(team_id=self.team.pk, group_type_index=0)-- assert len(result.groups) == 1- assert result.groups[0].group_key == "org:1"- mock_client.list_groups.assert_called_once()-- @freeze_time("2021-05-03")- @patch("posthog.personhog_client.client.get_personhog_client")- def test_personhog_success_path(self, mock_get_client):- from posthog.personhog_client.proto import ListGroupsResponse- from posthog.personhog_client.proto.generated.personhog.types.v1.group_pb2 import Group as ProtoGroup-- proto_group = ProtoGroup(- id=1,- team_id=self.team.pk,+ def test_scopes_results_to_team(self):+ # An identically-keyed group under a different team must never surface — the query is+ # team-scoped by HogQL, so this guards against a cross-team leak.+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={})+ raw_create_group_ch(+ team_id=self.team.pk + 100000,group_type_index=0,group_key="org:1",- group_properties=b'{"name": "Test Org"}',- created_at=1620000000000,- version=0,+ properties={"name": "OTHER TEAM"},+ created_at=now(),)- mock_response = ListGroupsResponse(groups=[proto_group], has_more=False)- mock_client = MagicMock()- mock_client.list_groups.return_value = mock_response- mock_get_client.return_value = mock_clientresult = list_groups(team_id=self.team.pk, group_type_index=0)assert len(result.groups) == 1assert result.groups[0].group_key == "org:1"- assert result.groups[0].group_properties == {"name": "Test Org"}- assert result.has_more is False- mock_client.list_groups.assert_called_once()+ assert result.groups[0].group_properties == {}- @freeze_time("2021-05-03")- @patch("posthog.personhog_client.client.get_personhog_client")- def test_personhog_pagination_has_more(self, mock_get_client):- from posthog.personhog_client.proto import ListGroupsResponse- from posthog.personhog_client.proto.generated.personhog.types.v1.group_pb2 import Group as ProtoGroup-- proto_groups = [- ProtoGroup(- id=2,- team_id=self.team.pk,- group_type_index=0,- group_key="org:2",- group_properties=b"{}",- created_at=1620086400000,- version=0,- ),- ProtoGroup(- id=1,+ def test_returns_latest_properties_after_update(self):+ # The groups table dedups by argMax(_timestamp); a newer write for the same (index, key)+ # must win and produce a single row — guards the choice of `groups` over `raw_groups`.+ with freeze_time("2021-05-01"):+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={"name": "Old"})+ with freeze_time("2021-05-02"):+ raw_create_group_ch(team_id=self.team.pk,group_type_index=0,group_key="org:1",- group_properties=b"{}",- created_at=1620000000000,- version=0,- ),- ]- mock_response = ListGroupsResponse(groups=proto_groups, has_more=True)- mock_client = MagicMock()- mock_client.list_groups.return_value = mock_response- mock_get_client.return_value = mock_client+ properties={"name": "New"},+ created_at=now(),+ )++ result = list_groups(team_id=self.team.pk, group_type_index=0)++ assert len(result.groups) == 1+ assert result.groups[0].group_properties == {"name": "New"}++ @freeze_time("2021-05-03")+ def test_preserves_complex_property_values(self):+ # Properties survive the ClickHouse string -> json.loads -> dict round-trip with types intact.+ props = {"count": 5, "active": True, "ratio": 1.5, "tags": ["a", "b"], "nested": {"x": 1}, "missing": None}+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties=props)++ result = list_groups(team_id=self.team.pk, group_type_index=0)++ assert len(result.groups) == 1+ assert result.groups[0].group_properties == props++ @freeze_time("2021-05-03")+ def test_search_is_case_insensitive(self):+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:alpha", properties={"name": "Acme Corp"})++ # Properties substring with a lowercased term, and key-exact with an uppercased term.+ by_props = list_groups(team_id=self.team.pk, group_type_index=0, search="acme")+ by_key = list_groups(team_id=self.team.pk, group_type_index=0, search="ORG:ALPHA")++ assert [g.group_key for g in by_props.groups] == ["org:alpha"]+ assert [g.group_key for g in by_key.groups] == ["org:alpha"]++ @freeze_time("2021-05-03")+ def test_search_no_match_returns_empty(self):+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={"name": "Acme"})++ result = list_groups(team_id=self.team.pk, group_type_index=0, search="zzz-no-such-thing")++ assert result.groups == []+ assert result.has_more is False++ @freeze_time("2021-05-04")+ def test_has_more_false_when_result_count_equals_limit(self):+ with freeze_time("2021-05-01"):+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={})+ with freeze_time("2021-05-02"):+ create_group(team_id=self.team.pk, group_type_index=0, group_key="org:2", properties={})result = list_groups(team_id=self.team.pk, group_type_index=0, limit=2)assert len(result.groups) == 2- assert result.has_more is True- assert result.groups[0].group_key == "org:2"- assert result.groups[1].group_key == "org:1"+ assert result.has_more is Falseclass TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):@@ -2592,19 +2635,30 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):@freeze_time("2021-05-02")def test_cursor_roundtrip(self):- cursor = _encode_groups_cursor(1620000000000_000, 42)- created_at_us, group_id = _decode_groups_cursor(cursor)+ cursor = _encode_groups_cursor(1620000000000_000, "org:42")+ created_at_us, group_key = _decode_groups_cursor(cursor)assert created_at_us == 1620000000000_000- assert group_id == 42+ assert group_key == "org:42"@freeze_time("2021-05-02")def test_cursor_backward_compat_ms(self):- cursor = _encode_groups_cursor(1620000000000, 42)- created_at_us, group_id = _decode_groups_cursor(cursor)+ cursor = _encode_groups_cursor(1620000000000, "org:42")+ created_at_us, group_key = _decode_groups_cursor(cursor)assert created_at_us == 1620000000000_000- assert group_id == 42+ assert group_key == "org:42"++ @freeze_time("2021-05-02")+ def test_old_format_cursor_is_treated_as_no_cursor(self):+ # Pre-deploy cursors encoded the tiebreaker as "i" (PG id) with no "k". The new keyset can't+ # honor that boundary, so the decoder degrades it to no cursor (restart from the first page).+ old_cursor = base64.urlsafe_b64encode(json.dumps({"c": 1620000000000_000, "i": 42}).encode()).decode()++ created_at_us, group_key = _decode_groups_cursor(old_cursor)++ assert created_at_us == 0+ assert group_key == ""@freeze_time("2021-05-02")def test_invalid_cursor_is_ignored(self):@@ -2643,55 +2697,20 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):assert response.status_code == 404@freeze_time("2021-05-02")- @patch("posthog.personhog_client.client.get_personhog_client")- def test_list_api_with_personhog(self, mock_get_client):- from posthog.personhog_client.proto import ListGroupsResponse- from posthog.personhog_client.proto.generated.personhog.types.v1.group_pb2 import Group as ProtoGroup-- proto_group = ProtoGroup(- id=99,- team_id=self.team.pk,- group_type_index=0,- group_key="org:phog",- group_properties=b'{"name": "PersonHog Org"}',- created_at=1620000000000,- version=0,- )- mock_response = ListGroupsResponse(groups=[proto_group], has_more=False)- mock_client = MagicMock()- mock_client.list_groups.return_value = mock_response- mock_get_client.return_value = mock_client-- response_data = self.client.get(f"/api/projects/{self.team.id}/groups?group_type_index=0").json()-- assert response_data["next"] is None- assert response_data["previous"] is None- assert len(response_data["results"]) == 1- assert response_data["results"][0]["group_key"] == "org:phog"- assert response_data["results"][0]["group_properties"] == {"name": "PersonHog Org"}-- @freeze_time("2021-05-02")- @patch("posthog.personhog_client.client.get_personhog_client")- def test_list_api_with_personhog_has_more_produces_next_url(self, mock_get_client):- from posthog.personhog_client.proto import ListGroupsResponse- from posthog.personhog_client.proto.generated.personhog.types.v1.group_pb2 import Group as ProtoGroup-- proto_groups = [- ProtoGroup(- id=i,+ @patch("ee.clickhouse.views.groups.list_groups")+ def test_list_api_has_more_produces_next_url(self, mock_list_groups):+ # The viewset turns a has_more result into a forward cursor in the `next` URL.+ groups = [+ Group(team_id=self.team.pk,group_type_index=0,group_key=f"org:{i}",- group_properties=b"{}",- created_at=1620000000000 + i * 1000,- version=0,+ group_properties={},+ created_at=now(),)for i in range(100)]- mock_response = ListGroupsResponse(groups=proto_groups, has_more=True)- mock_client = MagicMock()- mock_client.list_groups.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_list_groups.return_value = ListGroupsResult(groups=groups, has_more=True)response_data = self.client.get(f"/api/projects/{self.team.id}/groups?group_type_index=0").json()@@ -2699,205 +2718,3 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):assert "cursor=" in response_data["next"]assert "group_type_index=0" in response_data["next"]assert len(response_data["results"]) == 100-- @freeze_time("2021-05-02")- def test_list_api_fallback_on_personhog_error(self):- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key="org:fallback",- properties={"name": "Fallback Org"},- )-- mock_client = MagicMock()- mock_client.list_groups.side_effect = Exception("gRPC unavailable")- with patch("posthog.personhog_client.client.get_personhog_client", return_value=mock_client):- response_data = self.client.get(f"/api/projects/{self.team.id}/groups?group_type_index=0").json()-- assert len(response_data["results"]) == 1- assert response_data["results"][0]["group_key"] == "org:fallback"- assert response_data["results"][0]["group_properties"] == {"name": "Fallback Org"}---class TestGroupsListPersonhogORMParity(ClickhouseTestMixin, APIBaseTest):- """Verify the personhog path and ORM fallback path produce identical API responses.-- Each test creates data in the DB, then compares the serialized `results` array- from both paths to ensure field names, types, ordering, and values match exactly.- """-- def _build_proto_from_group(self, group):- from posthog.personhog_client.proto.generated.personhog.types.v1.group_pb2 import Group as ProtoGroup-- return ProtoGroup(- id=group.id,- team_id=group.team_id,- group_type_index=group.group_type_index,- group_key=group.group_key,- group_properties=json.dumps(group.group_properties).encode(),- created_at=int(group.created_at.timestamp() * 1000),- version=group.version if group.version is not None else 0,- )-- def _get_orm_response(self, url: str) -> dict:- with patch("posthog.personhog_client.client.get_personhog_client", return_value=None):- return self.client.get(url).json()-- def _get_personhog_response(self, url: str, groups: list, has_more: bool = False) -> dict:- from posthog.personhog_client.proto import ListGroupsResponse-- proto_groups = [self._build_proto_from_group(g) for g in groups]- mock_response = ListGroupsResponse(groups=proto_groups, has_more=has_more)- mock_client = MagicMock()- mock_client.list_groups.return_value = mock_response- with patch("posthog.personhog_client.client.get_personhog_client", return_value=mock_client):- return self.client.get(url).json()-- @freeze_time("2021-05-02")- def test_single_group_field_parity(self):- group = create_group(- team_id=self.team.pk,- group_type_index=0,- group_key="org:parity",- properties={"name": "Parity Test", "count": 42},- )-- url = f"/api/projects/{self.team.id}/groups?group_type_index=0"- orm_response = self._get_orm_response(url)- phog_response = self._get_personhog_response(url, [group])-- assert orm_response.keys() == phog_response.keys(), "Top-level response keys must match"- assert len(orm_response["results"]) == len(phog_response["results"]) == 1-- orm_item = orm_response["results"][0]- phog_item = phog_response["results"][0]-- assert set(orm_item.keys()) == set(phog_item.keys()), (- f"Result field names must match: ORM={set(orm_item.keys())}, personhog={set(phog_item.keys())}"- )- for key in orm_item:- assert orm_item[key] == phog_item[key], (- f"Field '{key}' differs: ORM={orm_item[key]!r}, personhog={phog_item[key]!r}"- )-- @freeze_time("2021-05-03")- def test_multiple_groups_ordering_parity(self):- with freeze_time("2021-05-01"):- g1 = create_group(- team_id=self.team.pk, group_type_index=0, group_key="org:oldest", properties={"name": "Oldest"}- )- with freeze_time("2021-05-02"):- g2 = create_group(- team_id=self.team.pk, group_type_index=0, group_key="org:middle", properties={"name": "Middle"}- )- with freeze_time("2021-05-03"):- g3 = create_group(- team_id=self.team.pk, group_type_index=0, group_key="org:newest", properties={"name": "Newest"}- )-- url = f"/api/projects/{self.team.id}/groups?group_type_index=0"- orm_response = self._get_orm_response(url)- phog_response = self._get_personhog_response(url, [g3, g2, g1])-- orm_keys = [r["group_key"] for r in orm_response["results"]]- phog_keys = [r["group_key"] for r in phog_response["results"]]- assert orm_keys == phog_keys, f"Ordering must match: ORM={orm_keys}, personhog={phog_keys}"-- for orm_item, phog_item in zip(orm_response["results"], phog_response["results"]):- for key in orm_item:- assert orm_item[key] == phog_item[key], (- f"Field '{key}' differs for group_key={orm_item['group_key']}: "- f"ORM={orm_item[key]!r}, personhog={phog_item[key]!r}"- )-- @freeze_time("2021-05-02")- def test_empty_properties_parity(self):- group = create_group(team_id=self.team.pk, group_type_index=0, group_key="org:empty", properties={})-- url = f"/api/projects/{self.team.id}/groups?group_type_index=0"- orm_response = self._get_orm_response(url)- phog_response = self._get_personhog_response(url, [group])-- assert orm_response["results"][0]["group_properties"] == phog_response["results"][0]["group_properties"] == {}-- @freeze_time("2021-05-02")- def test_created_at_serialization_parity(self):- group = create_group(team_id=self.team.pk, group_type_index=0, group_key="org:ts", properties={})-- url = f"/api/projects/{self.team.id}/groups?group_type_index=0"- orm_response = self._get_orm_response(url)- phog_response = self._get_personhog_response(url, [group])-- orm_ts = orm_response["results"][0]["created_at"]- phog_ts = phog_response["results"][0]["created_at"]- assert orm_ts == phog_ts, f"created_at serialization must match: ORM={orm_ts!r}, personhog={phog_ts!r}"-- @freeze_time("2021-05-02")- def test_search_results_parity(self):- g1 = create_group(- team_id=self.team.pk, group_type_index=0, group_key="org:match", properties={"name": "Matching Org"}- )- create_group(team_id=self.team.pk, group_type_index=0, group_key="org:other", properties={"name": "Other Org"})-- url = f"/api/projects/{self.team.id}/groups?group_type_index=0&search=Matching"- orm_response = self._get_orm_response(url)- phog_response = self._get_personhog_response(url, [g1])-- assert len(orm_response["results"]) == len(phog_response["results"]) == 1- assert orm_response["results"][0]["group_key"] == phog_response["results"][0]["group_key"] == "org:match"-- @freeze_time("2021-05-02")- def test_pagination_next_url_parity(self):- groups = []- for i in range(3):- with freeze_time(f"2021-05-0{i + 1}"):- groups.append(- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:{i}",- properties={},- )- )-- url = f"/api/projects/{self.team.id}/groups?group_type_index=0"-- orm_response = self._get_orm_response(url)- assert orm_response["next"] is None, "ORM: all groups fit in one page"-- phog_response = self._get_personhog_response(url, list(reversed(groups)), has_more=True)- assert phog_response["next"] is not None, "personhog: has_more=True should produce next URL"- assert "cursor=" in phog_response["next"]- assert "group_type_index=0" in phog_response["next"]-- @freeze_time("2021-05-02")- def test_response_envelope_keys_match(self):- create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={})-- url = f"/api/projects/{self.team.id}/groups?group_type_index=0"- orm_response = self._get_orm_response(url)-- expected_keys = {"next", "previous", "results"}- assert set(orm_response.keys()) == expected_keys, f"Response keys must be exactly {expected_keys}"-- result_keys = {"group_type_index", "group_key", "group_properties", "created_at"}- assert set(orm_response["results"][0].keys()) == result_keys, f"Result item keys must be exactly {result_keys}"-- @freeze_time("2021-05-02")- def test_result_field_types(self):- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key="org:types",- properties={"key": "val"},- )-- url = f"/api/projects/{self.team.id}/groups?group_type_index=0"- orm_response = self._get_orm_response(url)- result = orm_response["results"][0]-- assert isinstance(result["group_type_index"], int)- assert isinstance(result["group_key"], str)- assert isinstance(result["group_properties"], dict)- assert isinstance(result["created_at"], str)- assert result["created_at"].endswith("Z"), "created_at must be UTC ISO format ending with Z"diff --git a/posthog/models/group/util.py b/posthog/models/group/util.pyindex c7ce63d5b218..180946e365a7 100644--- a/posthog/models/group/util.py+++ b/posthog/models/group/util.py@@ -6,7 +6,6 @@ from zoneinfo import ZoneInfofrom django.conf import settingsfrom django.db import DatabaseError-from django.db.models import Qfrom django.utils.timezone import nowimport structlog@@ -359,6 +358,11 @@ class ListGroupsResult:has_more: bool+def _escape_clickhouse_like(value: str) -> str:+ """Escape LIKE/ILIKE wildcards so user input matches literally (mirrors Django's ``__icontains``)."""+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")++def list_groups(team_id: int,group_type_index: int,@@ -366,72 +370,121 @@ def list_groups(group_key_contains: str = "",search: str = "",cursor_created_at_us: int = 0,- cursor_id: int = 0,+ cursor_group_key: str = "",limit: int = 100,) -> ListGroupsResult:- """List groups with cursor pagination, routing through personhog with ORM fallback."""- from posthog.personhog_client.client import get_personhog_client- from posthog.personhog_client.converters import proto_group_to_model- from posthog.personhog_client.proto import ListGroupsRequest+ """List groups for the public groups API, served from ClickHouse.- client = get_personhog_client()- if client is not None:- try:- resp = client.list_groups(- ListGroupsRequest(- team_id=team_id,- group_type_index=group_type_index,- group_key_contains=group_key_contains,- search=search,- cursor_created_at_ms=cursor_created_at_us // 1000,- cursor_id=cursor_id,- limit=limit,- )- )- PERSONHOG_ROUTING_TOTAL.labels(- operation="list_groups", source="personhog", client_name=get_client_name()- ).inc()- return ListGroupsResult(- groups=[proto_group_to_model(g) for g in resp.groups],- has_more=resp.has_more,+ Filtering, full-text search, ``created_at`` ordering and keyset pagination all run against the+ deduped ``groups`` table, so this never reads the persons Postgres database; results are+ eventually consistent. ``search`` matches a substring of the raw properties JSON or the group+ key exactly (case-insensitive), preserving the previous endpoint's semantics. The keyset cursor+ breaks ``created_at`` ties on ``group_key`` (unique within a team and type).+ """+ from posthog.hogql import ast # noqa: PLC0415 — keep HogQL off this widely-imported module's import path+ from posthog.hogql.query import execute_hogql_query # noqa: PLC0415++ from posthog.models.team import Team # noqa: PLC0415++ team = Team.objects.get(pk=team_id)++ where_exprs: list[ast.Expr] = [+ ast.CompareOperation(+ left=ast.Field(chain=["index"]),+ op=ast.CompareOperationOp.Eq,+ right=ast.Constant(value=group_type_index),+ )+ ]++ if group_key_contains:+ where_exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.ILike,+ left=ast.Call(name="toString", args=[ast.Field(chain=["key"])]),+ right=ast.Constant(value=f"%{_escape_clickhouse_like(group_key_contains)}%"),)- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="list_groups",- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning(- "personhog_list_groups_failure",- team_id=team_id,- group_type_index=group_type_index,- exc_info=True,+ )++ if search:+ where_exprs.append(+ ast.Or(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.ILike,+ left=ast.Call(name="toString", args=[ast.Field(chain=["properties"])]),+ right=ast.Constant(value=f"%{_escape_clickhouse_like(search)}%"),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Call(name="lower", args=[ast.Call(name="toString", args=[ast.Field(chain=["key"])])]),+ right=ast.Call(name="lower", args=[ast.Constant(value=search)]),+ ),+ ])+ )- PERSONHOG_ROUTING_TOTAL.labels(operation="list_groups", source="django_orm", client_name=get_client_name()).inc()- try:- qs = Group.objects.filter( # nosemgrep: no-direct-persons-db-orm- team_id=team_id, group_type_index=group_type_index+ if cursor_created_at_us > 0:+ cursor_dt = datetime.datetime.fromtimestamp(cursor_created_at_us / 1_000_000, tz=datetime.UTC)+ where_exprs.append(+ ast.Or(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=ast.Field(chain=["created_at"]),+ right=ast.Constant(value=cursor_dt),+ ),+ ast.And(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["created_at"]),+ right=ast.Constant(value=cursor_dt),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=ast.Field(chain=["key"]),+ right=ast.Constant(value=cursor_group_key),+ ),+ ]+ ),+ ]+ ))- if group_key_contains:- qs = qs.filter(group_key__icontains=group_key_contains)- if search:- qs = qs.filter(Q(group_properties__icontains=search) | Q(group_key__iexact=search))- qs = qs.order_by("-created_at", "-id")- if cursor_created_at_us > 0:- cursor_dt = datetime.datetime.fromtimestamp(cursor_created_at_us / 1_000_000, tz=datetime.UTC)- qs = qs.filter(Q(created_at__lt=cursor_dt) | Q(created_at=cursor_dt, id__lt=cursor_id))- groups = list(qs[: limit + 1])- has_more = len(groups) > limit- if has_more:- groups = groups[:limit]- return ListGroupsResult(groups=groups, has_more=has_more)- except DatabaseError:- logger.warning(- "persons_db_list_groups_failure",++ query = ast.SelectQuery(+ select=[+ ast.Field(chain=["key"]),+ ast.Field(chain=["created_at"]),+ ast.Field(chain=["properties"]),+ ],+ select_from=ast.JoinExpr(table=ast.Field(chain=["groups"])),+ where=ast.And(exprs=where_exprs),+ order_by=[+ ast.OrderExpr(expr=ast.Field(chain=["created_at"]), order="DESC"),+ ast.OrderExpr(expr=ast.Field(chain=["key"]), order="DESC"),+ ],+ limit=ast.Constant(value=limit + 1),+ )++ response = execute_hogql_query(query, team=team, query_type="groups_list")++ rows = response.results or []+ has_more = len(rows) > limit+ if has_more:+ rows = rows[:limit]++ groups = [+ Group(team_id=team_id,group_type_index=group_type_index,- exc_info=True,+ group_key=group_key,+ group_properties=(+ json.loads(group_properties)+ if isinstance(group_properties, str) and group_properties+ else (group_properties or {})+ ),+ created_at=created_at,)- return ListGroupsResult(groups=[], has_more=False)+ for group_key, created_at, group_properties in rows+ ]+ return ListGroupsResult(groups=groups, has_more=has_more)