: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): support multi-column queries, timeouts, and error recovery (#126574)
Phil Haack2513b185f927
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 65164754b06e..ee21c22ab1de 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -1062,6 +1062,12 @@ class CohortListSerializer(serializers.ListSerializer):return super().to_representation(cohorts)+def _completed_calculations_newest_first(cohort: Any) -> QuerySet[CohortCalculationHistory]:+ return CohortCalculationHistory.objects.filter(cohort=cohort, finished_at__isnull=False).order_by(+ "-started_at", "-id"+ )++class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)earliest_timestamp_func = earliest_timestamp_func@@ -1189,18 +1195,14 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializreturn get_friendly_error_message(cohort.last_error_code, will_retry=will_retry)return None- # Fall back to querying calculation history.+ # Fall back to querying the most recent completed calculation.+ # If a newer completed run succeeded (error is empty/NULL), the cohort has recovered+ # and no stale error from an older failed run should be surfaced.# Old records may have error set but error_code=NULL; get_friendly_error_message# returns None for those, so they won't surface user-facing messages.- last_failed_calculation = (- CohortCalculationHistory.objects.filter(cohort=cohort)- .exclude(error__isnull=True)- .exclude(error="")- .order_by("-started_at")- .first()- )- if last_failed_calculation:- return get_friendly_error_message(last_failed_calculation.error_code, will_retry=will_retry)+ last_completed_calculation = _completed_calculations_newest_first(cohort).first()+ if last_completed_calculation and last_completed_calculation.error:+ return get_friendly_error_message(last_completed_calculation.error_code, will_retry=will_retry)return Nonedef validate_cohort_type(self, value):@@ -2507,13 +2509,7 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi# cohorts.if not is_basic_list:last_error_code_subquery = Subquery(- CohortCalculationHistory.objects.filter(- cohort=OuterRef("pk"),- error__isnull=False,- )- .exclude(error="")- .order_by("-started_at")- .values("error_code")[:1]+ _completed_calculations_newest_first(OuterRef("pk")).values("error_code")[:1])queryset = queryset.prefetch_related("experiment_set").annotate(last_error_code=last_error_code_subquery)diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 9b0ef9ee4b84..3f7cf4504d7f 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -6788,6 +6788,99 @@ [email protected],self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertIn("too much memory", response.json()["last_error_message"].lower())+ def test_cohort_last_error_message_clears_after_subsequent_success(self):+ """Test that a subsequent completed successful calculation clears last_error_message in detail, list, and fallback paths"""+ from posthog.api.cohort import CohortSerializer++ from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+ from products.cohorts.backend.models.util import CohortErrorCode++ cohort = Cohort.objects.create(+ team=self.team,+ name="Recovered Static Cohort",+ is_static=True,+ errors_calculating=0,+ )++ # Older failed calculation+ CohortCalculationHistory.objects.create(+ cohort=cohort,+ team=self.team,+ filters={},+ started_at=timezone.now() - timedelta(hours=2),+ finished_at=timezone.now() - timedelta(hours=2),+ error="This cohort's query has an issue and could not be completed.",+ error_code=CohortErrorCode.UNKNOWN,+ )++ # Newer successful calculation+ CohortCalculationHistory.objects.create(+ cohort=cohort,+ team=self.team,+ filters={},+ started_at=timezone.now() - timedelta(hours=1),+ finished_at=timezone.now() - timedelta(hours=1),+ count=468,+ error=None,+ error_code=None,+ )++ detail_response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort.id}")+ self.assertEqual(detail_response.status_code, status.HTTP_200_OK)+ self.assertIsNone(detail_response.json()["last_error_message"])++ list_response = self.client.get(f"/api/projects/{self.team.id}/cohorts/")+ self.assertEqual(list_response.status_code, status.HTTP_200_OK)+ cohort_data = next(c for c in list_response.json()["results"] if c["id"] == cohort.id)+ self.assertIsNone(cohort_data["last_error_message"])++ # Also verify the unannotated fallback path on CohortSerializer directly+ fresh_cohort = Cohort.objects.get(pk=cohort.pk)+ self.assertFalse(hasattr(fresh_cohort, "last_error_code"))+ self.assertIsNone(CohortSerializer().get_last_error_message(fresh_cohort))++ def test_cohort_last_error_message_preserved_while_retry_in_flight(self):+ """Test that an in-flight retry (finished_at=None) does not prematurely clear the last completed error"""+ from posthog.api.cohort import CohortSerializer++ from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+ from products.cohorts.backend.models.util import CohortErrorCode++ cohort = Cohort.objects.create(+ team=self.team,+ name="Retrying Cohort",+ errors_calculating=1,+ )++ CohortCalculationHistory.objects.create(+ cohort=cohort,+ team=self.team,+ filters={},+ started_at=timezone.now() - timedelta(minutes=10),+ finished_at=timezone.now() - timedelta(minutes=9),+ error="Timeout",+ error_code=CohortErrorCode.TIMEOUT,+ )++ # In-flight retry has started_at > previous failure, but finished_at is still None+ CohortCalculationHistory.objects.create(+ cohort=cohort,+ team=self.team,+ filters={},+ started_at=timezone.now() - timedelta(minutes=1),+ finished_at=None,+ error=None,+ error_code=None,+ )++ detail_response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort.id}")+ self.assertEqual(detail_response.status_code, status.HTTP_200_OK)+ self.assertIsNotNone(detail_response.json()["last_error_message"])+ self.assertIn("taking too long", detail_response.json()["last_error_message"].lower())++ fresh_cohort = Cohort.objects.get(pk=cohort.pk)+ self.assertIn("taking too long", (CohortSerializer().get_last_error_message(fresh_cohort) or "").lower())+class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):def _create_flag_referencing_cohort_transitively(self) -> tuple[int, int]:diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex 432716deea66..25d7b2365c54 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -807,7 +807,7 @@ def calculate_cohort_from_list(return# An import that fails without a row of its own resolves `last_error_message` to whichever- # older population failed, because that lookup takes the newest errored row over the+ # older population failed, because that lookup takes the newest finished history row over the# cohort's whole life. Recording the attempt also keeps imports in the calculation history# beside the query and filter population paths.history = CohortCalculationHistory.objects.create(@@ -954,7 +954,7 @@ def _populate_static_cohort(cohort.refresh_from_db()# A history record is the only way a population failure reaches the user: the cohort API- # reads `last_error_message` from the newest history row that carries an error. Without one,+ # reads `last_error_message` from the newest finished history row. Without one,# a population that died on a ClickHouse limit is indistinguishable from a cohort that# matched nobody.history = CohortCalculationHistory.objects.create(diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.pyindex 27055e237e34..bc121ef95e00 100644--- a/products/cohorts/backend/models/test/test_util.py+++ b/products/cohorts/backend/models/test/test_util.py@@ -1,6 +1,6 @@-from typing import Any+from typing import Any, cast-from posthog.test.base import BaseTest, _create_person, flush_persons_and_events+from posthog.test.base import BaseTest, _create_event, _create_person, flush_persons_and_eventsfrom unittest.mock import MagicMock, patchfrom django.db import DEFAULT_DB_ALIAS, OperationalError@@ -470,7 +470,7 @@ class TestCohortUtils(BaseTest):# Also check for other critical settingsself.assertIn("readonly=2", sql)- self.assertIn("max_execution_time=60", sql)+ self.assertIn("max_execution_time=1200", sql)self.assertIn("allow_experimental_object_type=1", sql)self.assertIn("optimize_min_equality_disjunction_chain_length=4294967295", sql)@@ -913,6 +913,297 @@ class TestCohortUtils(BaseTest):self.assertIn("group by 1", sql)self.assertIn("order by 2", sql)+ def test_insert_actors_into_cohort_by_query_uses_offline_workload_and_cohort_timeout_settings(self):+ from posthog.clickhouse.client.connection import ClickHouseUser, Workload++ from products.cohorts.backend.models.util import (+ COHORT_QUERY_TIMEOUT_SECONDS,+ insert_actors_into_cohort_by_query,+ )++ cohort = Cohort.objects.create(team=self.team, name="Static Query Cohort", is_static=True)+ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)++ with patch("products.cohorts.backend.models.util.sync_execute") as mock_sync_execute:+ insert_actors_into_cohort_by_query(+ cohort,+ "SELECT id AS actor_id FROM persons",+ {"custom_param": "val"},+ context,+ team_id=self.team.id,+ )++ mock_sync_execute.assert_called_once()+ _, kwargs = mock_sync_execute.call_args+ self.assertEqual(+ kwargs["settings"],+ {+ "max_execution_time": COHORT_QUERY_TIMEOUT_SECONDS,+ "send_timeout": COHORT_QUERY_TIMEOUT_SECONDS,+ "receive_timeout": COHORT_QUERY_TIMEOUT_SECONDS,+ "max_bytes_before_external_group_by": 21 * 1024**3,+ "max_bytes_before_external_sort": 21 * 1024**3,+ "max_bytes_ratio_before_external_group_by": 0,+ "max_bytes_ratio_before_external_sort": 0,+ },+ )+ self.assertEqual(kwargs["workload"], Workload.OFFLINE)+ self.assertEqual(kwargs["ch_user"], ClickHouseUser.COHORTS)+ self.assertEqual(kwargs["team_id"], self.team.id)++ @parameterized.expand(+ [+ (+ "multi_column_with_having_on_select_alias",+ "SELECT person_id, count() AS msd, any(event) AS domain FROM events GROUP BY person_id HAVING msd >= 2",+ ),+ (+ "multi_column_with_where_on_select_alias",+ "SELECT id AS person_id, properties.email AS msd, properties.domain AS domain FROM persons WHERE domain IS NOT NULL",+ ),+ (+ "multi_column_with_bounded_order_by_on_select_alias",+ "SELECT id AS person_id, toStartOfDay(created_at) AS msd, properties.domain AS domain FROM persons ORDER BY msd DESC LIMIT 50",+ ),+ (+ "single_column_non_field_aliased_as_person_id",+ "SELECT toUUID(person_id) AS person_id FROM events",+ ),+ (+ "grouped_by_non_actor_column_with_aggregated_id",+ "SELECT properties.email AS email, any(id) AS id FROM persons GROUP BY properties.email",+ ),+ (+ "group_by_all_with_extra_columns",+ "SELECT person_id, event AS domain, count() AS msd FROM events GROUP BY ALL",+ ),+ (+ "events_person_dot_id_with_extra_columns",+ "SELECT person.id, count() AS msd FROM events GROUP BY person.id HAVING msd >= 1",+ ),+ (+ "joined_persons_repeated_qualified_id",+ "SELECT p.id, q.id FROM persons AS p JOIN persons AS q ON p.id = q.id",+ ),+ (+ "joined_persons_qualified_id_with_id_alias_sibling",+ "SELECT p.id AS id, q.id FROM persons AS p JOIN persons AS q ON p.id = q.id",+ ),+ (+ "joined_persons_sibling_named_like_generated_alias",+ "SELECT p.id, p.created_at AS __cohort_id FROM persons AS p",+ ),+ (+ "union_of_grouped_and_plain_distinct_id_branches",+ "SELECT distinct_id FROM events GROUP BY distinct_id UNION ALL SELECT distinct_id FROM events",+ ),+ (+ "events_distinct_id_aggregating_with_having",+ "SELECT distinct_id, count() AS n FROM events GROUP BY distinct_id HAVING n >= 3",+ ),+ ]+ )+ def test_print_cohort_hogql_query_supports_multi_column_aliased_and_aggregating_queries(+ self, _name: str, hogql_query: str+ ):+ p_with_domain = _create_person(+ team_id=self.team.pk,+ distinct_ids=[f"p_domain_{_name}"],+ properties={"email": f"with_{_name}@example.com", "domain": "example.com"},+ )+ _create_person(+ team_id=self.team.pk,+ distinct_ids=[f"p_nodomain_{_name}"],+ properties={"email": f"without_{_name}@example.com"},+ )+ flush_persons_and_events()++ cohort = Cohort.objects.create(+ team=self.team,+ name=f"Test Cohort {_name}",+ is_static=True,+ query={"kind": "HogQLQuery", "query": hogql_query},+ )+ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)++ sql = print_cohort_hogql_query(cohort, context, team=self.team)++ self.assertIn("as actor_id", sql.lower())+ self.assertIn("max_execution_time=1200", sql)+ self.assertNotIn("max_bytes_before_external_group_by", sql)+ insert_cohort_query_actors_into_ch(cohort, team=self.team)++ if _name == "multi_column_with_where_on_select_alias":+ rows = sync_execute(+ f"SELECT person_id 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([str(r[0]) for r in rows], [str(p_with_domain.uuid)])++ def test_print_cohort_hogql_query_with_multi_column_distinct_id_query(self):+ from posthog.hogql import ast+ from posthog.hogql.parser import parse_select++ cohort = Cohort.objects.create(+ team=self.team,+ name="Test Multi-Column Distinct ID Cohort",+ is_static=True,+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ )+ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)++ def mock_get_query_runner(query, team, limit_context=None):+ mock_runner = MagicMock()+ mock_runner.to_query.return_value = cast(+ ast.SelectQuery,+ parse_select(+ "SELECT distinct_id, count() AS msd FROM raw_person_distinct_ids GROUP BY distinct_id HAVING msd >= 1"+ ),+ )+ return mock_runner++ with patch("posthog.hogql_queries.query_runner.get_query_runner", mock_get_query_runner):+ sql = print_cohort_hogql_query(cohort, context, team=self.team)+ insert_cohort_query_actors_into_ch(cohort, team=self.team)++ self.assertIn("person_distinct_id2", sql)+ self.assertIn("argMax(person_id, version) as actor_id", sql)+ self.assertIn("HAVING greaterOrEquals(msd, 1)", sql)+ self.assertIn("max_execution_time=1200", sql)++ def test_print_cohort_hogql_query_preserves_root_ctes_across_union_branches(self):+ cohort = Cohort.objects.create(+ team=self.team,+ name="Test CTE Union Cohort",+ is_static=True,+ query={+ "kind": "HogQLQuery",+ "query": (+ "WITH matched AS (SELECT person_id, event FROM events) "+ "SELECT person_id, count() AS msd FROM matched GROUP BY person_id "+ "UNION ALL "+ "SELECT person_id, count() AS msd FROM matched GROUP BY person_id"+ ),+ },+ )+ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)++ sql = print_cohort_hogql_query(cohort, context, team=self.team)++ self.assertEqual(sql.lower().count("as actor_id"), 2)+ self.assertIn("union all", sql.lower())+ insert_cohort_query_actors_into_ch(cohort, team=self.team)++ def test_insert_cohort_from_multi_column_aggregating_hogql_query(self):+ p1 = _create_person(+ team_id=self.team.pk,+ distinct_ids=["p1_distinct"],+ properties={"email": "[email protected]"},+ )+ p2 = _create_person(+ team_id=self.team.pk,+ distinct_ids=["p2_distinct"],+ properties={"email": "[email protected]"},+ )+ _create_event(team=self.team, event="$pageview", distinct_id="p1_distinct")+ _create_event(team=self.team, event="$pageview", distinct_id="p1_distinct")+ _create_event(team=self.team, event="$pageview", distinct_id="p2_distinct")+ flush_persons_and_events()++ cohort = Cohort.objects.create(+ team=self.team,+ is_static=True,+ name="multi-column hogql cohort",+ query={+ "kind": "HogQLQuery",+ "query": (+ "SELECT person_id, count() AS msd, any(event) AS domain "+ "FROM events GROUP BY person_id HAVING msd >= 2"+ ),+ },+ )++ insert_cohort_query_actors_into_ch(cohort, team=self.team)++ rows = sync_execute(+ f"SELECT person_id 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([str(r[0]) for r in rows], [str(p1.uuid)])++ # Also test aggregating distinct_id query from events populates successfully+ cohort_distinct = Cohort.objects.create(+ team=self.team,+ is_static=True,+ name="distinct_id aggregating cohort",+ query={+ "kind": "HogQLQuery",+ "query": "SELECT distinct_id, count() AS n FROM events GROUP BY distinct_id HAVING n >= 2",+ },+ )+ insert_cohort_query_actors_into_ch(cohort_distinct, team=self.team)+ rows_distinct = sync_execute(+ f"SELECT person_id 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_distinct.id},+ )+ self.assertEqual([str(r[0]) for r in rows_distinct], [str(p1.uuid)])++ # Also test plain multi-column distinct_id query from events populates successfully+ cohort_multi = Cohort.objects.create(+ team=self.team,+ is_static=True,+ name="distinct_id multi-column cohort",+ query={+ "kind": "HogQLQuery",+ "query": "SELECT distinct_id, event FROM events",+ },+ )+ insert_cohort_query_actors_into_ch(cohort_multi, team=self.team)+ rows_multi = sync_execute(+ f"SELECT person_id 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_multi.id},+ )+ self.assertCountEqual([str(r[0]) for r in rows_multi], [str(p1.uuid), str(p2.uuid)])++ def test_wrap_select_query_strips_inner_distinct_on_unbounded_query(self):+ cohort = Cohort.objects.create(+ team=self.team,+ name="Unbounded Distinct Cohort",+ is_static=True,+ query={"kind": "HogQLQuery", "query": "SELECT DISTINCT person_id, event FROM events"},+ )+ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)+ sql = print_cohort_hogql_query(cohort, context, team=self.team)+ self.assertNotIn("DISTINCT", sql)+ self.assertIn("SELECT person_id AS actor_id FROM (SELECT", sql)+ insert_cohort_query_actors_into_ch(cohort, team=self.team)++ def test_wrap_select_query_preserves_inner_distinct_on_bounded_query(self):+ cases = [+ ("SELECT DISTINCT person_id, event FROM events LIMIT 10", ["LIMIT 10"]),+ ("SELECT DISTINCT person_id, event FROM events LIMIT 1 BY event", ["LIMIT 1", "BY events.event"]),+ (+ "(SELECT DISTINCT person_id, event FROM events UNION ALL SELECT DISTINCT person_id, event FROM events) LIMIT 10",+ ["LIMIT 10", "UNION ALL"],+ ),+ ]+ for query_str, expected_tokens in cases:+ with self.subTest(query=query_str):+ cohort = Cohort.objects.create(+ team=self.team,+ name=f"Bounded Distinct Cohort {query_str}",+ is_static=True,+ query={"kind": "HogQLQuery", "query": query_str},+ )+ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)+ sql = print_cohort_hogql_query(cohort, context, team=self.team)+ self.assertIn("DISTINCT", sql)+ if "UNION ALL" in expected_tokens:+ self.assertEqual(sql.count("DISTINCT"), 2)+ for token in expected_tokens:+ self.assertIn(token, sql)+ insert_cohort_query_actors_into_ch(cohort, team=self.team)+class TestGetNestedCohortIds(BaseTest):def test_no_cohort_references(self):diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex 034dd5348bce..7e1b50b30360 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport copyimport uuid+import dataclassesfrom collections.abc import Callable, Sequencefrom datetime import datetimefrom enum import StrEnum@@ -71,6 +72,20 @@ TEMP_PRECALCULATED_MARKER = parser.parse("2021-06-07T15:00:00+00:00")# Cohort query timeout settingsCOHORT_QUERY_TIMEOUT_SECONDS = 1200 # Max execution time for ClickHouse cohort calculation queries+COHORT_QUERY_TIMEOUT_SETTINGS = {+ "max_execution_time": COHORT_QUERY_TIMEOUT_SECONDS,+ "send_timeout": COHORT_QUERY_TIMEOUT_SECONDS,+ "receive_timeout": COHORT_QUERY_TIMEOUT_SECONDS,+}++# The cohorts ClickHouse user caps a query at 42 GiB. On ClickHouse 26.6 the ratio-based spill settings never+# trigger under a per-query cap, so the ratios are zero and the byte thresholds (half the cap) govern.+COHORT_QUERY_SPILL_SETTINGS = {+ "max_bytes_before_external_group_by": 21 * 1024**3,+ "max_bytes_before_external_sort": 21 * 1024**3,+ "max_bytes_ratio_before_external_group_by": 0,+ "max_bytes_ratio_before_external_sort": 0,+}class CohortErrorCode(StrEnum):@@ -454,13 +469,36 @@ def _select_list_positions_are_known(select_list: list[ast.Expr]) -> bool:return True+def _is_bounded(select_query: ast.SelectQuery) -> bool:+ return select_query.limit is not None or select_query.offset is not None or select_query.limit_by is not None+++def _select_queries_under_bounded_set(query: ast.SelectQuery | ast.SelectSetQuery) -> set[int]:+ """Return `id()` of every SELECT that sits beneath a set query with a LIMIT or OFFSET."""+ found: set[int] = set()++ def visit(node: ast.SelectQuery | ast.SelectSetQuery, bounded: bool) -> None:+ if isinstance(node, ast.SelectQuery):+ if bounded:+ found.add(id(node))+ return+ bounded = bounded or node.limit is not None or node.offset is not None+ visit(node.initial_select_query, bounded)+ for subsequent in node.subsequent_select_queries:+ visit(subsequent.select_query, bounded)++ visit(query, False)+ return found++def _inline_positional_references(select_query: ast.SelectQuery) -> None:"""Replace positional GROUP BY/ORDER BY/LIMIT BY ordinals with the SELECT expression they point at.In ClickHouse a bare integer in GROUP BY/ORDER BY/LIMIT BY (`GROUP BY 2`) is a 1-based reference- into the SELECT list. `print_cohort_hogql_query` collapses that list to a single actor column, so- any ordinal other than 1 would dangle afterwards. Resolving each ordinal against the original- SELECT list up front keeps the grouping/ordering semantics intact once the list shrinks.+ into the SELECT list. The events and persons branches replace that SELECT list with a single+ actor column, leaving any ordinal other than 1 dangling. Resolving each ordinal against the+ original SELECT list up front keeps the grouping and ordering semantics intact if those+ branches collapse the list.Ordinals nested inside GROUP BY GROUPING SETS are not resolved, because those entries are tuplesof expressions rather than bare ordinals. Such a query keeps failing the way it does today.@@ -493,6 +531,80 @@ def _inline_positional_references(select_query: ast.SelectQuery) -> None:select_query.limit_by.exprs = [resolve(expr) for expr in select_query.limit_by.exprs]+def _select_expr_name(expr: ast.Expr) -> Optional[str]:+ if isinstance(expr, ast.Alias):+ return expr.alias+ if isinstance(expr, ast.Field):+ return str(expr.chain[-1])+ return None+++def _wrap_select_query_with_column(+ select_query: ast.SelectQuery,+ source_column: str,+ target_alias: str,+ *,+ keep_distinct: bool = False,+) -> None:+ """Wrap `select_query` in `SELECT <source_column> AS <target_alias> FROM (<select_query>)` in place.++ Collapsing `select_query.select` to a single column in place strips sibling SELECT aliases and+ grouping columns, which breaks queries whose GROUP BY, HAVING, WHERE, bounded ORDER BY, or+ LIMIT BY clauses reference those columns or aliases. Wrapping in an outer SELECT preserves the+ inner query's column list and semantics while projecting only the target column, and keeps CTEs+ on the outer node so root CTEs remain visible across UNION branches.+ """+ inner = copy.copy(select_query)+ if not (keep_distinct or _is_bounded(inner)):+ inner.distinct = None+ inner.ctes = None+ # `print_cohort_hogql_query` picks the last select expression named `source_column`. A dotted field such+ # as `person.id` has no output name the outer query can select, so only that expression gets a unique alias.+ source_name = source_column+ select = list(inner.select)+ selected_index = max(i for i, expr in enumerate(select) if _select_expr_name(expr) == source_column)+ selected = select[selected_index]+ if isinstance(selected, ast.Field) and len(selected.chain) > 1:+ source_name = f"__cohort_{source_column}"+ taken = {_select_expr_name(expr) for expr in select}+ while source_name in taken:+ source_name = f"_{source_name}"+ select[selected_index] = ast.Alias(alias=source_name, expr=selected)+ inner.select = select++ wrapper = ast.SelectQuery(+ select=[ast.Alias(alias=target_alias, expr=ast.Field(chain=[source_name]))],+ select_from=ast.JoinExpr(table=inner),+ ctes=select_query.ctes,+ )+ for field in dataclasses.fields(ast.SelectQuery):+ setattr(select_query, field.name, getattr(wrapper, field.name))+++def _select_columns(select_query: ast.SelectQuery) -> dict[str, ast.Expr]:+ columns: dict[str, ast.Expr] = {}+ for expr in select_query.select:+ if isinstance(expr, ast.Alias):+ columns[expr.alias] = expr.expr+ elif isinstance(expr, ast.Field):+ columns[str(expr.chain[-1])] = expr+ return columns+++def _is_aggregating_or_multi_column(select_query: ast.SelectQuery) -> bool:+ return bool(+ select_query.group_by+ or select_query.having+ or select_query.group_by_mode == "all"+ or len(select_query.select) > 1+ )+++def _selects_distinct_id_only(select_query: ast.SelectQuery) -> bool:+ columns = _select_columns(select_query)+ return "distinct_id" in columns and not any(name in columns for name in ("person_id", "actor_id", "id"))++def print_cohort_hogql_query(cohort: Cohort, hogql_context: HogQLContext, *, team: Team) -> str:from posthog.hogql_queries.query_runner import get_query_runner@@ -507,59 +619,61 @@ def print_cohort_hogql_query(cohort: Cohort, hogql_context: HogQLContext, *, teauses_distinct_id = Falseuses_actor_id = False+ queries_under_bounded_set = _select_queries_under_bounded_set(query)++ # Every branch of a UNION must resolve `distinct_id` the same way, so one grouped or multi-column+ # `distinct_id` branch sends all `distinct_id` branches through the person_distinct_id2 lookup.+ union_resolves_distinct_ids = any(+ _selects_distinct_id_only(select_query) and _is_aggregating_or_multi_column(select_query)+ for select_query in extract_select_queries(query)+ )+for select_query in extract_select_queries(query):# Positional GROUP BY/ORDER BY ordinals (e.g. `GROUP BY 2`) reference the Nth SELECT- # expression. We're about to collapse the SELECT list down to a single actor column,- # which leaves those ordinals pointing past the end of the new one-column list, so+ # expression. The events and persons branches replace that SELECT list with a single actor+ # column, which leaves those ordinals pointing past the end of the new one-column list, so# ClickHouse rejects the query with an out-of-bounds positional argument error. Inline- # the referenced expression now so the reference survives the collapse.+ # the referenced expressions now so the references survive if those branches collapse the list._inline_positional_references(select_query)# Ordering is meaningless for an unbounded cohort, and an ORDER BY that references a- # computed select alias (e.g. `ai_active_days`) would dangle once we collapse the- # SELECT to just the actor column below, breaking HogQL resolution. Drop it — but only- # when the query is unbounded. With a LIMIT/OFFSET the ordering decides which rows- # survive, so dropping it would silently make membership a non-deterministic subset;- # keep both so a bounded "top N" cohort stays deterministic.- is_bounded = (- select_query.limit is not None or select_query.offset is not None or select_query.limit_by is not None- )- if not is_bounded:+ # computed select alias (e.g. `ai_active_days`) would dangle if the events or persons+ # branch replaces the SELECT with just the actor column, breaking HogQL resolution. Drop+ # it — but only when the query is unbounded. With a LIMIT/OFFSET the ordering decides+ # which rows survive, so dropping it would silently make membership a non-deterministic+ # subset; keep both so a bounded "top N" cohort stays deterministic.+ if not _is_bounded(select_query):select_query.order_by = None- columns: dict[str, ast.Expr] = {}-- for expr in select_query.select:- if isinstance(expr, ast.Alias):- columns[expr.alias] = expr.expr- elif isinstance(expr, ast.Field):- columns[str(expr.chain[-1])] = expr-- column: ast.Expr | None = columns.get("person_id") or columns.get("actor_id") or columns.get("id")- if isinstance(column, ast.Alias):- select_query.select = [ast.Alias(expr=column.expr, alias="actor_id")]+ columns = _select_columns(select_query)+ actor_column = next((name for name in ("person_id", "actor_id", "id") if name in columns), None)+ distinct_id_column = columns.get("distinct_id")+ table = select_query.select_from.table if select_query.select_from else None+ is_aggregating_or_multi_column = _is_aggregating_or_multi_column(select_query)+ if actor_column is not None:+ if is_aggregating_or_multi_column:+ _wrap_select_query_with_column(+ select_query, actor_column, "actor_id", keep_distinct=id(select_query) in queries_under_bounded_set+ )+ else:+ select_query.select = [ast.Alias(expr=columns[actor_column], alias="actor_id")]+ uses_actor_id = True+ elif distinct_id_column is not None and (is_aggregating_or_multi_column or union_resolves_distinct_ids):+ _wrap_select_query_with_column(+ select_query, "distinct_id", "distinct_id", keep_distinct=id(select_query) in queries_under_bounded_set+ )+ uses_distinct_id = True+ elif isinstance(table, ast.Field) and table.chain[-1] == "events":+ select_query.select = [ast.Alias(expr=ast.Field(chain=["person", "id"]), alias="actor_id")]uses_actor_id = True- elif isinstance(column, ast.Field):- select_query.select = [ast.Alias(expr=column, alias="actor_id")]+ elif isinstance(table, ast.Field) and table.chain[-1] == "persons":+ select_query.select = [ast.Alias(expr=ast.Field(chain=["id"]), alias="actor_id")]uses_actor_id = True+ elif distinct_id_column is not None:+ select_query.select = [ast.Alias(expr=distinct_id_column, alias="distinct_id")]+ uses_distinct_id = Trueelse:- # Support the most common use cases- table = select_query.select_from.table if select_query.select_from else None- if isinstance(table, ast.Field) and table.chain[-1] == "events":- select_query.select = [ast.Alias(expr=ast.Field(chain=["person", "id"]), alias="actor_id")]- uses_actor_id = True- elif isinstance(table, ast.Field) and table.chain[-1] == "persons":- select_query.select = [ast.Alias(expr=ast.Field(chain=["id"]), alias="actor_id")]- uses_actor_id = True- else:- # Check if we have a distinct_id column- distinct_id_column = columns.get("distinct_id")- if distinct_id_column is not None:- # Use distinct_id and mark that we need to resolve it to person_id- select_query.select = [ast.Alias(expr=distinct_id_column, alias="distinct_id")]- uses_distinct_id = True- else:- raise ValueError("Could not find a person_id, actor_id, id, or distinct_id column in the query")+ raise ValueError("Could not find a person_id, actor_id, id, or distinct_id column in the query")# Check for mixed ID types in UNION queriesif uses_distinct_id and uses_actor_id:@@ -572,8 +686,10 @@ def print_cohort_hogql_query(cohort: Cohort, hogql_context: HogQLContext, *, teahogql_context.limit_top_select = Falsecreate_default_modifiers_for_team(team, hogql_context.modifiers)- # Apply HogQL global settings to ensure consistency with regular queries- settings = HogQLGlobalSettings()+ # The HogQL default of 0 would override the spill threshold the caller sets on the ClickHouse client.+ settings = HogQLGlobalSettings(+ max_execution_time=COHORT_QUERY_TIMEOUT_SECONDS, max_bytes_before_external_group_by=None+ )# If we're using distinct_id, wrap the query to resolve to person_idif uses_distinct_id:@@ -843,12 +959,9 @@ def _recalculate_cohortpeople_for_team_hogql(settings.pop("readonly", None)settings.update({- "max_execution_time": COHORT_QUERY_TIMEOUT_SECONDS,- "send_timeout": COHORT_QUERY_TIMEOUT_SECONDS,- "receive_timeout": COHORT_QUERY_TIMEOUT_SECONDS,+ **COHORT_QUERY_TIMEOUT_SETTINGS,"optimize_on_insert": 0,- "max_bytes_ratio_before_external_group_by": 0.5,- "max_bytes_ratio_before_external_sort": 0.5,+ **COHORT_QUERY_SPILL_SETTINGS,})@@ -1215,6 +1328,13 @@ def insert_actors_into_cohort_by_query(**context.values,**params,},+ settings={+ **COHORT_QUERY_TIMEOUT_SETTINGS,+ **COHORT_QUERY_SPILL_SETTINGS,+ },+ workload=Workload.OFFLINE,+ ch_user=ClickHouseUser.COHORTS,+ team_id=team_id,)diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex 009cd9ffeb83..fb001e05a5f6 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -1654,10 +1654,9 @@"posthog_cohortcalculationhistory"."error_code"FROM "posthog_cohortcalculationhistory"WHERE ("posthog_cohortcalculationhistory"."cohort_id" = 99999- AND NOT ("posthog_cohortcalculationhistory"."error" IS NULL)- AND NOT ("posthog_cohortcalculationhistory"."error" = ''- AND "posthog_cohortcalculationhistory"."error" IS NOT NULL))- ORDER BY "posthog_cohortcalculationhistory"."started_at" DESC+ AND "posthog_cohortcalculationhistory"."finished_at" IS NOT NULL)+ ORDER BY "posthog_cohortcalculationhistory"."started_at" DESC,+ "posthog_cohortcalculationhistory"."id" DESCLIMIT 1'''# ---