: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(metrics): add MetricsQuery node kind with facade-backed runner (#69445)
Daniel Visca5ed2e0d59474
diff --git a/frontend/src/queries/Query/Query.tsx b/frontend/src/queries/Query/Query.tsxindex f6e953699f63..8b1013c424d3 100644--- a/frontend/src/queries/Query/Query.tsx+++ b/frontend/src/queries/Query/Query.tsx@@ -24,6 +24,7 @@ import {import { QueryContext } from '~/queries/types'import { EndpointsUsageOverviewNode, EndpointsUsageTrendsNode } from 'products/endpoints/frontend/nodes'+import { MetricsQueryNode } from 'products/metrics/frontend/nodes'import {RevenueAnalyticsGrossRevenueNode,RevenueAnalyticsMRRNode,@@ -42,6 +43,7 @@ import {isHogQuery,isInsightVizNode,isMarketingAnalyticsAggregatedQuery,+ isMetricsQuery,isRevenueAnalyticsGrossRevenueQuery,isRevenueAnalyticsMRRQuery,isRevenueAnalyticsMetricsQuery,@@ -232,6 +234,15 @@ export function Query<Q extends Node>(props: QueryProps<Q>): JSX.Element | nullcontext={queryContext}/>)+ } else if (isMetricsQuery(query)) {+ component = (+ <MetricsQueryNode+ attachTo={props.attachTo}+ query={query}+ cachedResults={props.cachedResults}+ context={queryContext}+ />+ )} else if (isEndpointsUsageOverviewQuery(query)) {component = (<EndpointsUsageOverviewNodediff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 94734241b4cf..a29ad7217c52 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -914,6 +914,9 @@{"$ref": "#/definitions/LogValuesQuery"},+ {+ "$ref": "#/definitions/MetricsQuery"+ },{"$ref": "#/definitions/TraceSpansQuery"},@@ -1213,6 +1216,9 @@{"$ref": "#/definitions/LogValuesQueryResponse"},+ {+ "$ref": "#/definitions/MetricsQueryResponse"+ },{"$ref": "#/definitions/TraceSpansQueryResponse"},@@ -9131,6 +9137,99 @@],"type": "object"},+ "CachedMetricsQueryResponse": {+ "additionalProperties": false,+ "properties": {+ "cache_key": {+ "type": "string"+ },+ "cache_target_age": {+ "format": "date-time",+ "type": "string"+ },+ "calculation_trigger": {+ "description": "What triggered the calculation of the query, leave empty if user/immediate",+ "type": "string"+ },+ "error": {+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",+ "type": "string"+ },+ "hogql": {+ "description": "Generated HogQL query.",+ "type": "string"+ },+ "is_cached": {+ "type": "boolean"+ },+ "last_refresh": {+ "format": "date-time",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "next_allowed_client_refresh": {+ "format": "date-time",+ "type": "string"+ },+ "query_metadata": {+ "type": "object"+ },+ "query_status": {+ "$ref": "#/definitions/QueryStatus",+ "description": "Query status indicates whether next to the provided data, a query is still running."+ },+ "resolved_compare_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The resolved previous/comparison period date range, when comparing against another period"+ },+ "resolved_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "items": {+ "$ref": "#/definitions/MetricsQuerySeries"+ },+ "type": "array"+ },+ "timezone": {+ "type": "string"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ },+ "warnings": {+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",+ "items": {+ "anyOf": [+ {+ "$ref": "#/definitions/DataWarehouseSyncWarning"+ },+ {+ "$ref": "#/definitions/AccessControlFilterWarning"+ }+ ]+ },+ "type": "array"+ }+ },+ "required": [+ "cache_key",+ "is_cached",+ "last_refresh",+ "next_allowed_client_refresh",+ "results",+ "timezone"+ ],+ "type": "object"+ },"CachedNewExperimentQueryResponse": {"additionalProperties": false,"properties": {@@ -31461,6 +31560,226 @@"required": ["key", "operator", "type"],"type": "object"},+ "MetricsAggregation": {+ "enum": ["sum", "avg", "count", "min", "max", "quantile", "rate", "increase", "histogram_quantile"],+ "type": "string"+ },+ "MetricsAttributeScope": {+ "description": "Which attribute map a metric label key lives in; `auto` resolves resource attributes first, then datapoint attributes.",+ "enum": ["resource", "attribute", "auto"],+ "type": "string"+ },+ "MetricsFilterOp": {+ "enum": ["eq", "neq", "regex", "not_regex"],+ "type": "string"+ },+ "MetricsQuery": {+ "additionalProperties": false,+ "properties": {+ "clauses": {+ "items": {+ "$ref": "#/definitions/MetricsQueryClause"+ },+ "type": "array"+ },+ "dateRange": {+ "$ref": "#/definitions/DateRange",+ "description": "Defaults to the last 24 hours when omitted; dashboard date filters override it"+ },+ "formula": {+ "description": "Arithmetic over clause aliases (e.g. \"a / b\"); when set, only the formula series are returned",+ "type": "string"+ },+ "interval": {+ "description": "Bucket size, one of: second, minute, minute_5, minute_15, hour, hour_6, day, week; auto-picked from the range when omitted",+ "type": "string"+ },+ "kind": {+ "const": "MetricsQuery",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "response": {+ "$ref": "#/definitions/MetricsQueryResponse"+ },+ "tags": {+ "$ref": "#/definitions/QueryLogTags"+ },+ "version": {+ "description": "version of the node, used for schema migrations",+ "type": "number"+ }+ },+ "required": ["clauses", "kind"],+ "type": "object"+ },+ "MetricsQueryClause": {+ "additionalProperties": false,+ "properties": {+ "aggregation": {+ "$ref": "#/definitions/MetricsAggregation"+ },+ "filters": {+ "items": {+ "$ref": "#/definitions/MetricsQueryFilter"+ },+ "type": "array"+ },+ "groupBy": {+ "items": {+ "$ref": "#/definitions/MetricsQueryGroupBy"+ },+ "type": "array"+ },+ "metricName": {+ "type": "string"+ },+ "name": {+ "description": "Alias a formula refers to (e.g. \"a\"); must be unique within the query",+ "type": "string"+ },+ "quantile": {+ "description": "In (0, 1); required for `quantile` / `histogram_quantile` aggregations",+ "type": "number"+ }+ },+ "required": ["name", "metricName", "aggregation"],+ "type": "object"+ },+ "MetricsQueryFilter": {+ "additionalProperties": false,+ "properties": {+ "key": {+ "type": "string"+ },+ "op": {+ "$ref": "#/definitions/MetricsFilterOp"+ },+ "scope": {+ "$ref": "#/definitions/MetricsAttributeScope"+ },+ "value": {+ "type": "string"+ }+ },+ "required": ["key", "op", "value"],+ "type": "object"+ },+ "MetricsQueryGroupBy": {+ "additionalProperties": false,+ "properties": {+ "key": {+ "type": "string"+ },+ "scope": {+ "$ref": "#/definitions/MetricsAttributeScope"+ }+ },+ "required": ["key"],+ "type": "object"+ },+ "MetricsQueryPoint": {+ "additionalProperties": false,+ "properties": {+ "time": {+ "description": "Bucket start, ISO 8601",+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": ["time", "value"],+ "type": "object"+ },+ "MetricsQueryResponse": {+ "additionalProperties": false,+ "properties": {+ "error": {+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",+ "type": "string"+ },+ "hogql": {+ "description": "Generated HogQL query.",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "query_status": {+ "$ref": "#/definitions/QueryStatus",+ "description": "Query status indicates whether next to the provided data, a query is still running."+ },+ "resolved_compare_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The resolved previous/comparison period date range, when comparing against another period"+ },+ "resolved_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "items": {+ "$ref": "#/definitions/MetricsQuerySeries"+ },+ "type": "array"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ },+ "warnings": {+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",+ "items": {+ "anyOf": [+ {+ "$ref": "#/definitions/DataWarehouseSyncWarning"+ },+ {+ "$ref": "#/definitions/AccessControlFilterWarning"+ }+ ]+ },+ "type": "array"+ }+ },+ "required": ["results"],+ "type": "object"+ },+ "MetricsQuerySeries": {+ "additionalProperties": false,+ "properties": {+ "clause": {+ "description": "Clause alias that produced this series (`formula` for the formula result)",+ "type": "string"+ },+ "labels": {+ "additionalProperties": {+ "type": "string"+ },+ "description": "Label values identifying this series; empty for an ungrouped query",+ "type": "object"+ },+ "metricName": {+ "type": "string"+ },+ "points": {+ "items": {+ "$ref": "#/definitions/MetricsQueryPoint"+ },+ "type": "array"+ }+ },+ "required": ["labels", "points"],+ "type": "object"+ },"MinimalHedgehogConfig": {"additionalProperties": false,"properties": {@@ -31802,6 +32121,7 @@"LogsQuery","LogAttributesQuery","LogValuesQuery",+ "MetricsQuery","TraceSpansQuery","TraceSpansAggregationQuery","TraceSpansTreeQuery",@@ -38819,6 +39139,64 @@"required": ["results"],"type": "object"},+ {+ "additionalProperties": false,+ "properties": {+ "error": {+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",+ "type": "string"+ },+ "hogql": {+ "description": "Generated HogQL query.",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "query_status": {+ "$ref": "#/definitions/QueryStatus",+ "description": "Query status indicates whether next to the provided data, a query is still running."+ },+ "resolved_compare_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The resolved previous/comparison period date range, when comparing against another period"+ },+ "resolved_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "items": {+ "$ref": "#/definitions/MetricsQuerySeries"+ },+ "type": "array"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ },+ "warnings": {+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",+ "items": {+ "anyOf": [+ {+ "$ref": "#/definitions/DataWarehouseSyncWarning"+ },+ {+ "$ref": "#/definitions/AccessControlFilterWarning"+ }+ ]+ },+ "type": "array"+ }+ },+ "required": ["results"],+ "type": "object"+ },{"additionalProperties": false,"properties": {@@ -40655,6 +41033,9 @@{"$ref": "#/definitions/LogValuesQuery"},+ {+ "$ref": "#/definitions/MetricsQuery"+ },{"$ref": "#/definitions/TraceSpansQuery"},diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 1655df53803c..6ae13be8ff22 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -111,6 +111,7 @@ export enum NodeKind {LogsQuery = 'LogsQuery',LogAttributesQuery = 'LogAttributesQuery',LogValuesQuery = 'LogValuesQuery',+ MetricsQuery = 'MetricsQuery',TraceSpansQuery = 'TraceSpansQuery',TraceSpansAggregationQuery = 'TraceSpansAggregationQuery',TraceSpansTreeQuery = 'TraceSpansTreeQuery',@@ -249,6 +250,7 @@ export type AnyDataNode =| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery@@ -360,6 +362,9 @@ export type QuerySchema =| LogAttributesQuery| LogValuesQuery+ // Metrics+ | MetricsQuery+// Tracing| TraceSpansQuery| TraceSpansAggregationQuery@@ -434,6 +439,7 @@ export type AnyResponseType =| LogsQueryResponse| LogAttributesQueryResponse| LogValuesQueryResponse+ | MetricsQueryResponse| TraceSpansQueryResponse| TraceSpansAggregationQueryResponse| TraceSpansTreeQueryResponse@@ -3499,6 +3505,76 @@ export interface LogValuesQuery extends DataNode<LogValuesQueryResponse> {attributeType: string}+/** Which attribute map a metric label key lives in; `auto` resolves resource attributes first, then datapoint attributes. */+export type MetricsAttributeScope = 'resource' | 'attribute' | 'auto'++export type MetricsFilterOp = 'eq' | 'neq' | 'regex' | 'not_regex'++export type MetricsAggregation =+ | 'sum'+ | 'avg'+ | 'count'+ | 'min'+ | 'max'+ | 'quantile'+ | 'rate'+ | 'increase'+ | 'histogram_quantile'++export interface MetricsQueryFilter {+ key: string+ op: MetricsFilterOp+ value: string+ scope?: MetricsAttributeScope+}++export interface MetricsQueryGroupBy {+ key: string+ scope?: MetricsAttributeScope+}++export interface MetricsQueryClause {+ /** Alias a formula refers to (e.g. "a"); must be unique within the query */+ name: string+ metricName: string+ aggregation: MetricsAggregation+ filters?: MetricsQueryFilter[]+ groupBy?: MetricsQueryGroupBy[]+ /** In (0, 1); required for `quantile` / `histogram_quantile` aggregations */+ quantile?: number+}++export interface MetricsQueryPoint {+ /** Bucket start, ISO 8601 */+ time: string+ value: number+}++export interface MetricsQuerySeries {+ /** Label values identifying this series; empty for an ungrouped query */+ labels: Record<string, string>+ points: MetricsQueryPoint[]+ metricName?: string+ /** Clause alias that produced this series (`formula` for the formula result) */+ clause?: string+}++export interface MetricsQueryResponse extends AnalyticsQueryResponseBase {+ results: MetricsQuerySeries[]+}+export type CachedMetricsQueryResponse = CachedQueryResponse<MetricsQueryResponse>++export interface MetricsQuery extends DataNode<MetricsQueryResponse> {+ kind: NodeKind.MetricsQuery+ clauses: MetricsQueryClause[]+ /** Defaults to the last 24 hours when omitted; dashboard date filters override it */+ dateRange?: DateRange+ /** Bucket size, one of: second, minute, minute_5, minute_15, hour, hour_6, day, week; auto-picked from the range when omitted */+ interval?: string+ /** Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned */+ formula?: string+}+export interface SessionEventsItem {/** Session ID these events belong to */session_id: stringdiff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.tsindex c841f894f71b..78c218214655 100644--- a/frontend/src/queries/utils.ts+++ b/frontend/src/queries/utils.ts@@ -45,6 +45,7 @@ import {MarketingAnalyticsAggregatedQuery,MarketingAnalyticsTableQuery,MathType,+ MetricsQuery,Node,NodeKind,NonIntegratedConversionsTableQuery,@@ -253,6 +254,10 @@ export function isRevenueAnalyticsTopCustomersQuery(return node?.kind === NodeKind.RevenueAnalyticsTopCustomersQuery}+export function isMetricsQuery(node?: Record<string, any> | null): node is MetricsQuery {+ return node?.kind === NodeKind.MetricsQuery+}+export function isEndpointsUsageOverviewQuery(node?: Record<string, any> | null): node is EndpointsUsageOverviewQuery {return node?.kind === NodeKind.EndpointsUsageOverviewQuery}diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsxindex e10344e75c55..d1c6e25ca301 100644--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx@@ -552,6 +552,12 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {icon: IconLive,inMenu: false,},+ [NodeKind.MetricsQuery]: {+ name: 'Metrics',+ description: 'Chart a service metric over time',+ icon: IconLive,+ inMenu: false,+ },[NodeKind.TraceSpansQuery]: {name: 'Trace Spans',icon: IconLive,diff --git a/posthog/api/query.py b/posthog/api/query.pyindex 227c4cb69226..be78825261e8 100644--- a/posthog/api/query.py+++ b/posthog/api/query.py@@ -132,6 +132,14 @@ def _process_query_request(return query, query_id, execution_mode+# Query kinds whose product exposes its own scoped API keep scope parity here: an+# API token must hold the product scope, not just query:read, to run them through+# the generic endpoint.+_QUERY_KIND_SCOPES: dict[str, list[str]] = {+ "MetricsQuery": ["metrics:read"],+}++class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):# NOTE: Do we need to override the scopes for the "create"scope_object = "query"@@ -141,6 +149,13 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMiscope_object_write_actions: list[str] = []sharing_enabled_actions = ["retrieve"]+ def dangerously_get_required_scopes(self, request, view) -> list[str] | None:+ if getattr(view, "action", None) != "create":+ return None+ query = request.data.get("query") if isinstance(request.data, dict) else None+ kind = query.get("kind") if isinstance(query, dict) else None+ return _QUERY_KIND_SCOPES.get(kind) if isinstance(kind, str) else None+def get_throttles(self):if self.action == "draft_sql":return [AIBurstRateThrottle(), AISustainedRateThrottle()]diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 0b82dde4f578..5989fc59b9c2 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -212,6 +212,8 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:return {"product": Product.ERROR_TRACKING}case NodeKind.LOGS_QUERY | NodeKind.LOG_ATTRIBUTES_QUERY | NodeKind.LOG_VALUES_QUERY:return {"product": Product.LOGS}+ case NodeKind.METRICS_QUERY:+ return {"product": Product.METRICS}case NodeKind.RECORDINGS_QUERY | NodeKind.SESSION_BATCH_EVENTS_QUERY:return {"product": Product.REPLAY}case (diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex bd503f87cb6d..17a73ec245a9 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -51,6 +51,7 @@ from posthog.schema import (MCPToolSampleIntentsQuery,MCPToolStatsQuery,MCPToolTopUsersQuery,+ MetricsQuery,NodeKind,PathsQuery,PropertyGroupFilter,@@ -319,6 +320,7 @@ RunnableQueryNode = Union[EndpointsUsageOverviewQuery,EndpointsUsageTableQuery,EndpointsUsageTrendsQuery,+ MetricsQuery,MCPHarnessBreakdownQuery,MCPToolTopUsersQuery,MCPToolFailuresQuery,@@ -1203,6 +1205,18 @@ def get_query_runner(user=user,)+ if kind == "MetricsQuery":+ from products.metrics.backend.facade.queries import MetricsQueryRunner++ return MetricsQueryRunner(+ query=query,+ team=team,+ timings=timings,+ modifiers=modifiers,+ limit_context=limit_context,+ user=user,+ )+# Registered here for server-side CSV export only (ExportedAsset + Celery).# Direct queries are blocked by LogsQueryRunner.validate_query_runner_access.if kind == "LogsQuery":diff --git a/posthog/schema.py b/posthog/schema.pyindex 3cd1914503a4..44ead9866bc4 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -173,6 +173,9 @@ from posthog.schema_enums import (MetaAdsTableKeywords as MetaAdsTableKeywords,Method as Method,Metric as Metric,+ MetricsAggregation as MetricsAggregation,+ MetricsAttributeScope as MetricsAttributeScope,+ MetricsFilterOp as MetricsFilterOp,MetricSummary as MetricSummary,MrrOrGross as MrrOrGross,MultipleBreakdownType as MultipleBreakdownType,@@ -1990,6 +1993,48 @@ class MaxProductInfo(BaseModel):usage_limit: float | None = None+class MetricsQueryFilter(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ key: str+ op: MetricsFilterOp+ scope: MetricsAttributeScope | None = None+ value: str+++class MetricsQueryGroupBy(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ key: str+ scope: MetricsAttributeScope | None = None+++class MetricsQueryPoint(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ time: str = Field(..., description="Bucket start, ISO 8601")+ value: float+++class MetricsQuerySeries(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ clause: str | None = Field(+ default=None,+ description=("Clause alias that produced this series (`formula` for the formula result)"),+ )+ labels: dict[str, str] = Field(+ ...,+ description=("Label values identifying this series; empty for an ungrouped query"),+ )+ metricName: str | None = None+ points: list[MetricsQueryPoint]++class MinimalHedgehogConfig(BaseModel):model_config = ConfigDict(extra="forbid",@@ -2162,7 +2207,7 @@ class QueryResponseAlternative7(BaseModel):stdout: str | None = None-class QueryResponseAlternative84(BaseModel):+class QueryResponseAlternative85(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -5383,6 +5428,24 @@ class MetricPropertyFilter(BaseModel):value: list[str | float | bool] | str | float | bool | None = None+class MetricsQueryClause(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ aggregation: MetricsAggregation+ filters: list[MetricsQueryFilter] | None = None+ groupBy: list[MetricsQueryGroupBy] | None = None+ metricName: str+ name: str = Field(+ ...,+ description=('Alias a formula refers to (e.g. "a"); must be unique within the query'),+ )+ quantile: float | None = Field(+ default=None,+ description=("In (0, 1); required for `quantile` / `histogram_quantile` aggregations"),+ )++class MultiQuestionFormField(BaseModel):model_config = ConfigDict(extra="forbid",@@ -5604,7 +5667,7 @@ class QueryResponseAlternative29(BaseModel):status: ExternalQueryStatus-class QueryResponseAlternative91(BaseModel):+class QueryResponseAlternative92(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -11146,6 +11209,60 @@ class CachedMarketingAnalyticsTableQueryResponse(BaseModel):)+class CachedMetricsQueryResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ cache_key: str+ cache_target_age: AwareDatetime | None = None+ calculation_trigger: str | None = Field(+ default=None,+ description=("What triggered the calculation of the query, leave empty if user/immediate"),+ )+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ is_cached: bool+ last_refresh: AwareDatetime+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ next_allowed_client_refresh: AwareDatetime+ query_metadata: dict[str, Any] | None = None+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(+ default=None,+ description=("The resolved previous/comparison period date range, when comparing against another period"),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[MetricsQuerySeries]+ timezone: str+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose"+ " latest sync failed, is paused, hit a billing limit, or is otherwise"+ " stale. Results may not reflect current source data. Accumulated"+ " across every HogQL execution that contributes to this response — so"+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"+ " the same warnings as raw HogQL queries. Also carries access control"+ " warnings when a system-table query filters out objects the user can't"+ " access."+ ),+ )++class CachedNonIntegratedConversionsTableQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -17295,6 +17412,49 @@ class MaxBillingContext(BaseModel):usage_history: list[UsageHistoryItem] | None = None+class MetricsQueryResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(+ default=None,+ description=("The resolved previous/comparison period date range, when comparing against another period"),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[MetricsQuerySeries]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose"+ " latest sync failed, is paused, hit a billing limit, or is otherwise"+ " stale. Results may not reflect current source data. Accumulated"+ " across every HogQL execution that contributes to this response — so"+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"+ " the same warnings as raw HogQL queries. Also carries access control"+ " warnings when a system-table query filters out objects the user can't"+ " access."+ ),+ )++class MultiQuestionForm(BaseModel):model_config = ConfigDict(extra="forbid",@@ -20436,6 +20596,49 @@ class QueryResponseAlternative79(BaseModel):class QueryResponseAlternative80(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(+ default=None,+ description=("The resolved previous/comparison period date range, when comparing against another period"),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[MetricsQuerySeries]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose"+ " latest sync failed, is paused, hit a billing limit, or is otherwise"+ " stale. Results may not reflect current source data. Accumulated"+ " across every HogQL execution that contributes to this response — so"+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"+ " the same warnings as raw HogQL queries. Also carries access control"+ " warnings when a system-table query filters out objects the user can't"+ " access."+ ),+ )+++class QueryResponseAlternative81(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20482,7 +20685,7 @@ class QueryResponseAlternative80(BaseModel):)-class QueryResponseAlternative81(BaseModel):+class QueryResponseAlternative82(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20529,7 +20732,7 @@ class QueryResponseAlternative81(BaseModel):)-class QueryResponseAlternative82(BaseModel):+class QueryResponseAlternative83(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20576,7 +20779,7 @@ class QueryResponseAlternative82(BaseModel):)-class QueryResponseAlternative83(BaseModel):+class QueryResponseAlternative84(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20623,7 +20826,7 @@ class QueryResponseAlternative83(BaseModel):)-class QueryResponseAlternative85(BaseModel):+class QueryResponseAlternative86(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20669,7 +20872,7 @@ class QueryResponseAlternative85(BaseModel):)-class QueryResponseAlternative86(BaseModel):+class QueryResponseAlternative87(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20715,7 +20918,7 @@ class QueryResponseAlternative86(BaseModel):)-class QueryResponseAlternative87(BaseModel):+class QueryResponseAlternative88(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20758,7 +20961,7 @@ class QueryResponseAlternative87(BaseModel):)-class QueryResponseAlternative88(BaseModel):+class QueryResponseAlternative89(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20805,7 +21008,7 @@ class QueryResponseAlternative88(BaseModel):)-class QueryResponseAlternative92(BaseModel):+class QueryResponseAlternative93(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20848,7 +21051,7 @@ class QueryResponseAlternative92(BaseModel):)-class QueryResponseAlternative93(BaseModel):+class QueryResponseAlternative94(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20891,7 +21094,7 @@ class QueryResponseAlternative93(BaseModel):)-class QueryResponseAlternative94(BaseModel):+class QueryResponseAlternative95(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20944,7 +21147,7 @@ class QueryResponseAlternative94(BaseModel):)-class QueryResponseAlternative95(BaseModel):+class QueryResponseAlternative96(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20987,7 +21190,7 @@ class QueryResponseAlternative95(BaseModel):)-class QueryResponseAlternative96(BaseModel):+class QueryResponseAlternative97(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21035,7 +21238,7 @@ class QueryResponseAlternative96(BaseModel):)-class QueryResponseAlternative97(BaseModel):+class QueryResponseAlternative98(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21078,7 +21281,7 @@ class QueryResponseAlternative97(BaseModel):)-class QueryResponseAlternative98(BaseModel):+class QueryResponseAlternative99(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21121,7 +21324,7 @@ class QueryResponseAlternative98(BaseModel):)-class QueryResponseAlternative99(BaseModel):+class QueryResponseAlternative100(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21164,7 +21367,7 @@ class QueryResponseAlternative99(BaseModel):)-class QueryResponseAlternative100(BaseModel):+class QueryResponseAlternative101(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21207,7 +21410,7 @@ class QueryResponseAlternative100(BaseModel):)-class QueryResponseAlternative101(BaseModel):+class QueryResponseAlternative102(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21253,7 +21456,7 @@ class QueryResponseAlternative101(BaseModel):)-class QueryResponseAlternative102(BaseModel):+class QueryResponseAlternative103(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21296,7 +21499,7 @@ class QueryResponseAlternative102(BaseModel):)-class QueryResponseAlternative103(BaseModel):+class QueryResponseAlternative104(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21339,7 +21542,7 @@ class QueryResponseAlternative103(BaseModel):)-class QueryResponseAlternative104(BaseModel):+class QueryResponseAlternative105(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21382,7 +21585,7 @@ class QueryResponseAlternative104(BaseModel):)-class QueryResponseAlternative105(BaseModel):+class QueryResponseAlternative106(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -21425,7 +21628,7 @@ class QueryResponseAlternative105(BaseModel):)-class QueryResponseAlternative106(BaseModel):+class QueryResponseAlternative107(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -22807,6 +23010,7 @@ class AnyResponseType(| LogsQueryResponse| LogAttributesQueryResponse| LogValuesQueryResponse+ | MetricsQueryResponse| TraceSpansQueryResponse| TraceSpansAggregationQueryResponse| TraceSpansTreeQueryResponse@@ -22826,6 +23030,7 @@ class AnyResponseType(| LogsQueryResponse| LogAttributesQueryResponse| LogValuesQueryResponse+ | MetricsQueryResponse| TraceSpansQueryResponse| TraceSpansAggregationQueryResponse| TraceSpansTreeQueryResponse@@ -24142,6 +24347,33 @@ class MaxRecordingUniversalFilters(BaseModel):)+class MetricsQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ clauses: list[MetricsQueryClause]+ dateRange: DateRange | None = Field(+ default=None,+ description=("Defaults to the last 24 hours when omitted; dashboard date filters override it"),+ )+ formula: str | None = Field(+ default=None,+ description=('Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned'),+ )+ interval: str | None = Field(+ default=None,+ description=(+ "Bucket size, one of: second, minute, minute_5, minute_15, hour, hour_6,"+ " day, week; auto-picked from the range when omitted"+ ),+ )+ kind: Literal["MetricsQuery"] = "MetricsQuery"+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ response: MetricsQueryResponse | None = None+ tags: QueryLogTags | None = None+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")++class NonIntegratedConversionsTableQuery(BaseModel):model_config = ConfigDict(extra="forbid",@@ -26688,7 +26920,7 @@ class QueryResponseAlternative(| QueryResponseAlternative86| QueryResponseAlternative87| QueryResponseAlternative88- | QueryResponseAlternative91+ | QueryResponseAlternative89| QueryResponseAlternative92| QueryResponseAlternative93| QueryResponseAlternative94@@ -26704,6 +26936,7 @@ class QueryResponseAlternative(| QueryResponseAlternative104| QueryResponseAlternative105| QueryResponseAlternative106+ | QueryResponseAlternative107]):root: (@@ -26791,7 +27024,7 @@ class QueryResponseAlternative(| QueryResponseAlternative86| QueryResponseAlternative87| QueryResponseAlternative88- | QueryResponseAlternative91+ | QueryResponseAlternative89| QueryResponseAlternative92| QueryResponseAlternative93| QueryResponseAlternative94@@ -26807,6 +27040,7 @@ class QueryResponseAlternative(| QueryResponseAlternative104| QueryResponseAlternative105| QueryResponseAlternative106+ | QueryResponseAlternative107)@@ -27858,6 +28092,7 @@ class HogQLAutocomplete(BaseModel):| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery@@ -27956,6 +28191,7 @@ class HogQLMetadata(BaseModel):| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery@@ -28089,6 +28325,7 @@ class MaxInsightContext(BaseModel):| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery@@ -28219,6 +28456,7 @@ class QueryRequest(BaseModel):| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery@@ -28341,6 +28579,7 @@ class QuerySchemaRoot(| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery@@ -28433,6 +28672,7 @@ class QuerySchemaRoot(| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery@@ -28530,6 +28770,7 @@ class QueryUpgradeRequest(BaseModel):| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery@@ -28627,6 +28868,7 @@ class QueryUpgradeResponse(BaseModel):| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery@@ -28905,6 +29147,7 @@ class VisualizationArtifactContent(BaseModel):| LogsQuery| LogAttributesQuery| LogValuesQuery+ | MetricsQuery| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuerydiff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex b691ae94c816..0dad2ddaa1dd 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2468,6 +2468,31 @@ class MetaAdsTableKeywords(StrEnum):CAMPAIGNS = "campaigns"+class MetricsAggregation(StrEnum):+ SUM = "sum"+ AVG = "avg"+ COUNT = "count"+ MIN = "min"+ MAX = "max"+ QUANTILE = "quantile"+ RATE = "rate"+ INCREASE = "increase"+ HISTOGRAM_QUANTILE = "histogram_quantile"+++class MetricsAttributeScope(StrEnum):+ RESOURCE = "resource"+ ATTRIBUTE = "attribute"+ AUTO = "auto"+++class MetricsFilterOp(StrEnum):+ EQ = "eq"+ NEQ = "neq"+ REGEX = "regex"+ NOT_REGEX = "not_regex"++class MultiQuestionFormFieldType(StrEnum):TEXT = "text"NUMBER = "number"@@ -2536,6 +2561,7 @@ class NodeKind(StrEnum):LOGS_QUERY = "LogsQuery"LOG_ATTRIBUTES_QUERY = "LogAttributesQuery"LOG_VALUES_QUERY = "LogValuesQuery"+ METRICS_QUERY = "MetricsQuery"TRACE_SPANS_QUERY = "TraceSpansQuery"TRACE_SPANS_AGGREGATION_QUERY = "TraceSpansAggregationQuery"TRACE_SPANS_TREE_QUERY = "TraceSpansTreeQuery"diff --git a/products/metrics/backend/facade/queries.py b/products/metrics/backend/facade/queries.pynew file mode 100644index 000000000000..55d772864a5a--- /dev/null+++ b/products/metrics/backend/facade/queries.py@@ -0,0 +1,11 @@+"""Query-runner wiring facade for metrics.++Core dispatch (`posthog/hogql_queries/query_runner.py`) imports the runner+through this module so internal modules stay behind the facade seam. Import+lazily at the dispatch site — this module pulls in HogQL machinery that must+stay off the `django.setup()` path.+"""++from products.metrics.backend.metrics_query_runner import MetricsQueryRunner++__all__ = ["MetricsQueryRunner"]diff --git a/products/metrics/backend/metrics_query_runner.py b/products/metrics/backend/metrics_query_runner.pynew file mode 100644index 000000000000..ce96e678a133--- /dev/null+++ b/products/metrics/backend/metrics_query_runner.py@@ -0,0 +1,120 @@+"""Runner for the `MetricsQuery` schema node (insights, dashboards, /query).++A thin translation layer: schema `MetricsQuery` -> facade `MetricQueryRequest`+-> `run_metric_query` -> schema `MetricsQuerySeries`. The single-clause HogQL+engine lives in `metric_query_runner.py` (singular); this runner never+bypasses the facade, so the viewer, MCP tools, and insights all share one+query path.+"""++from datetime import datetime+from typing import TYPE_CHECKING++from posthog.schema import (+ CachedMetricsQueryResponse,+ DashboardFilter,+ DateRange,+ MetricsQuery,+ MetricsQueryPoint,+ MetricsQueryResponse,+ MetricsQuerySeries,+)++from posthog.hogql import ast++from posthog.hogql_queries.query_runner import AnalyticsQueryRunner+from posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.rbac.user_access_control import UserAccessControl++from products.metrics.backend.facade.api import run_metric_query+from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest+from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation++if TYPE_CHECKING:+ from posthog.models import User++# Metrics dashboards are usually about "what is happening now", so the+# node defaults to a tighter window than the analytics-wide -7d.+DEFAULT_DATE_FROM = "-24h"+++class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):+ query: MetricsQuery+ cached_response: CachedMetricsQueryResponse++ def validate_query_runner_access(self, user: "User") -> bool:+ user_access_control = UserAccessControl(user=user, team=self.team)+ return user_access_control.assert_access_level_for_resource("metrics", "viewer")++ def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:+ raise NotImplementedError(+ "MetricsQuery composes one HogQL query per clause via the metrics facade; there is no single statement"+ )++ def _query_date_range(self) -> QueryDateRange:+ # explicitDate keeps second-granular windows intact; without it,+ # QueryDateRange rounds date_to up to end of day.+ date_range = DateRange(+ date_from=(self.query.dateRange.date_from if self.query.dateRange else None) or DEFAULT_DATE_FROM,+ date_to=self.query.dateRange.date_to if self.query.dateRange else None,+ explicitDate=True,+ )+ return QueryDateRange(date_range=date_range, team=self.team, interval=None, now=datetime.now())++ def _to_request(self) -> MetricQueryRequest:+ date_range = self._query_date_range()+ clauses = tuple(+ MetricQueryClause(+ name=clause.name,+ metric_name=clause.metricName,+ aggregation=MetricAggregation(clause.aggregation.value),+ filters=tuple(+ MetricFilter(+ key=f.key,+ op=FilterOp(f.op.value),+ value=f.value,+ scope=AttributeScope(f.scope.value) if f.scope is not None else AttributeScope.AUTO,+ )+ for f in clause.filters or []+ ),+ group_by=tuple(+ MetricGroupBy(+ key=g.key,+ scope=AttributeScope(g.scope.value) if g.scope is not None else AttributeScope.AUTO,+ )+ for g in clause.groupBy or []+ ),+ quantile=clause.quantile,+ )+ for clause in self.query.clauses+ )+ return MetricQueryRequest(+ clauses=clauses,+ date_from=date_range.date_from(),+ date_to=date_range.date_to(),+ interval=self.query.interval,+ formula=self.query.formula,+ )++ def _calculate(self) -> MetricsQueryResponse:+ series = run_metric_query(team=self.team, request=self._to_request())+ return MetricsQueryResponse(+ results=[+ MetricsQuerySeries(+ labels=s.labels,+ points=[MetricsQueryPoint(time=p.time, value=p.value) for p in s.points],+ metricName=s.metric_name,+ clause=s.clause,+ )+ for s in series+ ]+ )++ def apply_dashboard_filters(self, dashboard_filter: DashboardFilter) -> None:+ # Metric label predicates are not PostHog property filters, so only the+ # dashboard's date range applies to this tile.+ if dashboard_filter.date_from or dashboard_filter.date_to:+ self.query.dateRange = DateRange(+ date_from=dashboard_filter.date_from,+ date_to=dashboard_filter.date_to,+ )diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.pynew file mode 100644index 000000000000..fecc814028d4--- /dev/null+++ b/products/metrics/backend/tests/test_metrics_query_runner.py@@ -0,0 +1,186 @@+import datetime as dt++import pytest+from freezegun import freeze_time+from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from parameterized import parameterized++from posthog.schema import (+ DashboardFilter,+ DateRange,+ MetricsQuery,+ MetricsQueryClause,+ MetricsQueryFilter,+ MetricsQueryGroupBy,+)++from posthog.constants import AvailableFeature+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.rbac.user_access_control import UserAccessControlError++from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation+from products.metrics.backend.metrics_query_runner import MetricsQueryRunner+from products.metrics.backend.tests._seeder import seed_metric++from ee.models.rbac.access_control import AccessControl+++class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):+ def _runner(self, query: MetricsQuery) -> MetricsQueryRunner:+ return MetricsQueryRunner(query=query, team=self.team)++ def test_translates_schema_node_to_facade_request(self) -> None:+ query = MetricsQuery(+ clauses=[+ MetricsQueryClause(+ name="a",+ metricName="http_requests_total",+ aggregation="histogram_quantile",+ quantile=0.95,+ filters=[MetricsQueryFilter(key="container", op="eq", value="capture", scope="attribute")],+ groupBy=[MetricsQueryGroupBy(key="namespace")],+ )+ ],+ dateRange=DateRange(date_from="2026-07-01T00:00:00Z", date_to="2026-07-01T01:00:00Z"),+ interval="minute",+ formula=None,+ )++ request = self._runner(query)._to_request()++ clause = request.clauses[0]+ assert clause.metric_name == "http_requests_total"+ assert clause.aggregation is MetricAggregation.HISTOGRAM_QUANTILE+ assert clause.quantile == 0.95+ assert clause.filters[0].op is FilterOp.EQ+ assert clause.filters[0].scope is AttributeScope.ATTRIBUTE+ assert clause.group_by[0].scope is AttributeScope.AUTO+ assert request.interval == "minute"+ assert (request.date_to - request.date_from) == dt.timedelta(hours=1)++ @freeze_time("2026-07-01T12:00:00Z")+ def test_default_date_range_is_last_24_hours(self) -> None:+ query = MetricsQuery(+ clauses=[MetricsQueryClause(name="a", metricName="http_requests_total", aggregation="sum")]+ )++ request = self._runner(query)._to_request()++ assert (request.date_to - request.date_from) == dt.timedelta(hours=24)++ @freeze_time("2026-07-01T12:00:00Z")+ def test_calculate_returns_one_series_per_group(self) -> None:+ base = dt.datetime(2026, 7, 1, 11, 30, tzinfo=dt.UTC)+ for container, value in (("capture", 5.0), ("ingestion", 7.0)):+ seed_metric(+ team_id=self.team.pk,+ metric_name="queue_depth",+ metric_type="gauge",+ points=[(base + dt.timedelta(minutes=i), value) for i in range(3)],+ labels={"container": container},+ )++ query = MetricsQuery(+ clauses=[+ MetricsQueryClause(+ name="a",+ metricName="queue_depth",+ aggregation="sum",+ groupBy=[MetricsQueryGroupBy(key="container")],+ )+ ],+ dateRange=DateRange(date_from="2026-07-01T11:00:00Z", date_to="2026-07-01T12:00:00Z"),+ )++ response = self._runner(query).calculate()++ by_container = {series.labels.get("container"): series for series in response.results}+ assert set(by_container) == {"capture", "ingestion"}+ assert max(point.value for point in by_container["capture"].points) == 5.0+ assert max(point.value for point in by_container["ingestion"].points) == 7.0++ def test_generic_query_endpoint_accepts_metrics_query(self) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.pk}/query/",+ {+ "query": {+ "kind": "MetricsQuery",+ "clauses": [{"name": "a", "metricName": "queue_depth", "aggregation": "sum"}],+ }+ },+ )++ assert response.status_code == 200, response.json()+ assert "results" in response.json()++ def test_insight_saves_with_metrics_query(self) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.pk}/insights/",+ {+ "name": "queue depth",+ "saved": True,+ "query": {+ "kind": "MetricsQuery",+ "clauses": [{"name": "a", "metricName": "queue_depth", "aggregation": "sum"}],+ "dateRange": {"date_from": "-24h"},+ },+ },+ format="json",+ )++ assert response.status_code == 201, response.json()+ assert response.json()["query"]["kind"] == "MetricsQuery"++ def test_validate_query_runner_access_granted(self) -> None:+ query = MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")])++ assert self._runner(query).validate_query_runner_access(self.user) is True++ def test_validate_query_runner_access_denied_without_resource_access(self) -> None:+ AccessControl.objects.create(team=self.team, resource="metrics", access_level="none")+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ query = MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")])++ with pytest.raises(UserAccessControlError):+ self._runner(query).validate_query_runner_access(self.user)++ @parameterized.expand(+ [+ (["query:read"], 403),+ (["query:read", "metrics:read"], 200),+ ]+ )+ def test_query_endpoint_scope_parity_for_api_keys(self, scopes: list[str], expected_status: int) -> None:+ value = generate_random_token_personal()+ PersonalAPIKey.objects.create(label="test", user=self.user, secure_value=hash_key_value(value), scopes=scopes)++ response = self.client.post(+ f"/api/projects/{self.team.pk}/query/",+ {+ "query": {+ "kind": "MetricsQuery",+ "clauses": [{"name": "a", "metricName": "queue_depth", "aggregation": "sum"}],+ }+ },+ HTTP_AUTHORIZATION=f"Bearer {value}",+ )++ assert response.status_code == expected_status, response.json()++ def test_dashboard_date_filters_override_query_date_range(self) -> None:+ query = MetricsQuery(+ clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")],+ dateRange=DateRange(date_from="-24h"),+ )+ runner = self._runner(query)++ runner.apply_dashboard_filters(DashboardFilter(date_from="-7d", date_to="-1d"))++ assert runner.query.dateRange is not None+ assert runner.query.dateRange.date_from == "-7d"+ assert runner.query.dateRange.date_to == "-1d"diff --git a/products/metrics/frontend/components/MetricsSeriesChart.tsx b/products/metrics/frontend/components/MetricsSeriesChart.tsxnew file mode 100644index 000000000000..ff149c1aaaeb--- /dev/null+++ b/products/metrics/frontend/components/MetricsSeriesChart.tsx@@ -0,0 +1,97 @@+import { useCallback, useMemo } from 'react'++import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'+import { dayjs } from 'lib/dayjs'++import { MetricsChartLegend } from './MetricsChartLegend'+import { formatSeriesName, seriesColor } from './metricsSeries'++/** Source-agnostic series shape: the REST viewer (`_MetricSeriesApi`) and the+ * `MetricsQuery` schema node (`MetricsQuerySeries`) both map onto it. */+export interface MetricsChartSeries {+ labels: Record<string, string>+ points: { time: string; value: number }[]+ metricName?: string | null+}++/** Multi-series metric line chart + legend, shared by the Viewer and the+ * dashboard/insight tile. Every series shares one time grid (the backend+ * zero-fills), so the x-axis comes from the first series. */+export function MetricsSeriesChart({+ series,+ fallbackName,+ className,+}: {+ series: MetricsChartSeries[]+ fallbackName: string+ className?: string+}): JSX.Element {+ const chartSeries = useMemo(+ () =>+ series.map((s, index) => ({+ name: formatSeriesName({ labels: s.labels, metric_name: s.metricName ?? undefined }, fallbackName),+ values: s.points.map((p) => p.value),+ color: seriesColor(index),+ })),+ [series, fallbackName]+ )+ const sparklineLabels = useMemo(() => (series[0]?.points ?? []).map((p) => p.time), [series])++ // Mirrors the format/timeUnit ladder LogsSparkline uses so the X-axis density+ // matches the selected range.+ const { timeUnit, tickFormat } = useMemo(() => {+ if (!sparklineLabels.length) {+ return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }+ }+ const first = dayjs(sparklineLabels[0])+ const last = dayjs(sparklineLabels[sparklineLabels.length - 1])+ const hoursDiff = last.diff(first, 'hours')+ if (hoursDiff <= 1) {+ return { timeUnit: 'second' as const, tickFormat: 'HH:mm:ss' }+ }+ if (hoursDiff <= 6) {+ return { timeUnit: 'minute' as const, tickFormat: 'HH:mm:ss' }+ }+ if (hoursDiff <= 48) {+ return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }+ }+ return { timeUnit: 'day' as const, tickFormat: 'D MMM HH:mm' }+ }, [sparklineLabels])++ const withXScale = useCallback(+ (scale: AnyScaleOptions): AnyScaleOptions =>+ ({+ ...scale,+ type: 'timeseries',+ ticks: {+ display: true,+ maxRotation: 0,+ maxTicksLimit: 6,+ font: { size: 10, lineHeight: 1 },+ callback: function (value: string | number) {+ return dayjs(value).format(tickFormat)+ },+ },+ time: { unit: timeUnit },+ }) as AnyScaleOptions,+ [timeUnit, tickFormat]+ )++ const renderLabel = useCallback((label: string): string => dayjs(label).format('D MMM YYYY HH:mm:ss'), [])++ return (+ <div className={className}>+ <div className="flex-1 min-h-0">+ <Sparkline+ type="line"+ data={chartSeries}+ labels={sparklineLabels}+ className="w-full h-full"+ withXScale={withXScale}+ renderLabel={renderLabel}+ />+ </div>+ <MetricsChartLegend series={chartSeries} />+ </div>+ )+}diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 7f4db299c29b..6fe3a0659408 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -2,6 +2,7 @@ import { useActions, useMountedLogic, useValues } from 'kea'import { useCallback, useEffect, useMemo, useState } from 'react'import {+ LemonButton,LemonBanner,LemonInputSelect,LemonSegmentedButton,@@ -121,6 +122,7 @@ export const MetricsViewer = (): JSX.Element => {liveRefresh,queryResultsLoading,queryError,+ savedInsightLoading,hasMetricName,} = useValues(logic)const {@@ -136,6 +138,7 @@ export const MetricsViewer = (): JSX.Element => {fetchQueryResults,fetchAnomaly,clearAnomaly,+ saveAsInsight,} = useActions(logic)const { items: pickerItems } = useValues(pickerLogic)@@ -274,6 +277,15 @@ export const MetricsViewer = (): JSX.Element => {tooltip={`Auto-refresh every ${LIVE_REFRESH_MS / 1000}s`}bordered/>+ <LemonButton+ size="small"+ type="secondary"+ onClick={() => saveAsInsight()}+ loading={savedInsightLoading}+ disabledReason={!hasMetricName ? 'Pick a metric first' : undefined}+ >+ Save as insight+ </LemonButton></div><div className="flex flex-col xl:flex-row gap-3 items-stretch"><div className="flex-1 min-w-0">diff --git a/products/metrics/frontend/components/metricsSeries.ts b/products/metrics/frontend/components/metricsSeries.tsindex d652e02fa7c8..5787f9624546 100644--- a/products/metrics/frontend/components/metricsSeries.ts+++ b/products/metrics/frontend/components/metricsSeries.ts@@ -7,7 +7,10 @@ export const seriesColor = (index: number): string => `data-color-${(index % SER// Human-readable series name from its label map (e.g. "service.name=checkout, env=prod"),// falling back to the metric name then a provided default for ungrouped/unlabelled series.-export const formatSeriesName = (series: _MetricSeriesApi, fallback: string): string => {+export const formatSeriesName = (+ series: Pick<_MetricSeriesApi, 'labels' | 'metric_name'>,+ fallback: string+): string => {const entries = Object.entries(series.labels ?? {})if (entries.length > 0) {return entries.map(([key, value]) => `${key}=${value}`).join(', ')diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex 709b659929a3..55ad0bc7f4a7 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -1,3 +1,4 @@+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import {FilterLogicalOperator,@@ -77,6 +78,37 @@ describe('metricsViewerLogic', () => {expect(logic.values.aggregation).toBe('increase')})+ // metricsQueryNode is what "Save as insight" persists: a wrong mapping here+ // silently saves insights that re-run a different query than the viewer showed.+ it('maps viewer state to a MetricsQuery node, translating p95 to quantile', () => {+ logic.actions.setMetricName('request_duration')+ logic.actions.setGroupByKeys(['container'])+ logic.actions.setFilterGroup(+ filterGroupWith([{ key: 'namespace', operator: PropertyOperator.Exact, value: ['posthog'] }])+ )+ logic.actions.setDateFrom('-24h')++ expect(logic.values.aggregation).toBe('p95')+ expect(logic.values.metricsQueryNode).toEqual({+ kind: NodeKind.MetricsQuery,+ clauses: [+ {+ name: 'a',+ metricName: 'request_duration',+ aggregation: 'quantile',+ quantile: 0.95,+ filters: [{ key: 'namespace', op: 'eq', value: 'posthog' }],+ groupBy: [{ key: 'container' }],+ },+ ],+ dateRange: { date_from: '-24h' },+ })+ })++ it('produces no MetricsQuery node without a metric name', () => {+ expect(logic.values.metricsQueryNode).toBeNull()+ })+// A failed query (bad regex, 500) used to render the same "No data" empty state as a genuinely// empty result. The failure records the message so the viewer can show a real error instead.// kea-loaders dispatches `<key>Failure(error.message, error)`, so the reducer reads the message.diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex 4065e13e6c62..693116f9249b 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -1,5 +1,8 @@import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'import { type MetricSummary } from 'lib/components/Metric/metricSummary'import { type SparklineTimeSeries } from 'lib/components/Sparkline'@@ -8,8 +11,12 @@ import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utilimport { dayjs } from 'lib/dayjs'import { escapeRegex } from 'lib/utils/actions'import { dateStringToDayJs } from 'lib/utils/dateFilters'+import { insightsApi } from 'scenes/insights/utils/api'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'+import { MetricsQuery, MetricsQueryClause, MetricsQueryFilter, NodeKind } from '~/queries/schema/schema-general'+import { QueryBasedInsightModel } from '~/types'import { PropertyOperator, UniversalFilterValue, UniversalFiltersGroup } from '~/types'import { metricsCharacterizeCreate, metricsQueryCreate } from 'products/metrics/frontend/generated/api'@@ -193,6 +200,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([actions.setAggregation(recommended)}},+ saveAsInsightFailure: ({ error }) => {+ lemonToast.error(`Failed to save insight: ${error}`)+ },cancelInProgressQuery: ({ controller }) => {if (values.queryAbortController !== null) {// An AbortError-named DOMException (not a bare string) is what api.ts and the global@@ -258,6 +268,29 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([},},],+ savedInsight: [+ null as QueryBasedInsightModel | null,+ {+ saveAsInsight: async () => {+ const query = values.metricsQueryNode+ if (!query) {+ return null+ }+ const insight = await insightsApi.create({+ name: `${values.metricName} (${values.aggregation})`,+ query,+ saved: true,+ })+ lemonToast.success('Insight saved', {+ button: {+ label: 'View insight',+ action: () => router.actions.push(urls.insightView(insight.short_id)),+ },+ })+ return insight+ },+ },+ ],anomalyReport: [null as _MetricAnomalyReportApi | null,{@@ -294,6 +327,44 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([})),selectors({hasMetricName: [(s) => [s.metricName], (metricName) => metricName.trim().length > 0],+ // The viewer state as a `MetricsQuery` schema node — what "Save as insight"+ // persists, so the saved tile re-runs exactly what the viewer shows.+ // The REST viewer's 'p95' shorthand maps to the node's quantile aggregation.+ metricsQueryNode: [+ (s) => [s.metricName, s.aggregation, s.dateFrom, s.dateTo, s.groupByKeys, s.queryFilters],+ (metricName, aggregation, dateFrom, dateTo, groupByKeys, queryFilters): MetricsQuery | null => {+ const trimmedName = metricName.trim()+ if (!trimmedName) {+ return null+ }+ const clause: MetricsQueryClause = {+ name: 'a',+ metricName: trimmedName,+ aggregation: aggregation === 'p95' ? 'quantile' : aggregation,+ ...(aggregation === 'p95' ? { quantile: 0.95 } : {}),+ ...(queryFilters.length+ ? {+ filters: queryFilters.map(+ (f): MetricsQueryFilter => ({+ key: f.key,+ op: f.op as MetricsQueryFilter['op'],+ value: f.value,+ })+ ),+ }+ : {}),+ ...(groupByKeys.length ? { groupBy: groupByKeys.map((key) => ({ key })) } : {}),+ }+ return {+ kind: NodeKind.MetricsQuery,+ clauses: [clause],+ dateRange: {+ date_from: dateFrom ?? DEFAULT_DATE_FROM,+ ...(dateTo ? { date_to: dateTo } : {}),+ },+ }+ },+ ],queryFilters: [(s) => [s.filterGroup],(filterGroup: UniversalFiltersGroup): _MetricFilterApi[] =>@@ -310,8 +381,6 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([...(resolveDate(dateTo) ? { dateTo: resolveDate(dateTo) as string } : {}),}),],- // The viewer renders the first series only for now; group-by lands- // multi-series rendering in a later PR.// Metrics has no compare/previous-series concept, so "current" is simply the first series.currentSeries: [(s) => [s.queryResults], (results): MetricsViewerSeries | undefined => results[0]],// All series rendered as chart lines (a group-by query returns one series per label combination).diff --git a/products/metrics/frontend/nodes/MetricsQueryNode.tsx b/products/metrics/frontend/nodes/MetricsQueryNode.tsxnew file mode 100644index 000000000000..3d97507d7244--- /dev/null+++ b/products/metrics/frontend/nodes/MetricsQueryNode.tsx@@ -0,0 +1,59 @@+import { BuiltLogic, LogicWrapper, useValues } from 'kea'+import { useState } from 'react'++import { SpinnerOverlay } from '@posthog/lemon-ui'++import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'++import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { AnyResponseType, MetricsQuery, MetricsQueryResponse } from '~/queries/schema/schema-general'+import { QueryContext } from '~/queries/types'++import { MetricsSeriesChart } from '../components/MetricsSeriesChart'++let uniqueNode = 0++/** Renders a `MetricsQuery` wherever the generic `Query` component is used —+ * saved insights, dashboard tiles, notebooks. */+export function MetricsQueryNode(props: {+ query: MetricsQuery+ cachedResults?: AnyResponseType+ context: QueryContext+ attachTo?: LogicWrapper | BuiltLogic+}): JSX.Element | null {+ const { onData, loadPriority, dataNodeCollectionId } = props.context.insightProps ?? {}+ const [key] = useState(() => `MetricsQueryNode.${uniqueNode++}`)+ const logic = dataNodeLogic({+ query: props.query,+ key,+ cachedResults: props.cachedResults,+ loadPriority,+ onData,+ dataNodeCollectionId: dataNodeCollectionId ?? key,+ })++ useAttachedLogic(logic, props.attachTo)++ const { response, responseLoading } = useValues(logic)+ const queryResponse = response as MetricsQueryResponse | undefined+ const series = queryResponse?.results ?? []+ const hasPoints = series.some((s) => s.points.length > 0)+ const fallbackName = props.query.clauses[0]?.metricName ?? 'metric'++ return (+ <div className="relative flex flex-col w-full h-full min-h-[200px]">+ {hasPoints ? (+ <MetricsSeriesChart+ series={series.map((s) => ({ labels: s.labels, points: s.points, metricName: s.metricName }))}+ fallbackName={fallbackName}+ className="flex flex-col w-full h-full"+ />+ ) : !responseLoading ? (+ <div className="flex-1 flex items-center justify-center text-secondary text-sm">+ No data for this metric in the selected range.+ </div>+ ) : null}+ {responseLoading && <SpinnerOverlay />}+ </div>+ )+}diff --git a/products/metrics/frontend/nodes/index.ts b/products/metrics/frontend/nodes/index.tsnew file mode 100644index 000000000000..26c4c0d9ec2c--- /dev/null+++ b/products/metrics/frontend/nodes/index.ts@@ -0,0 +1 @@+export { MetricsQueryNode } from './MetricsQueryNode'diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b6f8b4f47de6..0590c702a6a5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27587,6 +27587,120 @@ export namespace Schemas {version?: number | null;}+ export type MetricsAggregation = typeof MetricsAggregation[keyof typeof MetricsAggregation];+++ export const MetricsAggregation = {+ Sum: 'sum',+ Avg: 'avg',+ Count: 'count',+ Min: 'min',+ Max: 'max',+ Quantile: 'quantile',+ Rate: 'rate',+ Increase: 'increase',+ HistogramQuantile: 'histogram_quantile',+ } as const;++ export type MetricsFilterOp = typeof MetricsFilterOp[keyof typeof MetricsFilterOp];+++ export const MetricsFilterOp = {+ Eq: 'eq',+ Neq: 'neq',+ Regex: 'regex',+ NotRegex: 'not_regex',+ } as const;++ export type MetricsAttributeScope = typeof MetricsAttributeScope[keyof typeof MetricsAttributeScope];+++ export const MetricsAttributeScope = {+ Resource: 'resource',+ Attribute: 'attribute',+ Auto: 'auto',+ } as const;++ export interface MetricsQueryFilter {+ key: string;+ op: MetricsFilterOp;+ scope?: MetricsAttributeScope | null;+ value: string;+ }++ export interface MetricsQueryGroupBy {+ key: string;+ scope?: MetricsAttributeScope | null;+ }++ export interface MetricsQueryClause {+ aggregation: MetricsAggregation;+ filters?: MetricsQueryFilter[] | null;+ groupBy?: MetricsQueryGroupBy[] | null;+ metricName: string;+ /** Alias a formula refers to (e.g. "a"); must be unique within the query */+ name: string;+ /** In (0, 1); required for `quantile` / `histogram_quantile` aggregations */+ quantile?: number | null;+ }++ export interface MetricsQueryPoint {+ /** Bucket start, ISO 8601 */+ time: string;+ value: number;+ }++ /**+ * Label values identifying this series; empty for an ungrouped query+ */+ export type MetricsQuerySeriesLabels = {[key: string]: string};++ export interface MetricsQuerySeries {+ /** Clause alias that produced this series (`formula` for the formula result) */+ clause?: string | null;+ /** Label values identifying this series; empty for an ungrouped query */+ labels: MetricsQuerySeriesLabels;+ metricName?: string | null;+ points: MetricsQueryPoint[];+ }++ export interface MetricsQueryResponse {+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null;+ /** Generated HogQL query. */+ hogql?: string | null;+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatus | null;+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: MetricsQuerySeries[];+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;+ }++ export interface MetricsQuery {+ clauses: MetricsQueryClause[];+ /** Defaults to the last 24 hours when omitted; dashboard date filters override it */+ dateRange?: DateRange | null;+ /** Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned */+ formula?: string | null;+ /** Bucket size, one of: second, minute, minute_5, minute_15, hour, hour_6, day, week; auto-picked from the range when omitted */+ interval?: string | null;+ kind?: 'MetricsQuery';+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ response?: MetricsQueryResponse | null;+ tags?: QueryLogTags | null;+ /** version of the node, used for schema migrations */+ version?: number | null;+ }+export type TraceOrderColumn = typeof TraceOrderColumn[keyof typeof TraceOrderColumn];@@ -28514,7 +28628,7 @@ export namespace Schemas {query: string;response?: HogQLMetadataResponse | null;/** Query within which "expr" and "template" are validated. Defaults to "select * from events" */- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;tags?: QueryLogTags | null;/** Variables to be subsituted into the query */variables?: HogQLMetadataVariables;@@ -28540,7 +28654,7 @@ export namespace Schemas {query: string;response?: HogQLAutocompleteResponse | null;/** Query in whose context to validate. */- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;/** Start position of the editor word */startPosition: number;tags?: QueryLogTags | null;@@ -47233,7 +47347,7 @@ export namespace Schemas {* ```** For more details on HogQL queries, see the [PostHog HogQL documentation](/docs/hogql#api-access). */- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;/** Whether results should be calculated sync or async, and how much to rely on the cache:* - `'blocking'` - calculate synchronously (returning only when the query is done), UNLESS there are very fresh results in the cache* - `'async'` - kick off background calculation (returning immediately with a query status), UNLESS there are very fresh results in the cache@@ -48903,6 +49017,26 @@ export namespace Schemas {}export interface QueryResponseAlternative80 {+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null;+ /** Generated HogQL query. */+ hogql?: string | null;+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatus | null;+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: MetricsQuerySeries[];+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;+ }++ export interface QueryResponseAlternative81 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;hasMore?: boolean | null;@@ -48927,7 +49061,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative81 {+ export interface QueryResponseAlternative82 {/** Result rows for the comparison period when `compareFilter.compare` is true. */compare?: AggregatedSpanRow[] | null;/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */@@ -48949,7 +49083,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative82 {+ export interface QueryResponseAlternative83 {/** Result rows for the comparison period when `compareFilter.compare` is true. */compare?: SpanTreeNode[] | null;/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */@@ -48971,7 +49105,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative83 {+ export interface QueryResponseAlternative84 {/** Result rows for the comparison period when `compareFilter.compare` is true. */compare?: AttributeBreakdownRow[] | null;/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */@@ -48993,13 +49127,13 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative84 {+ export interface QueryResponseAlternative85 {questions: string[];/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative85 {+ export interface QueryResponseAlternative86 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;hasMore?: boolean | null;@@ -49022,7 +49156,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative86 {+ export interface QueryResponseAlternative87 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;hasMore?: boolean | null;@@ -49045,7 +49179,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative87 {+ export interface QueryResponseAlternative88 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49065,7 +49199,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative88 {+ export interface QueryResponseAlternative89 {columns?: string[] | null;/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -49089,7 +49223,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative91 {+ export interface QueryResponseAlternative92 {/** Timestamp of the newer trace */newerTimestamp?: string | null;/** ID of the newer trace (chronologically after current) */@@ -49104,7 +49238,7 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative92 {+ export interface QueryResponseAlternative93 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49124,7 +49258,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative93 {+ export interface QueryResponseAlternative94 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49144,7 +49278,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative94 {+ export interface QueryResponseAlternative95 {columns: unknown[];/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -49172,7 +49306,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative95 {+ export interface QueryResponseAlternative96 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49192,7 +49326,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative96 {+ export interface QueryResponseAlternative97 {columns?: unknown[] | null;/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -49217,9 +49351,9 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export type QueryResponseAlternative97ResultsItem = { [key: string]: unknown };+ export type QueryResponseAlternative98ResultsItem = { [key: string]: unknown };- export interface QueryResponseAlternative97 {+ export interface QueryResponseAlternative98 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49232,14 +49366,14 @@ export namespace Schemas {resolved_compare_date_range?: ResolvedDateRangeResponse | null;/** The date range used for the query */resolved_date_range?: ResolvedDateRangeResponse | null;- results: QueryResponseAlternative97ResultsItem[];+ results: QueryResponseAlternative98ResultsItem[];/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;/** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative98 {+ export interface QueryResponseAlternative99 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49259,7 +49393,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative99 {+ export interface QueryResponseAlternative100 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49279,7 +49413,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative100 {+ export interface QueryResponseAlternative101 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49299,7 +49433,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative101 {+ export interface QueryResponseAlternative102 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49320,7 +49454,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative102 {+ export interface QueryResponseAlternative103 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49340,7 +49474,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative103 {+ export interface QueryResponseAlternative104 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49360,7 +49494,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative104 {+ export interface QueryResponseAlternative105 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49380,7 +49514,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative105 {+ export interface QueryResponseAlternative106 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49400,7 +49534,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export interface QueryResponseAlternative106 {+ export interface QueryResponseAlternative107 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -49420,18 +49554,18 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106;+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107;export interface QueryStatusResponse {query_status: QueryStatus;}export interface QueryUpgradeRequest {- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;}export interface QueryUpgradeResponse {- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | RevenueAnalyticsGrossRevenueQuery | RevenueAnalyticsMetricsQuery | RevenueAnalyticsMRRQuery | RevenueAnalyticsOverviewQuery | RevenueAnalyticsTopCustomersQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;}export interface QuotaResourceLimit {diff --git a/tach.toml b/tach.tomlindex 0393e873cbea..c83cb7bfc47c 100644--- a/tach.toml+++ b/tach.toml@@ -98,6 +98,7 @@ depends_on = ["products.logs","products.marketing_analytics","products.messaging",+ "products.metrics","products.notebooks","products.notifications","products.posthog_ai",