: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): tolerate source queries without an id column when populating static cohorts (#72527)
posthog[bot]043e26b77ea0
diff --git a/posthog/hogql_queries/actors_query_runner.py b/posthog/hogql_queries/actors_query_runner.pyindex ff10fcf52a94..16fa1ccdcf7a 100644--- a/posthog/hogql_queries/actors_query_runner.py+++ b/posthog/hogql_queries/actors_query_runner.py@@ -17,7 +17,7 @@ from posthog.schema import ()from posthog.hogql import ast-from posthog.hogql.constants import HogQLQuerySettings+from posthog.hogql.constants import HogQLQuerySettings, LimitContextfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.parser import parse_expr, parse_order_exprfrom posthog.hogql.printer import prepare_and_print_ast@@ -295,7 +295,7 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):return self.strategy.input_columns()# TODO: Figure out a more sure way of getting the actor id than using the alias or chain name- def source_id_column(self, source_query: ast.SelectQuery | ast.SelectSetQuery) -> list[int | str]:+ def source_id_column(self, source_query: ast.SelectQuery | ast.SelectSetQuery) -> list[int | str] | None:# Figure out the id column of the source query, first column that has id in the nameif isinstance(source_query, ast.SelectQuery):select = source_query.select@@ -312,6 +312,12 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):if isinstance(column, ast.Field) and any("id" in str(part).lower() for part in column.chain):return [str(part) for part in column.chain]++ # During cohort calculation the caller (print_cohort_hogql_query) can still resolve the+ # actor id from the source query's own table (events → person.id, persons → id). Return+ # None so it gets that chance instead of crashing static-cohort population outright.+ if self.limit_context == LimitContext.COHORT_CALCULATION:+ return Noneraise ValueError("Source query must have an id column")def source_distinct_id_column(self, source_query: ast.SelectQuery | ast.SelectSetQuery) -> str | None:@@ -330,6 +336,8 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):assert self.source_query_runner is not None # For type checkingsource_query = self.source_query_runner.to_actors_query()source_id_chain = self.source_id_column(source_query)+ if source_id_chain is None:+ raise ValueError("Source query must have an id column")source_alias = "source"return ast.JoinExpr(@@ -349,7 +357,7 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):),)- def to_query(self) -> ast.SelectQuery:+ def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:with self.timings.measure("columns"):columns = []group_by = []@@ -455,6 +463,11 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):assert self.source_query_runner is not None # For type checkingsource_query = self.source_query_runner.to_actors_query()source_id_chain = self.source_id_column(source_query)+ if source_id_chain is None:+ # Cohort calculation with a source that exposes no id column: hand the source+ # query back so the cohort calculator resolves the actor id from its table.+ # Skipping the persons join is fine — we only need the set of actor ids.+ return source_querysource_distinct_id_column = self.source_distinct_id_column(source_query)source_alias = "source"@@ -517,7 +530,7 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):ast.CompareOperation(left=ast.Field(chain=[origin, self.strategy.origin_id]),right=ast.SelectQuery(- select=[ast.Field(chain=[source_alias, *self.source_id_column(source_query)])],+ select=[ast.Field(chain=[source_alias, *source_id_chain])],select_from=ast.JoinExpr(table=source_query, alias=source_alias),),op=ast.CompareOperationOp.In,@@ -545,7 +558,7 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):return select_query- def to_actors_query(self) -> ast.SelectQuery:+ def to_actors_query(self) -> ast.SelectQuery | ast.SelectSetQuery:return self.to_query()def apply_dashboard_filters(self, dashboard_filter: DashboardFilter):diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.pyindex 500572ac0ef9..a3cc816779c1 100644--- a/posthog/hogql_queries/hogql_cohort_query.py+++ b/posthog/hogql_queries/hogql_cohort_query.py@@ -83,6 +83,14 @@ def parse_and_validate_positive_integer(value: Optional[Union[str, int]], value_return parsed_value+def _require_select_query(query: ast.SelectQuery | ast.SelectSetQuery) -> ast.SelectQuery:+ # A constant `select=["id"]` actors query never yields a set query. Fail loudly rather than+ # via a strippable assert if that invariant ever breaks.+ if not isinstance(query, ast.SelectQuery):+ raise ValueError("Expected a single SELECT query from the actors query, got a set query")+ return query++def _apply_in_order_aggregation(query: ast.SelectQuery) -> ast.SelectQuery:"""Set optimize_aggregation_in_order on the inner argMax-dedup subquery.@@ -302,7 +310,7 @@ class HogQLCohortQuery:source=source,select=["id"],)- return ActorsQueryRunner(team=self.team, query=actors_query).to_query()+ return _require_select_query(ActorsQueryRunner(team=self.team, query=actors_query).to_query())def get_performed_event_condition(self, prop: Property, first_time: bool = False) -> ast.SelectQuery:math = None@@ -547,7 +555,7 @@ class HogQLCohortQuery:select=["id"],)query_runner = ActorsQueryRunner(team=self.team, query=actors_query)- return query_runner.to_query()+ return _require_select_query(query_runner.to_query())def get_person_metadata_condition(self, prop: Property) -> ast.SelectQuery:# type = "person_metadata"@@ -561,7 +569,7 @@ class HogQLCohortQuery:select=["id"],)query_runner = ActorsQueryRunner(team=self.team, query=actors_query)- return query_runner.to_query()+ return _require_select_query(query_runner.to_query())def get_static_cohort_condition(self, prop: Property) -> ast.SelectQuery:# Convert the cohort id to an int (not the no-op typing.cast) and bind it as a parameter.@@ -713,7 +721,7 @@ class HogQLCohortQuery:select=["id"],)query_runner = ActorsQueryRunner(team=self.team, query=actors_query)- return query_runner.to_query()+ return _require_select_query(query_runner.to_query())def build_conditions(prop: Optional[Union[PropertyGroup, Property]],diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.pyindex e8113934699c..8e394358349c 100644--- a/products/cohorts/backend/models/test/test_util.py+++ b/products/cohorts/backend/models/test/test_util.py@@ -732,6 +732,51 @@ class TestCohortUtils(BaseTest):self.assertIn("limit 100", sql.lower())self.assertIn("as actor_id", sql.lower())+ @parameterized.expand(+ [+ ("events_source", "SELECT count() AS cnt FROM events", "actor_id"),+ ("persons_source", "SELECT properties.email AS email FROM persons", "actor_id"),+ ]+ )+ def test_print_cohort_hogql_query_source_without_id_column_uses_table_fallback(self, _name, source_sql, expected):+ # A stored ActorsQuery whose source selects no id-named column used to crash in+ # ActorsQueryRunner.to_query with "Source query must have an id column" before+ # print_cohort_hogql_query could apply its events→person.id / persons→id fallback.+ cohort = Cohort.objects.create(+ team=self.team,+ name="Test Source Without ID Column",+ query={+ "kind": "ActorsQuery",+ "source": {"kind": "HogQLQuery", "query": source_sql},+ },+ )++ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)++ sql = print_cohort_hogql_query(cohort, context, team=self.team)++ self.assertIn(expected, sql)++ def test_print_cohort_hogql_query_source_without_id_column_still_raises_when_unresolvable(self):+ # When the source has no id column and its table isn't events/persons, the fallback+ # can't resolve an actor id — surface the clear "Could not find" error, not a crash+ # deep inside to_query.+ cohort = Cohort.objects.create(+ team=self.team,+ name="Test Unresolvable Source",+ query={+ "kind": "ActorsQuery",+ "source": {"kind": "HogQLQuery", "query": "SELECT count() AS cnt FROM sessions"},+ },+ )++ context = HogQLContext(team_id=self.team.id, enable_select_queries=True)++ with self.assertRaises(ValueError) as cm:+ print_cohort_hogql_query(cohort, context, team=self.team)++ self.assertIn("Could not find a person_id, actor_id, id, or distinct_id column", str(cm.exception))+class TestGetNestedCohortIds(BaseTest):def test_no_cohort_references(self):