: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(web-analytics): detect bots by google-published ip ranges in hogql (#68232)
Lucas Ricoycc997fd4768c
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex dcb246721b07..0451091db1d5 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -3377,7 +3377,7 @@"virtual": true},"$virt_is_bot": {- "description": "Whether the event was generated by a bot, crawler, or automation tool.",+ "description": "Whether the event was generated by a bot, crawler, or automation tool, detected from the user agent or from operator-published bot IP ranges.","label": "Is bot","type": "Boolean","virtual": truediff --git a/posthog/hogql/database/schema/test/test_traffic_type.py b/posthog/hogql/database/schema/test/test_traffic_type.pyindex 7ab5587d5f52..b052ebe47dcc 100644--- a/posthog/hogql/database/schema/test/test_traffic_type.py+++ b/posthog/hogql/database/schema/test/test_traffic_type.py@@ -3,6 +3,7 @@ import pytestfrom posthog.hogql import astfrom posthog.hogql.database.models import ExpressionFieldfrom posthog.hogql.database.schema.traffic_type import (+ client_ip_expr,create_bot_name_field,create_bot_operator_field,create_is_bot_field,@@ -45,6 +46,14 @@ class TestUserAgentExpr:assert expr.args[1] == ast.Field(chain=["poe", "properties", "$user_agent"])+class TestClientIPExpr:+ def test_default_properties_path(self):+ assert client_ip_expr() == ast.Field(chain=["properties", "$ip"])++ def test_custom_properties_path(self):+ assert client_ip_expr(["poe", "properties"]) == ast.Field(chain=["poe", "properties", "$ip"])++class TestExpressionFieldFactories:@pytest.mark.parametrize("factory_fn,field_name",@@ -86,15 +95,15 @@ FIELD_MARKERS = [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):+ def test_emits_marker_over_user_agent_and_ip(self, factory_fn, field_name, marker):field = factory_fn(name=field_name)assert isinstance(field.expr, ast.Call)assert field.expr.name == marker- assert field.expr.args == [user_agent_expr()]+ assert field.expr.args == [user_agent_expr(), client_ip_expr()]@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)assert field.expr.name == marker- assert field.expr.args == [user_agent_expr(["poe", "properties"])]+ assert field.expr.args == [user_agent_expr(["poe", "properties"]), client_ip_expr(["poe", "properties"])]diff --git a/posthog/hogql/database/schema/traffic_type.py b/posthog/hogql/database/schema/traffic_type.pyindex 6d13f0019a76..0722073bd44b 100644--- a/posthog/hogql/database/schema/traffic_type.py+++ b/posthog/hogql/database/schema/traffic_type.py@@ -22,18 +22,28 @@ def user_agent_expr(properties_path: Optional[list[str]] = None) -> ast.Expr:)+def client_ip_expr(properties_path: Optional[list[str]] = None) -> ast.Expr:+ if not properties_path:+ properties_path = ["properties"]+ return ast.Field(chain=[*properties_path, "$ip"])+++def _classification_args(properties_path: Optional[list[str]] = None) -> list[ast.Expr]:+ return [user_agent_expr(properties_path), client_ip_expr(properties_path)]++# 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=ast.Call(name="isLikelyBot", args=[user_agent_expr(properties_path)]), isolate_scope=True+ name=name, expr=ast.Call(name="isLikelyBot", args=_classification_args(properties_path)), isolate_scope=True)def create_traffic_type_field(name: str, properties_path: Optional[list[str]] = None) -> ExpressionField:return ExpressionField(name=name,- expr=ast.Call(name="getTrafficType", args=[user_agent_expr(properties_path)]),+ expr=ast.Call(name="getTrafficType", args=_classification_args(properties_path)),isolate_scope=True,)@@ -41,7 +51,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=ast.Call(name="getTrafficCategory", args=[user_agent_expr(properties_path)]),+ expr=ast.Call(name="getTrafficCategory", args=_classification_args(properties_path)),isolate_scope=True,)@@ -49,7 +59,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=ast.Call(name="getBotName", args=[user_agent_expr(properties_path)]),+ expr=ast.Call(name="getBotName", args=_classification_args(properties_path)),isolate_scope=True,)@@ -57,6 +67,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=ast.Call(name="getBotOperator", args=[user_agent_expr(properties_path)]),+ expr=ast.Call(name="getBotOperator", args=_classification_args(properties_path)),isolate_scope=True,)diff --git a/posthog/hogql/functions/mapping.py b/posthog/hogql/functions/mapping.pyindex 55c15a7157a1..eaa275be728a 100644--- a/posthog/hogql/functions/mapping.py+++ b/posthog/hogql/functions/mapping.py@@ -142,6 +142,30 @@ HOGQL_CLICKHOUSE_FUNCTIONS: dict[str, HogQLFunctionMeta] = {"cutFragment": HogQLFunctionMeta("cutFragment", 1, 1),"cutQueryStringAndFragment": HogQLFunctionMeta("cutQueryStringAndFragment", 1, 1),"cutURLParameter": HogQLFunctionMeta("cutURLParameter", 2, 2),+ # ip addresses+ "IPv4NumToString": HogQLFunctionMeta("IPv4NumToString", 1, 1),+ "IPv4StringToNum": HogQLFunctionMeta("IPv4StringToNum", 1, 1),+ "IPv4StringToNumOrDefault": HogQLFunctionMeta("IPv4StringToNumOrDefault", 1, 1),+ "IPv4StringToNumOrNull": HogQLFunctionMeta("IPv4StringToNumOrNull", 1, 1),+ "IPv6NumToString": HogQLFunctionMeta("IPv6NumToString", 1, 1),+ "IPv6StringToNum": HogQLFunctionMeta("IPv6StringToNum", 1, 1),+ "IPv6StringToNumOrDefault": HogQLFunctionMeta("IPv6StringToNumOrDefault", 1, 1),+ "IPv6StringToNumOrNull": HogQLFunctionMeta("IPv6StringToNumOrNull", 1, 1),+ "IPv4ToIPv6": HogQLFunctionMeta("IPv4ToIPv6", 1, 1),+ "toIPv4": HogQLFunctionMeta("toIPv4", 1, 1),+ "toIPv4OrDefault": HogQLFunctionMeta("toIPv4OrDefault", 1, 2),+ "toIPv4OrNull": HogQLFunctionMeta("toIPv4OrNull", 1, 1),+ "toIPv4OrZero": HogQLFunctionMeta("toIPv4OrZero", 1, 1),+ "toIPv6": HogQLFunctionMeta("toIPv6", 1, 1),+ "toIPv6OrDefault": HogQLFunctionMeta("toIPv6OrDefault", 1, 2),+ "toIPv6OrNull": HogQLFunctionMeta("toIPv6OrNull", 1, 1),+ "toIPv6OrZero": HogQLFunctionMeta("toIPv6OrZero", 1, 1),+ "isIPv4String": HogQLFunctionMeta("isIPv4String", 1, 1),+ "isIPv6String": HogQLFunctionMeta("isIPv6String", 1, 1),+ "isIPAddressInRange": HogQLFunctionMeta("isIPAddressInRange", 2, 2),+ "IPv4CIDRToRange": HogQLFunctionMeta("IPv4CIDRToRange", 2, 2),+ "IPv6CIDRToRange": HogQLFunctionMeta("IPv6CIDRToRange", 2, 2),+ "cutIPv6": HogQLFunctionMeta("cutIPv6", 3, 3),# tuples"tuple": HogQLFunctionMeta("tuple", 0, None),"tupleElement": HogQLFunctionMeta("tupleElement", 2, 3),diff --git a/posthog/hogql/functions/posthog.py b/posthog/hogql/functions/posthog.pyindex 04886b6da0fe..3bb80fd513a1 100644--- a/posthog/hogql/functions/posthog.py+++ b/posthog/hogql/functions/posthog.py@@ -93,13 +93,44 @@ HOGQL_POSTHOG_FUNCTIONS: dict[str, HogQLFunctionMeta] = {((StringType(), DateTimeType(), DateTimeType()), StringType()),],),- # Bot / traffic-type classification functions.- "getTrafficType": HogQLFunctionMeta("getTrafficType", 1, 1, signatures=[((StringType(),), StringType())]),- "getTrafficCategory": HogQLFunctionMeta("getTrafficCategory", 1, 1, signatures=[((StringType(),), StringType())]),- "isLikelyBot": HogQLFunctionMeta("isLikelyBot", 1, 1, signatures=[((StringType(),), BooleanType())]),- "getBotType": HogQLFunctionMeta("getBotType", 1, 1, signatures=[((StringType(),), StringType())]),- "getBotName": HogQLFunctionMeta("getBotName", 1, 1, signatures=[((StringType(),), StringType())]),- "getBotOperator": HogQLFunctionMeta("getBotOperator", 1, 1, signatures=[((StringType(),), StringType())]),+ # Bot / traffic-type classification functions. The optional second argument is the+ # client IP, matched against operator-published bot IP ranges.+ "getTrafficType": HogQLFunctionMeta(+ "getTrafficType",+ 1,+ 2,+ signatures=[((StringType(),), StringType()), ((StringType(), StringType()), StringType())],+ ),+ "getTrafficCategory": HogQLFunctionMeta(+ "getTrafficCategory",+ 1,+ 2,+ signatures=[((StringType(),), StringType()), ((StringType(), StringType()), StringType())],+ ),+ "isLikelyBot": HogQLFunctionMeta(+ "isLikelyBot",+ 1,+ 2,+ signatures=[((StringType(),), BooleanType()), ((StringType(), StringType()), BooleanType())],+ ),+ "getBotType": HogQLFunctionMeta(+ "getBotType",+ 1,+ 2,+ signatures=[((StringType(),), StringType()), ((StringType(), StringType()), StringType())],+ ),+ "getBotName": HogQLFunctionMeta(+ "getBotName",+ 1,+ 2,+ signatures=[((StringType(),), StringType()), ((StringType(), StringType()), StringType())],+ ),+ "getBotOperator": HogQLFunctionMeta(+ "getBotOperator",+ 1,+ 2,+ signatures=[((StringType(),), StringType()), ((StringType(), StringType()), StringType())],+ ),# Deprecated __preview_* aliases — kept so ad-hoc queries written against the preview names keep working."__preview_getTrafficType": HogQLFunctionMeta("__preview_getTrafficType", 1, 1, signatures=[((StringType(),), StringType())]diff --git a/posthog/hogql/functions/test/test_ip_functions.py b/posthog/hogql/functions/test/test_ip_functions.pynew file mode 100644index 000000000000..982aa6031314--- /dev/null+++ b/posthog/hogql/functions/test/test_ip_functions.py@@ -0,0 +1,39 @@+from posthog.test.base import BaseTest++from posthog.hogql.query import execute_hogql_query++# One expression per newly allowlisted IP function, so a typo'd mapping entry+# (wrong name, wrong arity) fails here instead of at user query time.+IP_FUNCTION_CASES: list[tuple[str, object]] = [+ ("IPv4NumToString(IPv4StringToNum('66.249.84.5'))", "66.249.84.5"),+ ("IPv4StringToNumOrDefault('nope')", 0),+ ("isNull(IPv4StringToNumOrNull('nope'))", 1),+ ("IPv6NumToString(IPv6StringToNum('2001:db8::1'))", "2001:db8::1"),+ ("IPv6NumToString(IPv6StringToNumOrDefault('nope'))", "::"),+ ("isNull(IPv6StringToNumOrNull('nope'))", 1),+ ("IPv6NumToString(IPv4ToIPv6(IPv4StringToNum('1.2.3.4')))", "::ffff:1.2.3.4"),+ ("toString(toIPv4('1.2.3.4'))", "1.2.3.4"),+ ("toString(toIPv4OrDefault('nope'))", "0.0.0.0"),+ ("isNull(toIPv4OrNull('nope'))", 1),+ ("toString(toIPv4OrZero('nope'))", "0.0.0.0"),+ ("toString(toIPv6('::1'))", "::1"),+ ("toString(toIPv6OrDefault('nope'))", "::"),+ ("isNull(toIPv6OrNull('nope'))", 1),+ ("toString(toIPv6OrZero('nope'))", "::"),+ ("isIPv4String('1.2.3.4')", 1),+ ("isIPv6String('::1')", 1),+ ("isIPAddressInRange('66.249.84.5', '66.249.80.0/20')", 1),+ ("toString(tupleElement(IPv4CIDRToRange(toIPv4('192.168.5.2'), 16), 1))", "192.168.0.0"),+ ("toString(tupleElement(IPv6CIDRToRange(toIPv6('2001:db8::8a2e:370:7334'), 32), 1))", "2001:db8::"),+ ("toString(cutIPv6(toIPv6('2001:db8::8a2e:370:7334'), 2, 0))", "2001:db8::8a2e:370:0"),+]+++class TestIPFunctions(BaseTest):+ def test_ip_functions_execute(self):+ select = ", ".join(expression for expression, _ in IP_FUNCTION_CASES)+ response = execute_hogql_query(f"SELECT {select}", self.team)++ assert len(response.results) == 1+ for (expression, expected), actual in zip(IP_FUNCTION_CASES, response.results[0]):+ assert actual == expected, f"{expression}: expected {expected!r}, got {actual!r}"diff --git a/posthog/hogql/functions/test/test_traffic_type_functions.py b/posthog/hogql/functions/test/test_traffic_type_functions.pyindex fed5978d55c4..2b4174780f7b 100644--- a/posthog/hogql/functions/test/test_traffic_type_functions.py+++ b/posthog/hogql/functions/test/test_traffic_type_functions.py@@ -1,3 +1,5 @@+import ipaddress+import pytestfrom posthog.test.base import BaseTest@@ -8,6 +10,7 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.errors import QueryErrorfrom posthog.hogql.functions.traffic_type import (get_bot_name,+ get_bot_operator,get_bot_type,get_traffic_category,get_traffic_type,@@ -18,6 +21,7 @@ from posthog.hogql.printer import prepare_and_print_astfrom products.actions.backend.models.action import Actionfrom products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS+from products.web_analytics.backend.hogql_queries.bot_ip_definitions import BOT_IP_DEFINITIONSclass TestTrafficTypeFunctions:@@ -349,6 +353,123 @@ class TestNullHandling:assert empty_string_arg.value == ""+class TestBotIPClassification:+ def test_is_bot_with_ip_arg_ors_ip_match_after_ua_match(self):+ node = ast.Call(name="isLikelyBot", args=[])+ user_agent_arg = ast.Field(chain=["properties", "$user_agent"])+ ip_arg = ast.Field(chain=["properties", "$ip"])++ result = is_bot(node=node, args=[user_agent_arg, ip_arg])++ assert isinstance(result, ast.Call)+ assert result.name == "toBool"+ or_expr = result.args[0]+ assert isinstance(or_expr, ast.Or)+ assert len(or_expr.exprs) == 2+ # UA branch comes first so or() short-circuits the IP check for UA-matched rows+ ua_match = or_expr.exprs[0]+ assert isinstance(ua_match, ast.CompareOperation)+ assert isinstance(ua_match.left, ast.Call)+ assert ua_match.left.name == "multiMatchAnyIndex"+ # IP branch: one prefix-length group per collapsed prefix width, each an IN set lookup+ ip_match = or_expr.exprs[1]+ assert isinstance(ip_match, ast.Or)+ for group in ip_match.exprs:+ assert isinstance(group, ast.CompareOperation)+ assert group.op == ast.CompareOperationOp.In+ assert isinstance(group.left, ast.Call)+ assert group.left.name == "tupleElement"++ def test_is_bot_without_ip_arg_has_no_ip_branch(self):+ node = ast.Call(name="isLikelyBot", args=[])+ result = is_bot(node=node, args=[ast.Field(chain=["properties", "$user_agent"])])++ assert isinstance(result, ast.Call)+ assert isinstance(result.args[0], ast.CompareOperation)++ @parameterized.expand(+ [+ (get_traffic_type, "Regular"),+ (get_traffic_category, "regular"),+ (get_bot_type, ""),+ (get_bot_name, ""),+ (get_bot_operator, ""),+ ]+ )+ def test_lookup_builders_fall_back_to_ip_lookup_when_ua_unmatched(self, function_builder, expected_default):+ node = ast.Call(name="test", args=[])+ user_agent_arg = ast.Field(chain=["properties", "$user_agent"])+ ip_arg = ast.Field(chain=["properties", "$ip"])++ result = function_builder(node=node, args=[user_agent_arg, ip_arg])++ assert isinstance(result, ast.Call)+ assert result.name == "if"+ # The unmatched-UA branch is now the IP lookup, itself defaulting to the constant+ fallback = result.args[1]+ assert isinstance(fallback, ast.Call)+ assert fallback.name == "if"+ ip_default = fallback.args[1]+ assert isinstance(ip_default, ast.Constant)+ assert ip_default.value == expected_default+ # IP definition index is a multiIf over the per-definition range matches+ ip_index_comparison = fallback.args[0]+ assert isinstance(ip_index_comparison, ast.CompareOperation)+ assert isinstance(ip_index_comparison.left, ast.Call)+ assert ip_index_comparison.left.name == "multiIf"+ assert len(ip_index_comparison.left.args) == 2 * len(BOT_IP_DEFINITIONS) + 1+++class TestBotIPDefinitionsDataStructure:+ def test_all_definitions_have_required_fields_and_valid_vocabulary(self):+ valid_types = {"AI Agent", "Bot", "Automation"}+ valid_categories = {+ "ai_crawler",+ "ai_search",+ "ai_assistant",+ "search_crawler",+ "seo_crawler",+ "social_crawler",+ "monitoring",+ "http_client",+ "headless_browser",+ }+ for key, ip_def in BOT_IP_DEFINITIONS.items():+ assert ip_def.name, f"IP definition {key} missing name"+ assert ip_def.operator, f"IP definition {key} missing operator"+ assert ip_def.traffic_type in valid_types, f"Invalid traffic_type for {key}: {ip_def.traffic_type}"+ assert ip_def.category in valid_categories, f"Invalid category for {key}: {ip_def.category}"+ assert ip_def.networks, f"IP definition {key} has no networks"++ def test_networks_parse_and_respect_prefix_floors(self):+ # A range wider than these floors would classify a huge slice of the internet as+ # bot traffic — refuse it here so a bad upstream refresh can't ship.+ for key, ip_def in BOT_IP_DEFINITIONS.items():+ for cidr in ip_def.networks:+ network = ipaddress.ip_network(cidr)+ floor = 16 if network.version == 4 else 32+ assert network.prefixlen >= floor, f"{key} range {cidr} wider than /{floor}"++ @parameterized.expand(+ [+ # Source IPs from the report that motivated IP-range detection: Google's mobile+ # rendering service crawling with a real Android UA (posthog#66604).+ "66.249.84.5",+ "74.125.150.10",+ "192.178.10.5",+ ]+ )+ def test_reported_google_renderer_ips_are_covered(self, ip):+ address = ipaddress.ip_address(ip)+ covered = any(+ address in ipaddress.ip_network(cidr)+ for ip_def in BOT_IP_DEFINITIONS.values()+ for cidr in ip_def.networks+ if ipaddress.ip_network(cidr).version == address.version+ )+ assert covered, f"{ip} not covered by any bot IP range"++class TestBotDefinitionsDataStructure:def test_all_bot_definitions_have_required_fields(self):for pattern, bot_def in BOT_DEFINITIONS.items():@@ -479,11 +600,26 @@ class TestMacroExpansionGuard(BaseTest):self._print("SELECT __preview_getTrafficType(__preview_getBotName(toString(properties.x))) FROM events")def test_non_duplicating_macro_inside_duplicating_macro_is_allowed(self):- # isBot does not duplicate its argument, so reaching it inside a duplicating macro's- # expansion is bounded (not exponential) and must still resolve, not raise.+ # One-arg isBot does not duplicate its argument, so reaching it inside a duplicating+ # macro's expansion is bounded (not exponential) and must still resolve, not raise.printed = self._print("SELECT __preview_getTrafficType(toString(__preview_isBot(properties.x))) FROM events")assert "multiMatchAnyIndex" in printed+ def test_two_arg_is_bot_expands_ip_ranges(self):+ printed = self._print(+ "SELECT isLikelyBot(toString(properties.$user_agent), toString(properties.$ip)) FROM events"+ )+ assert "multiMatchAnyIndex" in printed+ assert "IPv6CIDRToRange" in printed++ def test_two_arg_is_bot_nested_is_rejected(self):+ # The two-arg form duplicates its IP argument across the per-prefix-length range+ # checks, so nesting it is the same exponential vector as the lookup macros.+ with pytest.raises(QueryError, match="cannot be nested inside another expanded function call"):+ self._print(+ "SELECT isLikelyBot(toString(isLikelyBot(properties.x, toString(properties.$ip))), toString(properties.$ip)) FROM events"+ )+def test_matches_action_with_macro_property_still_resolves(self):# matchesAction expands a user-defined action, whose hogql property filters re-parse# arbitrary user HogQL. A guarded macro referenced there must still expand — the guarddiff --git a/posthog/hogql/functions/test/test_traffic_type_real_ua.py b/posthog/hogql/functions/test/test_traffic_type_real_ua.pyindex 3f7d9bb4c493..31d74713b9b2 100644--- a/posthog/hogql/functions/test/test_traffic_type_real_ua.py+++ b/posthog/hogql/functions/test/test_traffic_type_real_ua.py@@ -1,4 +1,5 @@import re+from ipaddress import ip_address, ip_networkfrom uuid import uuid4import pytest@@ -7,9 +8,21 @@ from posthog.test.base import BaseTest, _create_event, flush_persons_and_eventsfrom posthog.hogql.query import execute_hogql_queryfrom products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS+from products.web_analytics.backend.hogql_queries.bot_ip_definitions import BOT_IP_DEFINITIONSfrom products.web_analytics.backend.hogql_queries.bot_ua_fixtures import BOT_USER_AGENTS, CATEGORY_TO_TRAFFIC_CATEGORY+def _expected_ip_bot_name(ip: str) -> str:+ """Mirror the query-time multiIf: first BOT_IP_DEFINITIONS entry whose ranges contain the ip."""+ address = ip_address(ip)+ for ip_def in BOT_IP_DEFINITIONS.values():+ for cidr in ip_def.networks:+ network = ip_network(cidr)+ if network.version == address.version and address in network:+ return ip_def.name+ return ""++def _find_matching_pattern(ua: str) -> str | None:"""Simulate multiMatchAnyIndex: find first BOT_DEFINITIONS pattern that matches.@@ -230,6 +243,67 @@ class TestTrafficTypeIntegration(BaseTest):assert category == "no_user_agent"assert bot_name == ""+ def test_virt_properties_bot_ip_ranges(self):+ # Google's mobile rendering service: real Android UA with no bot token, only the+ # source IP (published in Google's crawler ranges) identifies it (posthog#66604).+ renderer_ua = (+ "Mozilla/5.0 (Linux; Android 11; moto g power (2022)) "+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Mobile Safari/537.36"+ )+ google_v6 = next(+ str(ip_network(cidr).network_address)+ for ip_def in BOT_IP_DEFINITIONS.values()+ for cidr in ip_def.networks+ if ":" in cidr+ )+ cases = [+ # (case_id, properties, expected_is_bot, expected_traffic_type, expected_bot_name)+ ("google-v4", {"$raw_user_agent": renderer_ua, "$ip": "66.249.84.5"}, 1, "Bot", None),+ ("google-special-v4", {"$raw_user_agent": renderer_ua, "$ip": "74.125.150.10"}, 1, "Bot", None),+ ("google-v6", {"$raw_user_agent": renderer_ua, "$ip": google_v6}, 1, "Bot", None),+ ("residential", {"$raw_user_agent": renderer_ua, "$ip": "203.0.113.7"}, 0, "Regular", ""),+ ("garbage-ip", {"$raw_user_agent": renderer_ua, "$ip": "not-an-ip"}, 0, "Regular", ""),+ ("missing-ip", {"$raw_user_agent": renderer_ua}, 0, "Regular", ""),+ # UA classification must keep precedence over the IP lookup+ (+ "ua-bot-residential-ip",+ {"$raw_user_agent": "Googlebot/2.1", "$ip": "203.0.113.7"},+ 1,+ "Bot",+ "Googlebot",+ ),+ ]++ tag = uuid4().hex+ for case_id, properties, *_ in cases:+ self._create_tagged_event(+ tag=tag,+ distinct_id=case_id,+ event="test_bot_ip",+ team=self.team,+ properties={**properties, "case_id": case_id},+ )+ flush_persons_and_events()++ response = self._query_tagged(+ "properties.case_id, `$virt_is_bot`, `$virt_traffic_type`, `$virt_bot_name`, `$virt_bot_operator`", tag+ )+ results_by_case = {row[0]: row for row in response.results}++ for case_id, properties, expected_is_bot, expected_traffic_type, expected_bot_name in cases:+ row = results_by_case.get(case_id)+ assert row is not None, f"No result for case {case_id}"+ _case, is_bot, traffic_type, bot_name, bot_operator = row+ assert is_bot == expected_is_bot, f"is_bot mismatch for {case_id}: got {is_bot}"+ assert traffic_type == expected_traffic_type, f"traffic_type mismatch for {case_id}: got {traffic_type}"+ if expected_bot_name is None:+ # IP-classified: which Google list an IP sits in shifts across upstream+ # refreshes, so derive the expected label from the data instead of pinning it+ expected_bot_name = _expected_ip_bot_name(properties["$ip"])+ assert bot_name == expected_bot_name, f"bot_name mismatch for {case_id}: got {bot_name}"+ if expected_is_bot:+ assert bot_operator == "Google", f"bot_operator mismatch for {case_id}: got {bot_operator}"+def test_virt_properties_empty_user_agent(self):tag = uuid4().hexself._create_tagged_event(diff --git a/posthog/hogql/functions/traffic_type.py b/posthog/hogql/functions/traffic_type.pyindex 71962dec80a8..d44e911d9f29 100644--- a/posthog/hogql/functions/traffic_type.py+++ b/posthog/hogql/functions/traffic_type.py@@ -7,23 +7,100 @@ can be used anywhere HogQL runs:- HogQLQuery runner for custom dashboards and insights- Trends and other query runners when filtering/grouping by traffic type+Each function takes the user agent and an optional client IP. The IP signal exists for+crawlers that send real browser user agents with no bot token (e.g. Google's mobile+rendering service) and only match via the operator-published IP ranges.+The legacy __preview_* names still resolve as deprecated aliases.-Bot definitions (patterns, categories, names) live in-products.web_analytics.backend.hogql_queries.bot_definitions so that changes to-bot data do not require a HogQL review.+Bot definitions (patterns, categories, names, IP ranges) live in+products.web_analytics.backend.hogql_queries so that changes to bot data do not require+a HogQL review."""+from typing import Optional+from posthog.hogql import astfrom products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS+from products.web_analytics.backend.hogql_queries.bot_ip_definitions import (+ BOT_IP_DEFINITIONS,+ bot_ip_prefix_groups_by_definition,+ merged_bot_ip_prefix_groups,+)+++def _safe_ip_expr(ip_expr: ast.Expr) -> ast.Expr:+ """Normalize the client IP to IPv6 (IPv4 maps to ::ffff:a.b.c.d).++ NULL, empty, and unparsable values become :: which matches no range.+ """+ return ast.Call(+ name="toIPv6OrDefault",+ args=[ast.Call(name="ifNull", args=[ip_expr, ast.Constant(value="")])],+ )+++def _ip_group_match(safe_ip: ast.Expr, prefixlen: int, addresses: tuple[str, ...]) -> ast.Expr:+ """Match one prefix-length group: zero the host bits, then a hash-set membership check.++ IPv6CIDRToRange(ip, N).1 is the network address of the ip's /N, so equality against the+ group's network addresses replaces per-CIDR range comparisons with a single IN lookup.+ """+ network_address = ast.Call(+ name="tupleElement",+ args=[+ ast.Call(name="IPv6CIDRToRange", args=[safe_ip, ast.Constant(value=prefixlen)]),+ ast.Constant(value=1),+ ],+ )+ return ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=network_address,+ right=ast.Array(exprs=[ast.Call(name="toIPv6", args=[ast.Constant(value=a)]) for a in addresses]),+ )+++def _build_ip_match_expr(ip_expr: ast.Expr) -> ast.Expr:+ """True when the IP falls in any known bot range (merged across all definitions)."""+ safe_ip = _safe_ip_expr(ip_expr)+ return ast.Or(+ exprs=[_ip_group_match(safe_ip, prefixlen, nets) for prefixlen, nets in merged_bot_ip_prefix_groups()]+ )+++def _build_ip_definition_index_expr(ip_expr: ast.Expr) -> ast.Expr:+ """1-based index of the matching BOT_IP_DEFINITIONS entry, 0 when no range matches."""+ safe_ip = _safe_ip_expr(ip_expr)+ multi_if_args: list[ast.Expr] = []+ for index, (_key, groups) in enumerate(bot_ip_prefix_groups_by_definition(), start=1):+ multi_if_args.append(ast.Or(exprs=[_ip_group_match(safe_ip, prefixlen, nets) for prefixlen, nets in groups]))+ multi_if_args.append(ast.Constant(value=index))+ multi_if_args.append(ast.Constant(value=0))+ return ast.Call(name="multiIf", args=multi_if_args)+++def _ip_label_lookup(ip_expr: ast.Expr, attr: str, default: str) -> ast.Expr:+ index_call = _build_ip_definition_index_expr(ip_expr)+ labels_array = ast.Array(+ exprs=[ast.Constant(value=getattr(ip_def, attr)) for ip_def in BOT_IP_DEFINITIONS.values()]+ )+ return ast.Call(+ name="if",+ args=[+ ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=index_call, right=ast.Constant(value=0)),+ ast.Constant(value=default),+ ast.ArrayAccess(array=labels_array, property=index_call, nullish=False),+ ],+ )def _build_bot_array_lookup(user_agent_expr: ast.Expr,- attr: str, # "name", "category", or "traffic_type"+ attr: str, # "name", "operator", "category", or "traffic_type"default: str = "",empty_ua_value: str = "",+ ip_expr: Optional[ast.Expr] = None,) -> ast.Expr:"""Build a multiMatchAnyIndex + array lookup expression for efficient bot detection.@@ -32,6 +109,9 @@ def _build_bot_array_lookup(NULL user agents are coalesced to empty string so they match the ^$ patternand get classified as empty_ua_value instead of falling through to default.++ When ip_expr is given, user agents that match no pattern fall back to the IP-range+ lookup before defaulting."""# Coalesce NULL to empty string so NULL user agents match the ^$ patternsafe_user_agent = ast.Call(name="ifNull", args=[user_agent_expr, ast.Constant(value="")])@@ -51,62 +131,77 @@ def _build_bot_array_lookup(# labels[index] - array access (1-based in ClickHouse)label_lookup = ast.ArrayAccess(array=labels_array, property=index_call, nullish=False)- # if(index = 0, default, labels[index])+ fallback: ast.Expr = ast.Constant(value=default)+ if ip_expr is not None:+ fallback = _ip_label_lookup(ip_expr, attr, default)++ # if(index = 0, fallback, labels[index])return ast.Call(name="if",args=[ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=index_call, right=ast.Constant(value=0)),- ast.Constant(value=default),+ fallback,label_lookup,],)+def _optional_ip_arg(args: list[ast.Expr]) -> Optional[ast.Expr]:+ return args[1] if len(args) > 1 else None++def get_bot_name(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:"""- HogQL function: getBotName(user_agent)+ HogQL function: getBotName(user_agent[, ip])Returns bot name: "Googlebot", "ChatGPT", etc. Empty string for regular traffic."""- return _build_bot_array_lookup(args[0], "name", default="", empty_ua_value="")+ return _build_bot_array_lookup(args[0], "name", default="", empty_ua_value="", ip_expr=_optional_ip_arg(args))def get_bot_operator(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:"""- HogQL function: getBotOperator(user_agent)+ HogQL function: getBotOperator(user_agent[, ip])Returns operator/company name: "Google", "OpenAI", "Anthropic", etc. Empty string for regular traffic."""- return _build_bot_array_lookup(args[0], "operator", default="", empty_ua_value="")+ return _build_bot_array_lookup(args[0], "operator", default="", empty_ua_value="", ip_expr=_optional_ip_arg(args))def get_traffic_type(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:"""- HogQL function: getTrafficType(user_agent)+ HogQL function: getTrafficType(user_agent[, ip])Returns one of: 'AI Agent', 'Bot', 'Automation', 'Regular'"""- return _build_bot_array_lookup(args[0], "traffic_type", default="Regular", empty_ua_value="Automation")+ return _build_bot_array_lookup(+ args[0], "traffic_type", default="Regular", empty_ua_value="Automation", ip_expr=_optional_ip_arg(args)+ )def get_traffic_category(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:"""- HogQL function: getTrafficCategory(user_agent)+ HogQL function: getTrafficCategory(user_agent[, ip])Returns subcategory: 'ai_crawler', 'ai_search', 'ai_assistant', 'search_crawler', 'seo_crawler', etc.For regular traffic, returns 'regular'."""- return _build_bot_array_lookup(args[0], "category", default="regular", empty_ua_value="no_user_agent")+ return _build_bot_array_lookup(+ args[0], "category", default="regular", empty_ua_value="no_user_agent", ip_expr=_optional_ip_arg(args)+ )def is_bot(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:"""- HogQL function: isLikelyBot(user_agent)+ HogQL function: isLikelyBot(user_agent[, ip])- Returns true if the user agent matches bot/automation patterns, false otherwise.- NULL user agents are treated as bots (empty UA is considered automation).+ Returns true if the user agent matches bot/automation patterns, or (when given) the+ client IP falls in a known bot IP range. NULL user agents are treated as bots+ (empty UA is considered automation).- Uses multiMatchAnyIndex for efficient single-pass matching (same as get_traffic_type etc.).+ Uses multiMatchAnyIndex for efficient single-pass matching (same as get_traffic_type etc.);+ the IP check is a handful of hash-set lookups and only evaluates for rows the UA check+ didn't already match (or() short-circuits)."""user_agent_expr = args[0]@@ -117,25 +212,27 @@ def is_bot(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:index_call = ast.Call(name="multiMatchAnyIndex", args=[safe_user_agent, patterns_array])- # Cast to Bool so results render as true/false (not 0/1) in insights breakdowns.- return ast.Call(- name="toBool",- args=[- ast.CompareOperation(- op=ast.CompareOperationOp.NotEq,- left=index_call,- right=ast.Constant(value=0),- )- ],+ matched: ast.Expr = ast.CompareOperation(+ op=ast.CompareOperationOp.NotEq,+ left=index_call,+ right=ast.Constant(value=0),)+ ip_expr = _optional_ip_arg(args)+ if ip_expr is not None:+ matched = ast.Or(exprs=[matched, _build_ip_match_expr(ip_expr)])++ # Cast to Bool so results render as true/false (not 0/1) in insights breakdowns.+ return ast.Call(name="toBool", args=[matched])def get_bot_type(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:"""- HogQL function: getBotType(user_agent)+ HogQL function: getBotType(user_agent[, ip])Returns the bot category or empty string for regular traffic.Categories: 'ai_crawler', 'ai_search', 'ai_assistant', 'search_crawler', 'seo_crawler','social_crawler', 'monitoring', 'http_client', 'headless_browser', 'no_user_agent', ''"""- return _build_bot_array_lookup(args[0], "category", default="", empty_ua_value="no_user_agent")+ return _build_bot_array_lookup(+ args[0], "category", default="", empty_ua_value="no_user_agent", ip_expr=_optional_ip_arg(args)+ )diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex b98b24e36e8b..59aecf5eed0e 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -1602,6 +1602,10 @@ class Resolver(CloningVisitor):unique_survey_submissions_filter(node=node, args=node.args, team_id=self.context.team_id))if node.name in ("isLikelyBot", "__preview_isBot"):+ # The two-arg form duplicates its IP argument across the per-prefix-length range+ # checks, so it needs the same re-entrancy guard as the lookup builders below.+ if len(node.args) > 1:+ return self._expand_duplicating_macro(node, lambda: is_bot(node=node, args=node.args))return self.visit(is_bot(node=node, args=node.args))# The bot-lookup builders below duplicate their argument, so they must expand under the# re-entrancy guard to bound nested expansion (see _expand_duplicating_macro).diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex fc487cda6f57..71dcdd811d92 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -3028,7 +3028,7 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {},"$virt_is_bot": {"label": "Is bot",- "description": "Whether the event was generated by a bot, crawler, or automation tool.",+ "description": "Whether the event was generated by a bot, crawler, or automation tool, detected from the user agent or from operator-published bot IP ranges.","type": "Boolean","virtual": True,},diff --git a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambrindex 099906ada80f..556458b4f365 100644--- a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr+++ b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr@@ -65,7 +65,7 @@HogQL defines what functions are available with most (but not all) having a 1:1 mapping to ClickHouse functions.These are the non-aggregated HogQL functions:```- ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'toTypeName', 'cityHash64', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']+ ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'toTypeName', 'cityHash64', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']```These are the aggregated HogQL functions:diff --git a/products/web_analytics/backend/hogql_queries/bot_ip_definitions.py b/products/web_analytics/backend/hogql_queries/bot_ip_definitions.pynew file mode 100644index 000000000000..7056673bce54--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/bot_ip_definitions.py@@ -0,0 +1,84 @@+from dataclasses import dataclass+from functools import cache+from ipaddress import IPv6Address, collapse_addresses, ip_network++from products.web_analytics.backend.hogql_queries.bot_ip_networks import (+ GOOGLE_COMMON_CRAWLER_NETWORKS,+ GOOGLE_SPECIAL_CRAWLER_NETWORKS,+ GOOGLE_USER_TRIGGERED_FETCHER_NETWORKS,+)+++@dataclass(frozen=True)+class BotIPDefinition:+ name: str # Display name: "Googlebot"+ category: str # Category, same vocabulary as BotDefinition: "search_crawler", ...+ traffic_type: str # Type, same vocabulary as BotDefinition: "Bot", ...+ operator: str # Operator/company: "Google"+ networks: tuple[str, ...] # Collapsed CIDR ranges (IPv4 and IPv6) published by the operator+ documentation_url: str | None = None+++# Some crawlers (e.g. Google's mobile rendering service) send real browser user agents+# with no bot token, so the operator-published source IP ranges are the only reliable+# classification signal. Refresh the network lists with+# products/web_analytics/scripts/refresh_bot_ip_ranges.py.+BOT_IP_DEFINITIONS: dict[str, BotIPDefinition] = {+ "google-common-crawlers": BotIPDefinition(+ "Googlebot",+ "search_crawler",+ "Bot",+ "Google",+ networks=GOOGLE_COMMON_CRAWLER_NETWORKS,+ documentation_url="https://developers.google.com/crawling/docs/verifying-google-crawlers",+ ),+ "google-special-crawlers": BotIPDefinition(+ "Google special crawler",+ "search_crawler",+ "Bot",+ "Google",+ networks=GOOGLE_SPECIAL_CRAWLER_NETWORKS,+ documentation_url="https://developers.google.com/crawling/docs/verifying-google-crawlers",+ ),+ "google-user-triggered-fetchers": BotIPDefinition(+ "Google fetcher",+ "search_crawler",+ "Bot",+ "Google",+ networks=GOOGLE_USER_TRIGGERED_FETCHER_NETWORKS,+ documentation_url="https://developers.google.com/crawling/docs/verifying-google-crawlers",+ ),+}++# The query-time matcher normalizes every address to IPv6 (IPv4 maps to ::ffff:a.b.c.d),+# so IPv4 CIDRs become IPv6 CIDRs with the prefix length shifted by 96 bits.+_IPV4_MAPPED_OFFSET = 96+++def _ipv6_prefix_groups(cidrs: tuple[str, ...]) -> tuple[tuple[int, tuple[str, ...]], ...]:+ groups: dict[int, list[str]] = {}+ for cidr in cidrs:+ network = ip_network(cidr)+ if network.version == 4:+ prefixlen = network.prefixlen + _IPV4_MAPPED_OFFSET+ address = str(IPv6Address(f"::ffff:{network.network_address}"))+ else:+ prefixlen = network.prefixlen+ address = str(network.network_address)+ groups.setdefault(prefixlen, []).append(address)+ return tuple((prefixlen, tuple(sorted(addresses))) for prefixlen, addresses in sorted(groups.items()))+++@cache+def bot_ip_prefix_groups_by_definition() -> tuple[tuple[str, tuple[tuple[int, tuple[str, ...]], ...]], ...]:+ """Per-definition (prefixlen, network addresses) groups, for labeled lookups (bot name etc.)."""+ return tuple((key, _ipv6_prefix_groups(definition.networks)) for key, definition in BOT_IP_DEFINITIONS.items())+++@cache+def merged_bot_ip_prefix_groups() -> tuple[tuple[int, tuple[str, ...]], ...]:+ """(prefixlen, network addresses) groups across all definitions, for the boolean is-bot check."""+ all_networks = [ip_network(cidr) for definition in BOT_IP_DEFINITIONS.values() for cidr in definition.networks]+ v4 = collapse_addresses(n for n in all_networks if n.version == 4)+ v6 = collapse_addresses(n for n in all_networks if n.version == 6)+ return _ipv6_prefix_groups(tuple(str(n) for n in [*v4, *v6]))diff --git a/products/web_analytics/backend/hogql_queries/bot_ip_networks.py b/products/web_analytics/backend/hogql_queries/bot_ip_networks.pynew file mode 100644index 000000000000..bb272c642f6b--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/bot_ip_networks.py@@ -0,0 +1,205 @@+# Generated by products/web_analytics/scripts/refresh_bot_ip_ranges.py — do not edit by hand.+# Collapsed CIDR ranges of Google-published crawler/fetcher IPs; see that script for+# the source URLs and for why user-triggered-fetchers.json (GCP egress) is excluded.++# https://developers.google.com/static/crawling/ipranges/common-crawlers.json+GOOGLE_COMMON_CRAWLER_NETWORKS: tuple[str, ...] = (+ "34.22.85.0/27",+ "34.64.82.64/28",+ "34.65.242.112/28",+ "34.80.50.80/28",+ "34.88.194.0/28",+ "34.89.10.80/28",+ "34.89.198.80/28",+ "34.96.162.48/28",+ "34.100.182.96/28",+ "34.101.50.144/28",+ "34.118.66.0/28",+ "34.118.254.0/28",+ "34.126.178.96/28",+ "34.146.150.144/28",+ "34.147.110.144/28",+ "34.151.74.144/28",+ "34.152.50.64/28",+ "34.154.114.144/28",+ "34.155.98.32/28",+ "34.165.18.176/28",+ "34.175.160.64/28",+ "34.176.130.16/28",+ "35.247.243.240/28",+ "66.249.64.0/23",+ "66.249.66.0/24",+ "66.249.67.0/26",+ "66.249.67.64/27",+ "66.249.68.0/25",+ "66.249.68.128/26",+ "66.249.68.192/27",+ "66.249.69.0/24",+ "66.249.70.0/23",+ "66.249.72.0/22",+ "66.249.76.0/23",+ "66.249.78.0/24",+ "66.249.79.0/26",+ "66.249.79.64/27",+ "66.249.79.128/25",+ "192.178.4.0/24",+ "192.178.5.0/27",+ "192.178.6.0/23",+ "2001:4860:4801:2::/64",+ "2001:4860:4801:c::/64",+ "2001:4860:4801:f::/64",+ "2001:4860:4801:10::/60",+ "2001:4860:4801:20::/59",+ "2001:4860:4801:40::/63",+ "2001:4860:4801:42::/64",+ "2001:4860:4801:44::/62",+ "2001:4860:4801:48::/62",+ "2001:4860:4801:4c::/63",+ "2001:4860:4801:4e::/64",+ "2001:4860:4801:50::/61",+ "2001:4860:4801:58::/63",+ "2001:4860:4801:60::/59",+ "2001:4860:4801:80::/61",+ "2001:4860:4801:88::/64",+ "2001:4860:4801:90::/61",+ "2001:4860:4801:a0::/61",+ "2001:4860:4801:a8::/62",+ "2001:4860:4801:ac::/63",+ "2001:4860:4801:ae::/64",+ "2001:4860:4801:b0::/62",+ "2001:4860:4801:b4::/63",+ "2001:4860:4801:b6::/64",+)++# https://developers.google.com/static/crawling/ipranges/special-crawlers.json+GOOGLE_SPECIAL_CRAWLER_NETWORKS: tuple[str, ...] = (+ "66.249.87.0/24",+ "66.249.89.0/24",+ "66.249.90.0/23",+ "66.249.92.0/24",+ "72.14.199.32/27",+ "72.14.199.64/26",+ "72.14.199.128/25",+ "74.125.148.0/23",+ "74.125.150.0/25",+ "74.125.150.128/26",+ "74.125.150.192/27",+ "74.125.151.0/24",+ "74.125.216.0/22",+ "108.177.2.0/24",+ "192.178.16.0/24",+ "192.178.17.0/27",+ "209.85.238.0/24",+ "2001:4860:4801:2008::/64",+ "2001:4860:4801:200c::/63",+ "2001:4860:4801:2010::/60",+ "2001:4860:4801:2020::/59",+ "2001:4860:4801:2040::/63",+ "2001:4860:4801:2042::/64",+ "2001:4860:4801:2044::/62",+ "2001:4860:4801:2048::/62",+ "2001:4860:4801:204c::/63",+ "2001:4860:4801:204e::/64",+ "2001:4860:4801:2050::/62",+ "2001:4860:4801:2054::/63",+ "2001:4860:4801:2056::/64",+ "2001:4860:4801:2060::/59",+ "2001:4860:4801:2080::/61",+ "2001:4860:4801:2088::/64",+ "2001:4860:4801:2090::/61",+ "2001:4860:4801:20a0::/62",+ "2001:4860:4801:20a4::/63",+ "2001:4860:4801:20a6::/64",+ "2001:4860:4801:20b0::/62",+ "2001:4860:4801:20b4::/63",+ "2001:4860:4801:20b6::/64",+)++# https://developers.google.com/static/crawling/ipranges/user-triggered-fetchers-google.json+GOOGLE_USER_TRIGGERED_FETCHER_NETWORKS: tuple[str, ...] = (+ "64.233.172.0/23",+ "66.102.6.0/23",+ "66.102.8.0/23",+ "66.249.80.0/22",+ "66.249.84.0/26",+ "66.249.84.96/27",+ "66.249.84.128/25",+ "66.249.85.0/25",+ "66.249.85.128/26",+ "66.249.88.0/24",+ "66.249.93.0/24",+ "74.125.208.0/24",+ "74.125.209.0/25",+ "74.125.209.128/26",+ "74.125.209.192/27",+ "74.125.210.0/24",+ "74.125.211.0/25",+ "74.125.212.0/24",+ "74.125.213.0/25",+ "74.125.214.0/23",+ "142.250.32.0/24",+ "142.250.33.0/25",+ "142.250.33.128/27",+ "192.178.8.0/25",+ "192.178.8.128/27",+ "192.178.9.0/24",+ "192.178.10.0/25",+ "192.178.11.0/24",+ "192.178.12.0/25",+ "192.178.12.128/26",+ "192.178.12.192/27",+ "192.178.13.0/24",+ "192.178.14.0/27",+ "192.178.15.0/24",+ "2001:4860:4801:4004::/64",+ "2001:4860:4801:4008::/63",+ "2001:4860:4801:400f::/64",+ "2001:4860:4801:4010::/64",+ "2001:4860:4801:4015::/64",+ "2001:4860:4801:4016::/63",+ "2001:4860:4801:4018::/64",+ "2001:4860:4801:401a::/63",+ "2001:4860:4801:401c::/64",+ "2001:4860:4801:4020::/61",+ "2001:4860:4801:4028::/62",+ "2001:4860:4801:4030::/61",+ "2001:4860:4801:4038::/62",+ "2001:4860:4801:403c::/64",+ "2001:4860:4801:4040::/59",+ "2001:4860:4801:4060::/63",+ "2001:4860:4801:4062::/64",+ "2001:4860:4801:4064::/62",+ "2001:4860:4801:4068::/62",+ "2001:4860:4801:406c::/63",+ "2001:4860:4801:406e::/64",+ "2001:4860:4801:4070::/60",+ "2001:4860:4801:4080::/61",+ "2001:4860:4801:4088::/62",+ "2001:4860:4801:4090::/62",+ "2001:4860:4801:4094::/63",+ "2001:4860:4801:4096::/64",+ "2001:4860:4801:40a0::/62",+ "2001:4860:4801:40a4::/64",+ "2001:4860:4801:40b0::/61",+ "2001:4860:4801:40b8::/63",+ "2001:4860:4801:40ba::/64",+ "2001:4860:4801:40c0::/62",+ "2001:4860:4801:40c4::/63",+ "2001:4860:4801:40c6::/64",+ "2001:4860:4801:40d0::/60",+ "2001:4860:4801:40e0::/62",+ "2001:4860:4801:40f0::/60",+ "2001:4860:4801:4100::/61",+ "2001:4860:4801:4110::/62",+ "2001:4860:4801:4120::/61",+ "2001:4860:4801:4130::/62",+ "2001:4860:4801:4134::/63",+ "2001:4860:4801:4136::/64",+ "2001:4860:4801:4140::/61",+ "2001:4860:4801:4150::/62",+ "2001:4860:4801:4154::/63",+ "2001:4860:4801:4156::/64",+ "2001:4860:4801:4160::/62",+ "2001:4860:4801:4164::/63",+ "2001:4860:4801:4166::/64",+)diff --git a/products/web_analytics/backend/hogql_queries/traffic_type.py b/products/web_analytics/backend/hogql_queries/traffic_type.pyindex 80466609be01..06446905a8bf 100644--- a/products/web_analytics/backend/hogql_queries/traffic_type.py+++ b/products/web_analytics/backend/hogql_queries/traffic_type.py@@ -6,6 +6,10 @@ These wrap the HogQL classification functions, usable anywhere HogQL runs:- HogQLQuery / Trends: filter or group by traffic type- Web analytics query runners+Each helper takes the user agent expression and an optional client IP expression; the IP+signal catches crawlers that send real browser user agents from operator-published IP+ranges (e.g. Google's mobile rendering service).+The legacy __preview_* names still resolve as deprecated aliases."""@@ -30,9 +34,13 @@ __all__ = []-def get_traffic_type_expr(user_agent_expr: ast.Expr) -> ast.Expr:+def _args(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None) -> list[ast.Expr]:+ return [user_agent_expr] if ip_expr is None else [user_agent_expr, ip_expr]+++def get_traffic_type_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:"""- Classifies user agent into traffic type.+ Classifies user agent (and optionally client IP) into traffic type.Returns an expression that evaluates to one of:- "AI Agent" - AI crawlers, search, and assistants (GPTBot, ClaudeBot, ChatGPT-User, etc.)@@ -40,40 +48,42 @@ def get_traffic_type_expr(user_agent_expr: ast.Expr) -> ast.Expr:- "Automation" - HTTP clients, headless browsers, empty UA- "Regular" - Default for unmatched user agents"""- return _get_traffic_type(node=ast.Call(name="getTrafficType", args=[]), args=[user_agent_expr])+ return _get_traffic_type(node=ast.Call(name="getTrafficType", args=[]), args=_args(user_agent_expr, ip_expr))-def get_traffic_category_expr(user_agent_expr: ast.Expr) -> ast.Expr:+def get_traffic_category_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:"""Returns subcategory expression for more granular classification.Categories: ai_crawler, ai_search, ai_assistant, search_crawler, seo_crawler,social_crawler, monitoring, http_client, headless_browser, no_user_agent, regular"""- return _get_traffic_category(node=ast.Call(name="getTrafficCategory", args=[]), args=[user_agent_expr])+ return _get_traffic_category(+ node=ast.Call(name="getTrafficCategory", args=[]), args=_args(user_agent_expr, ip_expr)+ )-def is_bot_expr(user_agent_expr: ast.Expr) -> ast.Expr:+def is_bot_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:"""Returns a boolean expression: true if bot/automation, false for regular traffic."""- return _is_bot(node=ast.Call(name="isLikelyBot", args=[]), args=[user_agent_expr])+ return _is_bot(node=ast.Call(name="isLikelyBot", args=[]), args=_args(user_agent_expr, ip_expr))-def get_bot_type_expr(user_agent_expr: ast.Expr) -> ast.Expr:+def get_bot_type_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:"""Returns the bot category or empty string for regular traffic.Categories: ai_crawler, ai_search, ai_assistant, search_crawler, seo_crawler,social_crawler, monitoring, http_client, headless_browser, no_user_agent, "" (regular)"""- return _get_bot_type(node=ast.Call(name="getBotType", args=[]), args=[user_agent_expr])+ return _get_bot_type(node=ast.Call(name="getBotType", args=[]), args=_args(user_agent_expr, ip_expr))-def get_bot_name_expr(user_agent_expr: ast.Expr) -> ast.Expr:+def get_bot_name_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:"""Returns the bot name or empty string for regular traffic.Examples: "Googlebot", "ChatGPT", "Claude", "curl", """""- return _get_bot_name(node=ast.Call(name="getBotName", args=[]), args=[user_agent_expr])+ return _get_bot_name(node=ast.Call(name="getBotName", args=[]), args=_args(user_agent_expr, ip_expr))diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.pyindex 8c0dd67490f4..96a45ccab4f3 100644--- a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py@@ -603,12 +603,20 @@ WHEREreturn apply_path_cleaning(path_expr, self.team)- def _get_traffic_type_expr(self, user_agent_expr: ast.Expr | None = None) -> ast.Expr:- return get_traffic_type_expr(user_agent_expr or ast.Field(chain=["events", "properties", "$raw_user_agent"]))+ def _get_traffic_type_expr(+ self, user_agent_expr: ast.Expr | None = None, ip_expr: ast.Expr | None = None+ ) -> ast.Expr:+ return get_traffic_type_expr(+ user_agent_expr or ast.Field(chain=["events", "properties", "$raw_user_agent"]),+ ip_expr or ast.Field(chain=["events", "properties", "$ip"]),+ )- def _get_traffic_category_expr(self, user_agent_expr: ast.Expr | None = None) -> ast.Expr:+ def _get_traffic_category_expr(+ self, user_agent_expr: ast.Expr | None = None, ip_expr: ast.Expr | None = None+ ) -> ast.Expr:return get_traffic_category_expr(- user_agent_expr or ast.Field(chain=["events", "properties", "$raw_user_agent"])+ user_agent_expr or ast.Field(chain=["events", "properties", "$raw_user_agent"]),+ ip_expr or ast.Field(chain=["events", "properties", "$ip"]),)def _unsample(self, n: Optional[int | float], _row: Optional[list[int | float]] = None):diff --git a/products/web_analytics/scripts/refresh_bot_ip_ranges.py b/products/web_analytics/scripts/refresh_bot_ip_ranges.pynew file mode 100644index 000000000000..4823ff00828c--- /dev/null+++ b/products/web_analytics/scripts/refresh_bot_ip_ranges.py@@ -0,0 +1,92 @@+#!/usr/bin/env python3+"""Refresh the bot IP ranges vendored in bot_ip_networks.py.++Google publishes the IP ranges its crawlers and fetchers operate from as+machine-readable JSON. Some of that traffic (notably the mobile rendering+service) uses real browser user agents with no bot token, so IP ranges are+the only reliable classification signal. This script fetches the published+lists, collapses adjacent CIDRs, and rewrites+products/web_analytics/backend/hogql_queries/bot_ip_networks.py.++We intentionally do NOT vendor user-triggered-fetchers.json: those ranges are+Google Cloud egress that third parties can run arbitrary workloads (including+VPNs and proxies serving real users) behind, so matching them would+misclassify human traffic.++Usage, from the repo root:+ python products/web_analytics/scripts/refresh_bot_ip_ranges.py++Then review the diff, run the bot IP tests, and commit.+"""++import sys+import json+import ipaddress+import urllib.request+from pathlib import Path++# Sanity floors: a published range wider than this is almost certainly an+# upstream mistake (or a policy change that deserves a human decision), since+# it would classify an enormous slice of the internet as bot traffic.+MIN_V4_PREFIXLEN = 16+MIN_V6_PREFIXLEN = 32++PROVIDERS: dict[str, str] = {+ "GOOGLE_COMMON_CRAWLER_NETWORKS": "https://developers.google.com/static/crawling/ipranges/common-crawlers.json",+ "GOOGLE_SPECIAL_CRAWLER_NETWORKS": "https://developers.google.com/static/crawling/ipranges/special-crawlers.json",+ "GOOGLE_USER_TRIGGERED_FETCHER_NETWORKS": "https://developers.google.com/static/crawling/ipranges/user-triggered-fetchers-google.json",+}++OUTPUT_PATH = Path(__file__).resolve().parents[1] / "backend" / "hogql_queries" / "bot_ip_networks.py"+++def fetch_networks(url: str) -> list[ipaddress.IPv4Network | ipaddress.IPv6Network]:+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected (urls come from the hardcoded PROVIDERS constant, never user input)+ with urllib.request.urlopen(url, timeout=30) as response:+ data = json.load(response)+ prefixes = data.get("prefixes")+ if not prefixes:+ raise ValueError(f"{url} returned no prefixes — upstream format may have changed")+ networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network] = []+ for entry in prefixes:+ cidr = entry.get("ipv4Prefix") or entry.get("ipv6Prefix")+ if cidr is None:+ raise ValueError(f"{url} entry has neither ipv4Prefix nor ipv6Prefix: {entry}")+ networks.append(ipaddress.ip_network(cidr))+ return networks+++def collapse(networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network]) -> list[str]:+ v4 = sorted(ipaddress.collapse_addresses(n for n in networks if isinstance(n, ipaddress.IPv4Network)))+ v6 = sorted(ipaddress.collapse_addresses(n for n in networks if isinstance(n, ipaddress.IPv6Network)))+ for v4_net in v4:+ if v4_net.prefixlen < MIN_V4_PREFIXLEN:+ raise ValueError(f"IPv4 range {v4_net} wider than /{MIN_V4_PREFIXLEN} floor — refusing")+ for v6_net in v6:+ if v6_net.prefixlen < MIN_V6_PREFIXLEN:+ raise ValueError(f"IPv6 range {v6_net} wider than /{MIN_V6_PREFIXLEN} floor — refusing")+ return [str(n) for n in [*v4, *v6]]+++def main() -> int:+ sections: list[str] = []+ for const_name, url in PROVIDERS.items():+ raw = fetch_networks(url)+ collapsed = collapse(raw)+ print(f"{const_name}: {len(raw)} published prefixes -> {len(collapsed)} collapsed networks") # noqa: T201+ lines = "\n".join(f' "{cidr}",' for cidr in collapsed)+ sections.append(f"# {url}\n{const_name}: tuple[str, ...] = (\n{lines}\n)")++ body = "\n\n".join(sections)+ OUTPUT_PATH.write_text(+ "# Generated by products/web_analytics/scripts/refresh_bot_ip_ranges.py — do not edit by hand.\n"+ "# Collapsed CIDR ranges of Google-published crawler/fetcher IPs; see that script for\n"+ "# the source URLs and for why user-triggered-fetchers.json (GCP egress) is excluded.\n\n"+ f"{body}\n"+ )+ print(f"wrote {OUTPUT_PATH}") # noqa: T201+ return 0+++if __name__ == "__main__":+ sys.exit(main())