: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(feature-flags): return 400 for unevaluable blast radius filters (#78191)
Harley Alexander5e80fa075ff7
diff --git a/products/feature_flags/backend/test/test_user_blast_radius.py b/products/feature_flags/backend/test/test_user_blast_radius.pynew file mode 100644index 000000000000..0ebcb7d22e42--- /dev/null+++ b/products/feature_flags/backend/test/test_user_blast_radius.py@@ -0,0 +1,46 @@+from django.test import SimpleTestCase++from clickhouse_driver.errors import ServerException+from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from posthog.errors import InternalCHQueryError, wrap_clickhouse_query_error+from posthog.models.property import PropertyValidationError++from products.feature_flags.backend.user_blast_radius import unevaluable_filters_as_validation_errors+++class TestUnevaluableFiltersAsValidationErrors(SimpleTestCase):+ def test_property_validation_error_surfaces_as_a_caller_error(self):+ # Raised by Property.__init__ during query build (e.g. a referenced cohort stored with a+ # value-less property); a plain ValueError subclass, so it used to escape as a 500.+ with self.assertRaises(ValidationError) as ctx, unevaluable_filters_as_validation_errors():+ raise PropertyValidationError("Value must be set for property type person & operator gt")+ self.assertIn("Value must be set", str(ctx.exception))++ @parameterized.expand(+ [+ ("cannot_parse_text", 6),+ ("cannot_parse_number", 72),+ ]+ )+ def test_clickhouse_value_parse_failure_surfaces_as_a_caller_error(self, _name, code):+ # A numeric operator against a null/non-numeric filter value fails the Float64 cast at+ # execution; these codes wrap to InternalCHQueryError (not Exposed), so they used to 500.+ # The 400 body must carry only the useful message: the DB::Exception framing and any+ # server stack trace tail are stripped, matching what ExposedCHQueryError exposes.+ raw = "DB::Exception: Cannot parse NaN: converting 'None' to Float64. Stack trace:\n0. DB::Exception::Exception"+ err = wrap_clickhouse_query_error(ServerException(raw, code=code))+ with self.assertRaises(ValidationError) as ctx, unevaluable_filters_as_validation_errors():+ raise err+ message = str(ctx.exception)+ self.assertIn("Cannot parse NaN", message)+ self.assertNotIn("Stack trace", message)+ self.assertNotIn("DB::Exception", message)++ def test_other_internal_clickhouse_errors_stay_server_faults(self):+ # Only the deterministic cannot-parse-value codes are the caller's input; anything else+ # (here LOGICAL_ERROR) must keep surfacing as a 500 so real faults reach error tracking.+ err = wrap_clickhouse_query_error(ServerException("Logical error: invariant violated", code=49))+ with self.assertRaises(InternalCHQueryError), unevaluable_filters_as_validation_errors():+ raise errdiff --git a/products/feature_flags/backend/user_blast_radius.py b/products/feature_flags/backend/user_blast_radius.pyindex 48e412cc5cf5..0fc94587f168 100644--- a/products/feature_flags/backend/user_blast_radius.py+++ b/products/feature_flags/backend/user_blast_radius.py@@ -16,9 +16,9 @@ from posthog.hogql.errors import (from posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from posthog.errors import ExposedCHQueryError+from posthog.errors import ExposedCHQueryError, InternalCHQueryErrorfrom posthog.models.filters import Filter-from posthog.models.property import GroupTypeIndex, Property, PropertyGroup+from posthog.models.property import GroupTypeIndex, Property, PropertyGroup, PropertyValidationErrorfrom posthog.models.team.team import Teamfrom posthog.queries.base import relative_date_parse_for_feature_flag_matching@@ -31,6 +31,13 @@ class BlastRadiusResult:total: int+# ClickHouse codes for "this literal can't be parsed as the column's type": 6 CANNOT_PARSE_TEXT,+# 72 CANNOT_PARSE_NUMBER — e.g. a numeric operator (gt/lt) against a null or non-numeric filter+# value casts 'None' to Float64 and fails deterministically. Both are classified USER_ERROR in+# posthog/errors.py but not user_safe, so they wrap to InternalCHQueryError, not Exposed.+_VALUE_PARSE_CH_ERROR_CODES = frozenset({6, 72})++@contextmanagerdef unevaluable_filters_as_validation_errors() -> Iterator[None]:# Sizing runs caller-supplied condition filters through HogQL and ClickHouse. Shapes those@@ -38,10 +45,13 @@ def unevaluable_filters_as_validation_errors() -> Iterator[None]:# 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+ # types are converted across query build and execution - plus ObjectDoesNotExist from cohort+ # lookups, PropertyValidationError from Property construction during query build (its message+ # already names the offending property), and the ClickHouse cannot-parse-value codes above.+ # 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.+ # during build/execution still surfaces as a server fault, as does any other+ # InternalCHQueryError.try:yieldexcept (@@ -49,8 +59,17 @@ def unevaluable_filters_as_validation_errors() -> Iterator[None]:HogQLNotImplementedError,ExposedCHQueryError,ObjectDoesNotExist,+ PropertyValidationError,) as e:raise ValidationError({"filters": str(e) or "These filters cannot be evaluated."}) from e+ except InternalCHQueryError as e:+ if e.code not in _VALUE_PARSE_CH_ERROR_CODES:+ raise+ # Unlike ExposedCHQueryError, InternalCHQueryError's str() keeps the raw server message.+ # Rewrap so ExposedCHQueryError.__str__ strips the DB::Exception framing and any stack+ # trace tail before the message is echoed back to the caller.+ sanitized = str(ExposedCHQueryError(e.message, code=e.code, code_name=e.code_name))+ raise ValidationError({"filters": sanitized or "These filters cannot be evaluated."}) from edef _normalize_property_value(prop: Property) -> None: