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): keep HogQL property filters out of the operator default (#97577)

posthog[bot]520f3b94829a
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 844d74c7c0f9..a9604b11d011 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -45,7 +45,7 @@ from posthog.api.services.flags_service import (
batch_evaluate_flag_for_team,
)
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
-from posthog.api.utils import action
+from posthog.api.utils import action, parse_actor_property_filters
from posthog.cdp.filters import build_behavioral_event_expr
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.constants import LIMIT, OFFSET
@@ -1847,14 +1847,7 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
cohort_properties: list[dict] = [{"type": "cohort", "key": "id", "value": cohort.pk}]
- request_properties = request.GET.get("properties")
- if request_properties:
- for prop in json.loads(request_properties):
- # Legacy person filters default to the "exact" operator when none is given;
- # ActorsQuery's PersonPropertyFilter requires it explicitly.
- if prop.get("type") != "cohort":
- prop.setdefault("operator", "exact")
- cohort_properties.append(prop)
+ cohort_properties.extend(parse_actor_property_filters(request.GET.get("properties")))
actors_query = ActorsQuery(
select=["id"],
diff --git a/posthog/api/person.py b/posthog/api/person.py
index bf804d47c600..7ff27956b625 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -1,5 +1,4 @@
import re
-import json
import uuid
import builtins
import dataclasses
@@ -39,7 +38,7 @@ from posthog.api.fields import CoercedStringListField
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.utils import action
+from posthog.api.utils import action, parse_actor_property_filters
from posthog.auth import PersonalAPIKeyAuthentication
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.constants import LIMIT, OFFSET
@@ -649,14 +648,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner # noqa: PLC0415
- person_properties: list[dict] = []
- raw_properties = request.GET.get("properties")
- if raw_properties:
- for prop in json.loads(raw_properties):
- # Legacy person filters default to the "exact" operator; ActorsQuery requires it explicitly.
- if prop.get("type") != "cohort":
- prop.setdefault("operator", "exact")
- person_properties.append(prop)
+ person_properties: list[dict] = parse_actor_property_filters(request.GET.get("properties"))
if filter.email:
person_properties.append({"type": "person", "key": "email", "value": filter.email, "operator": "exact"})
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index d82b8bfe24a5..97c574cb7da4 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -2627,7 +2627,14 @@ [email protected],
response = self.client.get(response.json()["next"])
self.assertEqual(len(response.json()["results"]), 50, response)
- def test_filter_by_cohort_prop(self):
+ @parameterized.expand(
+ [
+ ("hogql", {"type": "hogql", "key": "properties.$browser = 'Safari'"}),
+ ("type_less_person", {"key": "$browser", "value": "Safari"}),
+ ("person", {"key": "$browser", "value": "Safari", "type": "person"}),
+ ]
+ )
+ def test_filter_by_prop_without_an_operator(self, _name: str, prop: dict):
for i in range(5):
_create_person(
team=self.team,
@@ -2637,7 +2644,7 @@ [email protected],
_create_person(
team=self.team,
- distinct_ids=[f"target"],
+ distinct_ids=["target"],
properties={"$os": "Chrome", "$browser": "Safari"},
)
@@ -2647,10 +2654,8 @@ [email protected],
)
cohort.calculate_people_ch(pending_version=0)
- response = self.client.get(
- f"/api/cohort/{cohort.pk}/persons?properties=%s"
- % (json.dumps([{"key": "$browser", "value": "Safari", "type": "person"}]))
- )
+ response = self.client.get(f"/api/cohort/{cohort.pk}/persons?properties=%s" % (json.dumps([prop])))
+ self.assertEqual(response.status_code, 200, response.json())
self.assertEqual(len(response.json()["results"]), 1, response)
def test_filter_by_cohort_prop_from_clickhouse(self):
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 18e4cdbd9046..a38b896a6966 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -303,6 +303,34 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 1)
+ @parameterized.expand(
+ [
+ ("hogql", {"type": "hogql", "key": "properties.email like '%@example.com'"}, 2),
+ ("type_less_person", {"key": "email", "value": "[email protected]"}, 1),
+ ]
+ )
+ def test_properties_without_an_operator(self, _name: str, prop: dict, expected_count: int) -> None:
+ _create_person(
+ team=self.team,
+ distinct_ids=["distinct_id"],
+ properties={"email": "[email protected]"},
+ )
+ _create_person(
+ team=self.team,
+ distinct_ids=["distinct_id_2"],
+ properties={"email": "[email protected]"},
+ )
+ _create_person(
+ team=self.team,
+ distinct_ids=["distinct_id_3"],
+ properties={"email": "[email protected]"},
+ )
+ flush_persons_and_events()
+
+ response = self.client.get("/api/person/?properties={}".format(json.dumps([prop])))
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual(len(response.json()["results"]), expected_count)
+
@also_test_with_materialized_columns(person_properties=["random_prop"])
@snapshot_clickhouse_queries
def test_person_property_values(self):
diff --git a/posthog/api/test/test_utils.py b/posthog/api/test/test_utils.py
index 076402910744..3b72fd7f397d 100644
--- a/posthog/api/test/test_utils.py
+++ b/posthog/api/test/test_utils.py
@@ -19,6 +19,7 @@ from posthog.api.utils import (
hostname_in_allowed_url_list,
is_async_query,
is_insight_query,
+ parse_actor_property_filters,
raise_if_user_provided_url_unsafe,
safe_clickhouse_string,
validate_authorized_url_wildcards,
@@ -348,6 +349,25 @@ class TestUtils(BaseTest):
assert is_insight_query(query) == expected_insight
assert is_async_query(query) == expected_async
+ @parameterized.expand(
+ [
+ ("empty placeholder keeps no operator", [{}], [{}]),
+ (
+ "person_metadata gets the default",
+ [{"type": "person_metadata", "key": "created_at"}],
+ [{"type": "person_metadata", "key": "created_at", "operator": "exact"}],
+ ),
+ (
+ "a stray operator on a hogql filter is dropped",
+ [{"type": "hogql", "key": "properties.$browser = 'Safari'", "operator": "exact"}],
+ [{"type": "hogql", "key": "properties.$browser = 'Safari'"}],
+ ),
+ ("explicit empty type keeps no operator", [{"type": "empty"}], [{"type": "empty"}]),
+ ]
+ )
+ def test_parse_actor_property_filters(self, _name: str, properties: list[dict], expected: list[dict]) -> None:
+ assert parse_actor_property_filters(json.dumps(properties)) == expected
+
@parameterized.expand(
[
("empty allowlist", [], "http://localhost:8123", False),
diff --git a/posthog/api/utils.py b/posthog/api/utils.py
index 13f0708eab87..ba1eb6878181 100644
--- a/posthog/api/utils.py
+++ b/posthog/api/utils.py
@@ -35,6 +35,7 @@ from posthog.exceptions import (
generate_exception_response,
)
from posthog.helpers.impersonation import is_impersonated
+from posthog.hogql_queries.legacy_compatibility.clean_properties import clean_property
from posthog.models import Entity, User
from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
from posthog.models.entity import MathType
@@ -327,6 +328,21 @@ def get_pk_or_uuid(queryset: QuerySet, key: Union[int, str]) -> QuerySet:
return queryset.filter(pk=key)
+def parse_actor_property_filters(raw_properties: Optional[str]) -> list[dict]:
+ """Read the `properties` query parameter of a person or cohort actors endpoint.
+
+ Filters that `ActorsQuery` requires an `operator` on get `exact` when the caller omits it.
+ """
+ if not raw_properties:
+ return []
+ properties = json.loads(raw_properties)
+ if not isinstance(properties, list):
+ return []
+ # An empty filter, bare `{}` or explicit `{"type": "empty"}`, must keep no operator;
+ # `clean_property` only excludes `hogql` from its default, not `empty`.
+ return [clean_property(prop) if prop and prop.get("type") != "empty" else prop for prop in properties]
+
+
INSIGHT_KINDS = {
"TrendsQuery",
"FunnelsQuery",