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(hogql): keep shared CTE columns demanded by sibling union branches (#67719)

Jovan Sakovicd211de2b0bde
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index bb90c16695d5..b4042ad3f64a 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -209,6 +209,9 @@ def prepare_ast_for_printing(
if context.modifiers.optimizeProjections:
with context.timings.measure("projection_pushdown"):
node = pushdown_projections(node, context)
+ # Pushdown mutates SelectQueryType.columns, staling cached CTE tables. Drop them so a
+ # wrongly pruned column fails loudly at compile time instead of emitting broken SQL.
+ context.cte_database_table_cache.clear()
if dialect in SQL_TARGET_DIALECTS:
with context.timings.measure("resolve_lazy_tables"):
diff --git a/posthog/hogql/test/test_resolver.py b/posthog/hogql/test/test_resolver.py
index be4f19f1e2d9..84d5e8dc304c 100644
--- a/posthog/hogql/test/test_resolver.py
+++ b/posthog/hogql/test/test_resolver.py
@@ -11,6 +11,8 @@ from django.test import override_settings
from parameterized import parameterized
+from posthog.schema import HogQLQueryModifiers
+
import posthog.hogql.resolver_utils as resolver_utils
from posthog.hogql import ast
from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS
@@ -773,6 +775,40 @@ class TestResolver(BaseTest):
assert len(build_ids) == len(set(build_ids))
assert len(set(build_ids)) == 4
+ def test_star_cte_shared_by_union_branches_projects_all_columns(self):
+ # Regression: pushdown pruned a `SELECT *` CTE to the first UNION branch's column, and
+ # the cached CTE table (built pre-prune) masked the failure into silently broken SQL.
+ query = cast(
+ ast.SelectSetQuery,
+ clone_expr(
+ parse_select(
+ "with base as (select * from (select 1 as a, 2 as b, 3 as d)) "
+ "select a as v from base "
+ "union all select b as v from base "
+ "union all select d as v from base"
+ ),
+ clear_locations=True,
+ ),
+ )
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(optimizeProjections=True),
+ )
+ _, prepared = prepare_and_print_ast(query, context, "clickhouse")
+
+ # The single shared CTE must project every column referenced across the branches.
+ assert isinstance(prepared, ast.SelectSetQuery)
+ first_branch = prepared.initial_select_query
+ assert isinstance(first_branch, ast.SelectQuery) and first_branch.ctes is not None
+ base_cte = first_branch.ctes["base"].expr
+ assert isinstance(base_cte, ast.SelectQuery)
+ cte_cols: set[str] = set()
+ for col in base_cte.select:
+ assert isinstance(col, ast.Alias | ast.Field)
+ cte_cols.add(col.alias if isinstance(col, ast.Alias) else str(col.chain[-1]))
+ assert cte_cols == {"a", "b", "d"}, f"CTE dropped columns referenced by sibling UNION branches: got {cte_cols}"
+
def test_ctes_with_aliases_in_joins(self):
self.assertEqual(
self._print_hogql(
diff --git a/posthog/hogql/transforms/projection_pushdown.py b/posthog/hogql/transforms/projection_pushdown.py
index 6088e52348b4..262e18d82d94 100644
--- a/posthog/hogql/transforms/projection_pushdown.py
+++ b/posthog/hogql/transforms/projection_pushdown.py
@@ -13,19 +13,31 @@ class ProjectionPushdownOptimizer(TraversingVisitor):
Algorithm Overview:
──────────────────
- This optimizer works in a single top-down pass through the query tree:
+ This optimizer makes two top-down passes through the query tree: the first only collects
+ demands, the second prunes with the complete demand set. A CTE can be consumed by nodes
+ visited after it — notably sibling UNION branches — so pruning must wait for the full walk.
+
+ Each pass runs these phases per query:
Phase 1 - Register: Map subquery types to AST nodes for demand tracking
Phase 2 - Collect: Gather column demands from WHERE/GROUP BY/ORDER BY/etc
Phase 3 - Propagate: For demanded columns, visit their source to propagate to child queries
Phase 4 - Recurse: Visit child subqueries (repeat phases 1-4)
- Phase 5 - Prune: Remove unreferenced asterisk columns from this query
+ Phase 5 - Prune: Remove unreferenced asterisk columns from this query (second pass only)
"""
def __init__(self):
super().__init__()
self.demands: dict[int, set[str]] = defaultdict(set)
self.subquery_map: dict[int, ast.SelectQuery | ast.SelectSetQuery] = {}
+ # True during the first pass; gates pruning to the second (see class docstring)
+ self.collecting: bool = False
+
+ def optimize(self, node: ast.SelectQuery | ast.SelectSetQuery) -> ast.SelectQuery | ast.SelectSetQuery:
+ self.collecting = True
+ self.visit(node)
+ self.collecting = False
+ return cast(ast.SelectQuery | ast.SelectSetQuery, self.visit(node))
def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:
# Phase 1: Register subqueries and CTEs for demand tracking
@@ -68,10 +80,11 @@ class ProjectionPushdownOptimizer(TraversingVisitor):
if node.select_from:
self.visit(node.select_from)
- # Phase 5: Prune unreferenced asterisk columns from this query and CTEs
- self._prune_columns(node)
- if node.ctes:
- self._prune_cte_columns(node.ctes)
+ # Phase 5: Prune unreferenced asterisk columns from this query and CTEs (second pass only)
+ if not self.collecting:
+ self._prune_columns(node)
+ if node.ctes:
+ self._prune_cte_columns(node.ctes)
return node
@@ -290,4 +303,4 @@ def pushdown_projections(node: _T_AST, context: HogQLContext) -> _T_AST:
if not isinstance(node, (ast.SelectQuery, ast.SelectSetQuery)):
return node
optimizer = ProjectionPushdownOptimizer()
- return cast(_T_AST, optimizer.visit(node))
+ return cast(_T_AST, optimizer.optimize(node))
diff --git a/posthog/hogql/transforms/test/test_projection_pushdown.py b/posthog/hogql/transforms/test/test_projection_pushdown.py
index 0eace95faf4f..c358d8c3b04c 100644
--- a/posthog/hogql/transforms/test/test_projection_pushdown.py
+++ b/posthog/hogql/transforms/test/test_projection_pushdown.py
@@ -593,3 +593,21 @@ class TestProjectionPushdown(BaseTest):
}, f"Expected event, timestamp, and person_id but got {base_cols}"
assert optimized.to_hogql() == self.snapshot
+
+ def test_cte_shared_by_union_branches_keeps_all_demanded_columns(self):
+ # The WITH lives on the first UNION branch but every sibling branch consumes it, so
+ # pruning before all branches register their demands drops columns the siblings need.
+ optimized = self._optimize(
+ "WITH base AS (SELECT * FROM (SELECT 1 AS a, 2 AS b, 3 AS d)) "
+ "SELECT a FROM base "
+ "UNION ALL SELECT b FROM base "
+ "UNION ALL SELECT d FROM base"
+ )
+
+ first_branch = optimized.initial_select_query
+ assert isinstance(first_branch, ast.SelectQuery)
+ assert first_branch.ctes is not None
+ base_cte = first_branch.ctes["base"].expr
+ assert isinstance(base_cte, ast.SelectQuery)
+ base_cols = {self._col_name(col) for col in base_cte.select}
+ assert base_cols == {"a", "b", "d"}, f"CTE dropped columns demanded by sibling branches: got {base_cols}"