: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(cohorts): give dropped property captures a stable fingerprint (#117733)
posthog[bot]454d01e876cf
diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.pyindex e9e1512a37d9..b7c799ff3584 100644--- a/posthog/hogql_queries/hogql_cohort_query.py+++ b/posthog/hogql_queries/hogql_cohort_query.py@@ -81,6 +81,22 @@ def parse_and_validate_positive_integer(value: Optional[Union[str, int]], value_return parsed_value+def _behavioral_date_range(prop: Property) -> tuple[str, Optional[str]]:+ if prop.explicit_datetime:+ # Explicit datetime filter, can be a relative or absolute date, follows same convention+ # as all analytics datetime filters+ return prop.explicit_datetime, prop.explicit_datetime_to+ # Re-raise as a DRF ValidationError so recalculation records VALIDATION_ERROR instead of UNKNOWN.+ try:+ date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")+ date_interval = validate_interval(prop.time_interval)+ except ValueError as e:+ raise ValidationError(+ f"The {prop.value} cohort filter needs either a valid time range or an explicit_datetime: {e}"+ ) from e+ return f"-{date_value}{date_interval[:1]}", None++def _require_select_query(query: ast.SelectQuery | ast.SelectSetQuery) -> ast.SelectQuery:# A constant `select=["id"]` actors query never yields a set query. Fail loudly rather than# via a strippable assert if that invariant ever breaks.@@ -328,16 +344,7 @@ class HogQLCohortQuery:filter = parse_property_group_data(prop.event_filters)series[0].properties = filter- if prop.explicit_datetime:- # Explicit datetime filter, can be a relative or absolute date, follows same convention- # as all analytics datetime filters- date_from = prop.explicit_datetime- date_to = prop.explicit_datetime_to- else:- date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")- date_interval = validate_interval(prop.time_interval)- date_from = f"-{date_value}{date_interval[:1]}"- date_to = None+ date_from, date_to = _behavioral_date_range(prop)trends_query = TrendsQuery(dateRange=DateRange(date_from=date_from, date_to=date_to),@@ -350,14 +357,7 @@ class HogQLCohortQuery:def get_performed_event_multiple(self, prop: Property) -> ast.SelectQuery:count = parse_and_validate_positive_integer(prop.operator_value, "operator_value")- if prop.explicit_datetime:- date_from = prop.explicit_datetime- date_to = prop.explicit_datetime_to- else:- date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")- date_interval = validate_interval(prop.time_interval)- date_from = f"-{date_value}{date_interval[:1]}"- date_to = None+ date_from, date_to = _behavioral_date_range(prop)events_query = EventsQuery(after=date_from, before=date_to, select=["person_id", "count()"])if prop.event_type == "events":@@ -414,14 +414,7 @@ class HogQLCohortQuery:else:raise ValueError(f"Event type must be 'events' or 'actions'")- if prop.explicit_datetime:- date_from = prop.explicit_datetime- date_to = prop.explicit_datetime_to- else:- date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")- date_interval = validate_interval(prop.time_interval)- date_from = f"-{date_value}{date_interval[:1]}"- date_to = None+ date_from, date_to = _behavioral_date_range(prop)date_value = parse_and_validate_positive_integer(prop.seq_time_value, "seq_time_value")date_interval = validate_interval(prop.seq_time_interval)diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.pyindex 02c728262425..d048cda8d389 100644--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py@@ -6,6 +6,8 @@ import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_eventsfrom unittest.mock import MagicMock, patch+from rest_framework.exceptions import ValidationError+from posthog.clickhouse.client import sync_executefrom posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery@@ -27,6 +29,37 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):with self.assertRaises(ValueError):HogQLCohortQuery(cohort=cohort).get_query()+ def test_performed_event_multiple_without_time_range_raises_validation_error(self) -> None:+ # Recalculation maps a DRF ValidationError to the VALIDATION_ERROR code, not UNKNOWN.+ cohort = Cohort.objects.create(+ team=self.team,+ name="no time range",+ filters={+ "properties": {+ "type": "OR",+ "values": [+ {+ "type": "AND",+ "values": [+ {+ "key": "$pageview",+ "type": "behavioral",+ "value": "performed_event_multiple",+ "event_type": "events",+ "operator": "gte",+ "operator_value": 2,+ "conditionHash": "abc123",+ "bytecode": ["_H", 1, 29],+ }+ ],+ }+ ],+ }+ },+ )+ with self.assertRaisesMessage(ValidationError, "needs either a valid time range or an explicit_datetime"):+ HogQLCohortQuery(cohort=cohort).get_query()+@patch("posthoganalytics.feature_enabled", return_value=True)def test_multiple_person_properties_optimization(self, mock_feature_enabled: MagicMock) -> None:"""diff --git a/posthog/models/filters/mixins/test/test_property.py b/posthog/models/filters/mixins/test/test_property.pyindex fbe9324532c4..8c86b1d16f0f 100644--- a/posthog/models/filters/mixins/test/test_property.py+++ b/posthog/models/filters/mixins/test/test_property.py@@ -235,7 +235,7 @@ def test_property_group_multi_level_json_parsing():@pytest.mark.parametrize(- "invalid_property,expected_fields,expected_exception",+ "invalid_property,expected_fields,expected_exception,expected_fingerprint",[# Behavioral leaf missing its required event_type: fails Property.__init__'s own# attr-presence checks (PropertyValidationError, raised directly).@@ -243,6 +243,7 @@ def test_property_group_multi_level_json_parsing():{"key": "$pageview", "type": "behavioral", "value": "performed_event"},["key", "type", "value"],PropertyValidationError,+ "parse_properties.PropertyValidationError.behavioral.performed_event.event_type",id="missing_event_type",),# Behavioral leaf with a value that doesn't match any known BehavioralPropertyType@@ -252,6 +253,7 @@ def test_property_group_multi_level_json_parsing():{"key": "$pageview", "type": "behavioral", "value": "not_a_real_behavior", "event_type": "events"},["event_type", "key", "type", "value"],PropertyValidationError,+ "parse_properties.PropertyValidationError.behavioral.unknown.value",id="unknown_behavioral_value",),# "group" property with an out-of-range group_type_index: fails via@@ -262,12 +264,36 @@ def test_property_group_multi_level_json_parsing():{"key": "industry", "value": "tech", "type": "group", "group_type_index": 99},["group_type_index", "key", "type", "value"],ValidationError,+ "parse_properties.ValidationError.group",id="invalid_group_type_index",),+ # Aliased behavioral leaf with no time window: fails the conditional check, whose+ # message joins sets in hash order, so the fingerprint must come from the canonical value.+ pytest.param(+ {+ "key": "$pageview",+ "type": "behavioral",+ "value": "performed_event_multiple_times",+ "event_type": "events",+ "operator_value": 2,+ },+ ["event_type", "key", "operator_value", "type", "value"],+ PropertyValidationError,+ "parse_properties.PropertyValidationError.behavioral.performed_event_multiple",+ id="aliased_leaf_without_time_window",+ ),+ # Unrecognized property type: stored strings must not reach the fingerprint.+ pytest.param(+ {"key": "attr", "value": "x", "type": "not_a_type"},+ ["key", "type", "value"],+ PropertyValidationError,+ "parse_properties.PropertyValidationError.unknown.type",+ id="unknown_property_type",+ ),],)def test_property_group_parsing_reports_and_skips_unparsable_property(- invalid_property, expected_fields, expected_exception+ invalid_property, expected_fields, expected_exception, expected_fingerprint):# A property that fails to construct used to be dropped by a bare `except: continue`# with no visibility at all. It must still be dropped (callers across the codebase@@ -295,6 +321,7 @@ def test_property_group_parsing_reports_and_skips_unparsable_property(assert kwargs["additional_properties"] == {"property_type": invalid_property["type"],"property_fields": expected_fields,+ "$exception_fingerprint": expected_fingerprint,}@@ -315,7 +342,11 @@ def test_property_group_parsing_reports_non_mapping_property():mock_capture_exception.assert_called_once()args, kwargs = mock_capture_exception.call_argsassert isinstance(args[0], TypeError)- assert kwargs["additional_properties"] == {"property_type": None, "property_fields": None}+ assert kwargs["additional_properties"] == {+ "property_type": None,+ "property_fields": None,+ "$exception_fingerprint": "parse_properties.TypeError.unknown",+ }def test_property_group_parsing_disables_code_variable_capture_for_reported_exception():diff --git a/posthog/models/property/parse.py b/posthog/models/property/parse.pyindex 3290a691ee01..2a7bde5c74b8 100644--- a/posthog/models/property/parse.py+++ b/posthog/models/property/parse.py@@ -8,7 +8,14 @@ from posthog.constants import FILTER_TEST_ACCOUNTS, PROPERTIES, PropertyOperatorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.schema_enums import PropertyOperator-from .property import Property, PropertyGroup, PropertyValidationError+from .property import (+ BEHAVIORAL_VALUE_ALIASES,+ VALIDATE_BEHAVIORAL_PROP_TYPES,+ VALIDATE_PROP_TYPES,+ Property,+ PropertyGroup,+ PropertyValidationError,+)if TYPE_CHECKING:from posthog.models.team import Team@@ -42,6 +49,28 @@ def parse_property_group_data(data: Any) -> PropertyGroup:return PropertyGroup(type=PropertyOperatorType.AND, values=parse_properties(loaded_props))+def _unparsable_property_fingerprint(error: Exception, prop_dict: dict[str, Any]) -> str:+ """Group a dropped property by its shape, not by the message or by the exception in flight.++ Without this, a chained exception that is in flight changes the default fingerprint, so one+ known malformed filter opens a new error tracking issue each time. Only known names go into+ the fingerprint, so stored data cannot create an unbounded number of issues.+ """+ parts = ["parse_properties", type(error).__name__]+ prop_type = prop_dict.get("type")+ # Stored filters can hold a list here. Check str first, because an unhashable `in` lookup+ # would raise out of the except block in parse_properties.+ parts.append(prop_type if isinstance(prop_type, str) and prop_type in VALIDATE_PROP_TYPES else "unknown")+ value = prop_dict.get("value")+ if prop_type == "behavioral" and isinstance(value, str):+ behavioral_value = BEHAVIORAL_VALUE_ALIASES.get(value, value)+ parts.append(behavioral_value if behavioral_value in VALIDATE_BEHAVIORAL_PROP_TYPES else "unknown")+ attr = getattr(error, "attr", None)+ if attr:+ parts.append(attr)+ return ".".join(parts)++def parse_properties(properties: Optional[Any]) -> list[Property]:if isinstance(properties, list):_properties = []@@ -74,6 +103,7 @@ def parse_properties(properties: Optional[Any]) -> list[Property]:additional_properties={"property_type": prop_dict.get("type"),"property_fields": sorted(prop_dict.keys()) or None,+ "$exception_fingerprint": _unparsable_property_fingerprint(e, prop_dict),},)continuediff --git a/posthog/models/property/property.py b/posthog/models/property/property.pyindex 5a175eabd081..02c65e8f405c 100644--- a/posthog/models/property/property.py+++ b/posthog/models/property/property.py@@ -236,6 +236,11 @@ class PropertyValidationError(ValueError):owned type callers can catch, instead of having to discover each new internal raisesite (e.g. via validate_group_type_index) by reading Property.__init__'s source."""+ def __init__(self, message: str, attr: Optional[str] = None) -> None:+ super().__init__(message)+ # The failing attribute, so error tracking can group by it instead of by the message.+ self.attr = attr+class Property:key: str@@ -343,17 +348,19 @@ class Property:elif self.type == "hogql":pass # keep value as Noneelif value is None:- raise PropertyValidationError(f"Value must be set for property type {self.type} & operator {self.operator}")+ raise PropertyValidationError(+ f"Value must be set for property type {self.type} & operator {self.operator}", attr="value"+ )else:self.value = valueif self.type not in VALIDATE_PROP_TYPES.keys():- raise PropertyValidationError(f"Invalid property type: {self.type}")+ raise PropertyValidationError(f"Invalid property type: {self.type}", attr="type")for attr in VALIDATE_PROP_TYPES[self.type]:if getattr(self, attr, None) is None:raise PropertyValidationError(- f"Missing required attr {attr} for property type {self.type} with key {self.key}"+ f"Missing required attr {attr} for property type {self.type} with key {self.key}", attr=attr)if self.type == "behavioral":@@ -362,12 +369,12 @@ class Property:)required_attrs = VALIDATE_BEHAVIORAL_PROP_TYPES.get(behavioral_value)if required_attrs is None:- raise PropertyValidationError(f"Invalid behavioral value: {self.value}")+ raise PropertyValidationError(f"Invalid behavioral value: {self.value}", attr="value")for attr in required_attrs:if getattr(self, attr, None) is None:raise PropertyValidationError(- f"Missing required attr {attr} for property type {self.type}::{self.value}"+ f"Missing required attr {attr} for property type {self.type}::{self.value}", attr=attr)if behavioral_value in VALIDATE_CONDITIONAL_BEHAVIORAL_PROP_TYPES: