: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
perf(hogql): defer virtual-field default expansion to query time (#64018)
Robbie3ed641c50f47
diff --git a/posthog/hogql/database/schema/channel_type.py b/posthog/hogql/database/schema/channel_type.pyindex 926d271c5bab..0c15e6938ba1 100644--- a/posthog/hogql/database/schema/channel_type.py+++ b/posthog/hogql/database/schema/channel_type.py@@ -45,31 +45,21 @@ class ChannelTypeExprs:def create_initial_domain_type(name: str, timings: Optional[HogQLTimings] = None, properties_path: Optional[list[str]] = None) -> ExpressionField:- if timings is None:- timings = HogQLTimings()-if not properties_path:properties_path = ["properties"]-- with timings.measure("initial_domain_type_expr"):- expr = _initial_domain_type_expr()-+ # One call expanded in the resolver (see expand_domain_type_call), like the channel type.return ExpressionField(name=name,- expr=replace_placeholders(- expr,- {- "referring_domain": ast.Call(- name="toString", args=[ast.Field(chain=[*properties_path, "$initial_referring_domain"])]- )- },+ expr=ast.Call(+ name=DOMAIN_TYPE_FUNCTION,+ args=[ast.Call(name="toString", args=[ast.Field(chain=[*properties_path, "$initial_referring_domain"])])],),isolate_scope=True,)@cache-def _initial_domain_type_expr() -> ast.Expr:+def _domain_type_expr() -> ast.Expr:return parse_expr("""if(@@ -81,6 +71,15 @@ if()+# Referring-domain classification; expanded to SQL in the resolver (never a real CH function).+DOMAIN_TYPE_FUNCTION = "_domainType"+++def expand_domain_type_call(args: list[ast.Expr]) -> ast.Expr:+ # Resolver-side expansion of _domainType(referring_domain).+ return replace_placeholders(_domain_type_expr(), {"referring_domain": args[0]})++def create_initial_channel_type(name: str,custom_rules: Optional[list["CustomChannelRule"]] = None,@@ -231,6 +230,27 @@ def custom_rule_to_expr(custom_rule: "CustomChannelRule", source_exprs: ChannelTreturn ast.Call(name=custom_rule.combiner.lower(), args=conditions)+# Default channel-type classification; the resolver expands it to SQL (never a real ClickHouse function).+DEFAULT_CHANNEL_TYPE_FUNCTION = "_defaultChannelType"+++def expand_default_channel_type_call(args: list[ast.Expr]) -> ast.Expr:+ # args are the source exprs in the order create_channel_type_expr emits them.+ campaign, medium, source, referring_domain, has_gclid, has_fbclid, gad_source = args+ return replace_placeholders(+ _initial_default_channel_rules_expr(),+ placeholders={+ "campaign": wrap_with_lower(wrap_with_null_if_empty(campaign)),+ "medium": wrap_with_lower(wrap_with_null_if_empty(medium)),+ "source": wrap_with_lower(wrap_with_null_if_empty(source)),+ "referring_domain": referring_domain,+ "has_gclid": has_gclid,+ "has_fbclid": has_fbclid,+ "gad_source": wrap_with_null_if_empty(gad_source),+ },+ )++def create_channel_type_expr(custom_rules: Optional[list["CustomChannelRule"]],source_exprs: ChannelTypeExprs,@@ -249,26 +269,21 @@ def create_channel_type_expr(if_args.append(ast.Constant(value=None))custom_rule_expr = ast.Call(name="multiIf", args=if_args)- with timings.measure("default_channel_rules_parse"):- builtin_rules_expr = _initial_default_channel_rules_expr()- with timings.measure("default_channel_rules_replace"):- builtin_rules = replace_placeholders(- builtin_rules_expr,- placeholders={- "campaign": wrap_with_lower(wrap_with_null_if_empty(source_exprs.campaign)),- "medium": wrap_with_lower(wrap_with_null_if_empty(source_exprs.medium)),- "source": wrap_with_lower(wrap_with_null_if_empty(source_exprs.source)),- "referring_domain": source_exprs.referring_domain,- "has_gclid": source_exprs.has_gclid,- "has_fbclid": source_exprs.has_fbclid,- "gad_source": wrap_with_null_if_empty(source_exprs.gad_source),- },- )+ # One call rather than inlining the multiIf, so only queries that select the field pay the expansion.+ builtin_rules: ast.Expr = ast.Call(+ name=DEFAULT_CHANNEL_TYPE_FUNCTION,+ args=[+ source_exprs.campaign,+ source_exprs.medium,+ source_exprs.source,+ source_exprs.referring_domain,+ source_exprs.has_gclid,+ source_exprs.has_fbclid,+ source_exprs.gad_source,+ ],+ )if custom_rule_expr:- return ast.Call(- name="coalesce",- args=[custom_rule_expr, builtin_rules],- )+ return ast.Call(name="coalesce", args=[custom_rule_expr, builtin_rules])else:return builtin_rulesdiff --git a/posthog/hogql/database/schema/test/test_channel_type.py b/posthog/hogql/database/schema/test/test_channel_type.pyindex d68797ce7f7b..2986d9a25bf3 100644--- a/posthog/hogql/database/schema/test/test_channel_type.py+++ b/posthog/hogql/database/schema/test/test_channel_type.py@@ -147,6 +147,17 @@ class TestChannelType(ClickhouseTestMixin, APIBaseTest):)return (session_response.results or [])[0][0]+ def test_nested_expanded_function_is_rejected(self):+ # Nesting a printer-expanded marker (only reachable from user-written HogQL) would expand+ # exponentially; the printer must reject it rather than blow up.+ inner = "_defaultChannelType('a', 'b', 'c', 'd', 'e', 'f', 'g')"+ with self.assertRaises(Exception) as ctx:+ execute_hogql_query(+ parse_select(f"select _defaultChannelType({inner}, 'b', 'c', 'd', 'e', 'f', 'g') from events"),+ self.team,+ )+ assert "cannot be nested" in str(ctx.exception)+def test_direct(self):self.assertEqual("Direct",diff --git a/posthog/hogql/database/schema/test/test_traffic_type.py b/posthog/hogql/database/schema/test/test_traffic_type.pyindex c3bce17e5f06..7ab5587d5f52 100644--- a/posthog/hogql/database/schema/test/test_traffic_type.py+++ b/posthog/hogql/database/schema/test/test_traffic_type.py@@ -4,6 +4,7 @@ from posthog.hogql import astfrom posthog.hogql.database.models import ExpressionFieldfrom posthog.hogql.database.schema.traffic_type import (create_bot_name_field,+ create_bot_operator_field,create_is_bot_field,create_traffic_category_field,create_traffic_type_field,@@ -71,142 +72,29 @@ class TestExpressionFieldFactories:assert default_field.expr != custom_field.expr-class TestIsBotField:- def test_returns_bool_cast(self):- field = create_is_bot_field(name="$virt_is_bot")- assert isinstance(field.expr, ast.Call)- assert field.expr.name == "toBool"- comparison = field.expr.args[0]- assert isinstance(comparison, ast.CompareOperation)- assert comparison.op == ast.CompareOperationOp.NotEq-- def test_uses_multiMatchAnyIndex(self):- field = create_is_bot_field(name="$virt_is_bot")- assert isinstance(field.expr, ast.Call)- comparison = field.expr.args[0]- assert isinstance(comparison, ast.CompareOperation)- assert isinstance(comparison.left, ast.Call)- assert comparison.left.name == "multiMatchAnyIndex"-- def test_compares_against_zero(self):- field = create_is_bot_field(name="$virt_is_bot")- assert isinstance(field.expr, ast.Call)- comparison = field.expr.args[0]- assert isinstance(comparison, ast.CompareOperation)- assert isinstance(comparison.right, ast.Constant)- assert comparison.right.value == 0-- def test_wraps_user_agent_in_ifnull(self):- field = create_is_bot_field(name="$virt_is_bot")- assert isinstance(field.expr, ast.Call)- comparison = field.expr.args[0]- assert isinstance(comparison, ast.CompareOperation)- index_call = comparison.left- assert isinstance(index_call, ast.Call)- safe_ua = index_call.args[0]- assert isinstance(safe_ua, ast.Call)- assert safe_ua.name == "ifNull"- coalesce_call = safe_ua.args[0]- assert isinstance(coalesce_call, ast.Call)- assert coalesce_call.name == "coalesce"- # First coalesce arg should be nullIf for empty string handling- null_if = coalesce_call.args[0]- assert isinstance(null_if, ast.Call)- assert null_if.name == "nullIf"---class TestTrafficTypeField:- def test_returns_if_expression(self):- field = create_traffic_type_field(name="$virt_traffic_type")- assert isinstance(field.expr, ast.Call)- assert field.expr.name == "if"-- def test_default_value_is_regular(self):- field = create_traffic_type_field(name="$virt_traffic_type")- assert isinstance(field.expr, ast.Call)- default = field.expr.args[1]- assert isinstance(default, ast.Constant)- assert default.value == "Regular"-- def test_labels_contain_expected_values(self):- expr = create_traffic_type_field(name="$virt_traffic_type").expr- assert isinstance(expr, ast.Call)- array_access = expr.args[2]- assert isinstance(array_access, ast.ArrayAccess)- labels_array = array_access.array- assert isinstance(labels_array, ast.Array)- labels = [e.value for e in labels_array.exprs if isinstance(e, ast.Constant)]- assert "AI Agent" in labels- assert "Bot" in labels- assert "Automation" in labels-- def test_uses_multiMatchAnyIndex(self):- field = create_traffic_type_field(name="$virt_traffic_type")- assert isinstance(field.expr, ast.Call)- comparison = field.expr.args[0]- assert isinstance(comparison, ast.CompareOperation)- assert isinstance(comparison.left, ast.Call)- assert comparison.left.name == "multiMatchAnyIndex"---class TestTrafficCategoryField:- def test_returns_if_expression(self):- field = create_traffic_category_field(name="$virt_traffic_category")- assert isinstance(field.expr, ast.Call)- assert field.expr.name == "if"-- def test_default_value_is_regular(self):- field = create_traffic_category_field(name="$virt_traffic_category")- assert isinstance(field.expr, ast.Call)- default = field.expr.args[1]- assert isinstance(default, ast.Constant)- assert default.value == "regular"-- def test_labels_contain_expected_categories(self):- expr = create_traffic_category_field(name="$virt_traffic_category").expr- assert isinstance(expr, ast.Call)- array_access = expr.args[2]- assert isinstance(array_access, ast.ArrayAccess)- labels_array = array_access.array- assert isinstance(labels_array, ast.Array)- labels = [e.value for e in labels_array.exprs if isinstance(e, ast.Constant)]- assert "ai_crawler" in labels- assert "ai_search" in labels- assert "ai_assistant" in labels- assert "search_crawler" in labels- assert "seo_crawler" in labels- assert "social_crawler" in labels- assert "monitoring" in labels- assert "http_client" in labels- assert "headless_browser" in labels- assert "no_user_agent" in labels+# Each field creator emits a single bot/traffic-type marker call, expanded to the classification SQL in+# the resolver. These assert the field emits the right marker over its user-agent expression; the+# expansion structure (multiMatchAnyIndex, labels, defaults) is covered in test_traffic_type_functions.py.+FIELD_MARKERS = [+ (create_is_bot_field, "$virt_is_bot", "isLikelyBot"),+ (create_traffic_type_field, "$virt_traffic_type", "getTrafficType"),+ (create_traffic_category_field, "$virt_traffic_category", "getTrafficCategory"),+ (create_bot_name_field, "$virt_bot_name", "getBotName"),+ (create_bot_operator_field, "$virt_bot_operator", "getBotOperator"),+]-class TestBotNameField:- def test_returns_if_expression(self):- field = create_bot_name_field(name="$virt_bot_name")+class TestFieldMarkers:+ @pytest.mark.parametrize("factory_fn,field_name,marker", FIELD_MARKERS)+ def test_emits_marker_over_user_agent(self, factory_fn, field_name, marker):+ field = factory_fn(name=field_name)assert isinstance(field.expr, ast.Call)- assert field.expr.name == "if"+ assert field.expr.name == marker+ assert field.expr.args == [user_agent_expr()]- def test_default_value_is_empty_string(self):- field = create_bot_name_field(name="$virt_bot_name")+ @pytest.mark.parametrize("factory_fn,field_name,marker", FIELD_MARKERS)+ def test_marker_respects_custom_properties_path(self, factory_fn, field_name, marker):+ field = factory_fn(name=field_name, properties_path=["poe", "properties"])assert isinstance(field.expr, ast.Call)- default = field.expr.args[1]- assert isinstance(default, ast.Constant)- assert default.value == ""-- def test_labels_contain_expected_bot_names(self):- expr = create_bot_name_field(name="$virt_bot_name").expr- assert isinstance(expr, ast.Call)- array_access = expr.args[2]- assert isinstance(array_access, ast.ArrayAccess)- labels_array = array_access.array- assert isinstance(labels_array, ast.Array)- labels = [e.value for e in labels_array.exprs if isinstance(e, ast.Constant)]- assert "Googlebot" in labels- assert "ChatGPT" in labels- assert "Claude" in labels- assert "GPTBot" in labels- assert "OpenAI Search" in labels- assert "curl" in labels- assert "" in labels+ assert field.expr.name == marker+ assert field.expr.args == [user_agent_expr(["poe", "properties"])]diff --git a/posthog/hogql/database/schema/traffic_type.py b/posthog/hogql/database/schema/traffic_type.pyindex 692eed4bdb25..6d13f0019a76 100644--- a/posthog/hogql/database/schema/traffic_type.py+++ b/posthog/hogql/database/schema/traffic_type.py@@ -2,13 +2,6 @@ from typing import Optionalfrom posthog.hogql import astfrom posthog.hogql.database.models import ExpressionField-from posthog.hogql.functions.traffic_type import (- get_bot_name,- get_bot_operator,- get_traffic_category,- get_traffic_type,- is_bot,-)def user_agent_expr(properties_path: Optional[list[str]] = None) -> ast.Expr:@@ -29,22 +22,18 @@ def user_agent_expr(properties_path: Optional[list[str]] = None) -> ast.Expr:)-def _dummy_call(name: str = "__placeholder") -> ast.Call:- return ast.Call(name=name, args=[])--+# These one-node calls are expanded to the classification SQL in the resolver (see Resolver.visit_call),+# so the big expression only materializes for queries that select the field.def create_is_bot_field(name: str, properties_path: Optional[list[str]] = None) -> ExpressionField:return ExpressionField(- name=name,- expr=is_bot(node=_dummy_call(name), args=[user_agent_expr(properties_path)]),- isolate_scope=True,+ name=name, expr=ast.Call(name="isLikelyBot", args=[user_agent_expr(properties_path)]), isolate_scope=True)def create_traffic_type_field(name: str, properties_path: Optional[list[str]] = None) -> ExpressionField:return ExpressionField(name=name,- expr=get_traffic_type(node=_dummy_call(name), args=[user_agent_expr(properties_path)]),+ expr=ast.Call(name="getTrafficType", args=[user_agent_expr(properties_path)]),isolate_scope=True,)@@ -52,7 +41,7 @@ def create_traffic_type_field(name: str, properties_path: Optional[list[str]] =def create_traffic_category_field(name: str, properties_path: Optional[list[str]] = None) -> ExpressionField:return ExpressionField(name=name,- expr=get_traffic_category(node=_dummy_call(name), args=[user_agent_expr(properties_path)]),+ expr=ast.Call(name="getTrafficCategory", args=[user_agent_expr(properties_path)]),isolate_scope=True,)@@ -60,7 +49,7 @@ def create_traffic_category_field(name: str, properties_path: Optional[list[str]def create_bot_name_field(name: str, properties_path: Optional[list[str]] = None) -> ExpressionField:return ExpressionField(name=name,- expr=get_bot_name(node=_dummy_call(name), args=[user_agent_expr(properties_path)]),+ expr=ast.Call(name="getBotName", args=[user_agent_expr(properties_path)]),isolate_scope=True,)@@ -68,6 +57,6 @@ def create_bot_name_field(name: str, properties_path: Optional[list[str]] = Nonedef create_bot_operator_field(name: str, properties_path: Optional[list[str]] = None) -> ExpressionField:return ExpressionField(name=name,- expr=get_bot_operator(node=_dummy_call(name), args=[user_agent_expr(properties_path)]),+ expr=ast.Call(name="getBotOperator", args=[user_agent_expr(properties_path)]),isolate_scope=True,)diff --git a/posthog/hogql/functions/posthog.py b/posthog/hogql/functions/posthog.pyindex 7397f12decb3..04886b6da0fe 100644--- a/posthog/hogql/functions/posthog.py+++ b/posthog/hogql/functions/posthog.py@@ -36,6 +36,10 @@ HOGQL_POSTHOG_FUNCTIONS: dict[str, HogQLFunctionMeta] = {"lookupPaidMediumType": HogQLFunctionMeta("lookupPaidMediumType", 1, 1),"lookupOrganicSourceType": HogQLFunctionMeta("lookupOrganicSourceType", 1, 1),"lookupOrganicMediumType": HogQLFunctionMeta("lookupOrganicMediumType", 1, 1),+ # Expanded to SQL in the resolver's visit_call; these never map to a real CH function. (The+ # bot/traffic-type functions are registered further down; the resolver expands them too.)+ "_defaultChannelType": HogQLFunctionMeta("_defaultChannelType", 7, 7),+ "_domainType": HogQLFunctionMeta("_domainType", 1, 1),# posthog/models/exchange_rate/sql.py# convertCurrency(from_currency, to_currency, amount, timestamp?)"convertCurrency": HogQLFunctionMeta(diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex aca0e4f9885c..25ca3ac0125d 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -1594,6 +1594,16 @@ class Resolver(CloningVisitor):return self._expand_duplicating_macro(node, lambda: get_bot_name(node=node, args=node.args))if node.name in ("getBotOperator", "__preview_getBotOperator"):return self._expand_duplicating_macro(node, lambda: get_bot_operator(node=node, args=node.args))+ if node.name in ("_defaultChannelType", "_domainType"):+ from posthog.hogql.database.schema.channel_type import ( # noqa: PLC0415 — avoid resolver->schema import cycle+ expand_default_channel_type_call,+ expand_domain_type_call,+ )++ builder = (+ expand_default_channel_type_call if node.name == "_defaultChannelType" else expand_domain_type_call+ )+ return self._expand_duplicating_macro(node, lambda: builder(node.args))if self._is_higher_order_array_call(node):node = self._visit_higher_order_array_call(node)