: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(hogql): deduplicate shared type traversal (#130347)
Sandy Spicercad0fa1c4a14
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex ecbdebf7a233..eda82a8c4fa0 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -2396,6 +2396,23 @@ class TestPrinter(BaseTest):),)+ def test_select_alias_shared_type_chain(self) -> None:+ aliases = [f"tuple(e{i - 1}, e{i - 1}) AS e{i}" for i in range(1, 41)]+ query = f"SELECT event AS e0, {', '.join(aliases)}, count() FROM events GROUP BY e40"+ context = HogQLContext(+ team_id=self.team.pk,+ database=Database.create_for(team=self.team),+ enable_select_queries=True,+ )++ printed, _ = prepare_and_print_ast(parse_select(query), context, "clickhouse")++ self.assertEqual(+ printed,+ f"SELECT events.event AS e0, {', '.join(aliases)}, count() AS `count()` FROM {self._events_table_ref()} "+ f"WHERE equals(events.team_id, {self.team.pk}) GROUP BY e40 LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )+def test_select_from(self):self.assertEqual(self._select("select 1 from events"),diff --git a/posthog/hogql/visitor.py b/posthog/hogql/visitor.pyindex 69a07c0161ce..8035e270c98d 100644--- a/posthog/hogql/visitor.py+++ b/posthog/hogql/visitor.py@@ -46,6 +46,26 @@ class Visitor(Generic[T]):class TraversingVisitor(Visitor[None]):"""Visitor that traverses the AST tree without returning anything"""+ _visited_types: dict[int, ast.Type] | None = None++ def visit(self, node: AST | None) -> None:+ if not isinstance(node, ast.Type):+ return super().visit(node)++ # Alias references share type subgraphs, so walking every edge can expand exponentially.+ is_root_type = self._visited_types is None+ if self._visited_types is None:+ self._visited_types = {}+ if id(node) in self._visited_types:+ return+ self._visited_types[id(node)] = node+ try:+ super().visit(node)+ finally:+ # Later expressions and lazy-table resolution passes must see mutations to these types.+ if is_root_type:+ self._visited_types = None+def visit_cte(self, node: ast.CTE):self.visit(node.expr)