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): stop raw ClickHouse errors reaching the condition editor (#105921)

posthog[bot]5781ce1683ec
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 557cf5783eef..e1d5509e0bf7 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -40,7 +40,7 @@ from posthog.api.cohort import (
from posthog.api.services.flags_service import FlagVersionConflictError, PropertyMatchingVersionConflictError
from posthog.api.utils import ServiceRequest
from posthog.constants import AvailableFeature
-from posthog.models import TaggedItem, User
+from posthog.models import PropertyDefinition, TaggedItem, User
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
@@ -10535,6 +10535,53 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):
response_json = response.json()
self.assertLessEqual({"affected": 4, "total": 10}.items(), response_json.items())
+ def test_user_blast_radius_with_boolean_group_property(self):
+ # ClickHouse rejects this condition unless the query passes the group type. See
+ # _group_property_globals.
+ create_group_type_mapping_without_created_at(
+ team=self.team,
+ project_id=self.team.project_id,
+ group_type="organization",
+ group_type_index=0,
+ )
+ PropertyDefinition.objects.create(
+ team=self.team,
+ name="is_paying",
+ type=PropertyDefinition.Type.GROUP,
+ group_type_index=0,
+ property_type="Boolean",
+ )
+ for i in range(4):
+ create_group(
+ team_id=self.team.pk,
+ group_type_index=0,
+ group_key=f"org:{i}",
+ properties={"is_paying": i < 2},
+ )
+
+ condition = {
+ "properties": [
+ {
+ "key": "is_paying",
+ "type": "group",
+ "value": ["true"],
+ "operator": "exact",
+ "group_type_index": 0,
+ }
+ ],
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",
+ {"condition": condition, "group_type_index": 0},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertLessEqual({"affected": 2, "total": 4}.items(), response.json().items())
+ self.assertEqual(
+ set(get_user_blast_radius_persons(self.team, condition, group_type_index=0)), {"org:0", "org:1"}
+ )
+
def test_user_blast_radius_with_groups_zero_selected(self):
create_group_type_mapping_without_created_at(
team=self.team,
diff --git a/products/feature_flags/backend/test/test_user_blast_radius.py b/products/feature_flags/backend/test/test_user_blast_radius.py
index f9a3168771a6..9c3c7191a94e 100644
--- a/products/feature_flags/backend/test/test_user_blast_radius.py
+++ b/products/feature_flags/backend/test/test_user_blast_radius.py
@@ -4,10 +4,15 @@ 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.errors import CLICKHOUSE_ERROR_CODE_LOOKUP, 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
+from products.feature_flags.backend.user_blast_radius import (
+ UNEVALUABLE_FILTERS_MESSAGE,
+ unevaluable_filters_as_validation_errors,
+)
+
+PARSE_NAN_TO_FLOAT = "Cannot parse NaN: converting 'None' to Float64"
class TestUnevaluableFiltersAsValidationErrors(SimpleTestCase):
@@ -20,32 +25,36 @@ class TestUnevaluableFiltersAsValidationErrors(SimpleTestCase):
@parameterized.expand(
[
+ ("cannot_parse_text", 6, PARSE_NAN_TO_FLOAT, CLICKHOUSE_ERROR_CODE_LOOKUP[6].user_safe),
+ ("cannot_parse_number", 72, PARSE_NAN_TO_FLOAT, CLICKHOUSE_ERROR_CODE_LOOKUP[72].user_safe),
(
- "cannot_parse_text",
- 6,
- "Cannot parse a value as the requested type. Check your input formats and type conversions.",
+ "no_supertype",
+ 386,
+ "There is no supertype for types String, UInt8 because some of them are String",
+ UNEVALUABLE_FILTERS_MESSAGE,
),
(
- "cannot_parse_number",
- 72,
- "Cannot parse a number. Check for non-numeric values in your type conversions.",
+ "illegal_type_of_argument",
+ 43,
+ "Illegal type String of argument of function equals",
+ UNEVALUABLE_FILTERS_MESSAGE,
),
+ ("curated_copy", 70, "CANNOT_CONVERT_TYPE", CLICKHOUSE_ERROR_CODE_LOOKUP[70].user_safe),
]
)
- def test_clickhouse_value_parse_failure_surfaces_as_a_caller_error(
- self, _name: str, code: int, expected_message: str
+ def test_clickhouse_failure_surfaces_as_a_caller_error(
+ self, _name: str, code: int, raw: str, expected: str
) -> None:
- 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))
+ # The 400 carries only copy that PostHog wrote, because the ClickHouse message names
+ # engine types and generated SQL instead of the filter to correct. A code whose
+ # ErrorCodeMeta names a user-facing string keeps that string; the rest fall back to the
+ # generic line.
+ err = wrap_clickhouse_query_error(ServerException(f"DB::Exception: {raw}", code=code))
with self.assertRaises(ValidationError) as ctx, unevaluable_filters_as_validation_errors():
raise err
- message = str(ctx.exception)
- assert isinstance(ctx.exception.detail, dict)
- self.assertEqual(ctx.exception.detail["filters"], expected_message)
- self.assertNotIn("NaN", message)
- self.assertNotIn("None", message)
- self.assertNotIn("Stack trace", message)
- self.assertNotIn("DB::Exception", message)
+ detail = ctx.exception.detail
+ assert isinstance(detail, dict)
+ self.assertEqual(detail["filters"], expected)
def test_other_internal_clickhouse_errors_stay_server_faults(self):
# Only the deterministic cannot-parse-value codes are the caller's input; anything else
diff --git a/products/feature_flags/backend/user_blast_radius.py b/products/feature_flags/backend/user_blast_radius.py
index f48046332e49..fd3b5bccf179 100644
--- a/products/feature_flags/backend/user_blast_radius.py
+++ b/products/feature_flags/backend/user_blast_radius.py
@@ -21,7 +21,7 @@ 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
from posthog.dataclasses import frozen
-from posthog.errors import ExposedCHQueryError, InternalCHQueryError
+from posthog.errors import ExposedCHQueryError, InternalCHQueryError, look_up_clickhouse_error_code_meta
from posthog.models.property import GroupTypeIndex, Property, PropertyGroup, PropertyValidationError
from posthog.models.property.parse import parse_properties_for_team
from posthog.models.property.relative_date import relative_date_parse_for_feature_flag_matching
@@ -101,6 +101,17 @@ def sampled_person_blast_radius(team: Team, prop_group: PropertyGroup, query_typ
# in stored flag dependencies, which must fall back to sizing without the dependency.
_VALUE_PARSE_CH_ERROR_CODES = frozenset({6, 72})
+UNEVALUABLE_FILTERS_MESSAGE = "These filters can't be evaluated. Check the property values."
+
+
+def _group_property_globals(group_type_index: GroupTypeIndex) -> dict[str, int]:
+ """
+ HogQL reads the group type from this global to resolve group property types when a query
+ selects from `groups` directly. Without it, HogQL compares a Boolean group property as a
+ string, and ClickHouse rejects the query.
+ """
+ return {"group_id": group_type_index}
+
@contextmanager
def unevaluable_filters_as_validation_errors() -> Iterator[None]:
@@ -108,10 +119,13 @@ def unevaluable_filters_as_validation_errors() -> Iterator[None]:
# 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 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.
+ # instead of an opaque 500. The release condition editor and the workflow batch trigger print
+ # the 400 detail as it arrives. HogQL writes its messages for a person to read, so those are
+ # echoed. ClickHouse writes its messages for the engine, so the caller sees only copy that
+ # PostHog wrote: an ErrorCodeMeta user_safe string, or the generic message. Only
+ # deliberately-exposed error types are converted across query build and execution - plus
+ # ObjectDoesNotExist from cohort lookups and PropertyValidationError from Property
+ # construction during query build, whose message already names the offending property.
# 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, as does any other
@@ -121,19 +135,18 @@ def unevaluable_filters_as_validation_errors() -> Iterator[None]:
except (
ExposedHogQLError,
HogQLNotImplementedError,
- ExposedCHQueryError,
ObjectDoesNotExist,
PropertyValidationError,
) as e:
- raise ValidationError({"filters": str(e) or "These filters cannot be evaluated."}) from e
+ raise ValidationError({"filters": str(e) or UNEVALUABLE_FILTERS_MESSAGE}) from e
+ except ExposedCHQueryError as e:
+ curated_copy = look_up_clickhouse_error_code_meta(e).user_safe
+ message = curated_copy if isinstance(curated_copy, str) else UNEVALUABLE_FILTERS_MESSAGE
+ raise ValidationError({"filters": message}) 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 e
+ raise ValidationError({"filters": UNEVALUABLE_FILTERS_MESSAGE}) from e
def _normalize_property_value(prop: Property) -> None:
@@ -171,7 +184,7 @@ def replace_proxy_properties(team: Team, feature_flag_condition: dict) -> Proper
return prop_groups
except ValueError as e:
- raise ValidationError({"filters": str(e) or "These filters cannot be evaluated."}) from e
+ raise ValidationError({"filters": str(e) or UNEVALUABLE_FILTERS_MESSAGE}) from e
def get_user_blast_radius(
@@ -357,7 +370,7 @@ def _get_group_blast_radius(
query=select_query,
team=team,
workload=Workload.OFFLINE,
- context=HogQLContext(team_id=team.pk, database=database),
+ context=HogQLContext(team_id=team.pk, database=database, globals=_group_property_globals(group_type_index)),
)
total_affected = response.results[0][0] if response.results else 0
@@ -644,6 +657,7 @@ def _get_group_blast_radius_persons(
query=select_query,
team=team,
workload=Workload.OFFLINE,
+ context=HogQLContext(team_id=team.pk, globals=_group_property_globals(group_type_index)),
)
# Extract group keys from results