: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(data-modeling): resolve union-view parents, pivot joins, and nested union CTEs (#73483)
Jovan Sakovic97f2753f9367
diff --git a/products/data_modeling/backend/models/modeling.py b/products/data_modeling/backend/models/modeling.pyindex 6ab923243487..6bf9bffac83d 100644--- a/products/data_modeling/backend/models/modeling.py+++ b/products/data_modeling/backend/models/modeling.py@@ -19,7 +19,6 @@ from posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehfrom posthog.hogql.errors import QueryErrorfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.resolver import Resolver, ResolverFactory-from posthog.hogql.resolver_utils import extract_select_queriesfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -163,8 +162,14 @@ class BoundedResolver(Resolver):# views whose bodies are currently being visited; seeded with the current view name so# it counts as "visited" for cycle detectionself.resolving_views: set[str] = {initial_view_name} if initial_view_name else set()- # set by visit_join_expr, consumed by the body visit it triggers+ # set by visit_join_expr, consumed by the body visit it triggers (cycle detection needs+ # the name during resolution, before the id map below is populated)self._pending_view_name: str | None = None+ # id(resolved union body) -> the view it was inlined from. The base resolver stamps+ # `view_name` on SelectQuery bodies but not SelectSetQuery, so union-bodied views would+ # otherwise lose their identity; get_parents reads this to record the view as the parent+ # instead of descending into its own sources+ self.union_view_name_by_id: dict[int, str] = {}self.max_view_depth = max_view_depthself.deadline_seconds = deadline_secondsself.enforce_bounds = enforce_bounds@@ -246,9 +251,14 @@ class BoundedResolver(Resolver):previous_pending = self._pending_view_nameself._pending_view_name = view_nametry:- return super().visit_join_expr(node)+ result = super().visit_join_expr(node)finally:self._pending_view_name = previous_pending+ # a union body carries no view_name on the resolved tree; record its identity+ # so get_parents can recover the view name it was inlined from+ if isinstance(result, ast.JoinExpr) and isinstance(result.table, ast.SelectSetQuery):+ self.union_view_name_by_id[id(result.table)] = view_name+ return resultreturn super().visit_join_expr(node)@@ -423,6 +433,26 @@ def _lookup_cte(name: str, scope: CteScope) -> ast.CTE | None:return None+def _select_queries_with_scope(+ select: ast.SelectQuery | ast.SelectSetQuery, scope: CteScope+) -> list[tuple[ast.SelectQuery, CteScope]]:+ """Flatten a query into (leaf SelectQuery, CTE scope) pairs, threading scope per branch.++ A union's leading WITH must scope only that union's own branches. Computing one scope+ for the whole container and applying it to every flattened leaf loses the WITH that a+ *nested* union carries in a non-initial branch. Recursing branch by branch keeps each+ nested union's WITH bound to its own branches, at any depth or position.+ """+ if isinstance(select, ast.SelectQuery):+ return [(select, scope)]++ branch_scope = _scope_for_union_branches(select, scope)+ result = _select_queries_with_scope(select.initial_select_query, branch_scope)+ for node in select.subsequent_select_queries:+ result.extend(_select_queries_with_scope(node.select_query, branch_scope))+ return result++def get_parents_from_model_query(team: Team, model_name: str, model_query: str) -> set[str]:"""Get parents from a given query.@@ -462,13 +492,7 @@ def get_parents_from_model_query(team: Team, model_name: str, model_query: str)# each query is walked with the CTE scopes it can actually see, so a name defined in# one query's WITH never resolves a reference in an unrelated one- queries: list[tuple[ast.SelectQuery, CteScope]]- if isinstance(prepared_ast, ast.SelectSetQuery):- queries = [- (query, _scope_for_union_branches(prepared_ast, ())) for query in extract_select_queries(prepared_ast)- ]- else:- queries = [(prepared_ast, ())]+ queries: list[tuple[ast.SelectQuery, CteScope]] = _select_queries_with_scope(prepared_ast, ())parents: set[str] = set()@@ -484,52 +508,68 @@ def get_parents_from_model_query(team: Team, model_name: str, model_query: str)if query.ctes:scope = (query.ctes, *scope)- join = query.select_from-- if join is None:- continue-- while join is not None:- # every table in the FROM is a parent, so keep walking next_join past- # subqueries and expanded views rather than stopping at the first one- if isinstance(join.table, ast.SelectQuery):- if join.table.view_name is not None:- parents.add(join.table.view_name)+ # a FROM clause is a next_join chain; PIVOT/UNPIVOT over a join nests another chain,+ # so keep a stack of chains still to walk+ pending_joins: list[ast.JoinExpr | None] = [query.select_from]++ while pending_joins:+ join = pending_joins.pop()++ while join is not None:+ # every table in the FROM is a parent, so keep walking next_join past+ # subqueries and expanded views rather than stopping at the first one+ table: ast.Expr | None = join.table++ # PIVOT/UNPIVOT wrap a real source — a table, a subquery, or a whole join — so+ # unwrap to it; the source is the parent, not the pivot+ while isinstance(table, ast.PivotExpr | ast.UnpivotExpr):+ table = table.table++ if isinstance(table, ast.JoinExpr):+ # a pivot over a join result: walk that inner chain too+ pending_joins.append(table)+ join = join.next_join+ continue+ elif isinstance(table, ast.SelectQuery | ast.SelectSetQuery):+ # a saved-query view is the parent, so record it rather than descending past+ # it into its own sources. A SelectQuery view carries its name; a union body+ # doesn't, so recover it from the resolver's id map+ if isinstance(table, ast.SelectQuery):+ view_name = table.view_name+ else:+ view_name = resolver.union_view_name_by_id.get(id(table))+ if view_name is not None:+ parents.add(view_name)+ else:+ queries.extend(_select_queries_with_scope(table, scope))+ join = join.next_join+ continue+ elif isinstance(table, ast.ValuesQuery):+ # inline literal rows, no parent+ join = join.next_join+ continue++ if join.table_args is not None:+ # Table functions like numbers(), s3(), etc. are not real parents+ join = join.next_join+ continue+ elif isinstance(table, ast.Placeholder):+ parent_name = table.field+ elif isinstance(table, ast.Field):+ parent_name = ".".join(str(s) for s in table.chain)else:- queries.append((join.table, scope))+ raise ValueError(f"No handler for {table.__class__.__name__} in get_parents_from_model_query")- join = join.next_join- continue- elif isinstance(join.table, ast.SelectSetQuery):- branch_scope = _scope_for_union_branches(join.table, scope)- queries.extend((branch, branch_scope) for branch in extract_select_queries(join.table))- join = join.next_join- continue+ if isinstance(parent_name, str):+ cte = _lookup_cte(parent_name, scope)+ if cte is None:+ parents.add(parent_name)+ elif id(cte) not in expanded_ctes:+ expanded_ctes.add(id(cte))+ if isinstance(cte.expr, ast.SelectQuery | ast.SelectSetQuery):+ queries.extend(_select_queries_with_scope(cte.expr, scope))- if join.table_args is not None:- # Table functions like numbers(), s3(), etc. are not real parentsjoin = join.next_join- continue- elif isinstance(join.table, ast.Placeholder):- parent_name = join.table.field- elif isinstance(join.table, ast.Field):- parent_name = ".".join(str(s) for s in join.table.chain)- else:- raise ValueError(f"No handler for {join.table.__class__.__name__} in get_parents_from_model_query")-- if isinstance(parent_name, str):- cte = _lookup_cte(parent_name, scope)- if cte is None:- parents.add(parent_name)- elif id(cte) not in expanded_ctes:- expanded_ctes.add(id(cte))- if isinstance(cte.expr, ast.SelectSetQuery):- branch_scope = _scope_for_union_branches(cte.expr, scope)- queries.extend((branch, branch_scope) for branch in extract_select_queries(cte.expr))- elif isinstance(cte.expr, ast.SelectQuery):- queries.append((cte.expr, scope))-- join = join.next_joinreturn parentsdiff --git a/products/data_warehouse/backend/models/test/test_modeling.py b/products/data_warehouse/backend/models/test/test_modeling.pyindex a314c36ef541..e2323092711a 100644--- a/products/data_warehouse/backend/models/test/test_modeling.py+++ b/products/data_warehouse/backend/models/test/test_modeling.py@@ -579,22 +579,14 @@ class TestBoundedResolver(BaseTest):},)- @parameterized.expand(- [- # the branch that reads `b` is walked before the WITH on the leading branch is in scope- ("plain_caller", "select 1 from unioned", {"events", "leaf"}),- # the caller defines its own `b`, which the view's `b` must not resolve against- (- "caller_defines_colliding_cte",- "with b as (select id from persons) select 1 from unioned u join b bb on 1=1",- {"events", "leaf", "persons"},- ),- ],- )- def test_ctes_inside_union_bodied_view_are_not_parents(self, _name: str, query: str, expected_parents: set[str]):+ def test_ctes_inside_union_body_are_not_parents_when_walking_the_body(self):+ # When a union body is walked directly (syncing the union view itself), its branch+ # CTEs must not leak as parents — the branch that reads `b` is otherwise walked before+ # the leading WITH is in scope. The real sources (events, leaf) are the parents.self._make_union_bodied_view_with_ctes()- assert get_parents_from_model_query(self.team, "caller", query) == expected_parents+ body = "with a as (select event from events), b as (select event from leaf) select event from a union all select event from b"+ assert get_parents_from_model_query(self.team, "unioned", body) == {"events", "leaf"}def test_cycle_through_union_bodied_view_raises(self):# `view_name` is only stamped on ast.SelectQuery, so a view whose body is a top-level@@ -616,6 +608,71 @@ class TestBoundedResolver(BaseTest):assert exc_info.value.view_name == "u"+ def test_union_bodied_view_registers_as_parent_under_its_own_name(self):+ # A regular view registers as a parent under its own name (the resolver stamps+ # view_name on the SelectQuery body). A union-bodied view must behave the same way:+ # the DAG edge should point at the view, not skip past it to the view's own sources.+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="leaf",+ query={"query": "select event from events"},+ )+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="regular_view",+ query={"query": "select event from leaf"},+ )+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="union_view",+ query={"query": "select event from leaf union all select event from events"},+ )++ # baseline: a regular view is its consumer's parent+ assert get_parents_from_model_query(self.team, "caller", "select * from regular_view") == {"regular_view"}++ # a union-bodied view must be too — not replaced by {leaf, events}+ assert get_parents_from_model_query(self.team, "caller", "select * from union_view") == {"union_view"}++ def test_values_join_after_view_does_not_crash(self):+ # bug 2's fix walks past the first view instead of breaking, so a VALUES/PIVOT/UNPIVOT+ # join positioned after a view is now reached. VALUES carries no parent — it must be+ # skipped, not raise "No handler".+ self._make_diamond()++ parents = get_parents_from_model_query(+ self.team, "caller", "select 1 from shared s join (select 1 as n) v on 1=1"+ )+ assert parents == {"shared"}++ # the actual crash shape: a real VALUES clause joined after a view+ parents = get_parents_from_model_query(+ self.team, "caller", "select n from shared s cross join (values (1), (2)) as v(n)"+ )+ assert parents == {"shared"}++ def test_pivot_over_join_keeps_its_sources_as_parents(self):+ # PIVOT/UNPIVOT wrap their source in `.table`, which can be a whole join — its tables+ # are real parents and must not be dropped or crash the walk.+ parents = get_parents_from_model_query(+ self.team,+ "caller",+ "select 1 from events e join persons p on 1=1 pivot (count() for e.event in ('x'))",+ )+ assert parents == {"events", "persons"}++ def test_nested_non_initial_union_branch_with_own_cte(self):+ # A WITH on a parenthesized sub-union sitting in a *non-initial* branch must scope only+ # that sub-union's branches. Walking this body (syncing the view itself), `y` must+ # resolve as a CTE, not leak as a parent — its source `events` is the parent.+ body = (+ "select event from events "+ "union all "+ "(with y as (select event from events) select event from y union all select event from y)"+ )++ assert get_parents_from_model_query(self.team, "nested_union", body) == {"events"}+def test_depth_limit_raises_when_chain_too_deep(self):self._make_chain(length=4) # v0 → v1 → v2 → v3