: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(tracing): add apm-attribute-breakdown MCP tool for facet analysis (#63291)
Jon McCallum14eda71929bc
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 5f9b6b8e76de..65782658c6d2 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -873,6 +873,9 @@{"$ref": "#/definitions/TraceSpansTreeQuery"},+ {+ "$ref": "#/definitions/TraceSpansAttributeBreakdownQuery"+ },{"$ref": "#/definitions/ExperimentFunnelsQuery"},@@ -1132,6 +1135,9 @@},{"$ref": "#/definitions/TraceSpansTreeQueryResponse"+ },+ {+ "$ref": "#/definitions/TraceSpansAttributeBreakdownQueryResponse"}]},@@ -4510,6 +4516,29 @@"required": ["id", "tool_call_id", "content"],"type": "object"},+ "AttributeBreakdownRow": {+ "additionalProperties": false,+ "description": "One row of a span attribute breakdown: the spans matching the filters, grouped by one attribute's value. Spans without the attribute group under `value = ''`.",+ "properties": {+ "count": {+ "$ref": "#/definitions/integer"+ },+ "error_count": {+ "$ref": "#/definitions/integer"+ },+ "p50_duration_nano": {+ "type": "number"+ },+ "p95_duration_nano": {+ "type": "number"+ },+ "value": {+ "type": "string"+ }+ },+ "required": ["value", "count", "error_count", "p50_duration_nano", "p95_duration_nano"],+ "type": "object"+ },"AttributionMode": {"enum": ["first_touch", "last_touch", "linear", "time_decay", "position_based"],"type": "string"@@ -9929,6 +9958,99 @@],"type": "object"},+ "CachedTraceSpansAttributeBreakdownQueryResponse": {+ "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"+ },+ "compare": {+ "description": "Result rows for the comparison period when `compareFilter.compare` is true.",+ "items": {+ "$ref": "#/definitions/AttributeBreakdownRow"+ },+ "type": "array"+ },+ "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/AttributeBreakdownRow"+ },+ "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.",+ "items": {+ "$ref": "#/definitions/DataWarehouseSyncWarning"+ },+ "type": "array"+ }+ },+ "required": [+ "cache_key",+ "is_cached",+ "last_refresh",+ "next_allowed_client_refresh",+ "results",+ "timezone"+ ],+ "type": "object"+ },"CachedTraceSpansQueryResponse": {"additionalProperties": false,"properties": {@@ -28376,6 +28498,7 @@"TraceSpansQuery","TraceSpansAggregationQuery","TraceSpansTreeQuery",+ "TraceSpansAttributeBreakdownQuery","SessionBatchEventsQuery","DataTableNode","DataVisualizationNode",@@ -35038,6 +35161,64 @@"required": ["results"],"type": "object"},+ {+ "additionalProperties": false,+ "properties": {+ "compare": {+ "description": "Result rows for the comparison period when `compareFilter.compare` is true.",+ "items": {+ "$ref": "#/definitions/AttributeBreakdownRow"+ },+ "type": "array"+ },+ "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/AttributeBreakdownRow"+ },+ "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.",+ "items": {+ "$ref": "#/definitions/DataWarehouseSyncWarning"+ },+ "type": "array"+ }+ },+ "required": ["results"],+ "type": "object"+ },{"additionalProperties": false,"properties": {@@ -36000,6 +36181,9 @@{"$ref": "#/definitions/TraceSpansTreeQuery"},+ {+ "$ref": "#/definitions/TraceSpansAttributeBreakdownQuery"+ },{"$ref": "#/definitions/SuggestedQuestionsQuery"},@@ -41600,6 +41784,14 @@"required": ["results"],"type": "object"},+ "TraceSpanBreakdownOrderBy": {+ "enum": ["count", "error_count"],+ "type": "string"+ },+ "TraceSpanBreakdownType": {+ "enum": ["span_attribute", "span_resource_attribute"],+ "type": "string"+ },"TraceSpansAggregationQuery": {"additionalProperties": false,"properties": {@@ -41699,6 +41891,117 @@"required": ["results"],"type": "object"},+ "TraceSpansAttributeBreakdownQuery": {+ "additionalProperties": false,+ "properties": {+ "breakdownKey": {+ "description": "Attribute key to group by (e.g. `http.response.status_code`, `server.address`).",+ "type": "string"+ },+ "breakdownType": {+ "$ref": "#/definitions/TraceSpanBreakdownType",+ "description": "Where the key lives: span-level attributes or resource-level attributes."+ },+ "compareFilter": {+ "$ref": "#/definitions/CompareFilter",+ "description": "Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set."+ },+ "dateRange": {+ "$ref": "#/definitions/DateRange"+ },+ "filterGroup": {+ "$ref": "#/definitions/PropertyGroupFilter"+ },+ "kind": {+ "const": "TraceSpansAttributeBreakdownQuery",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "orderBy": {+ "$ref": "#/definitions/TraceSpanBreakdownOrderBy",+ "description": "Order rows by span count or error count, descending. Defaults to count."+ },+ "response": {+ "$ref": "#/definitions/TraceSpansAttributeBreakdownQueryResponse"+ },+ "serviceNames": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "tags": {+ "$ref": "#/definitions/QueryLogTags"+ },+ "version": {+ "description": "version of the node, used for schema migrations",+ "type": "number"+ }+ },+ "required": ["breakdownKey", "breakdownType", "dateRange", "kind"],+ "type": "object"+ },+ "TraceSpansAttributeBreakdownQueryResponse": {+ "additionalProperties": false,+ "properties": {+ "compare": {+ "description": "Result rows for the comparison period when `compareFilter.compare` is true.",+ "items": {+ "$ref": "#/definitions/AttributeBreakdownRow"+ },+ "type": "array"+ },+ "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/AttributeBreakdownRow"+ },+ "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.",+ "items": {+ "$ref": "#/definitions/DataWarehouseSyncWarning"+ },+ "type": "array"+ }+ },+ "required": ["results"],+ "type": "object"+ },"TraceSpansQuery": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 017f6797144a..6b1da432068c 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -114,6 +114,7 @@ export enum NodeKind {TraceSpansQuery = 'TraceSpansQuery',TraceSpansAggregationQuery = 'TraceSpansAggregationQuery',TraceSpansTreeQuery = 'TraceSpansTreeQuery',+ TraceSpansAttributeBreakdownQuery = 'TraceSpansAttributeBreakdownQuery',SessionBatchEventsQuery = 'SessionBatchEventsQuery',// Interface nodes@@ -239,6 +240,7 @@ export type AnyDataNode =| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| ExperimentFunnelsQuery| ExperimentTrendsQuery| CalendarHeatmapQuery@@ -341,6 +343,7 @@ export type QuerySchema =| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery// AI| SuggestedQuestionsQuery@@ -402,6 +405,7 @@ export type AnyResponseType =| TraceSpansQueryResponse| TraceSpansAggregationQueryResponse| TraceSpansTreeQueryResponse+ | TraceSpansAttributeBreakdownQueryResponse/** Tags that will be added to the Query log comment **/export interface QueryLogTags {@@ -3320,6 +3324,45 @@ export interface TraceSpansTreeQueryResponse extends AnalyticsQueryResponseBaseexport type CachedTraceSpansTreeQueryResponse = CachedQueryResponse<TraceSpansTreeQueryResponse>+/**+ * One row of a span attribute breakdown: the spans matching the filters, grouped by one+ * attribute's value. Spans without the attribute group under `value = ''`.+ */+export interface AttributeBreakdownRow {+ value: string+ count: integer+ error_count: integer+ p50_duration_nano: number+ p95_duration_nano: number+}++export type TraceSpanBreakdownType = 'span_attribute' | 'span_resource_attribute'+export type TraceSpanBreakdownOrderBy = 'count' | 'error_count'++export interface TraceSpansAttributeBreakdownQuery extends DataNode<TraceSpansAttributeBreakdownQueryResponse> {+ kind: NodeKind.TraceSpansAttributeBreakdownQuery+ dateRange: DateRange+ /** Attribute key to group by (e.g. `http.response.status_code`, `server.address`). */+ breakdownKey: string+ /** Where the key lives: span-level attributes or resource-level attributes. */+ breakdownType: TraceSpanBreakdownType+ /** Order rows by span count or error count, descending. Defaults to count. */+ orderBy?: TraceSpanBreakdownOrderBy+ /** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */+ compareFilter?: CompareFilter+ filterGroup?: PropertyGroupFilter+ serviceNames?: string[]+}++export interface TraceSpansAttributeBreakdownQueryResponse extends AnalyticsQueryResponseBase {+ results: AttributeBreakdownRow[]+ /** Result rows for the comparison period when `compareFilter.compare` is true. */+ compare?: AttributeBreakdownRow[]+}++export type CachedTraceSpansAttributeBreakdownQueryResponse =+ CachedQueryResponse<TraceSpansAttributeBreakdownQueryResponse>+export interface FileSystemCount {count: numberentries: FileSystemEntry[]diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsxindex e01bc2e045a7..d648c1e0308c 100644--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx@@ -561,6 +561,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {icon: IconLive,inMenu: false,},+ [NodeKind.TraceSpansAttributeBreakdownQuery]: {+ name: 'Trace Spans Attribute Breakdown',+ icon: IconLive,+ inMenu: false,+ },[NodeKind.WebAnalyticsExternalSummaryQuery]: {name: 'Web Analytics External Summary',icon: IconPieChart,diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 4a890cdfdfc0..452e7dfeb995 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -231,6 +231,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:| NodeKind.TRACE_SPANS_QUERY| NodeKind.TRACE_SPANS_AGGREGATION_QUERY| NodeKind.TRACE_SPANS_TREE_QUERY+ | NodeKind.TRACE_SPANS_ATTRIBUTE_BREAKDOWN_QUERY):return {"product": Product.LLM_ANALYTICS}case (diff --git a/posthog/schema.py b/posthog/schema.pyindex 9c71ef65151f..e61755f9ad87 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -265,6 +265,8 @@ from posthog.schema_enums import (TikTokAdsTableKeywords as TikTokAdsTableKeywords,TimeWindowMode as TimeWindowMode,TraceOrderColumn as TraceOrderColumn,+ TraceSpanBreakdownOrderBy as TraceSpanBreakdownOrderBy,+ TraceSpanBreakdownType as TraceSpanBreakdownType,UrlMatching as UrlMatching,UsageMetricDisplay as UsageMetricDisplay,UsageMetricFormat as UsageMetricFormat,@@ -2125,7 +2127,7 @@ class QueryResponseAlternative7(BaseModel):stdout: str | None = None-class QueryResponseAlternative82(BaseModel):+class QueryResponseAlternative83(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -4145,6 +4147,17 @@ class AssistantTrendsFilter(BaseModel):)+class AttributeBreakdownRow(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ count: int+ error_count: int+ p50_duration_nano: float+ p95_duration_nano: float+ value: str++class AutocompleteCompletionItem(BaseModel):model_config = ConfigDict(extra="forbid",@@ -5698,7 +5711,7 @@ class QueryResponseAlternative29(BaseModel):status: ExternalQueryStatus-class QueryResponseAlternative88(BaseModel):+class QueryResponseAlternative89(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -7055,6 +7068,51 @@ class TraceSpansAggregationQueryResponse(BaseModel):)+class TraceSpansAttributeBreakdownQueryResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ compare: list[AttributeBreakdownRow] | None = Field(+ default=None,+ description=("Result rows for the comparison period when `compareFilter.compare` is true."),+ )+ 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[AttributeBreakdownRow]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ warnings: list[DataWarehouseSyncWarning] | 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."+ ),+ )++class TraceSpansQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -11430,6 +11488,62 @@ class CachedTraceSpansAggregationQueryResponse(BaseModel):)+class CachedTraceSpansAttributeBreakdownQueryResponse(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"),+ )+ compare: list[AttributeBreakdownRow] | None = Field(+ default=None,+ description=("Result rows for the comparison period when `compareFilter.compare` is true."),+ )+ 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[AttributeBreakdownRow]+ timezone: str+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ warnings: list[DataWarehouseSyncWarning] | 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."+ ),+ )++class CachedTraceSpansQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -18769,7 +18883,52 @@ class QueryResponseAlternative81(BaseModel):)-class QueryResponseAlternative83(BaseModel):+class QueryResponseAlternative82(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ compare: list[AttributeBreakdownRow] | None = Field(+ default=None,+ description=("Result rows for the comparison period when `compareFilter.compare` is true."),+ )+ 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[AttributeBreakdownRow]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ warnings: list[DataWarehouseSyncWarning] | 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."+ ),+ )+++class QueryResponseAlternative84(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -18813,7 +18972,7 @@ class QueryResponseAlternative83(BaseModel):)-class QueryResponseAlternative84(BaseModel):+class QueryResponseAlternative85(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -18857,7 +19016,7 @@ class QueryResponseAlternative84(BaseModel):)-class QueryResponseAlternative85(BaseModel):+class QueryResponseAlternative86(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -18898,7 +19057,7 @@ class QueryResponseAlternative85(BaseModel):)-class QueryResponseAlternative86(BaseModel):+class QueryResponseAlternative87(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -18943,7 +19102,7 @@ class QueryResponseAlternative86(BaseModel):)-class QueryResponseAlternative89(BaseModel):+class QueryResponseAlternative90(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -18984,7 +19143,7 @@ class QueryResponseAlternative89(BaseModel):)-class QueryResponseAlternative90(BaseModel):+class QueryResponseAlternative91(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -19025,7 +19184,7 @@ class QueryResponseAlternative90(BaseModel):)-class QueryResponseAlternative91(BaseModel):+class QueryResponseAlternative92(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -19076,7 +19235,7 @@ class QueryResponseAlternative91(BaseModel):)-class QueryResponseAlternative92(BaseModel):+class QueryResponseAlternative93(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -19117,7 +19276,7 @@ class QueryResponseAlternative92(BaseModel):)-class QueryResponseAlternative93(BaseModel):+class QueryResponseAlternative94(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -19163,7 +19322,7 @@ class QueryResponseAlternative93(BaseModel):)-class QueryResponseAlternative94(BaseModel):+class QueryResponseAlternative95(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -19204,7 +19363,7 @@ class QueryResponseAlternative94(BaseModel):)-class QueryResponseAlternative95(BaseModel):+class QueryResponseAlternative96(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -20498,6 +20657,7 @@ class AnyResponseType(| TraceSpansQueryResponse| TraceSpansAggregationQueryResponse| TraceSpansTreeQueryResponse+ | TraceSpansAttributeBreakdownQueryResponse]):root: (@@ -20516,6 +20676,7 @@ class AnyResponseType(| TraceSpansQueryResponse| TraceSpansAggregationQueryResponse| TraceSpansTreeQueryResponse+ | TraceSpansAttributeBreakdownQueryResponse)@@ -21912,6 +22073,38 @@ class TraceSpansAggregationQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")+class TraceSpansAttributeBreakdownQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ breakdownKey: str = Field(+ ...,+ description=("Attribute key to group by (e.g. `http.response.status_code`, `server.address`)."),+ )+ breakdownType: TraceSpanBreakdownType = Field(+ ...,+ description=("Where the key lives: span-level attributes or resource-level attributes."),+ )+ compareFilter: CompareFilter | None = Field(+ default=None,+ description=(+ "Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set."+ ),+ )+ dateRange: DateRange+ filterGroup: PropertyGroupFilter | None = None+ kind: Literal["TraceSpansAttributeBreakdownQuery"] = "TraceSpansAttributeBreakdownQuery"+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ orderBy: TraceSpanBreakdownOrderBy | None = Field(+ default=None,+ description=("Order rows by span count or error count, descending. Defaults to count."),+ )+ response: TraceSpansAttributeBreakdownQueryResponse | None = None+ serviceNames: list[str] | None = None+ tags: QueryLogTags | None = None+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")++class TraceSpansQuery(BaseModel):model_config = ConfigDict(extra="forbid",@@ -23947,7 +24140,7 @@ class QueryResponseAlternative(| QueryResponseAlternative84| QueryResponseAlternative85| QueryResponseAlternative86- | QueryResponseAlternative88+ | QueryResponseAlternative87| QueryResponseAlternative89| QueryResponseAlternative90| QueryResponseAlternative91@@ -23955,6 +24148,7 @@ class QueryResponseAlternative(| QueryResponseAlternative93| QueryResponseAlternative94| QueryResponseAlternative95+ | QueryResponseAlternative96]):root: (@@ -24041,7 +24235,7 @@ class QueryResponseAlternative(| QueryResponseAlternative84| QueryResponseAlternative85| QueryResponseAlternative86- | QueryResponseAlternative88+ | QueryResponseAlternative87| QueryResponseAlternative89| QueryResponseAlternative90| QueryResponseAlternative91@@ -24049,6 +24243,7 @@ class QueryResponseAlternative(| QueryResponseAlternative93| QueryResponseAlternative94| QueryResponseAlternative95+ | QueryResponseAlternative96)@@ -25079,6 +25274,7 @@ class HogQLAutocomplete(BaseModel):| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| ExperimentFunnelsQuery| ExperimentTrendsQuery| CalendarHeatmapQuery@@ -25167,6 +25363,7 @@ class HogQLMetadata(BaseModel):| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| ExperimentFunnelsQuery| ExperimentTrendsQuery| CalendarHeatmapQuery@@ -25290,6 +25487,7 @@ class MaxInsightContext(BaseModel):| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -25410,6 +25608,7 @@ class QueryRequest(BaseModel):| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -25522,6 +25721,7 @@ class QuerySchemaRoot(| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -25604,6 +25804,7 @@ class QuerySchemaRoot(| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -25691,6 +25892,7 @@ class QueryUpgradeRequest(BaseModel):| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -25778,6 +25980,7 @@ class QueryUpgradeResponse(BaseModel):| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -26025,6 +26228,7 @@ class VisualizationArtifactContent(BaseModel):| TraceSpansQuery| TraceSpansAggregationQuery| TraceSpansTreeQuery+ | TraceSpansAttributeBreakdownQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuerydiff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 36a720a655d6..90264046832c 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2014,6 +2014,7 @@ class NodeKind(StrEnum):TRACE_SPANS_QUERY = "TraceSpansQuery"TRACE_SPANS_AGGREGATION_QUERY = "TraceSpansAggregationQuery"TRACE_SPANS_TREE_QUERY = "TraceSpansTreeQuery"+ TRACE_SPANS_ATTRIBUTE_BREAKDOWN_QUERY = "TraceSpansAttributeBreakdownQuery"SESSION_BATCH_EVENTS_QUERY = "SessionBatchEventsQuery"DATA_TABLE_NODE = "DataTableNode"DATA_VISUALIZATION_NODE = "DataVisualizationNode"@@ -2799,6 +2800,16 @@ class TraceOrderColumn(StrEnum):DURATION = "duration"+class TraceSpanBreakdownOrderBy(StrEnum):+ COUNT = "count"+ ERROR_COUNT = "error_count"+++class TraceSpanBreakdownType(StrEnum):+ SPAN_ATTRIBUTE = "span_attribute"+ SPAN_RESOURCE_ATTRIBUTE = "span_resource_attribute"++class DetailedResultsAggregationType(StrEnum):TOTAL = "total"AVERAGE = "average"diff --git a/products/tracing/backend/aggregation_query_runner.py b/products/tracing/backend/aggregation_query_runner.pyindex b0a6d83d6e1a..a30d948d9f8b 100644--- a/products/tracing/backend/aggregation_query_runner.py+++ b/products/tracing/backend/aggregation_query_runner.py@@ -23,6 +23,7 @@ from zoneinfo import ZoneInfofrom posthog.schema import (AggregatedSpanRow,+ AttributeBreakdownRow,CachedTraceSpansAggregationQueryResponse,CachedTraceSpansTreeQueryResponse,DateRange,@@ -35,6 +36,7 @@ from posthog.schema import (SpanTreeNode,TraceSpansAggregationQuery,TraceSpansAggregationQueryResponse,+ TraceSpansAttributeBreakdownQuery,TraceSpansTreeQuery,TraceSpansTreeQueryResponse,)@@ -78,7 +80,7 @@ class _SpanAggregationMixin:# with the narrower concrete type; the runtime attribute values come from `QueryRunner`# initialization on the concrete class, not from this mixin.if TYPE_CHECKING:- query: TraceSpansAggregationQuery | TraceSpansTreeQuery+ query: TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQueryteam: "Team"modifiers: HogQLQueryModifierstimings: HogQLTimings@@ -254,7 +256,7 @@ class _SpanAggregationMixin:def _build_query(self, query_date_range: QueryDateRange) -> ast.SelectQuery:raise NotImplementedError- def _row_from_clickhouse(self, row: list) -> AggregatedSpanRow | SpanTreeNode:+ def _row_from_clickhouse(self, row: list) -> AggregatedSpanRow | SpanTreeNode | AttributeBreakdownRow:raise NotImplementedErrordiff --git a/products/tracing/backend/attribute_breakdown_query_runner.py b/products/tracing/backend/attribute_breakdown_query_runner.pynew file mode 100644index 000000000000..aa50f20cb2f3--- /dev/null+++ b/products/tracing/backend/attribute_breakdown_query_runner.py@@ -0,0 +1,136 @@+from typing import TYPE_CHECKING++from posthog.schema import (+ AttributeBreakdownRow,+ CachedTraceSpansAttributeBreakdownQueryResponse,+ CompareFilter,+ DateRange,+ PropertyGroupFilter,+ PropertyGroupsMode,+ TraceSpanBreakdownOrderBy,+ TraceSpanBreakdownType,+ TraceSpansAttributeBreakdownQuery,+ TraceSpansAttributeBreakdownQueryResponse,+)++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode+from posthog.hogql_queries.utils.query_date_range import QueryDateRange++from products.tracing.backend.aggregation_query_runner import _ROW_LIMIT, _SpanAggregationMixin+from products.tracing.backend.logic import TIME_BUCKET_DATE_RANGE_WHERE++if TYPE_CHECKING:+ from posthog.models import Team++# Validated enum value → ClickHouse ORDER BY column. Lookup keeps user input out of the SQL string.+_ORDER_COLUMNS: dict[TraceSpanBreakdownOrderBy, str] = {+ TraceSpanBreakdownOrderBy.COUNT: "count",+ TraceSpanBreakdownOrderBy.ERROR_COUNT: "error_count",+}+++class TraceSpansAttributeBreakdownQueryRunner(+ _SpanAggregationMixin, AnalyticsQueryRunner[TraceSpansAttributeBreakdownQueryResponse]+):+ """Span counts grouped by one attribute's value — the "what's different" facet primitive.++ Single-table ``GROUP BY`` on a span or resource attribute value within a filtered span+ set. One row per distinct value; spans without the attribute group under ``''``.+ """++ query: TraceSpansAttributeBreakdownQuery+ cached_response: CachedTraceSpansAttributeBreakdownQueryResponse++ def __init__(self, query: TraceSpansAttributeBreakdownQuery, *args, **kwargs) -> None:+ super().__init__(query, *args, **kwargs)+ self.modifiers.convertToProjectTimezone = False+ self.modifiers.propertyGroupsMode = PropertyGroupsMode.OPTIMIZED+ self._extract_filters()++ def _calculate(self) -> TraceSpansAttributeBreakdownQueryResponse:+ current_rows, previous_rows = self._run_with_compare()+ return TraceSpansAttributeBreakdownQueryResponse(results=current_rows, compare=previous_rows)++ def _build_query(self, query_date_range: QueryDateRange) -> ast.SelectQuery:+ if self.query.breakdownType == TraceSpanBreakdownType.SPAN_RESOURCE_ATTRIBUTE:+ # resource_attributes' property group matches any key as-is.+ breakdown_chain: list[str | int] = ["resource_attributes", self.query.breakdownKey]+ else:+ # Span attribute keys carry a type suffix in the physical map (attributes_map_str);+ # the property-group resolver only rewrites suffixed keys to map access — a bare key+ # falls through to a JSON read, which is illegal on the Map column. Every value is+ # present in the __str map (the float/datetime maps are derived from it).+ breakdown_chain = ["attributes", f"{self.query.breakdownKey}__str"]+ order_column = _ORDER_COLUMNS[self.query.orderBy or TraceSpanBreakdownOrderBy.COUNT]++ query = parse_select(+ """+ SELECT+ {breakdown_field} AS value,+ count() AS count,+ countIf(status_code = 2) AS error_count,+ quantile(0.5)(duration_nano) AS p50_duration_nano,+ quantile(0.95)(duration_nano) AS p95_duration_nano+ FROM posthog.trace_spans+ WHERE {where}+ AND """+ + TIME_BUCKET_DATE_RANGE_WHERE+ + """+ AND timestamp >= {date_from}+ AND timestamp < {date_to}+ GROUP BY value+ ORDER BY """+ + order_column+ + """ DESC+ LIMIT {limit}+ """,+ placeholders={+ "breakdown_field": ast.Field(chain=breakdown_chain),+ "where": self._where_without_date_range(),+ "limit": ast.Constant(value=_ROW_LIMIT),+ **query_date_range.to_placeholders(),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return query++ def _row_from_clickhouse(self, row: list) -> AttributeBreakdownRow:+ return AttributeBreakdownRow(+ value=row[0] or "",+ count=row[1],+ error_count=row[2] or 0,+ p50_duration_nano=float(row[3] or 0),+ p95_duration_nano=float(row[4] or 0),+ )+++def run_attribute_breakdown_query(+ *,+ team: "Team",+ date_range: DateRange,+ breakdown_key: str,+ breakdown_type: TraceSpanBreakdownType,+ order_by: TraceSpanBreakdownOrderBy | None = None,+ compare_filter: CompareFilter | None = None,+ filter_group: PropertyGroupFilter | None = None,+ service_names: list[str] | None = None,+) -> TraceSpansAttributeBreakdownQueryResponse | CachedTraceSpansAttributeBreakdownQueryResponse:+ """Facade-friendly entry point for running an attribute breakdown query."""+ query = TraceSpansAttributeBreakdownQuery(+ dateRange=date_range,+ breakdownKey=breakdown_key,+ breakdownType=breakdown_type,+ orderBy=order_by,+ compareFilter=compare_filter,+ filterGroup=filter_group,+ serviceNames=service_names,+ )+ runner = TraceSpansAttributeBreakdownQueryRunner(query, team)+ response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert isinstance(+ response, TraceSpansAttributeBreakdownQueryResponse | CachedTraceSpansAttributeBreakdownQueryResponse+ )+ return responsediff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.pyindex 10404e6994c5..0336fcace025 100644--- a/products/tracing/backend/facade/api.py+++ b/products/tracing/backend/facade/api.py@@ -18,8 +18,21 @@ Do NOT:from typing import TYPE_CHECKING-from posthog.schema import CachedTraceSpansQueryResponse, DateRange, PropertyGroupFilter, TraceSpansQueryResponse+from posthog.schema import (+ CachedTraceSpansAttributeBreakdownQueryResponse,+ CachedTraceSpansQueryResponse,+ CompareFilter,+ DateRange,+ PropertyGroupFilter,+ TraceSpanBreakdownOrderBy,+ TraceSpanBreakdownType,+ TraceSpansAttributeBreakdownQueryResponse,+ TraceSpansQueryResponse,+)+from products.tracing.backend.attribute_breakdown_query_runner import (+ run_attribute_breakdown_query as _run_attribute_breakdown_query,+)from products.tracing.backend.count_query_runner import run_count_query as _run_count_queryfrom products.tracing.backend.duration_histogram_query_runner import (run_duration_histogram_query as _run_duration_histogram_query,@@ -54,6 +67,30 @@ def run_count_query()+def run_attribute_breakdown_query(+ *,+ team: "Team",+ date_range: DateRange,+ breakdown_key: str,+ breakdown_type: TraceSpanBreakdownType,+ order_by: TraceSpanBreakdownOrderBy | None = None,+ compare_filter: CompareFilter | None = None,+ filter_group: PropertyGroupFilter | None = None,+ service_names: list[str] | None = None,+) -> TraceSpansAttributeBreakdownQueryResponse | CachedTraceSpansAttributeBreakdownQueryResponse:+ """Run a span breakdown grouped by one attribute's value within a filtered span set."""+ return _run_attribute_breakdown_query(+ team=team,+ date_range=date_range,+ breakdown_key=breakdown_key,+ breakdown_type=breakdown_type,+ order_by=order_by,+ compare_filter=compare_filter,+ filter_group=filter_group,+ service_names=service_names,+ )++def run_duration_histogram_query(*,team: "Team",diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex 03a6232b9599..f93a816f977f 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -780,12 +780,6 @@ def run_attribute_values_query(return results-# Imported below the helpers above (and `translate_span_filter`) because the runners-# import `translate_span_filter` from this module. Keeping this import at the bottom-# avoids a partial-load circular import.-from .aggregation_query_runner import TraceSpansAggregationQueryRunner, TraceSpansTreeQueryRunner # noqa: E402--def run_aggregation_query(*,team: "Team",@@ -795,6 +789,10 @@ def run_aggregation_query(service_names: list[str] | None = None,) -> TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse:"""Facade-friendly entry point for running a flat span aggregation query."""+ # noqa-justified: the runners import `translate_span_filter` from this module, so a+ # module-level import here is circular and only resolves when this module loads first.+ from .aggregation_query_runner import TraceSpansAggregationQueryRunner # noqa: PLC0415+query = TraceSpansAggregationQuery(dateRange=date_range,compareFilter=compare_filter,@@ -818,6 +816,9 @@ def run_tree_query(service_names: list[str] | None = None,) -> TraceSpansTreeQueryResponse | CachedTraceSpansTreeQueryResponse:"""Facade-friendly entry point for running a span call-tree aggregation query."""+ # noqa-justified: same circular import as run_aggregation_query above.+ from .aggregation_query_runner import TraceSpansTreeQueryRunner # noqa: PLC0415+query = TraceSpansTreeQuery(dateRange=date_range,spanName=span_name,diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex d2e9d7483beb..23cbab027060 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -27,6 +27,8 @@ from posthog.schema import (DateRange,ProductKey,PropertyGroupFilter,+ TraceSpanBreakdownOrderBy,+ TraceSpanBreakdownType,TraceSpansQuery,TraceSpansQueryResponse,)@@ -38,7 +40,7 @@ from posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.event_usage import report_user_actionfrom posthog.hogql_queries.query_runner import ExecutionMode-from ..facade.api import run_count_query, run_duration_histogram_query+from ..facade.api import run_attribute_breakdown_query, run_count_query, run_duration_histogram_queryfrom ..has_spans_query_runner import team_has_spansfrom ..logic import (TraceSpansQueryRunner,@@ -252,6 +254,45 @@ class _TracingAggregationRequestSerializer(serializers.Serializer):query = _TracingAggregationQueryBodySerializer(help_text="The span aggregation query to execute.")+class _TracingAttributeBreakdownQueryBodySerializer(serializers.Serializer):+ breakdownKey = serializers.CharField(+ required=True,+ help_text='Attribute key to group by (e.g. "server.address", "http.response.status_code"). Discover keys with apm-attributes-list.',+ )+ breakdownType = serializers.ChoiceField(+ choices=["span_attribute", "span_resource_attribute"],+ help_text='Where the key lives: "span_attribute" for span-level attributes, "span_resource_attribute" for resource-level attributes.',+ )+ orderBy = serializers.ChoiceField(+ choices=["count", "error_count"],+ required=False,+ help_text="Order rows by span count or error count, descending. Defaults to count.",+ )+ dateRange = _TracingDateRangeSerializer(+ required=False,+ help_text="Date range for the primary window. Defaults to last hour.",+ )+ compareFilter = _CompareFilterSerializer(+ required=False,+ help_text="Optional comparison-window configuration. When omitted, only the primary window is returned.",+ )+ serviceNames = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Filter by service names.",+ )+ filterGroup = serializers.ListField(+ child=_SpanPropertyFilterSerializer(),+ required=False,+ default=[],+ help_text="Property filters scoping the spans the breakdown runs over (e.g. only error spans).",+ )+++class _TracingAttributeBreakdownRequestSerializer(serializers.Serializer):+ query = _TracingAttributeBreakdownQueryBodySerializer(help_text="The attribute breakdown query to execute.")++class _TracingTreeQueryBodySerializer(serializers.Serializer):spanName = serializers.CharField(required=True,@@ -664,6 +705,75 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)status=status.HTTP_200_OK,)+ @extend_schema(request=_TracingAttributeBreakdownRequestSerializer)+ @action(detail=False, methods=["POST"], url_path="attribute-breakdown", required_scopes=["tracing:read"])+ def attribute_breakdown(self, request: Request, *args, **kwargs) -> Response:+ tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)+ query_data = request.data.get("query", {}) or {}++ breakdown_key = query_data.get("breakdownKey")+ if not breakdown_key or not isinstance(breakdown_key, str):+ return Response(+ {"detail": "`breakdownKey` is required for attribute breakdown queries."},+ status=status.HTTP_400_BAD_REQUEST,+ )++ try:+ breakdown_type = TraceSpanBreakdownType(query_data.get("breakdownType") or "")+ except ValueError:+ return Response(+ {"detail": '`breakdownType` must be "span_attribute" or "span_resource_attribute".'},+ status=status.HTTP_400_BAD_REQUEST,+ )++ order_by: TraceSpanBreakdownOrderBy | None = None+ if query_data.get("orderBy"):+ try:+ order_by = TraceSpanBreakdownOrderBy(query_data["orderBy"])+ except ValueError:+ return Response(+ {"detail": '`orderBy` must be "count" or "error_count".'},+ status=status.HTTP_400_BAD_REQUEST,+ )++ date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)++ try:+ filter_group = (+ self.get_model(self._normalize_filter_group(query_data["filterGroup"]), PropertyGroupFilter)+ if query_data.get("filterGroup")+ else None+ )+ except (ValidationError, ValueError, ParseError):+ filter_group = None++ compare_filter: CompareFilter | None = None+ compare_data = query_data.get("compareFilter")+ if compare_data:+ try:+ compare_filter = self.get_model(compare_data, CompareFilter)+ except (ValidationError, ValueError, ParseError):+ compare_filter = None++ response = run_attribute_breakdown_query(+ team=self.team,+ date_range=date_range,+ breakdown_key=breakdown_key,+ breakdown_type=breakdown_type,+ order_by=order_by,+ compare_filter=compare_filter,+ filter_group=filter_group,+ service_names=query_data.get("serviceNames", None),+ )++ return Response(+ {+ "results": [row.model_dump() for row in response.results],+ "compare": [row.model_dump() for row in (response.compare or [])] if response.compare else None,+ },+ status=status.HTTP_200_OK,+ )+@extend_schema(request=_TracingTraceRequestSerializer)@action(detail=False, methods=["POST"], url_path="trace/(?P<trace_id>[a-zA-Z0-9]+)", required_scopes=["tracing:read"]diff --git a/products/tracing/backend/tests/test_attribute_breakdown.py b/products/tracing/backend/tests/test_attribute_breakdown.pynew file mode 100644index 000000000000..ee549726c0b2--- /dev/null+++ b/products/tracing/backend/tests/test_attribute_breakdown.py@@ -0,0 +1,120 @@+import datetime as dt++from parameterized import parameterized++from posthog.clickhouse.client import sync_execute++from products.tracing.backend.tests.test_keyset_pagination import DATE_FROM, DATE_TO, _b64, _TraceSpansTestBase++# CDP-style outbound POST spans hitting two destinations. Amplitude is the broken one —+# 4 of its 5 spans are errors — so a breakdown over `server.address` should surface it+# as the over-represented value among the bad spans. One span carries no attribute at+# all (groups under ''), and one lives in another service (excluded by serviceNames).+MS = 1_000_000 # ns per ms+SPANS = [+ # (service, server.address, k8s.pod.name, status_code, duration)+ ("cdp", "api2.amplitude.com", "pod-a", 2, dt.timedelta(milliseconds=100)),+ ("cdp", "api2.amplitude.com", "pod-a", 2, dt.timedelta(milliseconds=100)),+ ("cdp", "api2.amplitude.com", "pod-a", 2, dt.timedelta(milliseconds=100)),+ ("cdp", "api2.amplitude.com", "pod-a", 2, dt.timedelta(milliseconds=100)),+ ("cdp", "api2.amplitude.com", "pod-a", 0, dt.timedelta(milliseconds=100)),+ ("cdp", "api.mixpanel.com", "pod-b", 0, dt.timedelta(milliseconds=200)),+ ("cdp", "api.mixpanel.com", "pod-b", 0, dt.timedelta(milliseconds=200)),+ ("cdp", "api.mixpanel.com", "pod-b", 0, dt.timedelta(milliseconds=200)),+ ("cdp", None, "pod-b", 0, dt.timedelta(milliseconds=300)),+ ("other", "api2.amplitude.com", "pod-c", 0, dt.timedelta(milliseconds=100)),+]+++class TestTraceSpansAttributeBreakdown(_TraceSpansTestBase):+ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ cls._recreate_trace_spans_tables()++ base = dt.datetime(2026, 6, 2, 8, 0, 0)+ rows: list[str] = []+ for i, (service, address, pod, status_code, duration) in enumerate(SPANS):+ trace_id = _b64(i.to_bytes(16, "big"))+ span_id = _b64((1000 + i).to_bytes(8, "big"))+ ts_str = base.strftime("%Y-%m-%d %H:%M:%S.%f")+ end_str = (base + duration).strftime("%Y-%m-%d %H:%M:%S.%f")+ attributes = f"map('server.address__str', '{address}')" if address else "map()"+ rows.append(+ f"('019e8758-0000-0000-0000-{i:012d}', {cls.team.id}, '{trace_id}', '{span_id}', '', "+ f"'POST', 3, '{ts_str}', '{end_str}', '{ts_str}', {status_code}, '{service}', "+ f"{attributes}, map('k8s.pod.name', '{pod}'))"+ )+ sync_execute(+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "+ "timestamp, end_time, observed_timestamp, status_code, service_name, attributes_map_str, "+ "resource_attributes) VALUES " + ",".join(rows)+ )++ def _breakdown(self, **query_fields) -> list[dict]:+ query: dict = {"dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO}, **query_fields}+ response = self.client.post(+ f"/api/projects/{self.team.id}/tracing/spans/attribute-breakdown/",+ {"query": query},+ format="json",+ )+ self.assertEqual(response.status_code, 200, response.content)+ return response.json()["results"]++ @parameterized.expand(+ [+ (+ "span_attribute",+ "server.address",+ "span_attribute",+ {("api2.amplitude.com", 6, 4), ("api.mixpanel.com", 3, 0), ("", 1, 0)},+ ),+ (+ "resource_attribute",+ "k8s.pod.name",+ "span_resource_attribute",+ {("pod-a", 5, 4), ("pod-b", 4, 0), ("pod-c", 1, 0)},+ ),+ ]+ )+ def test_groups_by_attribute_value(self, _name, breakdown_key, breakdown_type, expected):+ rows = self._breakdown(breakdownKey=breakdown_key, breakdownType=breakdown_type)+ self.assertEqual(+ {(row["value"], row["count"], row["error_count"]) for row in rows},+ expected,+ )++ def test_computes_duration_quantiles(self):+ rows = self._breakdown(breakdownKey="server.address", breakdownType="span_attribute")+ by_value = {row["value"]: row for row in rows}+ # All amplitude spans run 100ms, so both quantiles sit on the constant.+ self.assertEqual(by_value["api2.amplitude.com"]["p50_duration_nano"], 100 * MS)+ self.assertEqual(by_value["api2.amplitude.com"]["p95_duration_nano"], 100 * MS)++ @parameterized.expand(+ [+ # Default order is count DESC; both rank amplitude top in this dataset.+ ("default_count_desc", {}, ("api2.amplitude.com", 4)),+ ("error_count", {"orderBy": "error_count"}, ("api2.amplitude.com", 4)),+ ]+ )+ def test_orders_by(self, _name, order_kwargs, expected_top):+ rows = self._breakdown(breakdownKey="server.address", breakdownType="span_attribute", **order_kwargs)+ self.assertEqual((rows[0]["value"], rows[0]["error_count"]), expected_top)++ def test_service_names_scope_the_breakdown(self):+ rows = self._breakdown(breakdownKey="server.address", breakdownType="span_attribute", serviceNames=["cdp"])+ by_value = {row["value"]: row["count"] for row in rows}+ self.assertEqual(by_value["api2.amplitude.com"], 5)++ def test_filter_group_scopes_the_breakdown(self):+ # The BubbleUp shape: breakdown of only the BAD spans.+ rows = self._breakdown(+ breakdownKey="server.address",+ breakdownType="span_attribute",+ filterGroup=[{"key": "status_code", "operator": "exact", "type": "span", "value": "Error"}],+ )+ self.assertEqual(+ {(row["value"], row["count"]) for row in rows},+ {("api2.amplitude.com", 4)},+ )diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex 03327274fadd..a82899ac7f8c 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -114,6 +114,57 @@ export interface _TracingAggregationRequestApi {query: _TracingAggregationQueryBodyApi}+/**+ * * `span_attribute` - span_attribute+ * * `span_resource_attribute` - span_resource_attribute+ */+export type BreakdownTypeEnumApi = (typeof BreakdownTypeEnumApi)[keyof typeof BreakdownTypeEnumApi]++export const BreakdownTypeEnumApi = {+ SpanAttribute: 'span_attribute',+ SpanResourceAttribute: 'span_resource_attribute',+} as const++/**+ * * `count` - count+ * * `error_count` - error_count+ */+export type _TracingAttributeBreakdownQueryBodyOrderByEnumApi =+ (typeof _TracingAttributeBreakdownQueryBodyOrderByEnumApi)[keyof typeof _TracingAttributeBreakdownQueryBodyOrderByEnumApi]++export const _TracingAttributeBreakdownQueryBodyOrderByEnumApi = {+ Count: 'count',+ ErrorCount: 'error_count',+} as const++export interface _TracingAttributeBreakdownQueryBodyApi {+ /** Attribute key to group by (e.g. "server.address", "http.response.status_code"). Discover keys with apm-attributes-list. */+ breakdownKey: string+ /** Where the key lives: "span_attribute" for span-level attributes, "span_resource_attribute" for resource-level attributes.+ *+ * * `span_attribute` - span_attribute+ * * `span_resource_attribute` - span_resource_attribute */+ breakdownType: BreakdownTypeEnumApi+ /** Order rows by span count or error count, descending. Defaults to count.+ *+ * * `count` - count+ * * `error_count` - error_count */+ orderBy?: _TracingAttributeBreakdownQueryBodyOrderByEnumApi+ /** Date range for the primary window. Defaults to last hour. */+ dateRange?: _TracingDateRangeApi+ /** Optional comparison-window configuration. When omitted, only the primary window is returned. */+ compareFilter?: _CompareFilterApi+ /** Filter by service names. */+ serviceNames?: string[]+ /** Property filters scoping the spans the breakdown runs over (e.g. only error spans). */+ filterGroup?: _SpanPropertyFilterApi[]+}++export interface _TracingAttributeBreakdownRequestApi {+ /** The attribute breakdown query to execute. */+ query: _TracingAttributeBreakdownQueryBodyApi+}+export interface _TracingCountBodyApi {/** Date range for the count. Defaults to last hour. */dateRange?: _TracingDateRangeApidiff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex 13d16f9504aa..d8a920b27c9a 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -14,6 +14,7 @@ import type {TracingSpansValuesRetrieveParams,_HasSpansResponseApi,_TracingAggregationRequestApi,+ _TracingAttributeBreakdownRequestApi,_TracingCountRequestApi,_TracingCountResponseApi,_TracingQueryRequestApi,@@ -38,6 +39,23 @@ export const tracingSpansAggregateCreate = async (})}+export const getTracingSpansAttributeBreakdownCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tracing/spans/attribute-breakdown/`+}++export const tracingSpansAttributeBreakdownCreate = async (+ projectId: string,+ _tracingAttributeBreakdownRequestApi: _TracingAttributeBreakdownRequestApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getTracingSpansAttributeBreakdownCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(_tracingAttributeBreakdownRequestApi),+ })+}+export const getTracingSpansAttributesRetrieveUrl = (projectId: string,params?: TracingSpansAttributesRetrieveParamsdiff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex 9439f6c509a4..49d77784299b 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -99,6 +99,116 @@ export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({.describe('The span aggregation query to execute.'),})+export const tracingSpansAttributeBreakdownCreateBodyQueryOneCompareFilterOneCompareDefault = false+export const tracingSpansAttributeBreakdownCreateBodyQueryOneFilterGroupDefault = []++export const TracingSpansAttributeBreakdownCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ breakdownKey: zod+ .string()+ .describe(+ 'Attribute key to group by (e.g. \"server.address\", \"http.response.status_code\"). Discover keys with apm-attributes-list.'+ ),+ breakdownType: zod+ .enum(['span_attribute', 'span_resource_attribute'])+ .describe(+ '\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ 'Where the key lives: \"span_attribute\" for span-level attributes, \"span_resource_attribute\" for resource-level attributes.\n\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ ),+ orderBy: zod+ .enum(['count', 'error_count'])+ .describe('\* `count` - count\n\* `error_count` - error_count')+ .optional()+ .describe(+ 'Order rows by span count or error count, descending. Defaults to count.\n\n\* `count` - count\n\* `error_count` - error_count'+ ),+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .nullish()+ .describe(+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.'+ ),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range. Same format as date_from. Omit or null for \"now\".'),+ })+ .optional()+ .describe('Date range for the primary window. Defaults to last hour.'),+ compareFilter: zod+ .object({+ compare: zod+ .boolean()+ .default(tracingSpansAttributeBreakdownCreateBodyQueryOneCompareFilterOneCompareDefault)+ .describe(+ 'When true, also fetch results for a comparison window and return them under `compare`.'+ ),+ compare_to: zod+ .string()+ .nullish()+ .describe(+ "Relative date offset for the comparison window (e.g. '-1h', '-1d', '-7d'). Defaults to the immediately previous period of equal length."+ ),+ })+ .optional()+ .describe(+ 'Optional comparison-window configuration. When omitted, only the primary window is returned.'+ ),+ serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),+ filterGroup: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'+ ),+ type: zod+ .enum(['span', 'span_attribute', 'span_resource_attribute'])+ .describe(+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'is_set',+ 'is_not_set',+ ])+ .describe(+ '\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'+ )+ .describe(+ 'Comparison operator.\n\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ 'Value to compare against. String, number, or array of strings. Omit for is_set\/is_not_set operators.'+ ),+ })+ )+ .default(tracingSpansAttributeBreakdownCreateBodyQueryOneFilterGroupDefault)+ .describe('Property filters scoping the spans the breakdown runs over (e.g. only error spans).'),+ })+ .describe('The attribute breakdown query to execute.'),+})+export const tracingSpansCountCreateBodyQueryOneFilterGroupDefault = []export const TracingSpansCountCreateBody = /* @__PURE__ */ zod.object({diff --git a/products/tracing/mcp/prompts/apm-attribute-breakdown.md b/products/tracing/mcp/prompts/apm-attribute-breakdown.mdnew file mode 100644index 000000000000..d2412f98cff4--- /dev/null+++ b/products/tracing/mcp/prompts/apm-attribute-breakdown.md@@ -0,0 +1,117 @@+Group spans by one attribute's value — the "what is different about the bad spans?" tool.++Returns one row per distinct value of the chosen attribute, across the spans matching the filters:++- `value` — the attribute's value (`''` for spans that don't carry the attribute)+- `count` — spans with that value+- `error_count` — of those, spans with OTel status `Error` (status_code = 2)+- `p50_duration_nano`, `p95_duration_nano` — duration quantiles in nanoseconds++Rows are ordered by `count` DESC (or `error_count` DESC via `orderBy`) and capped at 5000.++Use to answer:++- "Which attribute values are over-represented among the errored/slow spans?"+- "Which downstream destination (`server.address`) is failing?"+- "What `http.response.status_code` values are we getting back, and how often?"+- "Which pod / version / region is the bad traffic concentrated on?" (resource attributes)++For aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.++All parameters must be nested inside a `query` object.++# "What's different" workflow++1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.+2. Discover candidate keys with `apm-attributes-list` (don't guess — keys vary per project).+3. Run `apm-attribute-breakdown` per candidate key. A value owning most of the `count` is your signature.+4. To confirm over-representation, re-run without the bad-spans filter (or check `error_count / count` per row): a value at 95% of errors but 10% of all traffic is the smoking gun.++# Parameters++All parameters go inside `query`.++## query.breakdownKey (required)++The attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.++## query.breakdownType (required)++- `span_attribute` — span-level attributes (e.g. `server.address`, `db.statement`)+- `span_resource_attribute` — resource-level attributes (e.g. `k8s.pod.name`, `service.version`)++## query.orderBy++`count` (default) or `error_count` — rows are sorted by the chosen column, descending.++## query.dateRange++Date range for the primary window. Defaults to the last hour.++- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.+- `date_to`: End of the range. Same format. Omit or null for "now".++## query.compareFilter++Optional comparison-window configuration. Set `compare: true` to also get the breakdown for a previous window under `compare` — useful for "did this value's share change vs last week?" (`compare_to: "-7d"`).++## query.serviceNames++List of service names to restrict the breakdown to. Use `apm-services-list` to discover services.++## query.filterGroup++Property filters scoping the spans the breakdown runs over. Same filter shape and operators as `query-apm-spans`:++- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)+- `span_attribute` — span-level attributes+- `span_resource_attribute` — resource-level attributes++# Examples++## Which destinations do the errored spans hit?++```json+{+ "query": {+ "breakdownKey": "server.address",+ "breakdownType": "span_attribute",+ "filterGroup": [{ "key": "status_code", "operator": "exact", "type": "span", "value": "Error" }],+ "dateRange": { "date_from": "-1h" }+ }+}+```++## Which values drive the most errors overall?++```json+{+ "query": {+ "breakdownKey": "http.response.status_code",+ "breakdownType": "span_attribute",+ "orderBy": "error_count",+ "dateRange": { "date_from": "-6h" }+ }+}+```++## Is the bad pod's share new? (compare vs last week)++```json+{+ "query": {+ "breakdownKey": "k8s.pod.name",+ "breakdownType": "span_resource_attribute",+ "serviceNames": ["cdp-worker"],+ "dateRange": { "date_from": "-1d" },+ "compareFilter": { "compare": true, "compare_to": "-7d" }+ }+}+```++# Reminders++- `value: ''` groups the spans that don't carry the attribute at all — often itself a signal.+- Duration values are in nanoseconds (1s = 1,000,000,000).+- Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys before guessing.+- `error_count / count` per row is the error rate for that value — compute it when judging over-representation.diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yamlindex 9062b02179f4..6140ac2181e8 100644--- a/products/tracing/mcp/tools.yaml+++ b/products/tracing/mcp/tools.yaml@@ -18,6 +18,22 @@ ui_apps:item_name_field: nameclick_prop: onSpanClicktools:+ apm-attribute-breakdown:+ operation: tracing_spans_attribute_breakdown_create+ enabled: true+ scopes:+ - tracing:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Break down spans by attribute value+ description_file: ./prompts/apm-attribute-breakdown.md+ feature_flag: tracing+ response:+ include:+ - results+ - compareapm-attribute-values-list:operation: tracing_spans_values_retrieveenabled: truediff --git a/products/tracing/skills/exploring-apm-traces/SKILL.md b/products/tracing/skills/exploring-apm-traces/SKILL.mdindex a1dbc6702cc2..bac8c4fe4de0 100644--- a/products/tracing/skills/exploring-apm-traces/SKILL.md+++ b/products/tracing/skills/exploring-apm-traces/SKILL.md@@ -25,6 +25,7 @@ PostHog captures distributed traces from OpenTelemetry. Each trace is a tree of| `posthog:apm-spans-count` | Scalar span count — cheap filter pre-flight || `posthog:apm-spans-sparkline` | Span counts over time (zero-filled time series) || `posthog:apm-spans-duration-histogram` | Trace counts per log-scale duration bucket |+| `posthog:apm-attribute-breakdown` | Span counts grouped by one attribute's value || `posthog:apm-services-list` | List distinct service names || `posthog:apm-attributes-list` | List span or resource attribute keys || `posthog:apm-attribute-values-list` | List values for a specific attribute key |@@ -111,6 +112,13 @@ To rebuild the tree:1. Run `print_summary.py` — it prints the set of services involved in the trace.2. If service X is missing, the request never reached it (or instrumentation is missing — check `apm-services-list` to confirm X has emitted spans recently at all).+### "What's different about the bad spans?" (over-represented values)++1. Scope to the bad population: `filterGroup` with `status_code = Error`, or a `duration` threshold.+2. Discover candidate keys with `apm-attributes-list` — typical suspects: `server.address`, `http.response.status_code`, `db.system`, resource keys like `k8s.pod.name` / `service.version`.+3. Run `apm-attribute-breakdown` per candidate key on the bad set. A value owning most of the `count` is the signature.+4. Confirm over-representation: re-run without the bad-set filter (or compare `error_count / count` per row). A value at 95% of errors but 10% of traffic is the culprit; one at 95% of both is just volume.+### "When did it spike?" (trends over time)1. `apm-spans-sparkline` with your filters → total counts per time bucket (zero-filled, ~50 adaptive buckets per window).diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex eaf4ed0277a7..52242e575978 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -400,6 +400,21 @@"readOnlyHint": false}},+ "apm-attribute-breakdown": {+ "description": "Group spans by one attribute's value — the \"what is different about the bad spans?\" tool.\n\nReturns one row per distinct value of the chosen attribute, across the spans matching the filters:\n\n- `value` — the attribute's value (`''` for spans that don't carry the attribute)\n- `count` — spans with that value\n- `error_count` — of those, spans with OTel status `Error` (status_code = 2)\n- `p50_duration_nano`, `p95_duration_nano` — duration quantiles in nanoseconds\n\nRows are ordered by `count` DESC (or `error_count` DESC via `orderBy`) and capped at 5000.\n\nUse to answer:\n\n- \"Which attribute values are over-represented among the errored/slow spans?\"\n- \"Which downstream destination (`server.address`) is failing?\"\n- \"What `http.response.status_code` values are we getting back, and how often?\"\n- \"Which pod / version / region is the bad traffic concentrated on?\" (resource attributes)\n\nFor aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.\n\nAll parameters must be nested inside a `query` object.\n\n# \"What's different\" workflow\n\n1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.\n2. Discover candidate keys with `apm-attributes-list` (don't guess — keys vary per project).\n3. Run `apm-attribute-breakdown` per candidate key. A value owning most of the `count` is your signature.\n4. To confirm over-representation, re-run without the bad-spans filter (or check `error_count / count` per row): a value at 95% of errors but 10% of all traffic is the smoking gun.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.breakdownKey (required)\n\nThe attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.\n\n## query.breakdownType (required)\n\n- `span_attribute` — span-level attributes (e.g. `server.address`, `db.statement`)\n- `span_resource_attribute` — resource-level attributes (e.g. `k8s.pod.name`, `service.version`)\n\n## query.orderBy\n\n`count` (default) or `error_count` — rows are sorted by the chosen column, descending.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Set `compare: true` to also get the breakdown for a previous window under `compare` — useful for \"did this value's share change vs last week?\" (`compare_to: \"-7d\"`).\n\n## query.serviceNames\n\nList of service names to restrict the breakdown to. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters scoping the spans the breakdown runs over. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Which destinations do the errored spans hit?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"server.address\",\n \"breakdownType\": \"span_attribute\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"Error\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which values drive the most errors overall?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"http.response.status_code\",\n \"breakdownType\": \"span_attribute\",\n \"orderBy\": \"error_count\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Is the bad pod's share new? (compare vs last week)\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"k8s.pod.name\",\n \"breakdownType\": \"span_resource_attribute\",\n \"serviceNames\": [\"cdp-worker\"],\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n# Reminders\n\n- `value: ''` groups the spans that don't carry the attribute at all — often itself a signal.\n- Duration values are in nanoseconds (1s = 1,000,000,000).\n- Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys before guessing.\n- `error_count / count` per row is the error rate for that value — compute it when judging over-representation.",+ "category": "Tracing",+ "feature": "tracing",+ "summary": "Break down spans by attribute value",+ "title": "Break down spans by attribute value",+ "required_scopes": ["tracing:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "tracing"+ },"apm-attribute-values-list": {"description": "List values for a specific span or resource attribute key. Use to discover what values exist for a given attribute before building filters.","category": "Tracing",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex a925b71f010c..18178d11b8ea 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -416,6 +416,21 @@"readOnlyHint": false}},+ "apm-attribute-breakdown": {+ "description": "Group spans by one attribute's value — the \"what is different about the bad spans?\" tool.\n\nReturns one row per distinct value of the chosen attribute, across the spans matching the filters:\n\n- `value` — the attribute's value (`''` for spans that don't carry the attribute)\n- `count` — spans with that value\n- `error_count` — of those, spans with OTel status `Error` (status_code = 2)\n- `p50_duration_nano`, `p95_duration_nano` — duration quantiles in nanoseconds\n\nRows are ordered by `count` DESC (or `error_count` DESC via `orderBy`) and capped at 5000.\n\nUse to answer:\n\n- \"Which attribute values are over-represented among the errored/slow spans?\"\n- \"Which downstream destination (`server.address`) is failing?\"\n- \"What `http.response.status_code` values are we getting back, and how often?\"\n- \"Which pod / version / region is the bad traffic concentrated on?\" (resource attributes)\n\nFor aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.\n\nAll parameters must be nested inside a `query` object.\n\n# \"What's different\" workflow\n\n1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.\n2. Discover candidate keys with `apm-attributes-list` (don't guess — keys vary per project).\n3. Run `apm-attribute-breakdown` per candidate key. A value owning most of the `count` is your signature.\n4. To confirm over-representation, re-run without the bad-spans filter (or check `error_count / count` per row): a value at 95% of errors but 10% of all traffic is the smoking gun.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.breakdownKey (required)\n\nThe attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.\n\n## query.breakdownType (required)\n\n- `span_attribute` — span-level attributes (e.g. `server.address`, `db.statement`)\n- `span_resource_attribute` — resource-level attributes (e.g. `k8s.pod.name`, `service.version`)\n\n## query.orderBy\n\n`count` (default) or `error_count` — rows are sorted by the chosen column, descending.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Set `compare: true` to also get the breakdown for a previous window under `compare` — useful for \"did this value's share change vs last week?\" (`compare_to: \"-7d\"`).\n\n## query.serviceNames\n\nList of service names to restrict the breakdown to. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters scoping the spans the breakdown runs over. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Which destinations do the errored spans hit?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"server.address\",\n \"breakdownType\": \"span_attribute\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"Error\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which values drive the most errors overall?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"http.response.status_code\",\n \"breakdownType\": \"span_attribute\",\n \"orderBy\": \"error_count\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Is the bad pod's share new? (compare vs last week)\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"k8s.pod.name\",\n \"breakdownType\": \"span_resource_attribute\",\n \"serviceNames\": [\"cdp-worker\"],\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n# Reminders\n\n- `value: ''` groups the spans that don't carry the attribute at all — often itself a signal.\n- Duration values are in nanoseconds (1s = 1,000,000,000).\n- Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys before guessing.\n- `error_count / count` per row is the error rate for that value — compute it when judging over-representation.",+ "category": "Tracing",+ "feature": "tracing",+ "summary": "Break down spans by attribute value",+ "title": "Break down spans by attribute value",+ "required_scopes": ["tracing:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "tracing"+ },"apm-attribute-values-list": {"description": "List values for a specific span or resource attribute key. Use to discover what values exist for a given attribute before building filters.","category": "Tracing",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c94736b91765..12a823643e47 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7839,6 +7839,14 @@ export namespace Schemas {delete_verified_at: string | null;}+ export interface AttributeBreakdownRow {+ count: number;+ error_count: number;+ p50_duration_nano: number;+ p95_duration_nano: number;+ value: string;+ }+export interface UnmatchedUtmSample {/** A raw utm_source value that doesn't match the integration exactly */raw_value: string;@@ -9916,6 +9924,18 @@ export namespace Schemas {value: string | number;}+ /**+ * * `span_attribute` - span_attribute+ * * `span_resource_attribute` - span_resource_attribute+ */+ export type BreakdownTypeEnum = typeof BreakdownTypeEnum[keyof typeof BreakdownTypeEnum];+++ export const BreakdownTypeEnum = {+ SpanAttribute: 'span_attribute',+ SpanResourceAttribute: 'span_resource_attribute',+ } as const;+export interface BreakdownValue {count: number;value: string;@@ -21385,6 +21405,65 @@ export namespace Schemas {version?: number | null;}+ export type TraceSpanBreakdownType = typeof TraceSpanBreakdownType[keyof typeof TraceSpanBreakdownType];+++ export const TraceSpanBreakdownType = {+ SpanAttribute: 'span_attribute',+ SpanResourceAttribute: 'span_resource_attribute',+ } as const;++ export type TraceSpanBreakdownOrderBy = typeof TraceSpanBreakdownOrderBy[keyof typeof TraceSpanBreakdownOrderBy];+++ export const TraceSpanBreakdownOrderBy = {+ Count: 'count',+ ErrorCount: 'error_count',+ } as const;++ export interface TraceSpansAttributeBreakdownQueryResponse {+ /** 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. */+ 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: AttributeBreakdownRow[];+ /** 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. */+ warnings?: DataWarehouseSyncWarning[] | null;+ }++ export interface TraceSpansAttributeBreakdownQuery {+ /** Attribute key to group by (e.g. `http.response.status_code`, `server.address`). */+ breakdownKey: string;+ /** Where the key lives: span-level attributes or resource-level attributes. */+ breakdownType: TraceSpanBreakdownType;+ /** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */+ compareFilter?: CompareFilter | null;+ dateRange: DateRange;+ filterGroup?: PropertyGroupFilter | null;+ kind?: 'TraceSpansAttributeBreakdownQuery';+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ /** Order rows by span count or error count, descending. Defaults to count. */+ orderBy?: TraceSpanBreakdownOrderBy | null;+ response?: TraceSpansAttributeBreakdownQueryResponse | null;+ serviceNames?: string[] | null;+ tags?: QueryLogTags | null;+ /** version of the node, used for schema migrations */+ version?: number | null;+ }+export type RecordingOrder = typeof RecordingOrder[keyof typeof RecordingOrder];@@ -21743,7 +21822,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 | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | 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 | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | null;tags?: QueryLogTags | null;/** Variables to be subsituted into the query */variables?: HogQLMetadataVariables;@@ -21769,7 +21848,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 | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | 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 | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | null;/** Start position of the editor word */startPosition: number;tags?: QueryLogTags | null;@@ -37389,7 +37468,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 | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | 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 | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | 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@@ -39135,12 +39214,34 @@ export namespace Schemas {}export interface QueryResponseAlternative82 {+ /** 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. */+ 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: AttributeBreakdownRow[];+ /** 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. */+ warnings?: DataWarehouseSyncWarning[] | null;+ }++ export interface QueryResponseAlternative83 {questions: string[];/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative83 {+ export interface QueryResponseAlternative84 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;hasMore?: boolean | null;@@ -39163,7 +39264,7 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative84 {+ export interface QueryResponseAlternative85 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;hasMore?: boolean | null;@@ -39186,7 +39287,7 @@ export namespace Schemas {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;/** Generated HogQL query. */@@ -39206,7 +39307,7 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative86 {+ export interface QueryResponseAlternative87 {columns?: string[] | null;/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -39230,7 +39331,7 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative88 {+ export interface QueryResponseAlternative89 {/** Timestamp of the newer trace */newerTimestamp?: string | null;/** ID of the newer trace (chronologically after current) */@@ -39245,7 +39346,7 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative89 {+ export interface QueryResponseAlternative90 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -39265,7 +39366,7 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative90 {+ export interface QueryResponseAlternative91 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -39285,7 +39386,7 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative91 {+ export interface QueryResponseAlternative92 {columns: unknown[];/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -39313,7 +39414,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. */@@ -39333,7 +39434,7 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}- export interface QueryResponseAlternative93 {+ export interface QueryResponseAlternative94 {columns?: unknown[] | null;/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -39358,9 +39459,9 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}- export type QueryResponseAlternative94ResultsItem = { [key: string]: unknown };+ export type QueryResponseAlternative95ResultsItem = { [key: string]: unknown };- export interface QueryResponseAlternative94 {+ export interface QueryResponseAlternative95 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -39373,14 +39474,14 @@ export namespace Schemas {resolved_compare_date_range?: ResolvedDateRangeResponse | null;/** The date range used for the query */resolved_date_range?: ResolvedDateRangeResponse | null;- results: QueryResponseAlternative94ResultsItem[];+ results: QueryResponseAlternative95ResultsItem[];/** 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. */warnings?: DataWarehouseSyncWarning[] | 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. */@@ -39400,18 +39501,18 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | 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 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95;+ 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 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96;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 | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | 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 | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | 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 | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | 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 | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | PropertyValuesQuery;}export interface QuotaResourceLimit {@@ -43997,6 +44098,46 @@ export namespace Schemas {query: _TracingAggregationQueryBody;}+ /**+ * * `count` - count+ * * `error_count` - error_count+ */+ export type _TracingAttributeBreakdownQueryBodyOrderByEnum = typeof _TracingAttributeBreakdownQueryBodyOrderByEnum[keyof typeof _TracingAttributeBreakdownQueryBodyOrderByEnum];+++ export const _TracingAttributeBreakdownQueryBodyOrderByEnum = {+ Count: 'count',+ ErrorCount: 'error_count',+ } as const;++ export interface _TracingAttributeBreakdownQueryBody {+ /** Attribute key to group by (e.g. "server.address", "http.response.status_code"). Discover keys with apm-attributes-list. */+ breakdownKey: string;+ /** Where the key lives: "span_attribute" for span-level attributes, "span_resource_attribute" for resource-level attributes.+ *+ * * `span_attribute` - span_attribute+ * * `span_resource_attribute` - span_resource_attribute */+ breakdownType: BreakdownTypeEnum;+ /** Order rows by span count or error count, descending. Defaults to count.+ *+ * * `count` - count+ * * `error_count` - error_count */+ orderBy?: _TracingAttributeBreakdownQueryBodyOrderByEnum;+ /** Date range for the primary window. Defaults to last hour. */+ dateRange?: _TracingDateRange;+ /** Optional comparison-window configuration. When omitted, only the primary window is returned. */+ compareFilter?: _CompareFilter;+ /** Filter by service names. */+ serviceNames?: string[];+ /** Property filters scoping the spans the breakdown runs over (e.g. only error spans). */+ filterGroup?: _SpanPropertyFilter[];+ }++ export interface _TracingAttributeBreakdownRequest {+ /** The attribute breakdown query to execute. */+ query: _TracingAttributeBreakdownQueryBody;+ }+export interface _TracingCountBody {/** Date range for the count. Defaults to last hour. */dateRange?: _TracingDateRange;diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.tsindex 4de2549faab3..bf5d404a8611 100644--- a/services/mcp/src/generated/tracing/api.ts+++ b/services/mcp/src/generated/tracing/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 10 enabled ops+ * PostHog API - MCP 11 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -106,6 +106,122 @@ export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({.describe('The span aggregation query to execute.'),})+export const TracingSpansAttributeBreakdownCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const tracingSpansAttributeBreakdownCreateBodyQueryOneCompareFilterOneCompareDefault = false+export const tracingSpansAttributeBreakdownCreateBodyQueryOneFilterGroupDefault = []++export const TracingSpansAttributeBreakdownCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ breakdownKey: zod+ .string()+ .describe(+ 'Attribute key to group by (e.g. "server.address", "http.response.status_code"). Discover keys with apm-attributes-list.'+ ),+ breakdownType: zod+ .enum(['span_attribute', 'span_resource_attribute'])+ .describe('* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute')+ .describe(+ 'Where the key lives: "span_attribute" for span-level attributes, "span_resource_attribute" for resource-level attributes.\n\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute'+ ),+ orderBy: zod+ .enum(['count', 'error_count'])+ .describe('* `count` - count\n* `error_count` - error_count')+ .optional()+ .describe(+ 'Order rows by span count or error count, descending. Defaults to count.\n\n* `count` - count\n* `error_count` - error_count'+ ),+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .nullish()+ .describe(+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.'+ ),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range. Same format as date_from. Omit or null for "now".'),+ })+ .optional()+ .describe('Date range for the primary window. Defaults to last hour.'),+ compareFilter: zod+ .object({+ compare: zod+ .boolean()+ .default(tracingSpansAttributeBreakdownCreateBodyQueryOneCompareFilterOneCompareDefault)+ .describe(+ 'When true, also fetch results for a comparison window and return them under `compare`.'+ ),+ compare_to: zod+ .string()+ .nullish()+ .describe(+ "Relative date offset for the comparison window (e.g. '-1h', '-1d', '-7d'). Defaults to the immediately previous period of equal length."+ ),+ })+ .optional()+ .describe(+ 'Optional comparison-window configuration. When omitted, only the primary window is returned.'+ ),+ serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),+ filterGroup: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type "span", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For "span_attribute"/"span_resource_attribute", use the attribute key (e.g. "http.method").'+ ),+ type: zod+ .enum(['span', 'span_attribute', 'span_resource_attribute'])+ .describe(+ '* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ '"span" filters built-in span fields. "span_attribute" filters span-level attributes. "span_resource_attribute" filters resource-level attributes.\n\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'is_set',+ 'is_not_set',+ ])+ .describe(+ '* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_set` - is_set\n* `is_not_set` - is_not_set'+ )+ .describe(+ 'Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_set` - is_set\n* `is_not_set` - is_not_set'+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ 'Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators.'+ ),+ })+ )+ .default(tracingSpansAttributeBreakdownCreateBodyQueryOneFilterGroupDefault)+ .describe('Property filters scoping the spans the breakdown runs over (e.g. only error spans).'),+ })+ .describe('The attribute breakdown query to execute.'),+})+export const TracingSpansAttributesRetrieveParams = /* @__PURE__ */ zod.object({project_id: zod.string()diff --git a/services/mcp/src/tools/generated/tracing.ts b/services/mcp/src/tools/generated/tracing.tsindex 94bb22cc7f40..3ccc6cdcd04e 100644--- a/services/mcp/src/tools/generated/tracing.ts+++ b/services/mcp/src/tools/generated/tracing.ts@@ -4,6 +4,7 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {TracingSpansAggregateCreateBody,+ TracingSpansAttributeBreakdownCreateBody,TracingSpansAttributesRetrieveQueryParams,TracingSpansCountCreateBody,TracingSpansDurationHistogramCreateBody,@@ -19,6 +20,27 @@ import { withUiApp } from '@/resources/ui-apps'import { pickResponseFields } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+const ApmAttributeBreakdownSchema = TracingSpansAttributeBreakdownCreateBody++const apmAttributeBreakdown = (): ToolBase<typeof ApmAttributeBreakdownSchema, unknown> => ({+ name: 'apm-attribute-breakdown',+ schema: ApmAttributeBreakdownSchema,+ handler: async (context: Context, params: z.infer<typeof ApmAttributeBreakdownSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.query !== undefined) {+ body['query'] = params.query+ }+ const result = await context.api.request<unknown>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/attribute-breakdown/`,+ body,+ })+ const filtered = pickResponseFields(result, ['results', 'compare']) as typeof result+ return filtered+ },+})+const ApmAttributeValuesListSchema = TracingSpansValuesRetrieveQueryParamsconst apmAttributeValuesList = (): ToolBase<typeof ApmAttributeValuesListSchema, unknown> => ({@@ -239,6 +261,7 @@ const queryApmSpans = (): ToolBase<typeof QueryApmSpansSchema, unknown> =>})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'apm-attribute-breakdown': apmAttributeBreakdown,'apm-attribute-values-list': apmAttributeValuesList,'apm-attributes-list': apmAttributesList,'apm-services-list': apmServicesList,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-breakdown.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-breakdown.jsonnew file mode 100644index 000000000000..b49984b48442--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-breakdown.json@@ -0,0 +1,124 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "query": {+ "description": "The attribute breakdown query to execute.",+ "properties": {+ "breakdownKey": {+ "description": "Attribute key to group by (e.g. \"server.address\", \"http.response.status_code\"). Discover keys with apm-attributes-list.",+ "type": "string"+ },+ "breakdownType": {+ "description": "Where the key lives: \"span_attribute\" for span-level attributes, \"span_resource_attribute\" for resource-level attributes.\n\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute",+ "enum": ["span_attribute", "span_resource_attribute"],+ "type": "string"+ },+ "compareFilter": {+ "description": "Optional comparison-window configuration. When omitted, only the primary window is returned.",+ "properties": {+ "compare": {+ "default": false,+ "description": "When true, also fetch results for a comparison window and return them under `compare`.",+ "type": "boolean"+ },+ "compare_to": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Relative date offset for the comparison window (e.g. '-1h', '-1d', '-7d'). Defaults to the immediately previous period of equal length."+ }+ },+ "type": "object"+ },+ "dateRange": {+ "description": "Date range for the primary window. Defaults to last hour.",+ "properties": {+ "date_from": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc."+ },+ "date_to": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "End of the date range. Same format as date_from. Omit or null for \"now\"."+ }+ },+ "type": "object"+ },+ "filterGroup": {+ "default": [],+ "description": "Property filters scoping the spans the breakdown runs over (e.g. only error spans).",+ "items": {+ "properties": {+ "key": {+ "description": "Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").",+ "type": "string"+ },+ "operator": {+ "description": "Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_set` - is_set\n* `is_not_set` - is_not_set",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex",+ "gt",+ "lt",+ "is_set",+ "is_not_set"+ ],+ "type": "string"+ },+ "type": {+ "description": "\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute",+ "enum": ["span", "span_attribute", "span_resource_attribute"],+ "type": "string"+ },+ "value": {+ "description": "Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators."+ }+ },+ "required": ["key", "type", "operator"],+ "type": "object"+ },+ "type": "array"+ },+ "orderBy": {+ "description": "Order rows by span count or error count, descending. Defaults to count.\n\n* `count` - count\n* `error_count` - error_count",+ "enum": ["count", "error_count"],+ "type": "string"+ },+ "serviceNames": {+ "description": "Filter by service names.",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["breakdownKey", "breakdownType"],+ "type": "object"+ }+ },+ "required": ["query"],+ "type": "object"+}