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.

chore(cohorts): populate static-from-filters cohorts via HogQLCohortQuery (#61232)

Sandy Spicerf129065b6b5d
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index ae1cc60438ee..7040e21d65c1 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -584,6 +584,124 @@ [email protected]
people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)
self.assertEqual(people_in_cohort.count(), 0)
+ @patch(
+ "posthog.tasks.calculate_cohort.insert_cohort_from_filters.delay",
+ side_effect=insert_cohort_from_filters,
+ )
+ def test_static_cohort_create_with_behavioral_criteria(self, _insert_cohort_from_filters: MagicMock):
+ performed = _create_person(distinct_ids=["did-pageview"], team_id=self.team.pk)
+ _create_person(distinct_ids=["no-pageview"], team_id=self.team.pk)
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="did-pageview",
+ timestamp=datetime.now() - timedelta(hours=12),
+ )
+ flush_persons_and_events()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts/",
+ {
+ "name": "behavioral snapshot",
+ "is_static": True,
+ "filters": {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {
+ "key": "$pageview",
+ "type": "behavioral",
+ "value": "performed_event",
+ "event_type": "events",
+ "time_value": 30,
+ "time_interval": "day",
+ }
+ ],
+ }
+ ],
+ }
+ },
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, 201)
+ cohort = Cohort.objects.get(pk=response.json()["id"])
+ self.assertTrue(cohort.is_static)
+ self.assertEqual(cohort.count, 1)
+
+ people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)
+ self.assertEqual(people_in_cohort.count(), 1)
+ first_person = people_in_cohort.first()
+ assert first_person is not None
+ self.assertEqual(first_person.uuid, performed.uuid)
+
+ @patch(
+ "posthog.tasks.calculate_cohort.insert_cohort_from_filters.delay",
+ side_effect=insert_cohort_from_filters,
+ )
+ def test_static_cohort_create_with_or_nested_criteria(self, _insert_cohort_from_filters: MagicMock):
+ first_match = _create_person(
+ distinct_ids=["or-match-1"],
+ team_id=self.team.pk,
+ properties={"email": "[email protected]"},
+ )
+ second_match = _create_person(
+ distinct_ids=["or-match-2"],
+ team_id=self.team.pk,
+ properties={"email": "[email protected]"},
+ )
+ _create_person(
+ distinct_ids=["or-miss"],
+ team_id=self.team.pk,
+ properties={"email": "[email protected]"},
+ )
+ flush_persons_and_events()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts/",
+ {
+ "name": "or criteria snapshot",
+ "is_static": True,
+ "filters": {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "OR",
+ "values": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "[email protected]",
+ "operator": PropertyOperator.EXACT,
+ },
+ {
+ "key": "email",
+ "type": "person",
+ "value": "[email protected]",
+ "operator": PropertyOperator.EXACT,
+ },
+ ],
+ }
+ ],
+ }
+ },
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, 201)
+ cohort = Cohort.objects.get(pk=response.json()["id"])
+ self.assertTrue(cohort.is_static)
+ self.assertEqual(cohort.count, 2)
+
+ people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)
+ self.assertEqual({p.uuid for p in people_in_cohort}, {first_match.uuid, second_match.uuid})
+
def test_static_cohort_rejects_criteria_edits_after_creation(self):
cohort = Cohort.objects.create(
team=self.team,
diff --git a/posthog/models/cohort/util.py b/posthog/models/cohort/util.py
index 350d0b0d3289..41e72eb4829c 100644
--- a/posthog/models/cohort/util.py
+++ b/posthog/models/cohort/util.py
@@ -695,6 +695,15 @@ def _recalculate_cohortpeople_for_team(cohort: Cohort, pending_version: int, tea
raise
+def hogql_cohort_subquery_sql(cohort: Cohort, *, team: Team) -> tuple[str, HogQLContext]:
+ from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery
+
+ sql, hogql_context = HogQLCohortQuery(cohort=cohort, team=team).get_query_executor().generate_clickhouse_sql()
+
+ # Clickhouse rejects a top-level SETTINGS clause when the SELECT is used as a subquery, so we trim it.
+ return sql[: sql.rfind("SETTINGS")], hogql_context
+
+
def _recalculate_cohortpeople_for_team_hogql(
cohort: Cohort, pending_version: int, team: Team, history: CohortCalculationHistory
) -> int:
@@ -709,17 +718,9 @@ def _recalculate_cohortpeople_for_team_hogql(
history.save(update_fields=["finished_at", "count", "error", "error_code"])
return 0
else:
- from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery
-
- cohort_query, hogql_context = (
- HogQLCohortQuery(cohort=cohort, team=team).get_query_executor().generate_clickhouse_sql()
- )
+ cohort_query, hogql_context = hogql_cohort_subquery_sql(cohort, team=team)
cohort_params = hogql_context.values
- # Hacky: Clickhouse doesn't like there being a top level "SETTINGS" clause in a SelectSet statement when that SelectSet
- # statement is used in a subquery. We remove it here.
- cohort_query = cohort_query[: cohort_query.rfind("SETTINGS")]
-
recalculate_cohortpeople_sql = RECALCULATE_COHORT_BY_ID.format(cohort_filter=cohort_query)
def execute_query():
@@ -1068,21 +1069,13 @@ def insert_cohort_query_actors_into_ch(cohort: Cohort, *, team: Team):
def build_static_cohort_filters_query(cohort: Cohort, *, team: Team) -> tuple[str, dict[str, Any], HogQLContext]:
- from posthog.queries.cohort_query import CohortQuery
+ # Compile the cohort's criteria (cohort.properties) to ClickHouse SQL. The cohort is static, but
+ # it's being populated for the first time, so we evaluate the criteria rather than reading the
+ # (still-empty) static cohort table — HogQLCohortQuery builds from cohort.properties regardless of is_static.
+ cohort_query, hogql_context = hogql_cohort_subquery_sql(cohort, team=team)
- context = HogQLContext(enable_select_queries=True, team_id=team.id)
- query_builder = CohortQuery(
- Filter(
- data={"properties": cohort.properties},
- team=team,
- hogql_context=context,
- ),
- team,
- cohort_pk=cohort.pk,
- persons_on_events_mode=team.person_on_events_mode,
- )
- base_query, params = query_builder.get_query()
- return f"SELECT id AS actor_id FROM ({base_query})", params, context
+ # Params live on hogql_context.values, which the consumer already spreads — pass {} to avoid spreading twice.
+ return f"SELECT id AS actor_id FROM ({cohort_query})", {}, hogql_context
def insert_cohort_filter_actors_into_ch(cohort: Cohort, *, team: Team):