: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(llma): ai column rewriter preserves select names (#59366)
Carlos Marchalde473d403b66
diff --git a/posthog/hogql_queries/ai/ai_column_rewriter.py b/posthog/hogql_queries/ai/ai_column_rewriter.pyindex 593fb8a67a16..dc926062735e 100644--- a/posthog/hogql_queries/ai/ai_column_rewriter.py+++ b/posthog/hogql_queries/ai/ai_column_rewriter.py@@ -80,10 +80,22 @@ class AiColumnToPropertyRewriter(CloningVisitor):def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:was_in_scope = self._in_ai_events_scopeold_qualifier = self._table_qualifier- if _has_ai_events_from(node):+ in_ai_events_scope = _has_ai_events_from(node)+ natural_names: list[str | None] = []+ if in_ai_events_scope:self._in_ai_events_scope = Trueself._table_qualifier = node.select_from.alias or "ai_events" if node.select_from else "ai_events"+ # Snapshot the pre-rewrite name of each SELECT-list bare Field. The rewrite+ # turns `trace_id` into `properties.$ai_trace_id`, which loses the column+ # name a parent query would reference (e.g. `SELECT trace_id FROM (...)`).+ # We re-alias below to keep the subquery's exposed column names stable.+ natural_names = [_select_item_natural_name(item, self._table_qualifier) for item in node.select]result = super().visit_select_query(node)+ if in_ai_events_scope:+ result.select = [+ ast.Alias(alias=name, expr=item) if name and not isinstance(item, ast.Alias) else item+ for name, item in zip(natural_names, result.select)+ ]self._in_ai_events_scope = was_in_scopeself._table_qualifier = old_qualifierreturn result@@ -127,6 +139,28 @@ class AiColumnToPropertyRewriter(CloningVisitor):return new_node+def _select_item_natural_name(item: ast.Expr, table_qualifier: str) -> str | None:+ """Return the column name this SELECT-list bare Field would lose during rewrite.++ Returns the original column name for bare (`["trace_id"]`) or table-qualified+ (`["ai_events", "trace_id"]`) AI column refs that this rewriter would otherwise+ transform into `properties.$ai_*` and silently lose the column name.+ """+ if not isinstance(item, ast.Field):+ return None+ chain = item.chain+ if len(chain) == 1 and isinstance(chain[0], str) and chain[0] in AI_COLUMN_TO_PROPERTY:+ return chain[0]+ if (+ len(chain) == 2+ and chain[0] == table_qualifier+ and isinstance(chain[1], str)+ and chain[1] in AI_COLUMN_TO_PROPERTY+ ):+ return chain[1]+ return None++def _has_ai_events_from(query: ast.SelectQuery) -> bool:"""Check if a SELECT query has FROM posthog.ai_events.diff --git a/posthog/hogql_queries/ai/test/test_ai_column_rewriter.py b/posthog/hogql_queries/ai/test/test_ai_column_rewriter.pyindex 3c8e53f6a7b5..23f8c4c9aa97 100644--- a/posthog/hogql_queries/ai/test/test_ai_column_rewriter.py+++ b/posthog/hogql_queries/ai/test/test_ai_column_rewriter.py@@ -118,8 +118,13 @@ class TestAiColumnToPropertyRewriter:query = parse_select("SELECT trace_id FROM posthog.ai_events AS ai_events")result = rewrite_query_for_events_table(query)assert isinstance(result, ast.SelectQuery)- assert isinstance(result.select[0], ast.Field)- assert result.select[0].chain == ["properties", "$ai_trace_id"]+ # Rewritten select item is re-aliased to its original column name so the+ # query's output schema stays stable for downstream consumers.+ item = result.select[0]+ assert isinstance(item, ast.Alias)+ assert item.alias == "trace_id"+ assert isinstance(item.expr, ast.Field)+ assert item.expr.chain == ["properties", "$ai_trace_id"]assert result.select_from is not Noneassert isinstance(result.select_from.table, ast.Field)assert result.select_from.table.chain == ["events"]@@ -155,6 +160,25 @@ class TestAiColumnToPropertyRewriter:assert isinstance(inner_select.expr, ast.Field)assert inner_select.expr.chain == ["properties", "$ai_trace_id"]+ def test_subquery_inner_bare_field_gets_alias_for_outer_reference(self):+ # Regression: sentiment GENERATIONS_QUERY had `SELECT trace_id` (no AS) inside+ # a subquery, and the outer query referenced `trace_id`. After rewrite the+ # inner column became `properties.$ai_trace_id` and the outer reference failed+ # with `Unable to resolve field: trace_id. Did you mean: $ai_trace_id?`.+ query = parse_select("SELECT trace_id FROM (SELECT trace_id FROM posthog.ai_events AS ai_events)")+ result = rewrite_query_for_events_table(query)+ assert isinstance(result, ast.SelectQuery)+ assert isinstance(result.select[0], ast.Field)+ assert result.select[0].chain == ["trace_id"]+ assert result.select_from is not None+ inner = result.select_from.table+ assert isinstance(inner, ast.SelectQuery)+ inner_item = inner.select[0]+ assert isinstance(inner_item, ast.Alias)+ assert inner_item.alias == "trace_id"+ assert isinstance(inner_item.expr, ast.Field)+ assert inner_item.expr.chain == ["properties", "$ai_trace_id"]+def test_force_rewrite_ignores_scope(self):node = ast.Field(chain=["trace_id"])result = AiColumnToPropertyRewriter(force_rewrite=True).visit(node)@@ -233,18 +257,28 @@ class TestAiColumnToPropertyRewriter:query = parse_select("SELECT e.trace_id, e.latency, e.is_error, e.timestamp FROM posthog.ai_events AS e")result = rewrite_query_for_events_table(query)assert isinstance(result, ast.SelectQuery)- # String column: e.trace_id → events.properties.$ai_trace_id- assert isinstance(result.select[0], ast.Field)- assert result.select[0].chain == ["events", "properties", "$ai_trace_id"]- # Numeric column: e.latency → toFloat(events.properties.$ai_latency)- assert isinstance(result.select[1], ast.Call)- assert result.select[1].name == "toFloat"- # Boolean column: e.is_error → if(events.properties.$ai_is_error = 'true', 1, 0)- assert isinstance(result.select[2], ast.Call)- assert result.select[2].name == "if"- # Native column: e.timestamp → events.timestamp- assert isinstance(result.select[3], ast.Field)- assert result.select[3].chain == ["events", "timestamp"]+ # String column: e.trace_id → Alias("trace_id", events.properties.$ai_trace_id)+ item0 = result.select[0]+ assert isinstance(item0, ast.Alias)+ assert item0.alias == "trace_id"+ assert isinstance(item0.expr, ast.Field)+ assert item0.expr.chain == ["events", "properties", "$ai_trace_id"]+ # Numeric column: e.latency → Alias("latency", toFloat(events.properties.$ai_latency))+ item1 = result.select[1]+ assert isinstance(item1, ast.Alias)+ assert item1.alias == "latency"+ assert isinstance(item1.expr, ast.Call)+ assert item1.expr.name == "toFloat"+ # Boolean column: e.is_error → Alias("is_error", if(events.properties.$ai_is_error = 'true', 1, 0))+ item2 = result.select[2]+ assert isinstance(item2, ast.Alias)+ assert item2.alias == "is_error"+ assert isinstance(item2.expr, ast.Call)+ assert item2.expr.name == "if"+ # Native column: e.timestamp → events.timestamp (already keeps its name, no alias needed)+ item3 = result.select[3]+ assert isinstance(item3, ast.Field)+ assert item3.chain == ["events", "timestamp"]# FROM clause rewritten, alias strippedassert result.select_from is not Noneassert isinstance(result.select_from.table, ast.Field)