: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(hogql): tag user-supplied hogql in queries + prometheus label (#60214)
Sam Pennington24ec3931c085
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex f66282d2441c..2140d6cce555 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -412,6 +412,9 @@ class QueryTags(BaseModel):has_joins: Optional[bool] = Nonehas_json_operations: Optional[bool] = None+ # True when the query embeds a user-supplied HogQL string; used to split user vs platform errors in system.query_log.+ contains_user_hogql: Optional[bool] = None+hogql_features: Optional[HogQLFeatures] = Nonemodifiers: Optional[object] = None@@ -525,6 +528,18 @@ def tag_queries(**kwargs) -> None:query_tags.set(updated_tags)+def tag_contains_user_hogql() -> None:+ """Mark the current query as embedding a user-supplied HogQL string; used to separate user vs platform errors in system.query_log.++ Idempotent — safe to call inside hot loops (recursive ``property_to_expr``, breakdown+ iteration, ``@property`` accessors) since the early-return skips the ``model_copy``+ inside ``tag_queries`` after the first call per query context.+ """+ if get_query_tag_value("contains_user_hogql"):+ return+ tag_queries(contains_user_hogql=True)++def get_team_query_tags(team: "Team") -> dict[str, Any]:from posthog.models.organization import Organizationdiff --git a/posthog/clickhouse/test/test_query_tagging.py b/posthog/clickhouse/test/test_query_tagging.pyindex 0bf252b52162..418cc0a40467 100644--- a/posthog/clickhouse/test/test_query_tagging.py+++ b/posthog/clickhouse/test/test_query_tagging.py@@ -26,6 +26,7 @@ from posthog.clickhouse.query_tagging import (get_query_tag_value,get_query_tags,reset_query_tags,+ tag_contains_user_hogql,tag_queries,tags_context,update_tags,@@ -292,6 +293,47 @@ def test_get_caller_source_skips_infrastructure():assert prefix.startswith(_PROJECT_ROOT_PREFIX)+def test_tag_contains_user_hogql_sets_flag():+ reset_query_tags()+ assert get_query_tag_value("contains_user_hogql") is None+ tag_contains_user_hogql()+ assert get_query_tag_value("contains_user_hogql") is True+++def test_tag_contains_user_hogql_is_idempotent():+ reset_query_tags()+ tag_contains_user_hogql()+ tag_contains_user_hogql()+ assert get_query_tag_value("contains_user_hogql") is True+++def test_tag_contains_user_hogql_short_circuits_after_first_call():+ # Repeated calls (recursive property_to_expr, breakdown loops, @property accessors)+ # must skip the model_copy(deep=True) inside tag_queries after the first call.+ reset_query_tags()+ tag_contains_user_hogql()+ first_tags = get_query_tags()+ tag_contains_user_hogql()+ tag_contains_user_hogql()+ # Same object — no fresh copy was set by the no-op calls+ assert get_query_tags() is first_tags+++def test_contains_user_hogql_excluded_from_json_when_none():+ qt = QueryTags(git_commit="test", container_hostname="test", service_name="test")+ assert "contains_user_hogql" not in qt.to_json()+++def test_contains_user_hogql_included_in_json_when_set():+ qt = QueryTags(+ contains_user_hogql=True,+ git_commit="test",+ container_hostname="test",+ service_name="test",+ )+ assert '"contains_user_hogql":true' in qt.to_json()++def test_source_file_excluded_from_json_when_none():qt = QueryTags(git_commit="test", container_hostname="test", service_name="test")data = qt.to_json()@@ -440,6 +482,30 @@ class TestQueryTaggingSourceInQueryLog(BaseTest, ClickhouseTestMixin):assert comment["hogql_features"] == {"tables": ["events"], "events": []}assert comment["product"] == Product.PRODUCT_ANALYTICS.value+ def test_hogql_query_runner_marks_contains_user_hogql(self):+ from posthog.schema import HogQLQuery++ from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner++ marker = str(uuid.uuid4())+ reset_query_tags()+ tag_queries(kind="request", id="test", team_id=self.team.pk, feature="query")++ runner = HogQLQueryRunner(query=HogQLQuery(query=f"SELECT '{marker}'"), team=self.team) # noqa: S608+ runner._calculate()++ comment = self._get_log_comment(marker)+ assert comment.get("contains_user_hogql") is True++ def test_platform_query_does_not_mark_contains_user_hogql(self):+ marker = str(uuid.uuid4())+ reset_query_tags()+ tag_queries(kind="request", id="test", team_id=self.team.pk, feature="query", product=Product.INTERNAL)+ sync_execute(f"SELECT '{marker}'") # noqa: S608++ comment = self._get_log_comment(marker)+ assert "contains_user_hogql" not in comment+def test_execute_hogql_query_with_mcp_source_still_attributes_via_features(self):# Pulling MCP traffic apart by what it actually does is the whole point# of this fallback — confirm a $exception query from MCP attributes todiff --git a/posthog/hogql/property.py b/posthog/hogql/property.pyindex fa50c5c71098..1ee0bfed2281 100644--- a/posthog/hogql/property.py+++ b/posthog/hogql/property.py@@ -48,6 +48,7 @@ from posthog.hogql.parser import CacheOrigin, parse_exprfrom posthog.hogql.utils import map_virtual_propertiesfrom posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.constants import AUTOCAPTURE_EVENT, TREND_FILTER_TYPE_ACTIONS, PropertyOperatorTypefrom posthog.models import Cohort, Property, PropertyDefinition, Teamfrom posthog.models.element import Element@@ -806,6 +807,7 @@ def property_to_expr(raise QueryError(f"property_to_expr with property of type {type(property).__name__} not implemented")if property.type == "hogql":+ tag_contains_user_hogql()return parse_expr(property.key, cache_origin=CacheOrigin.USER)elif property.type == "event_metadata" and scope == "group" and GROUP_KEY_PATTERN.match(property.key) is not None:group_type_index = property.key.split("_")[1]diff --git a/posthog/hogql_queries/actors_query_runner.py b/posthog/hogql_queries/actors_query_runner.pyindex ee54dec07006..4b7c364becac 100644--- a/posthog/hogql_queries/actors_query_runner.py+++ b/posthog/hogql_queries/actors_query_runner.py@@ -26,6 +26,7 @@ from posthog.hogql.property import has_aggregationfrom posthog.hogql.resolver_utils import extract_select_queriesfrom posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.actor_strategies import ActorStrategy, GroupStrategy, PersonStrategy, SessionStrategyfrom posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunnerfrom posthog.hogql_queries.insights.insight_actors_query_runner import InsightActorsQueryRunner@@ -250,6 +251,11 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):)def _calculate(self) -> ActorsQueryResponse:+ # `ActorsQuery.select` and `ActorsQuery.orderBy` are user-supplied HogQL strings,+ # parsed by `to_query()`. Tag here so platform sub-query callers (e.g.+ # `hogql_cohort_query._actors_query_from_source`) that invoke `to_query()` with+ # platform-constant select lists are not mis-attributed.+ tag_contains_user_hogql()try:self.calculating = Truereturn self._calculate_internal()diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.pyindex 644fb07e76a6..0bb871a3f19c 100644--- a/posthog/hogql_queries/events_query_runner.py+++ b/posthog/hogql_queries/events_query_runner.py@@ -24,6 +24,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.api.element import ElementSerializerfrom posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.insights.insight_actors_query_runner import InsightActorsQueryRunnerfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner, get_query_runner@@ -419,6 +420,11 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):return stmtdef _calculate(self) -> EventsQueryResponse:+ # Tag here (not in `to_query()`) so platform code that calls `to_query()` as a+ # sub-query helper — e.g. `hogql_cohort_query.py` — doesn't false-positive when+ # the `select` / `where` strings it builds are platform constants. User-facing+ # `EventsQuery` execution always lands in `_calculate()` via the runner.+ tag_contains_user_hogql()query_result = self.paginator.execute_hogql_query(query=self.to_query(),team=self.team,diff --git a/posthog/hogql_queries/experiments/base_query_utils.py b/posthog/hogql_queries/experiments/base_query_utils.pyindex 1902a3209068..05d3be9f2c80 100644--- a/posthog/hogql_queries/experiments/base_query_utils.py+++ b/posthog/hogql_queries/experiments/base_query_utils.py@@ -24,6 +24,7 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_exprfrom posthog.hogql.property import action_to_expr, property_to_expr+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.experiments.hogql_aggregation_utils import (aggregation_needs_numeric_input,build_aggregation_call,@@ -135,11 +136,13 @@ def get_source_value_expr(source: Union[EventsNode, ActionsNode, ExperimentDataW# Extract the inner expression from the HogQL expressionmath_hogql = source.math_hogqlif math_hogql:+ tag_contains_user_hogql()_, inner_expr, _, _ = extract_aggregation_and_inner_expr(math_hogql)return inner_exprelif isinstance(source, ExperimentDataWarehouseNode):metric_property = getattr(source, "math_property", None)if metric_property:+ tag_contains_user_hogql()return parse_expr(metric_property)# Default to count - emit 1 so we can easily sum it up@@ -350,6 +353,7 @@ def get_source_aggregation_expr(elif math_type == ExperimentMetricMathType.HOGQL:math_hogql = getattr(source, "math_hogql", None)if math_hogql is not None:+ tag_contains_user_hogql()aggregation_function, _, params, distinct = extract_aggregation_and_inner_expr(math_hogql)if aggregation_function:inner_value_expr = parse_expr(f"{table_alias}.value")diff --git a/posthog/hogql_queries/experiments/metric_source.py b/posthog/hogql_queries/experiments/metric_source.pyindex 394298a9c118..9b6487e2d69d 100644--- a/posthog/hogql_queries/experiments/metric_source.py+++ b/posthog/hogql_queries/experiments/metric_source.py@@ -13,6 +13,8 @@ from posthog.schema import ActionsNode, EventsNode, ExperimentDataWarehouseNodefrom posthog.hogql import astfrom posthog.hogql.parser import parse_expr+from posthog.clickhouse.query_tagging import tag_contains_user_hogql+@dataclassclass MetricSourceInfo:@@ -73,6 +75,8 @@ class MetricSourceInfo:"""if isinstance(source, ExperimentDataWarehouseNode):# Datawarehouse sources always use their own join key, ignore entity_key parameter+ # `data_warehouse_join_key` is the user-supplied HogQL parsed below.+ tag_contains_user_hogql()return cls(kind="datawarehouse",table_name=source.table_name,diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.pyindex 08aef8f07092..cdb4a30a2899 100644--- a/posthog/hogql_queries/hogql_query_runner.py+++ b/posthog/hogql_queries/hogql_query_runner.py@@ -23,6 +23,7 @@ from posthog.hogql.variables import replace_variablesfrom posthog import settings as app_settingsfrom posthog.caching.utils import ThresholdMode, staleness_threshold_map+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner@@ -90,6 +91,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):return self.to_query()def _calculate(self) -> HogQLQueryResponse:+ tag_contains_user_hogql()if (self.is_query_serviceand app_settings.API_QUERIES_LEGACY_TEAM_LISTdiff --git a/posthog/hogql_queries/insights/funnels/funnel_event_query.py b/posthog/hogql_queries/insights/funnels/funnel_event_query.pyindex a355a680433f..e74aba1fe7e2 100644--- a/posthog/hogql_queries/insights/funnels/funnel_event_query.py+++ b/posthog/hogql_queries/insights/funnels/funnel_event_query.py@@ -28,6 +28,7 @@ from posthog.hogql.parser import parse_exprfrom posthog.hogql.property import action_to_expr, property_to_exprfrom posthog.clickhouse.materialized_columns import ColumnName+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.insights.funnels.funnel_aggregation_operations import FirstTimeForUserAggregationQueryfrom posthog.hogql_queries.insights.funnels.funnel_query_context import FunnelQueryContextfrom posthog.hogql_queries.insights.funnels.utils import (@@ -244,6 +245,7 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):detail=f"Unsupported timestamp field type for {table_entity.table_name}.{table_entity.timestamp_field}")+ tag_contains_user_hogql()select: list[ast.Expr] = [ast.Alias(alias="timestamp",@@ -558,6 +560,7 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):# Aggregating by HogQLelif funnelsFilter.funnelAggregateByHogQL and funnelsFilter.funnelAggregateByHogQL != "person_id":+ tag_contains_user_hogql()aggregation_target = parse_expr(funnelsFilter.funnelAggregateByHogQL)if isinstance(aggregation_target, str):diff --git a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py b/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.pyindex c12cab3a2f28..032f744a9ed2 100644--- a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py+++ b/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py@@ -27,6 +27,7 @@ from posthog.hogql.property import action_to_expr, property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.caching.insights_api import BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL, REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.insights.lifecycle.lifecycle_validation_rules import (RequireLifecycleDataWarehouseSeriesForCustomAggregationTarget,)@@ -290,6 +291,7 @@ class LifecycleQueryRunner(AnalyticsQueryRunner[LifecycleQueryResponse]):@propertydef timestamp_field(self) -> ast.Expr:if self.is_data_warehouse_series:+ tag_contains_user_hogql()return parse_expr(self.data_warehouse_series.timestamp_field)return ast.Field(chain=["events", "timestamp"])@@ -408,6 +410,7 @@ class LifecycleQueryRunner(AnalyticsQueryRunner[LifecycleQueryResponse]):@propertydef target_field(self):if self.is_data_warehouse_series:+ tag_contains_user_hogql()return parse_expr(self.data_warehouse_series.aggregation_target_field)if self.has_group_type:return ast.Field(chain=["events", f"$group_{self.group_type_index}"])@@ -417,6 +420,7 @@ class LifecycleQueryRunner(AnalyticsQueryRunner[LifecycleQueryResponse]):def created_at_field(self):"""Returns the correct created_at field to use based on aggregation type."""if self.is_data_warehouse_series:+ tag_contains_user_hogql()return parse_expr(self.data_warehouse_series.created_at_field)if self.has_group_type:return ast.Field(chain=["events", f"group_{self.group_type_index}", "created_at"])diff --git a/posthog/hogql_queries/insights/trends/aggregation_operations.py b/posthog/hogql_queries/insights/trends/aggregation_operations.pyindex cdff40063e93..34ee9e8b24f8 100644--- a/posthog/hogql_queries/insights/trends/aggregation_operations.py+++ b/posthog/hogql_queries/insights/trends/aggregation_operations.py@@ -16,6 +16,7 @@ from posthog.hogql.database.schema.exchange_rate import convert_currency_callfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.placeholders import replace_placeholders+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.constants import NON_TIME_SERIES_DISPLAY_TYPESfrom posthog.hogql_queries.insights.data_warehouse_mixin import DataWarehouseInsightQueryMixinfrom posthog.hogql_queries.insights.trends.utils import is_groups_math@@ -74,6 +75,7 @@ class AggregationOperations(DataWarehouseInsightQueryMixin):def select_aggregation(self) -> ast.Expr:if self.series.math == "hogql" and self.series.math_hogql is not None:+ tag_contains_user_hogql()parsed = parse_expr(self.series.math_hogql)# An outer alias on the user expression (`avg(x) as foo`) is shadowed by the# `AS total` wrap added downstream. If we leave it in place, ClickHouse'sdiff --git a/posthog/hogql_queries/insights/trends/breakdown.py b/posthog/hogql_queries/insights/trends/breakdown.pyindex 6b6a8f144364..a91f394803f5 100644--- a/posthog/hogql_queries/insights/trends/breakdown.py+++ b/posthog/hogql_queries/insights/trends/breakdown.py@@ -21,6 +21,7 @@ from posthog.hogql.parser import parse_exprfrom posthog.hogql.property import apply_path_cleaningfrom posthog.hogql.timings import HogQLTimings+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.insights.trends.display import TrendsDisplayfrom posthog.hogql_queries.insights.trends.utils import get_properties_chainfrom posthog.hogql_queries.insights.utils.breakdowns import (@@ -307,6 +308,8 @@ class Breakdown:is_numeric_breakdown = isinstance(histogram_bin_count, int)+ if breakdown_type == "hogql":+ tag_contains_user_hogql()if breakdown_type == "hogql" or breakdown_type == "event_metadata":left = strip_user_aliases(parse_expr(breakdown_value))else:@@ -418,6 +421,8 @@ class Breakdown:expr=hogql_to_string(ast.Constant(value=cohort_breakdown)),)+ if breakdown_type == "hogql":+ tag_contains_user_hogql()if breakdown_type == "hogql" or breakdown_type == "event_metadata":inner = strip_user_aliases(parse_expr(cast(str, value)))return ast.Alias(alias=alias, expr=self._get_breakdown_values_transform(inner))diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 399e6c5e1dd4..2ada15261ca1 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -122,7 +122,7 @@ logger = structlog.get_logger(__name__)QUERY_EXECUTION_TOTAL = Counter("posthog_query_execution_total","Query executions by category",- labelnames=["query_type", "category", "error_type"],+ labelnames=["query_type", "category", "error_type", "contains_user_hogql"],)QUERY_EXECUTION_DURATION = Histogram(@@ -145,6 +145,14 @@ SURVEY_QUERY_EXECUTION_DURATION = Histogram(buckets=[0.05, 0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 20.0, 30.0, 60.0, 120.0],)++def _contains_user_hogql_label() -> str:+ # Read the tag set by `tag_contains_user_hogql()` at HogQL parse sites; lets+ # observability split user-HogQL failures from query-builder failures on the+ # same metric. The tag is the canonical source — see `posthog.clickhouse.query_tagging`.+ return "true" if get_query_tag_value("contains_user_hogql") else "false"++EXTENDED_CACHE_AGE = timedelta(days=1)@@ -1660,7 +1668,12 @@ class QueryRunner(ABC, Generic[Q, R, CR]):query_start = perf_counter()try:query_result, query_duration_ms = self._call_with_rate_limits(dashboard_id=dashboard_id)- QUERY_EXECUTION_TOTAL.labels(query_type=query_type, category="success", error_type="none").inc()+ QUERY_EXECUTION_TOTAL.labels(+ query_type=query_type,+ category="success",+ error_type="none",+ contains_user_hogql=_contains_user_hogql_label(),+ ).inc()if survey_query_metric_labels:SURVEY_QUERY_EXECUTION_TOTAL.labels(**survey_query_metric_labels, category="success", error_type="none"@@ -1670,6 +1683,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):query_type=query_type,category=classify_query_error(e),error_type=clickhouse_error_type(e),+ contains_user_hogql=_contains_user_hogql_label(),).inc()if survey_query_metric_labels:SURVEY_QUERY_EXECUTION_TOTAL.labels(diff --git a/posthog/hogql_queries/sessions_query_runner.py b/posthog/hogql_queries/sessions_query_runner.pyindex 6a527d011760..665b3e17b110 100644--- a/posthog/hogql_queries/sessions_query_runner.py+++ b/posthog/hogql_queries/sessions_query_runner.py@@ -18,6 +18,7 @@ from posthog.hogql.parser import parse_expr, parse_order_exprfrom posthog.hogql.property import action_to_expr, has_aggregation, map_virtual_properties, property_to_exprfrom posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.models import Person@@ -609,6 +610,8 @@ class SessionsQueryRunner(AnalyticsQueryRunner[SessionsQueryResponse]):return stmtdef _calculate(self) -> SessionsQueryResponse:+ # `SessionsQuery.select`, `where`, `orderBy` are user-supplied HogQL strings.+ tag_contains_user_hogql()query_result = self.paginator.execute_hogql_query(query=self.to_query(),team=self.team,diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex 0eabd0da819b..a8337434a59d 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -487,8 +487,13 @@ class TestQueryRunner(BaseTest):])def test_query_execution_metrics(self, _name, calculate_mode, expected_exception, success_delta, failure_delta):+ from posthog.clickhouse.query_tagging import reset_query_tagsfrom posthog.hogql_queries.query_runner import QUERY_EXECUTION_DURATION, QUERY_EXECUTION_TOTAL+ # Sibling tests in this class invoke real HogQL runners that flip+ # `contains_user_hogql` on the ContextVar; reset so we observe "false".+ reset_query_tags()+TestQueryRunner = self.setup_test_query_runner_class()if calculate_mode == "error":TestQueryRunner.calculate = lambda self: TheTestBasicQueryResponse(results=[], error="Some error occurred")@@ -501,10 +506,10 @@ class TestQueryRunner(BaseTest):runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)before_success = QUERY_EXECUTION_TOTAL.labels(- query_type="TestQuery", category="success", error_type="none"+ query_type="TestQuery", category="success", error_type="none", contains_user_hogql="false")._value.get()before_failure = QUERY_EXECUTION_TOTAL.labels(- query_type="TestQuery", category="error", error_type="ValueError"+ query_type="TestQuery", category="error", error_type="ValueError", contains_user_hogql="false")._value.get()before_duration_sum = QUERY_EXECUTION_DURATION.labels(query_type="TestQuery")._sum.get()@@ -515,17 +520,77 @@ class TestQueryRunner(BaseTest):runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)assert (- QUERY_EXECUTION_TOTAL.labels(query_type="TestQuery", category="success", error_type="none")._value.get()+ QUERY_EXECUTION_TOTAL.labels(+ query_type="TestQuery", category="success", error_type="none", contains_user_hogql="false"+ )._value.get()- before_success== success_delta)assert (- QUERY_EXECUTION_TOTAL.labels(query_type="TestQuery", category="error", error_type="ValueError")._value.get()+ QUERY_EXECUTION_TOTAL.labels(+ query_type="TestQuery", category="error", error_type="ValueError", contains_user_hogql="false"+ )._value.get()- before_failure== failure_delta)assert QUERY_EXECUTION_DURATION.labels(query_type="TestQuery")._sum.get() > before_duration_sum+ @parameterized.expand([("success_path", None), ("error_path", ValueError)])+ def test_query_execution_metric_labels_with_contains_user_hogql(+ self, _name: str, expected_exception: Optional[type[Exception]]+ ) -> None:+ # Verifies the `contains_user_hogql` label flows from the canonical+ # `QueryTags.contains_user_hogql` tag (set by `tag_contains_user_hogql()`+ # at HogQL parse sites) rather than being recomputed schema-side.+ from posthog.clickhouse.query_tagging import reset_query_tags, tag_contains_user_hogql+ from posthog.hogql_queries.query_runner import QUERY_EXECUTION_TOTAL++ TestQueryRunner = self.setup_test_query_runner_class()++ if expected_exception is None:++ def calculate_tags(self: Any) -> Any:+ tag_contains_user_hogql()+ return TheTestBasicQueryResponse(results=[])++ TestQueryRunner.calculate = calculate_tags+ label_kwargs = {+ "query_type": "TestQuery",+ "category": "success",+ "error_type": "none",+ "contains_user_hogql": "true",+ }+ else:++ def calculate_tags_then_raise(self: Any) -> Any:+ tag_contains_user_hogql()+ raise ValueError("boom")++ TestQueryRunner.calculate = calculate_tags_then_raise+ label_kwargs = {+ "query_type": "TestQuery",+ "category": "error",+ "error_type": "ValueError",+ "contains_user_hogql": "true",+ }++ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)+ # ContextVar persists across tests; reset both before (so we observe a real+ # transition false→true via calculate) and after (so siblings don't see "true").+ reset_query_tags()+ before = QUERY_EXECUTION_TOTAL.labels(**label_kwargs)._value.get()++ try:+ if expected_exception:+ with pytest.raises(expected_exception):+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ else:+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)++ assert QUERY_EXECUTION_TOTAL.labels(**label_kwargs)._value.get() - before == 1+ finally:+ reset_query_tags()+@parameterized.expand([(@@ -560,8 +625,12 @@ class TestQueryRunner(BaseTest):assert completed_kwargs["extra_properties"]["error_category"] == expected_error_categorydef test_query_execution_metrics_not_recorded_on_cache_hit(self):+ from posthog.clickhouse.query_tagging import reset_query_tagsfrom posthog.hogql_queries.query_runner import QUERY_EXECUTION_DURATION, QUERY_EXECUTION_TOTAL+ # Sibling tests may have flipped `contains_user_hogql` on the ContextVar.+ reset_query_tags()+TestQueryRunner = self.setup_test_query_runner_class()runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)@@ -569,10 +638,10 @@ class TestQueryRunner(BaseTest):runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)before_success = QUERY_EXECUTION_TOTAL.labels(- query_type="TestQuery", category="success", error_type="none"+ query_type="TestQuery", category="success", error_type="none", contains_user_hogql="false")._value.get()before_failure = QUERY_EXECUTION_TOTAL.labels(- query_type="TestQuery", category="error", error_type="ValueError"+ query_type="TestQuery", category="error", error_type="ValueError", contains_user_hogql="false")._value.get()before_duration_sum = QUERY_EXECUTION_DURATION.labels(query_type="TestQuery")._sum.get()@@ -581,11 +650,15 @@ class TestQueryRunner(BaseTest):runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)assert (- QUERY_EXECUTION_TOTAL.labels(query_type="TestQuery", category="success", error_type="none")._value.get()+ QUERY_EXECUTION_TOTAL.labels(+ query_type="TestQuery", category="success", error_type="none", contains_user_hogql="false"+ )._value.get()== before_success)assert (- QUERY_EXECUTION_TOTAL.labels(query_type="TestQuery", category="error", error_type="ValueError")._value.get()+ QUERY_EXECUTION_TOTAL.labels(+ query_type="TestQuery", category="error", error_type="ValueError", contains_user_hogql="false"+ )._value.get()== before_failure)assert QUERY_EXECUTION_DURATION.labels(query_type="TestQuery")._sum.get() == before_duration_sumdiff --git a/products/customer_analytics/backend/hogql_queries/usage_metrics_query_runner.py b/products/customer_analytics/backend/hogql_queries/usage_metrics_query_runner.pyindex 1d5c85f22b6d..1efd08c1a4e6 100644--- a/products/customer_analytics/backend/hogql_queries/usage_metrics_query_runner.py+++ b/products/customer_analytics/backend/hogql_queries/usage_metrics_query_runner.py@@ -8,6 +8,7 @@ from posthog.schema import CachedUsageMetricsQueryResponse, UsageMetric, UsageMefrom posthog.hogql import astfrom posthog.hogql.parser import parse_expr+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.models.group_usage_metric import GroupUsageMetric@@ -215,6 +216,7 @@ class UsageMetricsQueryRunner(AnalyticsQueryRunner[UsageMetricsQueryResponse]):timestamp_field = source_descriptor[2]if not timestamp_field:raise ValueError("data_warehouse usage metric is missing 'timestamp_field' in filters")+ tag_contains_user_hogql()return parse_expr(timestamp_field)return ast.Field(chain=["timestamp"])@@ -253,6 +255,7 @@ class UsageMetricsQueryRunner(AnalyticsQueryRunner[UsageMetricsQueryResponse]):if metric.math == GroupUsageMetric.Math.SUM:if metric.is_data_warehouse:+ tag_contains_user_hogql()value_arg: ast.Expr = ast.Call(name="toFloat", args=[parse_expr(metric.math_property)])else:value_arg = ast.Call(name="toFloat", args=[ast.Field(chain=["properties", metric.math_property])])@@ -336,6 +339,7 @@ class UsageMetricsQueryRunner(AnalyticsQueryRunner[UsageMetricsQueryResponse]):key_field = source_descriptor[3]if not key_field:raise ValueError("data_warehouse usage metric is missing 'key_field' in filters")+ tag_contains_user_hogql()return ast.CompareOperation(op=ast.CompareOperationOp.Eq,left=parse_expr(key_field),diff --git a/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py b/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.pyindex 744c3357402a..14ed190c02f8 100644--- a/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py+++ b/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py@@ -29,6 +29,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.timings import HogQLTimingsfrom posthog.caching.insights_api import BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL, REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL+from posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.constants import HOGQL, PAGEVIEW_EVENT, SCREEN_EVENTfrom posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunnerfrom posthog.hogql_queries.insights.funnels.utils import funnel_window_interval_unit_to_sql@@ -129,6 +130,7 @@ class PathsQueryRunner(AnalyticsQueryRunner[PathsQueryResponse]):event_hogql: ast.Expr = parse_expr("event")if self._should_query_event(HOGQL) and self.query.pathsFilter.pathsHogQLExpression:+ tag_contains_user_hogql()event_hogql = parse_expr(self.query.pathsFilter.pathsHogQLExpression)if self._should_query_event(PAGEVIEW_EVENT):@@ -219,6 +221,7 @@ class PathsQueryRunner(AnalyticsQueryRunner[PathsQueryResponse]):# HogQL aggregation (currently only properties.$session_id is exposed in the UI,# but funnelAggregateByHogQL supports arbitrary expressions).if funnelsFilter.funnelAggregateByHogQL and funnelsFilter.funnelAggregateByHogQL != "person_id":+ tag_contains_user_hogql()return parse_expr(funnelsFilter.funnelAggregateByHogQL)# Default: person aggregation