: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
feat(query-tagging): attribute HogQLQuery runs from parsed AST features (#58186)
Robbie584925f0a9a9
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex c59e9fb4145e..efa4f0e2526c 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -260,6 +260,16 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:assert_never(kind)+class HogQLFeatures(BaseModel):+ """Tables and event filters extracted from a HogQL AST — feeds product+ attribution in ``add_fallback_query_tags`` for ``kind=HogQLQuery``."""++ tables: list[str] = []+ events: list[str] = []++ model_config = ConfigDict(validate_assignment=True)++class TemporalTags(BaseModel):"""Tags for temporalio workflows and activities.@@ -389,6 +399,8 @@ class QueryTags(BaseModel):has_joins: Optional[bool] = Nonehas_json_operations: Optional[bool] = None+ hogql_features: Optional[HogQLFeatures] = None+modifiers: Optional[object] = Nonenumber_of_entities: Optional[int] = Noneperson_on_events_mode: Optional[str] = None # PersonsOnEventsMode@@ -532,8 +544,32 @@ def _apply_fallback_tags(tags: QueryTags, mapped: FallbackTags) -> None:tags.feature = mapped["feature"]+# Event-level matches pinpoint a single product; consulted before tables since they're more specific.+_EVENT_TO_TAGS: tuple[tuple[frozenset[str], FallbackTags], ...] = (+ (+ frozenset({"$ai_generation", "$ai_span", "$ai_trace", "$ai_embedding", "$ai_metric", "$ai_feedback"}),+ {"product": Product.LLM_ANALYTICS},+ ),+ (frozenset({"$exception"}), {"product": Product.ERROR_TRACKING}),+ (frozenset({"$web_vitals"}), {"product": Product.WEB_ANALYTICS}),+ (frozenset({"$feature_flag_called"}), {"product": Product.FEATURE_FLAGS}),+)++# Union of every event the fallback can match — exposed so HogQLFeatureExtractor can use it as+# its allow-list without duplicating the names. Adding a new mapping to _EVENT_TO_TAGS+# automatically widens what the extractor records.+EVENT_TAG_MATCHERS: frozenset[str] = frozenset().union(*(matchers for matchers, _ in _EVENT_TO_TAGS))++# Table-level fallbacks — only consulted if no event filter narrowed things down.+_TABLE_TO_TAGS: tuple[tuple[frozenset[str], FallbackTags], ...] = (+ (frozenset({"session_replay_events", "raw_session_replay_events"}), {"product": Product.REPLAY}),+ (frozenset({"logs", "log_attributes"}), {"product": Product.LOGS}),+ (frozenset({"events"}), {"product": Product.PRODUCT_ANALYTICS}),+)++def add_fallback_query_tags(tags: QueryTags) -> None:- """Order: scene → kind → mcp source. Never overrides values that are already set."""+ """Order: scene → kind → hogql features (HogQLQuery only) → mcp source. Never overrides set values."""if tags.scene and (scene_mapped := SCENE_TO_TAGS.get(tags.scene)) is not None:_apply_fallback_tags(tags, scene_mapped)@@ -545,6 +581,22 @@ def add_fallback_query_tags(tags: QueryTags) -> None:if kind is not None and (kind_mapped := kind_fallback_tags(kind)) is not None:_apply_fallback_tags(tags, kind_mapped)+ if (+ tags.product is None+ and tags.query_type == NodeKind.HOG_QL_QUERY.value+ and (features := tags.hogql_features) is not None+ ):+ events_set, tables_set = set(features.events), set(features.tables)+ features_mapped = next(+ (m for matchers, m in _EVENT_TO_TAGS if events_set & matchers),+ None,+ ) or next(+ (m for matchers, m in _TABLE_TO_TAGS if tables_set & matchers),+ None,+ )+ if features_mapped is not None:+ _apply_fallback_tags(tags, features_mapped)+from posthog.event_usage import EventSourceif tags.product is None and tags.source == EventSource.MCP:diff --git a/posthog/clickhouse/test/test_query_tagging.py b/posthog/clickhouse/test/test_query_tagging.pyindex fa3d2556dae5..0bf252b52162 100644--- a/posthog/clickhouse/test/test_query_tagging.py+++ b/posthog/clickhouse/test/test_query_tagging.py@@ -15,6 +15,7 @@ from posthog.clickhouse.query_tagging import (_PROJECT_ROOT_PREFIX,_SOURCE_SKIP_PREFIXES,Feature,+ HogQLFeatures,Product,QueryTags,TemporalTags,@@ -404,6 +405,58 @@ class TestQueryTaggingSourceInQueryLog(BaseTest, ClickhouseTestMixin):assert comment.get("product") != Product.MCP.value+ def test_execute_hogql_query_populates_hogql_features_tag(self):+ # End-to-end: a HogQLQuery against `events` filtered by `$exception` should+ # land in query_log with both the AST-derived hogql_features tag and the+ # error_tracking product attribution that derives from it.+ marker = str(uuid.uuid4())+ reset_query_tags()+ tag_queries(kind="request", id="test", team_id=self.team.pk, feature="query")+ execute_hogql_query(+ f"SELECT count() FROM events WHERE distinct_id = '{marker}' AND event = '$exception'", # noqa: S608+ team=self.team,+ query_type="HogQLQuery",+ )++ comment = self._get_log_comment(marker)++ assert comment["hogql_features"] == {"tables": ["events"], "events": ["$exception"]}+ assert comment["product"] == Product.ERROR_TRACKING.value++ def test_execute_hogql_query_attributes_plain_events_query_to_product_analytics(self):+ # Plain `events` query (no narrowing event filter) should fall back to+ # product_analytics via the table-level rule.+ marker = str(uuid.uuid4())+ reset_query_tags()+ tag_queries(kind="request", id="test", team_id=self.team.pk, feature="query")+ execute_hogql_query(+ f"SELECT count() FROM events WHERE distinct_id = '{marker}'", # noqa: S608+ team=self.team,+ query_type="HogQLQuery",+ )++ comment = self._get_log_comment(marker)++ assert comment["hogql_features"] == {"tables": ["events"], "events": []}+ assert comment["product"] == Product.PRODUCT_ANALYTICS.value++ def test_execute_hogql_query_with_mcp_source_still_attributes_via_features(self):+ # Pulling MCP traffic apart by what it actually does is the whole point+ # of this fallback — confirm a $exception query from MCP attributes to+ # error_tracking, not the catch-all MCP product.+ marker = str(uuid.uuid4())+ reset_query_tags()+ tag_queries(kind="request", id="test", team_id=self.team.pk, source="mcp", feature="query")+ execute_hogql_query(+ f"SELECT count() FROM events WHERE distinct_id = '{marker}' AND event = '$exception'", # noqa: S608+ team=self.team,+ query_type="HogQLQuery",+ )++ comment = self._get_log_comment(marker)++ assert comment["product"] == Product.ERROR_TRACKING.value+class TestAddFallbackQueryTags(BaseTest):def test_does_not_override_set_product(self):@@ -474,3 +527,103 @@ class TestAddFallbackQueryTags(BaseTest):add_fallback_query_tags(tags)assert tags.product is Noneassert tags.feature is None++ @parameterized.expand(+ [+ ("ai_generation", ["$ai_generation"], Product.LLM_ANALYTICS),+ ("ai_span", ["$ai_span"], Product.LLM_ANALYTICS),+ ("ai_trace", ["$ai_trace"], Product.LLM_ANALYTICS),+ ("ai_embedding", ["$ai_embedding"], Product.LLM_ANALYTICS),+ ("ai_metric", ["$ai_metric"], Product.LLM_ANALYTICS),+ ("ai_feedback", ["$ai_feedback"], Product.LLM_ANALYTICS),+ ("exception", ["$exception"], Product.ERROR_TRACKING),+ ("web_vitals", ["$web_vitals"], Product.WEB_ANALYTICS),+ ("feature_flag_called", ["$feature_flag_called"], Product.FEATURE_FLAGS),+ ]+ )+ def test_hogql_features_event_fills_product(self, _name, events, expected_product):+ tags = QueryTags(+ query_type="HogQLQuery",+ hogql_features=HogQLFeatures(tables=["events"], events=events),+ )+ add_fallback_query_tags(tags)+ assert tags.product == expected_product++ @parameterized.expand(+ [+ ("session_replay", ["session_replay_events"], Product.REPLAY),+ ("logs_table", ["logs"], Product.LOGS),+ ("events_table", ["events"], Product.PRODUCT_ANALYTICS),+ ]+ )+ def test_hogql_features_table_fills_product_when_no_event_match(self, _name, tables, expected_product):+ tags = QueryTags(+ query_type="HogQLQuery",+ hogql_features=HogQLFeatures(tables=tables, events=[]),+ )+ add_fallback_query_tags(tags)+ assert tags.product == expected_product++ def test_hogql_features_event_takes_precedence_over_table(self):+ # Querying the events table for $exception should attribute to error+ # tracking, not product analytics — events are more specific.+ tags = QueryTags(+ query_type="HogQLQuery",+ hogql_features=HogQLFeatures(tables=["events"], events=["$exception"]),+ )+ add_fallback_query_tags(tags)+ assert tags.product == Product.ERROR_TRACKING++ def test_hogql_features_only_apply_to_hogqlquery_kind(self):+ # A TrendsQuery would already be product_analytics via kind fallback;+ # we shouldn't let the AST features override that. More importantly,+ # the AST contents of e.g. an LLM-analytics insight (which uses+ # TrendsQuery on $ai_generation) shouldn't get re-attributed.+ tags = QueryTags(+ query_type="TrendsQuery",+ hogql_features=HogQLFeatures(tables=["events"], events=["$exception"]),+ )+ add_fallback_query_tags(tags)+ assert tags.product == Product.PRODUCT_ANALYTICS++ def test_hogql_features_does_not_override_set_product(self):+ tags = QueryTags(+ product=Product.MCP,+ query_type="HogQLQuery",+ hogql_features=HogQLFeatures(tables=["events"], events=["$exception"]),+ )+ add_fallback_query_tags(tags)+ assert tags.product == Product.MCP++ def test_hogql_features_take_precedence_over_mcp_source(self):+ # The whole point of the hogql_features fallback is to pull MCP traffic+ # apart by what it actually does — so even when source=mcp, a recognised+ # event filter must win over the catch-all MCP attribution.+ tags = QueryTags(+ query_type="HogQLQuery",+ source="mcp",+ hogql_features=HogQLFeatures(tables=["events"], events=["$exception"]),+ )+ add_fallback_query_tags(tags)+ assert tags.product == Product.ERROR_TRACKING++ def test_hogql_features_table_only_take_precedence_over_mcp_source(self):+ # Same precedence holds for the table-only path.+ tags = QueryTags(+ query_type="HogQLQuery",+ source="mcp",+ hogql_features=HogQLFeatures(tables=["session_replay_events"], events=[]),+ )+ add_fallback_query_tags(tags)+ assert tags.product == Product.REPLAY++ def test_hogql_features_unmapped_features_fall_through_to_mcp(self):+ # No interesting events, no recognised tables — let the MCP source+ # fallback fire instead.+ tags = QueryTags(+ query_type="HogQLQuery",+ source="mcp",+ hogql_features=HogQLFeatures(tables=[], events=[]),+ )+ add_fallback_query_tags(tags)+ assert tags.product == Product.MCPdiff --git a/posthog/hogql/feature_extractor.py b/posthog/hogql/feature_extractor.pynew file mode 100644index 000000000000..79cec2ba9cfd--- /dev/null+++ b/posthog/hogql/feature_extractor.py@@ -0,0 +1,86 @@+"""Extract product-attribution features from a HogQL select query.++Feeds ``add_fallback_query_tags`` so HogQL queries can be attributed to a+product surface (LLM analytics, error tracking, web analytics, replay, …)+based on what tables and event filters they reference.+"""++from posthog.hogql import ast+from posthog.hogql.database.schema.events import EventsTable+from posthog.hogql.visitor import TraversingVisitor++from posthog.clickhouse.query_tagging import EVENT_TAG_MATCHERS, HogQLFeatures+++class HogQLFeatureExtractor(TraversingVisitor):+ """Records ``tables`` (FROM/JOIN sources) and ``events`` (event-name literals+ compared to the events ``event`` column). Works on raw or resolved ASTs;+ uses type info when available, falls back to chain matching otherwise."""++ def __init__(self) -> None:+ super().__init__()+ self.tables: set[str] = set()+ self.events: set[str] = set()++ def visit_join_expr(self, node: ast.JoinExpr) -> None:+ if isinstance(node.table, ast.Field) and node.table.chain:+ head = node.table.chain[0]+ if isinstance(head, str):+ self.tables.add(head)+ super().visit_join_expr(node)++ def visit_compare_operation(self, node: ast.CompareOperation) -> None:+ if node.op in (ast.CompareOperationOp.Eq, ast.CompareOperationOp.In):+ # Aliases can stack (resolver passes re-wrap), so unroll until we hit a non-Alias node.+ left, right = node.left, node.right+ while isinstance(left, ast.Alias):+ left = left.expr+ while isinstance(right, ast.Alias):+ right = right.expr+ for field_side, value_side in ((left, right), (right, left)):+ if _looks_like_event_field(field_side):+ self.events.update(v for v in _iter_string_constants(value_side) if v in EVENT_TAG_MATCHERS)+ super().visit_compare_operation(node)+++def _looks_like_event_field(expr: ast.Expr) -> bool:+ """``True`` iff ``expr`` references the events table's ``event`` column.+ Mirrors ``is_events_only_field`` from the session where-clause extractor."""+ if not isinstance(expr, ast.Field) or not expr.chain:+ return False++ type_ = expr.type+ if isinstance(type_, ast.PropertyType):+ type_ = type_.field_type+ if isinstance(type_, ast.FieldAliasType):+ type_ = type_.type+ if isinstance(type_, ast.FieldType):+ if type_.name != "event":+ return False+ table_type = type_.table_type+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):+ table_type = table_type.table_type+ return isinstance(table_type, ast.TableType) and isinstance(table_type.table, EventsTable)++ # No type info — fall back to last-identifier chain match (covers ``event``, ``e.event``, ``events.event``).+ return expr.chain[-1] == "event"+++def _iter_string_constants(expr: ast.Expr):+ """Yield string literals from a constant, tuple, or array — covers ``= 'X'`` and ``IN ('X', 'Y')``."""+ if isinstance(expr, ast.Constant):+ if isinstance(expr.value, str):+ yield expr.value+ return+ if isinstance(expr, (ast.Tuple, ast.Array)):+ for sub in expr.exprs:+ yield from _iter_string_constants(sub)+++def extract_hogql_features(query: ast.SelectQuery | ast.SelectSetQuery | None) -> HogQLFeatures:+ """Sorted for deterministic tag output."""+ if query is None:+ return HogQLFeatures()+ visitor = HogQLFeatureExtractor()+ visitor.visit(query)+ return HogQLFeatures(tables=sorted(visitor.tables), events=sorted(visitor.events))diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex 96002b97fea1..15e00c55ec25 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -37,6 +37,7 @@ from posthog.hogql.direct_connection import ()from posthog.hogql.errors import ExposedHogQLError, QueryError, ResolutionErrorfrom posthog.hogql.escape_sql import escape_postgres_identifier+from posthog.hogql.feature_extractor import extract_hogql_featuresfrom posthog.hogql.filters import replace_filtersfrom posthog.hogql.hogql import HogQLContextfrom posthog.hogql.modifiers import create_default_modifiers_for_team@@ -796,11 +797,14 @@ class HogQLQueryExecutor:assert clickhouse_context is not Nonetimings_dict = self.timings.to_dict()with self.timings.measure("clickhouse_execute"):+ with self.timings.measure("extract_hogql_features"):+ hogql_features = extract_hogql_features(self.select_query)tag_queries(team_id=self.team.pk,query_type=self.query_type,has_joins="JOIN" in self.clickhouse_sql,has_json_operations="JSONExtract" in self.clickhouse_sql or "JSONHas" in self.clickhouse_sql,+ hogql_features=hogql_features,timings=timings_dict,modifiers=({k: v for k, v in self.modifiers.model_dump().items() if v is not None} if self.modifiers else {}diff --git a/posthog/hogql/test/test_feature_extractor.py b/posthog/hogql/test/test_feature_extractor.pynew file mode 100644index 000000000000..fe9a690854da--- /dev/null+++ b/posthog/hogql/test/test_feature_extractor.py@@ -0,0 +1,148 @@+from typing import cast++from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.feature_extractor import HogQLFeatureExtractor, extract_hogql_features+from posthog.hogql.parser import parse_select+from posthog.hogql.resolver import resolve_types+++class TestHogQLFeatureExtractor(BaseTest):+ @parameterized.expand(+ [+ ("simple_events_select", "SELECT count() FROM events", ["events"], []),+ ("aliased_events_table", "SELECT * FROM events AS e LIMIT 10", ["events"], []),+ ("session_replay_table", "SELECT session_id FROM session_replay_events", ["session_replay_events"], []),+ (+ "join_persons_and_events",+ "SELECT * FROM events AS e JOIN persons AS p ON p.id = e.person_id",+ ["events", "persons"],+ [],+ ),+ ("subquery_inner_join", "SELECT * FROM (SELECT * FROM events) AS sub", ["events"], []),+ ]+ )+ def test_extracts_table_references(self, _name, sql, expected_tables, expected_events):+ features = extract_hogql_features(parse_select(sql))+ assert features.tables == expected_tables+ assert features.events == expected_events++ @parameterized.expand(+ [+ ("ai_generation_eq", "SELECT * FROM events WHERE event = '$ai_generation'", ["$ai_generation"]),+ ("exception_eq", "SELECT * FROM events WHERE event = '$exception'", ["$exception"]),+ ("web_vitals_eq", "SELECT * FROM events WHERE event = '$web_vitals'", ["$web_vitals"]),+ (+ "feature_flag_called_eq",+ "SELECT * FROM events WHERE event = '$feature_flag_called'",+ ["$feature_flag_called"],+ ),+ (+ "in_clause_multiple_ai",+ "SELECT * FROM events WHERE event IN ('$ai_generation', '$ai_span')",+ ["$ai_generation", "$ai_span"],+ ),+ (+ "constant_on_left",+ "SELECT * FROM events WHERE '$exception' = event",+ ["$exception"],+ ),+ (+ "aliased_event_field",+ "SELECT * FROM events AS e WHERE e.event = '$ai_generation'",+ ["$ai_generation"],+ ),+ (+ "uninteresting_event_dropped",+ "SELECT * FROM events WHERE event = 'pageview' OR event = '$ai_generation'",+ ["$ai_generation"],+ ),+ ("unknown_event_dropped", "SELECT * FROM events WHERE event = 'random_event'", []),+ ]+ )+ def test_extracts_event_filters(self, _name, sql, expected_events):+ features = extract_hogql_features(parse_select(sql))+ assert features.events == expected_events++ def test_handles_none_query(self):+ features = extract_hogql_features(None)+ assert features.tables == []+ assert features.events == []++ def test_combined_tables_and_events(self):+ features = extract_hogql_features(+ parse_select(+ "SELECT count() FROM events AS e JOIN persons AS p ON p.id = e.person_id "+ "WHERE e.event = '$ai_generation'"+ )+ )+ assert features.tables == ["events", "persons"]+ assert features.events == ["$ai_generation"]++ def test_visitor_dedups(self):+ visitor = HogQLFeatureExtractor()+ visitor.visit(+ parse_select(+ "SELECT * FROM events WHERE event = '$exception' "+ "UNION ALL SELECT * FROM events WHERE event = '$exception'"+ )+ )+ assert visitor.tables == {"events"}+ assert visitor.events == {"$exception"}++ def _resolve(self, sql: str) -> ast.SelectQuery | ast.SelectSetQuery:+ database = Database.create_for(team=self.team)+ context = HogQLContext(database=database, team_id=self.team.pk, enable_select_queries=True)+ node = parse_select(sql)+ return cast(ast.SelectQuery | ast.SelectSetQuery, resolve_types(node, context, dialect="clickhouse"))++ def test_resolved_ast_uses_type_system(self):+ # After resolution, `event = '$exception'` carries a FieldType pointing+ # at EventsTable; the extractor should pick it up via types just like+ # it does via chain matching.+ features = extract_hogql_features(self._resolve("SELECT * FROM events WHERE event = '$exception'"))+ assert features.events == ["$exception"]++ def test_nested_aliases_on_field_and_constant(self):+ # Aliases can stack — e.g. resolver passes that re-wrap. Verify both+ # the field and the constant unwrap fully so the comparison is still+ # recognised.+ field = ast.Alias(+ alias="outer",+ expr=ast.Alias(alias="inner", expr=ast.Field(chain=["event"])),+ )+ constant = ast.Alias(+ alias="outer",+ expr=ast.Alias(alias="inner", expr=ast.Constant(value="$exception")),+ )+ compare = ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=field, right=constant)++ visitor = HogQLFeatureExtractor()+ visitor.visit(compare)+ assert visitor.events == {"$exception"}++ def test_resolved_event_field_on_non_events_table_ignored(self):+ # Construct a Field whose chain ends in "event" but whose resolved+ # type lives on a non-EventsTable. The chain-only heuristic would+ # accept it; the type-aware path must reject it.+ from posthog.hogql.database.schema.query_log_archive import QueryLogArchiveTable++ non_events_table_type = ast.TableType(table=QueryLogArchiveTable())+ field = ast.Field(+ chain=["query_log", "event"],+ type=ast.FieldType(name="event", table_type=non_events_table_type),+ )+ compare = ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=field,+ right=ast.Constant(value="$exception"),+ )++ visitor = HogQLFeatureExtractor()+ visitor.visit(compare)+ assert visitor.events == set()