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): preserve persons list search when saving static cohort (#65375)

Lucky negi97f8c09ca566
diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.py
index 354c53b3c1ea..0aea83008fd0 100644
--- a/products/cohorts/backend/models/test/test_util.py
+++ b/products/cohorts/backend/models/test/test_util.py
@@ -11,6 +11,7 @@ from rest_framework.exceptions import ValidationError as DRFValidationError
from posthog.hogql.hogql import HogQLContext
+from posthog.clickhouse.client import sync_execute
from posthog.exceptions import (
ClickHouseAtCapacity,
ClickHouseEstimatedQueryExecutionTimeTooLong,
@@ -18,14 +19,17 @@ from posthog.exceptions import (
ClickHouseQuerySizeExceeded,
ClickHouseQueryTimeOut,
)
+from posthog.models.person.sql import PERSON_STATIC_COHORT_TABLE
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
from products.cohorts.backend.models.util import (
CohortErrorCode,
+ _sanitize_query_for_cohort,
get_all_cohort_dependencies,
get_friendly_error_message,
get_nested_cohort_ids,
get_static_cohort_size,
+ insert_cohort_query_actors_into_ch,
parse_error_code,
print_cohort_hogql_query,
simplified_cohort_filter_properties,
@@ -400,6 +404,59 @@ class TestCohortUtils(BaseTest):
self.assertIn("allow_experimental_object_type=1", sql)
self.assertIn("optimize_min_equality_disjunction_chain_length=4294967295", sql)
+ @parameterized.expand(
+ [
+ (
+ "persons_list",
+ {"kind": "ActorsQuery", "search": "example.com", "select": ["person"]},
+ "example.com",
+ ),
+ (
+ "insight_modal",
+ {
+ "kind": "ActorsQuery",
+ "search": "example.com",
+ "source": {"kind": "InsightActorsQuery", "source": {"kind": "TrendsQuery", "series": []}},
+ },
+ None,
+ ),
+ ]
+ )
+ def test_sanitize_query_for_cohort_search_handling(self, _name, query_dict, expected_search):
+ sanitized = _sanitize_query_for_cohort(query_dict)
+ if expected_search is None:
+ self.assertNotIn("search", sanitized)
+ else:
+ self.assertEqual(sanitized["search"], expected_search)
+
+ def test_insert_cohort_from_actors_query_preserves_persons_list_search(self):
+ _create_person(
+ team_id=self.team.pk,
+ distinct_ids=["match"],
+ properties={"email": "[email protected]"},
+ )
+ _create_person(
+ team_id=self.team.pk,
+ distinct_ids=["other"],
+ properties={"email": "[email protected]"},
+ )
+ flush_persons_and_events()
+
+ cohort = Cohort.objects.create(
+ team=self.team,
+ is_static=True,
+ name="search cohort",
+ query={"kind": "ActorsQuery", "search": "example.com"},
+ )
+
+ insert_cohort_query_actors_into_ch(cohort, team=self.team)
+
+ rows = sync_execute(
+ f"SELECT count() FROM {PERSON_STATIC_COHORT_TABLE} WHERE team_id = %(team_id)s AND cohort_id = %(cohort_id)s",
+ {"team_id": self.team.id, "cohort_id": cohort.id},
+ )
+ self.assertEqual(rows[0][0], 1)
+
def test_get_static_cohort_size_with_strong_consistency(self):
cohort = _create_cohort(team=self.team, name="test_cohort", groups=[], is_static=True)
diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.py
index 225175989058..1e3ae92656a1 100644
--- a/products/cohorts/backend/models/util.py
+++ b/products/cohorts/backend/models/util.py
@@ -297,8 +297,11 @@ def _sanitize_query_for_cohort(query_dict: dict) -> dict:
Cohort population only needs person IDs, so we remove recordings data
(which can use complex UDFs like aggregate_funnel_array that may not
- be available or are needlessly expensive) and search terms (the cohort
- should include all matching persons, not just those matching a search).
+ be available or are needlessly expensive).
+
+ Insight-derived actor queries may include ad-hoc modal search terms that
+ should not narrow the saved cohort; direct Persons list queries use
+ search as the primary filter and must keep it.
"""
query_dict = copy.deepcopy(query_dict)
@@ -308,13 +311,12 @@ def _sanitize_query_for_cohort(query_dict: dict) -> dict:
if not query_dict["select"]:
query_dict["select"] = ["actor"]
- # Intentionally strip search: the cohort should capture all persons matching
- # the query, not just those matching an ad-hoc search in the persons modal.
- query_dict.pop("search", None)
-
- source = query_dict.get("source", {})
- if isinstance(source, dict) and source.get("includeRecordings"):
- source["includeRecordings"] = False
+ source = query_dict.get("source")
+ if isinstance(source, dict):
+ # Modal search while inspecting insight actors is UI-only.
+ query_dict.pop("search", None)
+ if source.get("includeRecordings"):
+ source["includeRecordings"] = False
return query_dict