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(flags): count group blast radius via HogQL with one database build (#91449)

Sandy Spicer848fb79957e0
diff --git a/posthog/models/team/team.py b/posthog/models/team/team.py
index 16290882f03f..09a8f238bc07 100644
--- a/posthog/models/team/team.py
+++ b/posthog/models/team/team.py
@@ -908,19 +908,24 @@ class Team(UUIDTClassicModel):
@lru_cache(maxsize=5) # noqa: B019 - TODO: refactor to module-level cache
def groups_seen_so_far(self, group_type_index: GroupTypeIndex) -> int:
- from posthog.clickhouse.client import sync_execute
+ return self.count_groups_seen_so_far(group_type_index)
+
+ def count_groups_seen_so_far(self, group_type_index: GroupTypeIndex, database: Optional["Database"] = None) -> int:
+ from posthog.hogql import ast # noqa: PLC0415 — breaks team import cycle
+ from posthog.hogql.context import HogQLContext # noqa: PLC0415 — breaks team import cycle
+ from posthog.hogql.query import execute_hogql_query # noqa: PLC0415 — breaks team import cycle
with tags_context(product=Product.FEATURE_FLAGS, feature=Feature.QUERY):
- # nosemgrep: clickhouse-fstring-param-audit - no interpolation, only parameterized values
- return sync_execute(
- f"""
- SELECT
- count(DISTINCT group_key)
- FROM groups
- WHERE team_id = %(team_id)s AND group_type_index = %(group_type_index)s
- """,
- {"team_id": self.pk, "group_type_index": group_type_index},
- )[0][0]
+ return execute_hogql_query(
+ # `raw_groups` holds one row per group update, so DISTINCT does the dedup. The `groups`
+ # lazy table would first collapse every row of the team through its argMax subquery.
+ "SELECT count(DISTINCT key) FROM raw_groups WHERE index = {group_type_index}",
+ placeholders={"group_type_index": ast.Constant(value=group_type_index)},
+ team=self,
+ query_type="groups_seen_so_far",
+ # A caller that runs several queries can pass a prebuilt database to skip a rebuild.
+ context=HogQLContext(team_id=self.pk, database=database),
+ ).results[0][0]
@property
def timezone_info(self) -> ZoneInfo:
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index 5ec5a4b38d26..e9eedd948d43 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -158,10 +158,21 @@
# name: TestBlastRadius.test_user_blast_radius_with_group_key_property.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT count(DISTINCT group_key)
+ SELECT count(DISTINCT groups.group_key) AS `count(DISTINCT key)`
FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
+ WHERE and(equals(groups.team_id, 99999), equals(groups.group_type_index, 0))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestBlastRadius.test_user_blast_radius_with_group_key_property.2
@@ -191,6 +202,26 @@
use_hive_partitioning=0
'''
# ---
+# name: TestBlastRadius.test_user_blast_radius_with_group_key_property.3
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT count(DISTINCT groups.group_key) AS `count(DISTINCT key)`
+ FROM groups
+ WHERE and(equals(groups.team_id, 99999), equals(groups.group_type_index, 0))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestBlastRadius.test_user_blast_radius_with_groups
'''
/* user_id:0 request:_snapshot_ */
@@ -222,10 +253,21 @@
# name: TestBlastRadius.test_user_blast_radius_with_groups.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT count(DISTINCT group_key)
+ SELECT count(DISTINCT groups.group_key) AS `count(DISTINCT key)`
FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
+ WHERE and(equals(groups.team_id, 99999), equals(groups.group_type_index, 0))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestBlastRadius.test_user_blast_radius_with_groups_multiple_queries
@@ -259,10 +301,21 @@
# name: TestBlastRadius.test_user_blast_radius_with_groups_multiple_queries.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT count(DISTINCT group_key)
+ SELECT count(DISTINCT groups.group_key) AS `count(DISTINCT key)`
FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
+ WHERE and(equals(groups.team_id, 99999), equals(groups.group_type_index, 0))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestBlastRadius.test_user_blast_radius_with_multiple_precalculated_cohorts
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 0d02dc8e3f74..891f257fc2cc 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -35,7 +35,7 @@ from posthog.api.cohort import BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS, get_cohort_a
from posthog.api.services.flags_service import FlagVersionConflictError
from posthog.constants import AvailableFeature
from posthog.models import TaggedItem, User
-from posthog.models.group.util import create_group
+from posthog.models.group.util import create_group, raw_create_group_ch
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
@@ -10119,6 +10119,8 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):
group_key=f"org:{i}",
properties={"industry": f"{i}"},
)
+ # A property update writes a second ClickHouse row for the same key; it is still one group.
+ raw_create_group_ch(self.team.pk, 1, "org:0", {"industry": "updated"}, created_at=now())
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",
diff --git a/products/feature_flags/backend/user_blast_radius.py b/products/feature_flags/backend/user_blast_radius.py
index b317e7dcd954..a741425d29b5 100644
--- a/products/feature_flags/backend/user_blast_radius.py
+++ b/products/feature_flags/backend/user_blast_radius.py
@@ -8,10 +8,15 @@ from rest_framework.exceptions import ValidationError
from posthog.schema import PropertyOperator
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
from posthog.hogql.errors import (
ExposedHogQLError,
NotImplementedError as HogQLNotImplementedError,
)
+from posthog.hogql.property import property_to_expr
+from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
@@ -143,9 +148,6 @@ def get_user_blast_radius_persons(
def _get_person_blast_radius(team: Team, filter: Filter) -> BlastRadiusResult:
"""Calculate blast radius for person-based feature flags using HogQL."""
- from posthog.hogql.context import HogQLContext
- from posthog.hogql.database.database import Database
- from posthog.hogql.query import execute_hogql_query
properties = filter.property_groups.flat
@@ -178,8 +180,6 @@ def _get_person_blast_radius(team: Team, filter: Filter) -> BlastRadiusResult:
def _build_person_query(team: Team, filter: Filter, return_count: bool = True, cursor: Optional[str] = None):
"""Build HogQL AST query to count or select distinct persons matching filters."""
- from posthog.hogql import ast
- from posthog.hogql.property import property_to_expr
# Build the main SELECT with either count(DISTINCT persons.id) or DISTINCT persons.id
if return_count:
@@ -231,7 +231,6 @@ def _build_person_query(team: Team, filter: Filter, return_count: bool = True, c
def _get_group_blast_radius(team: Team, filter: Filter, group_type_index: GroupTypeIndex) -> BlastRadiusResult:
"""Calculate blast radius for group-based feature flags using HogQL."""
- from posthog.hogql.query import execute_hogql_query
properties = filter.property_groups.flat
@@ -257,14 +256,17 @@ def _get_group_blast_radius(team: Team, filter: Filter, group_type_index: GroupT
# Execute the query with OFFLINE workload (groups queries can be massive)
tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.QUERY)
+ # One database build shared by both counts, as in _get_person_blast_radius above.
+ database = Database.create_for(team=team)
response = execute_hogql_query(
query=select_query,
team=team,
workload=Workload.OFFLINE,
+ context=HogQLContext(team_id=team.pk, database=database),
)
total_affected = response.results[0][0] if response.results else 0
- total_groups = team.groups_seen_so_far(group_type_index)
+ total_groups = team.count_groups_seen_so_far(group_type_index, database=database)
return BlastRadiusResult(affected=total_affected, total=total_groups)
@@ -280,8 +282,6 @@ def _build_group_query(
cursor: Optional[str] = None,
):
"""Build HogQL AST query to count or select distinct groups matching filters."""
- from posthog.hogql import ast
- from posthog.hogql.property import property_to_expr
# Build the main SELECT with either count(DISTINCT groups.key) or DISTINCT groups.key
if return_count:
@@ -510,7 +510,6 @@ def _build_group_query(
def _get_person_blast_radius_persons(team: Team, filter: Filter, cursor: Optional[str] = None) -> list[str]:
"""Get distinct person IDs matching person-based feature flag filters."""
- from posthog.hogql.query import execute_hogql_query
# Build the SELECT query to get person IDs
select_query = _build_person_query(team, filter, return_count=False, cursor=cursor)
@@ -530,7 +529,6 @@ def _get_group_blast_radius_persons(
team: Team, filter: Filter, group_type_index: GroupTypeIndex, cursor: Optional[str] = None
) -> list[str]:
"""Get distinct group keys matching group-based feature flag filters."""
- from posthog.hogql.query import execute_hogql_query
properties = filter.property_groups.flat