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(data-modeling): let CTEs shadow view names in cycle detection (#74212)

Jovan Sakovicf42d820c9e73
diff --git a/products/data_modeling/backend/models/modeling.py b/products/data_modeling/backend/models/modeling.py
index 6bf9bffac83d..14a8ecf215c5 100644
--- a/products/data_modeling/backend/models/modeling.py
+++ b/products/data_modeling/backend/models/modeling.py
@@ -223,7 +223,14 @@ class BoundedResolver(Resolver):
def visit_join_expr(self, node: ast.JoinExpr):
"""Override to add cycle detection and depth limiting for view tables."""
# CTEs are handled entirely by the parent class, but for views we track visited for cycle detection
- if isinstance(node.table, ast.Field) and self.database is not None:
+ if (
+ isinstance(node.table, ast.Field)
+ and self.database is not None
+ # CTEs shadow database tables (the parent checks self.ctes before any table lookup),
+ # so a name bound in the current WITH scope is never a view reference; without this
+ # skip, a view whose body defines a same-named CTE reads as a cycle with itself
+ and self.ctes.get(".".join(str(n) for n in node.table.chain)) is None
+ ):
try:
database_table = self.database.get_table([str(n) for n in node.table.chain])
except QueryError:
diff --git a/products/data_warehouse/backend/models/test/test_modeling.py b/products/data_warehouse/backend/models/test/test_modeling.py
index e2323092711a..90be4664e0cc 100644
--- a/products/data_warehouse/backend/models/test/test_modeling.py
+++ b/products/data_warehouse/backend/models/test/test_modeling.py
@@ -673,6 +673,23 @@ class TestBoundedResolver(BaseTest):
assert get_parents_from_model_query(self.team, "nested_union", body) == {"events"}
+ @parameterized.expand(
+ [
+ # `WITH x AS (...) SELECT FROM x` saved as view `x`: the CTE shadows the view's
+ # own name, so this is not a self-cycle.
+ ("own_name", "reservations_all"),
+ # A CTE shadowing a different existing view must win over inlining that view.
+ ("other_view_name", "some_other_view"),
+ ]
+ )
+ def test_cte_shadowing_a_view_name_resolves_to_the_cte(self, _name, shadowed_name):
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team, name=shadowed_name, query={"query": "select id from persons"}
+ )
+ body = f"with {shadowed_name} as (select event from events) select * from {shadowed_name}"
+
+ assert get_parents_from_model_query(self.team, "reservations_all", body) == {"events"}
+
def test_depth_limit_raises_when_chain_too_deep(self):
self._make_chain(length=4) # v0 → v1 → v2 → v3