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): drop dangling ORDER BY when building static cohort query (#68779)

posthog[bot]2fd19ce0e316
diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.py
index 17242f001b80..e8113934699c 100644
--- a/products/cohorts/backend/models/test/test_util.py
+++ b/products/cohorts/backend/models/test/test_util.py
@@ -671,6 +671,67 @@ class TestCohortUtils(BaseTest):
self.assertIn("Could not find a person_id, actor_id, id, or distinct_id column", str(cm.exception))
+ def test_print_cohort_hogql_query_drops_order_by_on_stripped_alias(self):
+ """An ActorsQuery ordering by a computed select alias must not dangle once we collapse the SELECT.
+
+ Without clearing ORDER BY, the alias is stripped from the SELECT but still referenced by the
+ ORDER BY, so HogQL resolution raises `QueryError: Unable to resolve field: <alias>`.
+ """
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="Test Ordered Actors Cohort",
+ query={
+ "kind": "ActorsQuery",
+ "select": ["actor_id", "count() as event_count"],
+ "orderBy": ["event_count DESC"],
+ "source": {
+ "kind": "InsightActorsQuery",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ # Total-value aggregation so the actors query targets all matched people
+ # rather than a single interval (which would require a `day`).
+ "trendsFilter": {"display": "BoldNumber"},
+ },
+ },
+ },
+ )
+
+ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)
+
+ # Before the fix this raised `QueryError: Unable to resolve field: event_count`.
+ # Producing SQL at all is the core regression check; the top-level ORDER BY must be gone
+ # and the SELECT collapsed to the actor column. (`event_count` may still appear as a
+ # harmless unused column in an inner subquery, which the collapse does not descend into.)
+ sql = print_cohort_hogql_query(cohort, context, team=self.team)
+
+ self.assertNotIn("order by", sql.lower())
+ self.assertIn("as actor_id", sql.lower())
+
+ def test_print_cohort_hogql_query_keeps_order_by_and_limit_for_bounded_query(self):
+ """A bounded cohort query (ORDER BY + LIMIT on a real column) must stay deterministic.
+
+ Here the ORDER BY targets a real column that survives the SELECT collapse, so dropping it
+ would leave the LIMIT selecting an arbitrary, non-deterministic subset on every recalculation.
+ Both the ordering and the limit must be preserved.
+ """
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="Test Bounded Actors Cohort",
+ query={
+ "kind": "HogQLQuery",
+ "query": "SELECT id AS actor_id, created_at FROM persons ORDER BY created_at DESC LIMIT 100",
+ },
+ )
+
+ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)
+
+ sql = print_cohort_hogql_query(cohort, context, team=self.team)
+
+ self.assertIn("order by", sql.lower())
+ self.assertIn("limit 100", sql.lower())
+ self.assertIn("as actor_id", sql.lower())
+
class TestGetNestedCohortIds(BaseTest):
def test_no_cohort_references(self):
diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.py
index 425c9d1dc357..f0e4da67df08 100644
--- a/products/cohorts/backend/models/util.py
+++ b/products/cohorts/backend/models/util.py
@@ -364,6 +364,18 @@ def print_cohort_hogql_query(cohort: Cohort, hogql_context: HogQLContext, *, tea
uses_actor_id = False
for select_query in extract_select_queries(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:
+ select_query.order_by = None
+
columns: dict[str, ast.Expr] = {}
for expr in select_query.select: