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(cohorts): unwrap single-element list values for single-value operators (#90212)

Gustavo H. Strassburger7daf581a29f6
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index c24127fd462e..844d74c7c0f9 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -78,7 +78,7 @@ from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.filters.filter import Filter
from posthog.models.filters.utils import earliest_timestamp_func
from posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist
-from posthog.models.property.property import Property
+from posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORS, Property
from posthog.models.property.relative_date import determine_parsed_date_for_property_matching
from posthog.models.team.team import DEPRECATED_ATTRS, Team
from posthog.models.utils import UUIDT
@@ -326,6 +326,59 @@ class CohortFilter(FilterBytecodeMixin, BaseModel, extra="forbid"):
# Keep in sync with OperatorType in posthog/models/property/property.py
DATE_OPERATORS = ("is_date_after", "is_date_before")
+# Operators that compare against exactly one value. A multi-value list is meaningful for
+# `icontains`/`not_icontains` in HogQL, which turns it into multiSearchAnyCaseInsensitive, so
+# only the single-element case is unwrapped here.
+SINGLE_VALUE_OPERATORS = (
+ "icontains",
+ "not_icontains",
+ *STRING_PREFIX_SUFFIX_OPERATORS,
+ *DATE_OPERATORS,
+)
+
+# Filter variants that inherit PersonValueValidationMixin, and so store an unwrapped value.
+SINGLE_VALUE_FILTER_TYPES = ("person", "person_metadata")
+
+
+def _single_value_operator_value(operator: str | None, value: Any) -> Any:
+ """Unwrap `["x"]` to `"x"` for operators that compare against one string.
+
+ The two cohort readers disagree about a single-element list. HogQL unwraps it
+ (posthog/hogql/property.py), so the cohort lists the person, while the Rust flag evaluator
+ stringifies it and searches for the literal text `["x"]`, so the flag never matches. Storing
+ the unwrapped string is what both readers already agree on.
+ """
+ if operator in SINGLE_VALUE_OPERATORS and isinstance(value, list) and len(value) == 1:
+ # Unwrapping `[None]` gives `None`, which the missing-value check below rejects. That
+ # payload saves today, so leave a non-string element wrapped.
+ if isinstance(value[0], str):
+ return value[0]
+ return value
+
+
+def _coerce_stored_filter_values(filters: Any) -> Any:
+ """Apply the single-value unwrap to a stored filters dict, without re-running validation.
+
+ `update()` compares the incoming filters against the stored ones to decide whether the
+ criteria changed. Incoming filters have already been unwrapped by `validate_filters`, so a row
+ written before the unwrap existed would compare unequal on a save that touched no criteria,
+ and a static cohort holding such a value would become uneditable.
+ """
+ if isinstance(filters, list):
+ return [_coerce_stored_filter_values(item) for item in filters]
+ if not isinstance(filters, dict):
+ return filters
+
+ coerced = {
+ key: _coerce_stored_filter_values(value) if key in ("properties", "values") else value
+ for key, value in filters.items()
+ }
+ # An is_set/is_not_set filter stores no value key, and validate_filters serializes with
+ # exclude_none, so writing `value: None` here would make an unchanged filter compare unequal.
+ if coerced.get("type") in SINGLE_VALUE_FILTER_TYPES and "value" in coerced:
+ coerced["value"] = _single_value_operator_value(coerced.get("operator"), coerced.get("value"))
+ return coerced
+
class PersonValueValidationMixin(BaseModel):
"""Shared value/operator presence and date-value validation for the person and
@@ -336,6 +389,12 @@ class PersonValueValidationMixin(BaseModel):
operator: str | None = None # accept any legacy operator
value: Any | None = None # mostly likely it's list[str], str, or None
+ @model_validator(mode="after")
+ def _coerce_single_value_list(self) -> "PersonValueValidationMixin":
+ # Runs before the date check below so that check sees the unwrapped value.
+ self.value = _single_value_operator_value(self.operator, self.value)
+ return self
+
@model_validator(mode="after")
def _missing_keys_check(self):
missing: list[str] = []
@@ -1268,7 +1327,9 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
def update(self, cohort: Cohort, validated_data: dict, *args: Any, **kwargs: Any) -> Cohort: # type: ignore
request = self.context["request"]
existing_has_criteria = cohort_filters_have_values(cohort.filters)
- filters_changed = "filters" in validated_data and validated_data.get("filters") != cohort.filters
+ filters_changed = "filters" in validated_data and validated_data.get("filters") != _coerce_stored_filter_values(
+ cohort.filters
+ )
create_in_folder = validated_data.pop("_create_in_folder", None)
if create_in_folder is not None:
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index b677b84a9c82..d82b8bfe24a5 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -3747,6 +3747,46 @@ [email protected],
self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ @parameterized.expand(
+ [
+ ("holding_legacy_single_element_list", "icontains", "@example.com"),
+ ("with_is_set_filter_without_value_key", "is_set", None),
+ ]
+ )
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_rename_static_cohort_with_unchanged_criteria(
+ self, _name: str, operator: str, value: str | None, patch_calculate_cohort, patch_capture
+ ) -> None:
+ person_filter = {"key": "email", "type": "person", "operator": operator, "value": value}
+ stored_filters = CohortFilters.model_validate(
+ {"properties": {"type": "OR", "values": [person_filter]}}, context={"team": self.team}
+ ).model_dump(exclude_none=True)
+ if value is not None:
+ # A row written before the unwrap shipped. HogQL builds the same bytecode either way.
+ stored_filters["properties"]["values"][0]["value"] = [value]
+ static_cohort = Cohort.objects.create(
+ team=self.team,
+ name="static cohort",
+ is_static=True,
+ filters=stored_filters,
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/cohorts/{static_cohort.pk}",
+ data={
+ "name": "renamed static cohort",
+ "filters": stored_filters,
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ static_cohort.refresh_from_db()
+ self.assertEqual(static_cohort.name, "renamed static cohort")
+ assert static_cohort.filters is not None
+ # The save also repairs a legacy list in place: the persisted value is the unwrapped scalar.
+ self.assertEqual(static_cohort.filters["properties"]["values"][0].get("value"), value)
+
@parameterized.expand([("with_filters", True), ("without_filters", False)])
@patch("posthog.api.cohort.report_user_action")
@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
@@ -4392,6 +4432,52 @@ [email protected],
self.assertEqual(response.status_code, 201, response.json())
self.assertNotEqual(response.json()["id"], None)
+ @parameterized.expand(
+ [
+ ("icontains_single_list", "person", "email", "icontains", ["@example.com"], "@example.com"),
+ ("not_icontains_single_list", "person", "email", "not_icontains", ["@example.com"], "@example.com"),
+ ("starts_with_single_list", "person", "email", "starts_with", ["admin"], "admin"),
+ ("not_starts_with_single_list", "person", "email", "not_starts_with", ["admin"], "admin"),
+ ("ends_with_single_list", "person", "email", "ends_with", [".com"], ".com"),
+ ("not_ends_with_single_list", "person", "email", "not_ends_with", [".com"], ".com"),
+ ("is_date_after_single_list", "person", "email", "is_date_after", ["-7d"], "-7d"),
+ ("is_date_before_single_list", "person", "email", "is_date_before", ["-7d"], "-7d"),
+ (
+ "person_metadata_single_list",
+ "person_metadata",
+ "created_at",
+ "is_date_after",
+ ["2024-01-01"],
+ "2024-01-01",
+ ),
+ ("icontains_multi_list_kept", "person", "email", "icontains", ["@a.com", "@b.com"], ["@a.com", "@b.com"]),
+ ("icontains_plain_string_kept", "person", "email", "icontains", "@example.com", "@example.com"),
+ ("icontains_empty_list_kept", "person", "email", "icontains", [], []),
+ ("icontains_non_string_element_kept", "person", "email", "icontains", [None], [None]),
+ ("exact_single_list_kept", "person", "email", "exact", ["admin"], ["admin"]),
+ ]
+ )
+ @patch("posthog.api.cohort.report_user_action")
+ def test_cohort_single_value_operator_unwraps_single_element_list(
+ self, _name, filter_type, key, operator, value, expected, patch_capture
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={
+ "name": f"cohort with {operator}",
+ "filters": {
+ "properties": {
+ "type": "OR",
+ "values": [{"key": key, "type": filter_type, "operator": operator, "value": value}],
+ }
+ },
+ },
+ )
+ self.assertEqual(response.status_code, 201, response.json())
+ cohort = Cohort.objects.get(pk=response.json()["id"])
+ assert cohort.filters is not None
+ self.assertEqual(cohort.filters["properties"]["values"][0]["value"], expected)
+
@patch("posthog.api.cohort.report_user_action")
def test_cohort_property_validation_cohort_filter(self, patch_capture):
# First create a cohort to reference