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(notebooks): order sql node refs before the ctes that read them (#77297)

Sinan Kucukkoseler924ef0e6696d
diff --git a/products/notebooks/backend/sql_v2_references.py b/products/notebooks/backend/sql_v2_references.py
index 138b4282bb01..881c12c47a6a 100644
--- a/products/notebooks/backend/sql_v2_references.py
+++ b/products/notebooks/backend/sql_v2_references.py
@@ -58,17 +58,21 @@ class SQLV2Ref:
last_run_code: str | None = None
-class _TableReferenceCollector(TraversingVisitor):
+class _ReferenceCollector(TraversingVisitor):
+ """Base for the two scans below: both gather the names of `candidates` a query reaches."""
+
+ def __init__(self, candidates: set[str]) -> None:
+ self.candidates = candidates
+ self.found: set[str] = set()
+
+
+class _TableReferenceCollector(_ReferenceCollector):
"""Collect the FROM/JOIN targets of a query that name one of `candidates`.
Only bare single-identifier tables count — ``from df1`` matches, a column called
``df1`` does not — so a reference is a genuine table position, not any mention.
"""
- def __init__(self, candidates: set[str]) -> None:
- self.candidates = candidates
- self.found: set[str] = set()
-
def visit_join_expr(self, node: ast.JoinExpr) -> None:
table = node.table
if isinstance(table, ast.Field) and len(table.chain) == 1 and table.chain[0] in self.candidates:
@@ -78,14 +82,38 @@ class _TableReferenceCollector(TraversingVisitor):
super().visit_join_expr(node)
-def _references(query: ast.SelectQuery | ast.SelectSetQuery, candidates: set[str]) -> set[str]:
- collector = _TableReferenceCollector(candidates)
+class _NameReferenceCollector(_ReferenceCollector):
+ """Collect every bare identifier naming one of `candidates`, in any position.
+
+ A superset of `_TableReferenceCollector`: a scalar CTE (``with 5 as cutoff``) is read as a
+ column, not a table, so FROM/JOIN positions alone can't see that dependency. Only safe for
+ ordering an already-chosen set of CTEs — never for deciding what to inline, where a column
+ that merely shares a node's name must not pull that node in.
+ """
+
+ def visit_field(self, node: ast.Field) -> None:
+ if len(node.chain) == 1 and node.chain[0] in self.candidates:
+ name = node.chain[0]
+ if isinstance(name, str):
+ self.found.add(name)
+ super().visit_field(node)
+
+
+def _collect(collector: _ReferenceCollector, query: ast.Expr) -> set[str]:
collector.visit(query)
# A name the query defines as its own CTE shadows the ref — don't pull it in.
own_ctes = set(query.ctes.keys()) if isinstance(query, ast.SelectQuery) and query.ctes else set()
return collector.found - own_ctes
+def _references(query: ast.Expr, candidates: set[str]) -> set[str]:
+ return _collect(_TableReferenceCollector(candidates), query)
+
+
+def _ordering_dependencies(query: ast.Expr, candidates: set[str]) -> set[str]:
+ return _collect(_NameReferenceCollector(candidates), query)
+
+
def resolve_sql_v2_references(code: str, refs: dict[str, str | None]) -> str:
"""Return `code` with every referenced upstream definition inlined as a CTE.
@@ -152,11 +180,43 @@ def resolve_sql_v2_references(code: str, refs: dict[str, str | None]) -> str:
root = main if isinstance(main, ast.SelectQuery) else parse_select(f"select * from ({code}\n)")
if not isinstance(root, ast.SelectQuery): # narrow for the type checker; the wrap is always a SelectQuery
return code
- ctes: dict[str, ast.CTE] = dict(root.ctes or {})
- for name in order:
- # setdefault so the user's own CTE of the same name always wins over a node ref.
- ctes.setdefault(name, ast.CTE(name=name, expr=parse_ref(name), cte_type="subquery"))
- root.ctes = ctes
+ user_ctes: dict[str, ast.CTE] = dict(root.ctes or {})
+ # The user's own CTE of the same name always wins over a node ref.
+ injected = {
+ name: ast.CTE(name=name, expr=parse_ref(name), cte_type="subquery") for name in order if name not in user_ctes
+ }
+
+ # A CTE must be printed before every CTE that reads it, and the user's own WITH clauses
+ # can read node refs just as node definitions can read a shadowing user CTE. So the two
+ # sides get merged in one dependency order rather than concatenated — appending the refs
+ # after a `with … as (select … from df1)` leaves df1 an unknown table.
+ all_names = set(injected) | set(user_ctes)
+ merged: dict[str, ast.CTE] = {}
+ emitting: set[str] = set()
+
+ def emit(name: str) -> None:
+ if name in merged or name in emitting:
+ return
+ emitting.add(name)
+ cte = injected.get(name) or user_ctes[name]
+ # Ordering has to see expression-position reads too: an inlined definition reading the
+ # user's `with 5 as cutoff` depends on it even though no FROM/JOIN names it.
+ table_dependencies = _references(cte.expr, all_names)
+ for dependency in sorted(_ordering_dependencies(cte.expr, all_names) - {name}):
+ # The node-ref cycle check above only walks node names, so a cycle running through
+ # one of the user's own CTEs reaches here instead. No ordering satisfies it, so fail
+ # with a 400 rather than dispatch a query that can't resolve. Only a real table
+ # position counts: the broader scan above also matches columns, where a name shared
+ # with a CTE is not a dependency at all.
+ if dependency in emitting and dependency in table_dependencies:
+ raise SQLV2ReferenceError(f"Reference cycle through '{dependency}'.")
+ emit(dependency)
+ emitting.discard(name)
+ merged[name] = cte
+
+ for name in [*injected, *user_ctes]:
+ emit(name)
+ root.ctes = merged
return print_prepared_ast(root, context=HogQLContext(team_id=None), dialect="hogql")
diff --git a/products/notebooks/backend/test/test_sql_v2_references.py b/products/notebooks/backend/test/test_sql_v2_references.py
index 24d30b656dee..5c1397c1e5e4 100644
--- a/products/notebooks/backend/test/test_sql_v2_references.py
+++ b/products/notebooks/backend/test/test_sql_v2_references.py
@@ -1,5 +1,13 @@
+from posthog.test.base import BaseTest
+
from django.test import SimpleTestCase
+from parameterized import parameterized
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
+
from products.notebooks.backend.sql_v2_references import (
SQLV2Ref,
SQLV2ReferenceError,
@@ -172,6 +180,44 @@ class TestResolveSQLV2References(SimpleTestCase):
self.assertIn("mine AS", resolved)
self.assertIn("df1 AS", resolved)
+ @parameterized.expand(
+ [
+ # The user's own WITH reads a node frame, so the injected CTE has to precede it.
+ ("user_cte_reads_a_ref", "with mine as (select id from df1) select * from mine", "df1 AS", "mine AS"),
+ # And the reverse: the node's definition reads a name the user's WITH shadows.
+ ("ref_reads_a_shadowed_cte", "with df1 as (select 5 as id) select * from df2", "df1 AS", "df2 AS"),
+ # A scalar CTE is read as a column, so this dependency appears in no FROM/JOIN at all.
+ ("ref_reads_a_scalar_cte", "with 5 as cutoff select id from df3", "5 AS cutoff", "df3 AS"),
+ ]
+ )
+ def test_ctes_are_merged_in_dependency_order(self, _name, code, first, second):
+ # Whichever side a CTE comes from, it must be printed before the one that reads it —
+ # appending the refs after the user's WITH leaves them unknown tables.
+ resolved = resolve_sql_v2_references(
+ code,
+ {
+ "df1": "select uuid as id from events",
+ "df2": "select id from df1 where id > 0",
+ "df3": "select uuid as id from events where 1 > cutoff",
+ },
+ )
+ self.assertLess(resolved.index(first), resolved.index(second))
+
+ @parameterized.expand(
+ [
+ ("subquery_in_from", "select id from (select id from df1)"),
+ ("subquery_in_where", "select uuid from events where uuid in (select id from df1)"),
+ ("scalar_subquery_in_select_list", "select (select count() from df1) as c"),
+ ("union_inside_a_user_cte", "with u as (select id from df1 union all select 1 as id) select id from u"),
+ ]
+ )
+ def test_refs_nested_below_the_top_level_are_still_inlined(self, _name, code):
+ # Every other case here reads the ref from a top-level FROM/JOIN, so a collector that
+ # stopped descending into subqueries would still pass them while silently dropping the
+ # CTE — the query then fails in ClickHouse with an unknown table.
+ resolved = resolve_sql_v2_references(code, {"df1": "select uuid as id from events"})
+ self.assertIn("df1 AS (", resolved)
+
def test_union_query_with_a_trailing_line_comment_still_resolves(self):
# The UNION wrap embeds the raw text in `select * from (…)`; without a newline before
# the closing paren a trailing `--` comment swallows the wrapper and the parse crashes.
@@ -198,6 +244,25 @@ class TestResolveSQLV2References(SimpleTestCase):
{"a": "select * from b", "b": "select * from a"},
)
+ def test_cycle_through_a_user_cte_raises(self):
+ # The cycle check above only walks node names, so a cycle closed by the user's own CTE
+ # reaches the merge instead. Naming a CTE after a table the node reads is an easy
+ # collision to hit, and it must fail here as a 400 rather than as a ClickHouse error.
+ with self.assertRaises(SQLV2ReferenceError):
+ resolve_sql_v2_references(
+ "with events as (select * from df1) select * from df1",
+ {"df1": "select * from events"},
+ )
+
+ def test_columns_sharing_a_cte_name_are_not_a_cycle(self):
+ # Ordering scans every identifier, not just table positions, so two CTEs selecting a
+ # column named after each other look circular. They aren't, and must still resolve.
+ resolved = resolve_sql_v2_references(
+ "with a as (select b from df1), b as (select a from df1) select * from a",
+ {"df1": "select uuid as a, uuid as b from events"},
+ )
+ self.assertIn("df1 AS (", resolved)
+
def test_invalid_referenced_definition_raises(self):
with self.assertRaises(SQLV2ReferenceError):
resolve_sql_v2_references("select * from df1", {"df1": "select from where ("})
@@ -210,3 +275,33 @@ class TestResolveSQLV2References(SimpleTestCase):
def test_unreferenced_never_run_node_is_ignored(self):
# A never-run node nobody references must not block the run.
self.assertEqual(resolve_sql_v2_references("select 1", {"df1": None}), "select 1")
+
+
+class TestResolvedQueryIsValidHogQL(BaseTest):
+ # Every other assertion in this file matches a substring of the resolved SQL, which cannot see
+ # a query that is well-formed but unresolvable: the CTE-ordering bug emitted a perfectly good
+ # `df1 AS (…)` *after* the CTE reading it, so every substring check passed while ClickHouse
+ # rejected the query. Resolving it for real is the only assertion that catches that class.
+ @parameterized.expand(
+ [
+ ("user_cte_reads_a_ref", "with mine as (select id from df1) select id from mine"),
+ ("ref_reads_a_shadowed_cte", "with df1 as (select 5 as id) select id from df2"),
+ (
+ "chained_user_ctes_over_a_ref",
+ "with a as (select id from df1), b as (select id from a) select id from b",
+ ),
+ ("nested_subquery", "select id from (select id from df1)"),
+ ("ref_reads_a_scalar_cte", "with 5 as cutoff select id from df3"),
+ ]
+ )
+ def test_resolved_query_typechecks(self, _name, code):
+ resolved = resolve_sql_v2_references(
+ code,
+ {
+ "df1": "select uuid as id from events",
+ "df2": "select id from df1 where id > 0",
+ "df3": "select uuid as id from events where 1 > cutoff",
+ },
+ )
+ context = HogQLContext(team_id=self.team.pk, team=self.team, enable_select_queries=True)
+ prepare_and_print_ast(parse_select(resolved), context=context, dialect="clickhouse")