: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
fix(taxonomy): make $group_key selectable as a group property (#98451)
ruby childsc2bdadcadf22
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex 0a16776b138a..b97b54680068 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -4585,7 +4585,9 @@"groups": {"$group_key": {"description": "Specified group key",- "label": "Group key"+ "label": "Group key",+ "type": "String",+ "virtual": true},"$virt_mrr": {"description": "The current MRR for this group.",diff --git a/posthog/api/test/test_property_definition.py b/posthog/api/test/test_property_definition.pyindex dcd41fd75d53..ddcfc8ea9778 100644--- a/posthog/api/test/test_property_definition.py+++ b/posthog/api/test/test_property_definition.py@@ -571,18 +571,28 @@ class TestPropertyDefinitionAPI(APIBaseTest):("Get all group1 properties","type=group&group_type_index=1",- ["group1 another", "group1 property", "$virt_revenue", "$virt_mrr"],+ ["group1 another", "group1 property", "$group_key", "$virt_revenue", "$virt_mrr"],),("Get all group2 properties","type=group&group_type_index=2",- ["group2 property", "$virt_revenue", "$virt_mrr"],+ ["group2 property", "$group_key", "$virt_revenue", "$virt_mrr"],),("Search group1 properties containing 'prop'","type=group&search=prop&group_type_index=1",["group1 property"],),+ (+ "Search for the group key by its name",+ "type=group&search=group_key&group_type_index=1",+ ["$group_key"],+ ),+ (+ "Search for the group key by its label",+ "type=group&search=Group%20key&group_type_index=1",+ ["$group_key"],+ ),])def test_group_property_filter(self, _name: str, query_params: str, expected_results: list[str]) -> None:@@ -986,8 +996,10 @@ class TestPropertyDefinitionAPI(APIBaseTest):)assert response.status_code == status.HTTP_200_OK# Virtual properties should still be included when excluding hidden- virtual_props = [prop for prop in response.json()["results"] if prop["name"].startswith("$virt_")]- assert len(virtual_props) == len(PropertyDefinitionViewSet._BUILTIN_VIRTUAL_PERSON_PROPERTIES)+ virtual_props = [prop for prop in response.json()["results"] if prop.get("virtual")]+ assert {p["name"] for p in virtual_props} == {+ p["name"] for p in PropertyDefinitionViewSet._BUILTIN_VIRTUAL_PERSON_PROPERTIES+ }@parameterized.expand([@@ -1027,35 +1039,45 @@ class TestPropertyDefinitionAPI(APIBaseTest):)assert response.status_code == status.HTTP_200_OK# Virtual properties should still be included when excluding core properties- virtual_props = [prop for prop in response.json()["results"] if prop["name"].startswith("$virt_")]- assert len(virtual_props) == len(PropertyDefinitionViewSet._BUILTIN_VIRTUAL_PERSON_PROPERTIES)+ virtual_props = [prop for prop in response.json()["results"] if prop.get("virtual")]+ assert {p["name"] for p in virtual_props} == {+ p["name"] for p in PropertyDefinitionViewSet._BUILTIN_VIRTUAL_PERSON_PROPERTIES+ }response = self.client.get(f"/api/projects/{self.team.pk}/property_definitions/?type=group&group_type_index=0&exclude_core_properties=true")assert response.status_code == status.HTTP_200_OK# Virtual properties should still be included when excluding core properties- virtual_props = [prop for prop in response.json()["results"] if prop["name"].startswith("$virt_")]- assert len(virtual_props) == len(PropertyDefinitionViewSet._BUILTIN_VIRTUAL_GROUP_PROPERTIES)+ virtual_props = [prop for prop in response.json()["results"] if prop.get("virtual")]+ assert {p["name"] for p in virtual_props} == {+ p["name"] for p in PropertyDefinitionViewSet._BUILTIN_VIRTUAL_GROUP_PROPERTIES+ }def test_virtual_property_type_filter(self):response = self.client.get(f"/api/projects/{self.team.pk}/property_definitions/?type=person")assert response.status_code == status.HTTP_200_OK# Should include virtual properties when type=person- virtual_props = [prop for prop in response.json()["results"] if prop["name"].startswith("$virt_")]- assert len(virtual_props) == len(PropertyDefinitionViewSet._BUILTIN_VIRTUAL_PERSON_PROPERTIES)+ virtual_props = [prop for prop in response.json()["results"] if prop.get("virtual")]+ assert {p["name"] for p in virtual_props} == {+ p["name"] for p in PropertyDefinitionViewSet._BUILTIN_VIRTUAL_PERSON_PROPERTIES+ }response = self.client.get(f"/api/projects/{self.team.pk}/property_definitions/?type=group&group_type_index=0")assert response.status_code == status.HTTP_200_OK# Should include virtual properties when type=group- virtual_props = [prop for prop in response.json()["results"] if prop["name"].startswith("$virt_")]- assert len(virtual_props) == len(PropertyDefinitionViewSet._BUILTIN_VIRTUAL_GROUP_PROPERTIES)+ virtual_props = [prop for prop in response.json()["results"] if prop.get("virtual")]+ assert {p["name"] for p in virtual_props} == {+ p["name"] for p in PropertyDefinitionViewSet._BUILTIN_VIRTUAL_GROUP_PROPERTIES+ }response = self.client.get(f"/api/projects/{self.team.pk}/property_definitions/?type=event")assert response.status_code == status.HTTP_200_OK# Should include virtual event properties (bot detection)- virtual_props = [prop for prop in response.json()["results"] if prop["name"].startswith("$virt_")]- assert len(virtual_props) == len(PropertyDefinitionViewSet._BUILTIN_VIRTUAL_EVENT_PROPERTIES)+ virtual_props = [prop for prop in response.json()["results"] if prop.get("virtual")]+ assert {p["name"] for p in virtual_props} == {+ p["name"] for p in PropertyDefinitionViewSet._BUILTIN_VIRTUAL_EVENT_PROPERTIES+ }virtual_names = {p["name"] for p in virtual_props}assert "$virt_is_bot" in virtual_namesassert "$virt_traffic_type" in virtual_namesdiff --git a/posthog/hogql/property.py b/posthog/hogql/property.pyindex 4100b6cfe504..bb417a31b283 100644--- a/posthog/hogql/property.py+++ b/posthog/hogql/property.py@@ -246,6 +246,27 @@ def _wildcard_bounds(value: str) -> tuple[str, str]:GROUP_KEY_PATTERN = re.compile(r"^\$group_[0-4]$")+# The group's key is a column on the groups table, not an entry in its property JSON. Flag matching and+# the release-condition blast radius already resolve it that way; HogQL has to agree everywhere.+GROUP_KEY_PROPERTY = "$group_key"+++def group_property_chain(group_type_index: int | float | None, key: str) -> list[str]:+ """Field chain that reads group property `key` through the events table's `group_N` lazy join.++ `$group_key` is the `key` column, `$virt_*` properties are expression fields on the groups table, and+ anything else lives in the property JSON. The breakdown builders and `property_to_expr` all go through+ here so the three shapes cannot drift apart.+ """+ if group_type_index is None:+ raise QueryError("A group property needs a group_type_index")+ prefix = f"group_{int(group_type_index)}"+ if key == GROUP_KEY_PROPERTY:+ return [prefix, "key"]+ if key.startswith("$virt_"):+ return [prefix, key]+ return [prefix, "properties", key]+def _stringify_group_key_value(value: object) -> str | list[str]:"""Group keys ($group_0–$group_4) are always stored as strings. A numeric filter@@ -1275,7 +1296,13 @@ def property_to_expr(operator = cast(Optional[PropertyOperator], property.operator) or PropertyOperator.EXACTvalue = property.value- if property.key and GROUP_KEY_PATTERN.match(str(property.key)):+ # `$group_key` is the group's key column, not an entry in its property JSON. Flag+ # matching and the blast radius already resolve it that way, so resolve it here too;+ # otherwise the same filter silently matches nothing in insights, cohorts and the+ # groups list.+ is_group_key_column = property.type == "group" and property.key == GROUP_KEY_PROPERTY++ if property.key and (is_group_key_column or GROUP_KEY_PATTERN.match(str(property.key))):value = _stringify_group_key_value(value)if property.type == "person" and property.key == "distinct_id":@@ -1335,6 +1362,8 @@ def property_to_expr(property.key = keyelse:raise QueryError("Data warehouse person property filter value must be a string")+ elif is_group_key_column:+ chain = ["key"] if scope == "group" else group_property_chain(property.group_type_index, GROUP_KEY_PROPERTY)elif property.type == "group" and scope != "group":chain = [f"group_{property.group_type_index}", "properties"]elif property.type == "session" and scope in ["event", "replay"]:@@ -1372,7 +1401,7 @@ def property_to_expr(# We pretend elements chain is a property, but it is actually a column on the events tableif chain == ["properties"] and property.key == "$elements_chain":field = ast.Field(chain=["elements_chain"])- elif property.key == "":+ elif property.key == "" or is_group_key_column:field = ast.Field(chain=[*chain])else:field = ast.Field(chain=[*chain, property.key])diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.pyindex c98786885504..81fdcd4add25 100644--- a/posthog/hogql/test/test_property.py+++ b/posthog/hogql/test/test_property.py@@ -173,6 +173,52 @@ class TestProperty(BaseTest):self._parse_expr("properties.arr > 100"),)+ @parameterized.expand(+ [+ # `$group_key` is the group's key column, not an entry in its property JSON+ ("event_scope", {"group_type_index": 0, "value": "org_123"}, None, "group_0.key = 'org_123'"),+ ("group_scope", {"group_type_index": 2, "value": "org_123"}, "group", "key = 'org_123'"),+ # groups.key is a String column, so a numeric key has to reach it as a string+ ("numeric_value", {"group_type_index": 0, "value": 13}, None, "group_0.key = '13'"),+ (+ "multiple_values",+ {"group_type_index": 0, "value": ["org_1", "org_2"]},+ None,+ "group_0.key in ('org_1', 'org_2')",+ ),+ # Multi-value starts_with expands per value by recursing with the original key, so the+ # column has to survive that round trip+ (+ "multi_value_starts_with",+ {"group_type_index": 0, "operator": "starts_with", "value": ["org_1", "org_2"]},+ None,+ "toString(group_0.key) ilike 'org_1%' or toString(group_0.key) ilike 'org_2%'",+ ),+ ]+ )+ def test_property_to_expr_group_key(+ self, _name: str, filter_fields: dict[str, Any], scope: Optional[Literal["group"]], expected: str+ ) -> None:+ self.assertEqual(+ self._property_to_expr({"type": "group", "key": "$group_key", **filter_fields}, scope=scope),+ self._parse_expr(expected),+ )++ def test_property_to_expr_group_key_prints_the_group_join(self) -> None:+ # The AST tests above stop at `group_0.key`; this proves the resolver reaches the groups table's+ # key column through the events lazy join and does not fall back to a JSON extract.+ where = self._property_to_expr({"type": "group", "group_type_index": 0, "key": "$group_key", "value": "org_1"})+ query = ast.SelectQuery(+ select=[ast.Call(name="count", args=[])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ where=where,+ )+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ sql, _ = prepare_and_print_ast(query, context=context, dialect="clickhouse")+ assert "groups" in sql+ assert "group_key" in sql+ assert "group_properties" not in sql+def test_property_to_expr_group_booleans(self):PropertyDefinition.objects.create(team=self.team,diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 462ec18515ae..dcb69b2b40b0 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -3928,6 +3928,10 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"$group_key": {"label": "Group key","description": "Specified group key",+ "type": "String",+ # Not a row in the group's property JSON — it is the group's key column. Marked+ # virtual so the property definitions API still offers it as a selectable filter.+ "virtual": True,},"$virt_revenue": {"description": "The total revenue for this group. This will always be the current total revenue even when referring to a group via events.",diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.pyindex 75024614be38..b57e8cfa101f 100644--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py@@ -632,3 +632,29 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):funnel_event_query = FunnelEventQuery(context=context).to_query()select = format_query(funnel_event_query)self.assertIn(f"ifNull(toString(session.{breakdown_property}), '')", select)++ @parameterized.expand(+ [+ ("$group_key", ["group_0", "key"]),+ ("$virt_revenue", ["group_0", "$virt_revenue"]),+ ("industry", ["group_0", "properties", "industry"]),+ ]+ )+ @time_machine.travel("2025-11-12", tick=False)+ def test_group_breakdown_chain(self, breakdown_property: str, expected_chain: list[str]):+ query = FunnelsQuery(+ series=[EventsNode(event="$pageview"), EventsNode(event="$autocapture")],+ breakdownFilter=BreakdownFilter(+ breakdown=breakdown_property, breakdown_type=BreakdownType.GROUP, breakdown_group_type_index=0+ ),+ )+ context = FunnelQueryContext(query=query, team=self.team)++ # A single group breakdown is not wrapped in an array, unlike the session breakdown above.+ if_null = FunnelEventQuery(context=context)._get_breakdown_expr()+ assert isinstance(if_null, ast.Call) and if_null.name == "ifNull"+ to_string = if_null.args[0]+ assert isinstance(to_string, ast.Call) and to_string.name == "toString"+ field = to_string.args[0]+ assert isinstance(field, ast.Field)+ self.assertEqual(field.chain, expected_chain)diff --git a/products/product_analytics/backend/hogql_queries/funnels/utils.py b/products/product_analytics/backend/hogql_queries/funnels/utils.pyindex b94b5ded19d2..452dde521667 100644--- a/products/product_analytics/backend/hogql_queries/funnels/utils.py+++ b/products/product_analytics/backend/hogql_queries/funnels/utils.py@@ -13,7 +13,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.parser import parse_expr-from posthog.hogql.property import apply_path_cleaning+from posthog.hogql.property import apply_path_cleaning, group_property_chainfrom posthog.constants import FUNNEL_WINDOW_INTERVAL_TYPESfrom posthog.hogql_queries.utils.breakdowns import ALL_USERS_COHORT_ID, NOT_IN_COHORT_ID@@ -76,8 +76,16 @@ def get_breakdown_expr(if properties_column is None:# breakdown already refers to a top-level fieldreturn ast.Field(chain=[breakdown])- else:- return ast.Field(chain=[*properties_column.split("."), breakdown])+ column_chain = properties_column.split(".")+ # A group breakdown arrives as `group_N.properties`, but `$group_key` and `$virt_*` are not JSON entries.+ if (+ isinstance(breakdown, str)+ and len(column_chain) == 2+ and column_chain[0].startswith("group_")+ and column_chain[1] == "properties"+ ):+ return ast.Field(chain=[*group_property_chain(int(column_chain[0].removeprefix("group_")), breakdown)])+ return ast.Field(chain=[*column_chain, breakdown])# Fail loudly rather than silently skipping cleaning if a caller forgets the teamif path_cleaning and team is None:diff --git a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_utils.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_utils.pyindex 1ccccdeef2d5..298a904a3294 100644--- a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_utils.py+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_utils.py@@ -30,6 +30,10 @@ class TestBreakdownExtractExpr(SimpleTestCase):expr = breakdown_extract_expr("$virt_revenue", "group", group_type_index=0)self.assertEqual(_chain(expr), ["group_0", "$virt_revenue"])+ def test_group_breakdown_group_key_reads_the_key_column(self) -> None:+ expr = breakdown_extract_expr("$group_key", "group", group_type_index=0)+ self.assertEqual(_chain(expr), ["group_0", "key"])+def test_group_breakdown_without_index_raises_clear_error(self) -> None:# A missing index must fail loudly rather than emit an unresolvable `group_None` field.with self.assertRaises(ValueError):diff --git a/products/product_analytics/backend/hogql_queries/retention/utils.py b/products/product_analytics/backend/hogql_queries/retention/utils.pyindex 0320e051bb0f..861773ff78d9 100644--- a/products/product_analytics/backend/hogql_queries/retention/utils.py+++ b/products/product_analytics/backend/hogql_queries/retention/utils.py@@ -2,6 +2,7 @@ from typing import castfrom posthog.hogql import astfrom posthog.hogql.parser import parse_expr+from posthog.hogql.property import group_property_chainfrom posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.utils.breakdowns import strip_user_aliases@@ -31,12 +32,7 @@ def breakdown_extract_expr(property_name: str, breakdown_type: str, group_type_ielif breakdown_type == "group":if group_type_index is None:raise ValueError("group_type_index is required for group breakdowns")- group_index = int(group_type_index)- if property_name.startswith("$virt_"):- # Virtual properties exist as expression fields on the groups table- properties_chain = [f"group_{group_index}", property_name]- else:- properties_chain = [f"group_{group_index}", "properties", property_name]+ properties_chain = group_property_chain(int(group_type_index), property_name)else:# Default to event propertiesproperties_chain = ["events", "properties", property_name]diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_utils.py b/products/product_analytics/backend/hogql_queries/trends/test/test_utils.pyindex 7e78932d5e96..fad0a6d11a9c 100644--- a/products/product_analytics/backend/hogql_queries/trends/test/test_utils.py+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_utils.py@@ -42,6 +42,12 @@ def test_properties_chain_groups():assert "group_type_index missing from params" in str(e.value)+def test_properties_chain_group_key_and_virtual_properties():+ # The key column and the expression fields are not entries in the group's property JSON+ assert get_properties_chain(BreakdownType.GROUP, "$group_key", 1) == ["group_1", "key"]+ assert get_properties_chain(BreakdownType.GROUP, "$virt_revenue", 0) == ["group_0", "$virt_revenue"]++def test_properties_chain_events():p1 = get_properties_chain(breakdown_type=BreakdownType.EVENT, breakdown_field="anything", group_type_index=None)assert p1 == ["properties", "anything"]diff --git a/products/product_analytics/backend/hogql_queries/trends/utils.py b/products/product_analytics/backend/hogql_queries/trends/utils.pyindex f6a5169513d6..0cc211405281 100644--- a/products/product_analytics/backend/hogql_queries/trends/utils.py+++ b/products/product_analytics/backend/hogql_queries/trends/utils.py@@ -17,7 +17,7 @@ from posthog.schema import ()from posthog.hogql import ast-from posthog.hogql.property import action_to_expr, property_to_expr+from posthog.hogql.property import action_to_expr, group_property_chain, property_to_exprif TYPE_CHECKING:from posthog.models import Team@@ -39,12 +39,7 @@ def get_properties_chain(return ["session", breakdown_field]if breakdown_type == "group" and group_type_index is not None:- group_type_index_int = int(group_type_index)- if breakdown_field.startswith("$virt_"):- # Virtual properties exist as expression fields on the groups table- return [f"group_{group_type_index_int}", breakdown_field]- else:- return [f"group_{group_type_index_int}", "properties", breakdown_field]+ return [*group_property_chain(int(group_type_index), breakdown_field)]elif breakdown_type == "group" and group_type_index is None:raise Exception("group_type_index missing from params")