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(workflows): papercut - return 400 for unevaluable blast-radius filters (#73154)

Harley Alexander35dd2d6d645c
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 24054b7142b8..0d4a85b64f74 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -64,7 +64,7 @@ from products.feature_flags.backend.models.feature_flag import (
FeatureFlagDashboards,
get_feature_flags_for_team_in_cache,
)
-from products.feature_flags.backend.user_blast_radius import get_user_blast_radius_persons
+from products.feature_flags.backend.user_blast_radius import get_user_blast_radius, get_user_blast_radius_persons
from products.product_analytics.backend.models.insight import Insight
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.models import Survey
@@ -8896,6 +8896,58 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):
response_json = response.json()
self.assertLessEqual({"affected": 4, "total": 10}.items(), response_json.items())
+ @parameterized.expand(
+ [
+ (
+ "event_filter_in_person_scope",
+ {"key": "$browser", "type": "event", "value": ["Chrome"], "operator": "exact"},
+ "does not work in 'person' scope",
+ ),
+ (
+ "non_numeric_cohort_id",
+ {"key": "id", "type": "cohort", "value": "not-a-cohort-id"},
+ "expected a number",
+ ),
+ (
+ "missing_cohort",
+ {"key": "id", "type": "cohort", "value": 999999999},
+ "does not exist",
+ ),
+ ]
+ )
+ def test_user_blast_radius_rejects_unevaluable_filters(self, _name, prop, message_fragment):
+ from rest_framework.exceptions import ValidationError # noqa: PLC0415
+
+ with self.assertRaises(ValidationError) as ctx:
+ get_user_blast_radius(self.team, {"properties": [prop]})
+ self.assertIn(message_fragment, str(ctx.exception))
+
+ def test_user_blast_radius_execution_value_error_is_not_masked_as_caller_error(self):
+ # A bare ValueError from query execution is a server fault, not invalid filters.
+ with (
+ patch(
+ "products.feature_flags.backend.user_blast_radius._get_person_blast_radius",
+ side_effect=ValueError("could not load timezone"),
+ ),
+ self.assertRaises(ValueError),
+ ):
+ get_user_blast_radius(
+ self.team,
+ {"properties": [{"key": "group", "type": "person", "value": ["1"], "operator": "exact"}]},
+ )
+
+ def test_user_blast_radius_endpoint_returns_400_for_unevaluable_filters(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",
+ {
+ "condition": {
+ "properties": [{"key": "$browser", "type": "event", "value": ["Chrome"], "operator": "exact"}]
+ }
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["type"], "validation_error")
+
def test_user_blast_radius_with_flag_dependency(self):
for i in range(10):
_create_person(
diff --git a/products/feature_flags/backend/user_blast_radius.py b/products/feature_flags/backend/user_blast_radius.py
index c319683e1e46..8674f5e158be 100644
--- a/products/feature_flags/backend/user_blast_radius.py
+++ b/products/feature_flags/backend/user_blast_radius.py
@@ -1,17 +1,29 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
from dataclasses import dataclass
from typing import Optional
+from django.core.exceptions import ObjectDoesNotExist
+
from rest_framework.exceptions import ValidationError
from posthog.schema import PropertyOperator
+from posthog.hogql.errors import (
+ ExposedHogQLError,
+ NotImplementedError as HogQLNotImplementedError,
+)
+
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.errors import ExposedCHQueryError
from posthog.models.filters import Filter
from posthog.models.property import GroupTypeIndex, Property, PropertyGroup
from posthog.models.team.team import Team
from posthog.queries.base import relative_date_parse_for_feature_flag_matching
+from products.cohorts.backend.models.cohort import Cohort
+
@dataclass
class BlastRadiusResult:
@@ -19,6 +31,28 @@ class BlastRadiusResult:
total: int
+@contextmanager
+def unevaluable_filters_as_validation_errors() -> Iterator[None]:
+ # Sizing runs caller-supplied condition filters through HogQL and ClickHouse. Shapes those
+ # layers reject - behavioral or event filters in person scope, deleted cohort references,
+ # malformed regexes, values that don't cast to the property's type - fail deterministically
+ # on every request, so they're the caller's input, not a server fault: surface them as a 400
+ # carrying the layer's own message instead of an opaque 500. Only deliberately-exposed error
+ # types (plus ObjectDoesNotExist from cohort lookups) are converted across query build and
+ # execution; caller-shaped ValueError is converted separately in the parse phase
+ # (replace_proxy_properties), so a bare ValueError from HogQL internals or team config
+ # during build/execution still surfaces as a server fault.
+ try:
+ yield
+ except (
+ ExposedHogQLError,
+ HogQLNotImplementedError,
+ ExposedCHQueryError,
+ ObjectDoesNotExist,
+ ) as e:
+ raise ValidationError({"filters": str(e) or "These filters cannot be evaluated."}) from e
+
+
def _normalize_property_value(prop: Property) -> None:
"""
Normalize property values to strings to match JSON-stored properties in ClickHouse.
@@ -35,17 +69,26 @@ def _normalize_property_value(prop: Property) -> None:
def replace_proxy_properties(team: Team, feature_flag_condition: dict):
- prop_groups = Filter(data=feature_flag_condition, team=team).property_groups
-
- for prop in prop_groups.flat:
- if prop.operator in ("is_date_before", "is_date_after"):
- relative_date = relative_date_parse_for_feature_flag_matching(str(prop.value))
- if relative_date:
- prop.value = relative_date.strftime("%Y-%m-%d %H:%M:%S")
- else:
- _normalize_property_value(prop)
+ # Parse phase: everything here derives directly from the caller's filter JSON, so a
+ # ValueError is caller input (malformed property shape, non-numeric cohort id) and becomes
+ # a 400. Cohort ids are cast eagerly so a bad id fails here instead of surfacing as a bare
+ # ValueError from deep inside query building.
+ try:
+ prop_groups = Filter(data=feature_flag_condition, team=team).property_groups
+
+ for prop in prop_groups.flat:
+ if prop.type in ("cohort", "static-cohort", "precalculated-cohort"):
+ Cohort._meta.pk.get_prep_value(prop.value)
+ if prop.operator in ("is_date_before", "is_date_after"):
+ relative_date = relative_date_parse_for_feature_flag_matching(str(prop.value))
+ if relative_date:
+ prop.value = relative_date.strftime("%Y-%m-%d %H:%M:%S")
+ else:
+ _normalize_property_value(prop)
- return Filter(data={"properties": prop_groups.to_dict()}, team=team)
+ return Filter(data={"properties": prop_groups.to_dict()}, team=team)
+ except ValueError as e:
+ raise ValidationError({"filters": str(e) or "These filters cannot be evaluated."}) from e
def get_user_blast_radius(
@@ -54,12 +97,13 @@ def get_user_blast_radius(
group_type_index: Optional[GroupTypeIndex] = None,
) -> BlastRadiusResult:
# No rollout % calculations here, since it makes more sense to compute that on the frontend
- cleaned_filter = replace_proxy_properties(team, feature_flag_condition)
+ with unevaluable_filters_as_validation_errors():
+ cleaned_filter = replace_proxy_properties(team, feature_flag_condition)
- if group_type_index is not None:
- affected, total = _get_group_blast_radius(team, cleaned_filter, group_type_index)
- else:
- affected, total = _get_person_blast_radius(team, cleaned_filter)
+ if group_type_index is not None:
+ affected, total = _get_group_blast_radius(team, cleaned_filter, group_type_index)
+ else:
+ affected, total = _get_person_blast_radius(team, cleaned_filter)
return BlastRadiusResult(affected=affected, total=total)
@@ -70,12 +114,13 @@ def get_user_blast_radius_persons(
cursor: Optional[str] = None,
):
# No rollout % calculations here, since it makes more sense to compute that on the frontend
- cleaned_filter = replace_proxy_properties(team, feature_flag_condition)
+ with unevaluable_filters_as_validation_errors():
+ cleaned_filter = replace_proxy_properties(team, feature_flag_condition)
- if group_type_index is not None:
- return _get_group_blast_radius_persons(team, cleaned_filter, group_type_index, cursor=cursor)
- else:
- return _get_person_blast_radius_persons(team, cleaned_filter, cursor=cursor)
+ if group_type_index is not None:
+ return _get_group_blast_radius_persons(team, cleaned_filter, group_type_index, cursor=cursor)
+ else:
+ return _get_person_blast_radius_persons(team, cleaned_filter, cursor=cursor)
def _get_person_blast_radius(team: Team, filter: Filter) -> tuple[int, int]:
diff --git a/products/workflows/backend/services/batch_audience.py b/products/workflows/backend/services/batch_audience.py
index 59cfd4874e51..8a30bccd0c8f 100644
--- a/products/workflows/backend/services/batch_audience.py
+++ b/products/workflows/backend/services/batch_audience.py
@@ -13,7 +13,11 @@ from posthog.models.filters import Filter
from posthog.models.property import GroupTypeIndex
from posthog.models.team.team import Team
-from products.feature_flags.backend.user_blast_radius import get_user_blast_radius_persons, replace_proxy_properties
+from products.feature_flags.backend.user_blast_radius import (
+ get_user_blast_radius_persons,
+ replace_proxy_properties,
+ unevaluable_filters_as_validation_errors,
+)
logger = structlog.get_logger(__name__)
@@ -73,11 +77,12 @@ def get_batch_audience_person_ids(
# Group keys are already unique; the flags-owned group query needs no dedup.
return get_user_blast_radius_persons(team, filters, group_type_index, cursor)
- cleaned_filter = replace_proxy_properties(team, filters)
- select_query = _build_audience_person_query(team, cleaned_filter, cursor=cursor, dedupe_key=dedupe_key)
+ with unevaluable_filters_as_validation_errors():
+ cleaned_filter = replace_proxy_properties(team, filters)
+ select_query = _build_audience_person_query(team, cleaned_filter, cursor=cursor, dedupe_key=dedupe_key)
- tag_queries(product=Product.WORKFLOWS, feature=Feature.QUERY)
- response = execute_hogql_query(query=select_query, team=team)
+ tag_queries(product=Product.WORKFLOWS, feature=Feature.QUERY)
+ response = execute_hogql_query(query=select_query, team=team)
return [str(row[0]) for row in response.results] if response.results else []
@@ -100,25 +105,26 @@ def get_batch_audience_count(
else:
raise ValueError(f"Unsupported dedupe_key: {dedupe_key!r} (supported: {SUPPORTED_DEDUPE_KEYS})")
- cleaned_filter = replace_proxy_properties(team, filters)
+ with unevaluable_filters_as_validation_errors():
+ cleaned_filter = replace_proxy_properties(team, filters)
- where_exprs: list[ast.Expr] = [
- ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Field(chain=["persons", "team_id"]),
- right=ast.Constant(value=team.pk),
- ),
- property_to_expr(cleaned_filter.property_groups, team, scope="person"),
- ]
-
- select_query = ast.SelectQuery(
- select=[ast.Call(name="count", distinct=True, args=[group_expr])],
- select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),
- where=ast.And(exprs=where_exprs),
- )
+ where_exprs: list[ast.Expr] = [
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["persons", "team_id"]),
+ right=ast.Constant(value=team.pk),
+ ),
+ property_to_expr(cleaned_filter.property_groups, team, scope="person"),
+ ]
+
+ select_query = ast.SelectQuery(
+ select=[ast.Call(name="count", distinct=True, args=[group_expr])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),
+ where=ast.And(exprs=where_exprs),
+ )
- tag_queries(product=Product.WORKFLOWS, feature=Feature.QUERY)
- response = execute_hogql_query(query=select_query, team=team)
+ tag_queries(product=Product.WORKFLOWS, feature=Feature.QUERY)
+ response = execute_hogql_query(query=select_query, team=team)
return response.results[0][0] if response.results else 0