: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 trace spans aggregation query and API (#58253)
Frank Hamandb466068c76f2
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex fb714c0ceca8..bcf1050b645e 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -22,6 +22,7 @@ import { getCurrentExporterData, isSharedView } from '~/exporter/exporterViewLogimport { OrganizationOAuthApplicationApi } from '~/generated/core/api.schemas'import { Variable } from '~/queries/nodes/DataVisualization/types'import {+ AggregatedSpanRow,AnyResponseType,DashboardFilter,DataWarehouseManagedViewsetKind,@@ -56,6 +57,7 @@ import {RecordingsQueryResponse,RefreshType,SourceConfig,+ SpanTreeNode,TileFilters,UserProductListItem,} from '~/queries/schema/schema-general'@@ -2864,6 +2866,29 @@ const api = {}> {return new ApiRequest().tracingSpans().withAction('sparkline').create({ data: { query } })},+ async aggregate(query: {+ dateRange?: { date_from?: string | null; date_to?: string | null }+ serviceNames?: string[]+ filterGroup?: PropertyGroupFilter+ compareFilter?: { compare?: boolean; compare_to?: string | null }+ }): Promise<{+ results: AggregatedSpanRow[]+ compare?: AggregatedSpanRow[] | null+ }> {+ return new ApiRequest().tracingSpans().withAction('aggregate').create({ data: { query } })+ },+ async tree(query: {+ spanName: string+ dateRange?: { date_from?: string | null; date_to?: string | null }+ serviceNames?: string[]+ filterGroup?: PropertyGroupFilter+ compareFilter?: { compare?: boolean; compare_to?: string | null }+ }): Promise<{+ results: SpanTreeNode[]+ compare?: SpanTreeNode[] | null+ }> {+ return new ApiRequest().tracingSpans().withAction('tree').create({ data: { query } })+ },async serviceNames(params: { dateRange?: string; search?: string }): Promise<{ results: { name: string }[] }> {return new ApiRequest().tracingSpans()diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 18485606ba6a..f821ad205237 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -375,6 +375,47 @@],"type": "string"},+ "AggregatedSpanRow": {+ "additionalProperties": false,+ "description": "One aggregated span row keyed by `(service_name, name)`. Used by the delta-table view.",+ "properties": {+ "avg_duration_nano": {+ "type": "number"+ },+ "count": {+ "$ref": "#/definitions/integer"+ },+ "error_count": {+ "$ref": "#/definitions/integer"+ },+ "name": {+ "type": "string"+ },+ "p50_duration_nano": {+ "type": "number"+ },+ "p95_duration_nano": {+ "type": "number"+ },+ "service_name": {+ "type": "string"+ },+ "total_duration_nano": {+ "type": "number"+ }+ },+ "required": [+ "service_name",+ "name",+ "count",+ "total_duration_nano",+ "avg_duration_nano",+ "p50_duration_nano",+ "p95_duration_nano",+ "error_count"+ ],+ "type": "object"+ },"AggregationAxisFormat": {"enum": ["numeric", "duration", "duration_ms", "percentage", "percentage_scaled", "currency", "short"],"type": "string"@@ -625,6 +666,12 @@{"$ref": "#/definitions/TraceSpansQuery"},+ {+ "$ref": "#/definitions/TraceSpansAggregationQuery"+ },+ {+ "$ref": "#/definitions/TraceSpansTreeQuery"+ },{"$ref": "#/definitions/ExperimentFunnelsQuery"},@@ -875,6 +922,12 @@},{"$ref": "#/definitions/TraceSpansQueryResponse"+ },+ {+ "$ref": "#/definitions/TraceSpansAggregationQueryResponse"+ },+ {+ "$ref": "#/definitions/TraceSpansTreeQueryResponse"}]},@@ -8836,6 +8889,88 @@],"type": "object"},+ "CachedTraceSpansAggregationQueryResponse": {+ "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/AggregatedSpanRow"+ },+ "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_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "items": {+ "$ref": "#/definitions/AggregatedSpanRow"+ },+ "type": "array"+ },+ "timezone": {+ "type": "string"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ }+ },+ "required": [+ "cache_key",+ "is_cached",+ "last_refresh",+ "next_allowed_client_refresh",+ "results",+ "timezone"+ ],+ "type": "object"+ },"CachedTraceSpansQueryResponse": {"additionalProperties": false,"properties": {@@ -8919,6 +9054,88 @@],"type": "object"},+ "CachedTraceSpansTreeQueryResponse": {+ "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/SpanTreeNode"+ },+ "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_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "items": {+ "$ref": "#/definitions/SpanTreeNode"+ },+ "type": "array"+ },+ "timezone": {+ "type": "string"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ }+ },+ "required": [+ "cache_key",+ "is_cached",+ "last_refresh",+ "next_allowed_client_refresh",+ "results",+ "timezone"+ ],+ "type": "object"+ },"CachedTracesQueryResponse": {"additionalProperties": false,"properties": {@@ -25868,6 +26085,8 @@"LogAttributesQuery","LogValuesQuery","TraceSpansQuery",+ "TraceSpansAggregationQuery",+ "TraceSpansTreeQuery","SessionBatchEventsQuery","DataTableNode","DataVisualizationNode",@@ -31408,6 +31627,100 @@"required": ["results"],"type": "object"},+ {+ "additionalProperties": false,+ "properties": {+ "compare": {+ "description": "Result rows for the comparison period when `compareFilter.compare` is true.",+ "items": {+ "$ref": "#/definitions/AggregatedSpanRow"+ },+ "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_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "items": {+ "$ref": "#/definitions/AggregatedSpanRow"+ },+ "type": "array"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ }+ },+ "required": ["results"],+ "type": "object"+ },+ {+ "additionalProperties": false,+ "properties": {+ "compare": {+ "description": "Result rows for the comparison period when `compareFilter.compare` is true.",+ "items": {+ "$ref": "#/definitions/SpanTreeNode"+ },+ "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_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "items": {+ "$ref": "#/definitions/SpanTreeNode"+ },+ "type": "array"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ }+ },+ "required": ["results"],+ "type": "object"+ },{"additionalProperties": false,"properties": {@@ -32147,6 +32460,12 @@{"$ref": "#/definitions/TraceSpansQuery"},+ {+ "$ref": "#/definitions/TraceSpansAggregationQuery"+ },+ {+ "$ref": "#/definitions/TraceSpansTreeQuery"+ },{"$ref": "#/definitions/SuggestedQuestionsQuery"},@@ -35869,6 +36188,60 @@"enum": ["span", "span_attribute", "span_resource_attribute"],"type": "string"},+ "SpanTreeNode": {+ "additionalProperties": false,+ "description": "One node in an aggregated span call tree. The `(service_name, name)` pair identifies the node; `(parent_service, parent_name)` links it to its parent. Spans without a matching parent in the window get `parent_name = '<ROOT>'` so orphans surface explicitly.",+ "properties": {+ "avg_duration_nano": {+ "type": "number"+ },+ "avg_start_offset_nano": {+ "description": "Average nanoseconds from the parent span's start to this span's start. Zero for root spans. Used to order children left-to-right by typical start time in the flame graph.",+ "type": "number"+ },+ "count": {+ "$ref": "#/definitions/integer"+ },+ "error_count": {+ "$ref": "#/definitions/integer"+ },+ "name": {+ "type": "string"+ },+ "p50_duration_nano": {+ "type": "number"+ },+ "p95_duration_nano": {+ "type": "number"+ },+ "parent_name": {+ "type": "string"+ },+ "parent_service": {+ "type": "string"+ },+ "service_name": {+ "type": "string"+ },+ "total_duration_nano": {+ "type": "number"+ }+ },+ "required": [+ "parent_service",+ "parent_name",+ "service_name",+ "name",+ "count",+ "total_duration_nano",+ "avg_duration_nano",+ "p50_duration_nano",+ "p95_duration_nano",+ "error_count",+ "avg_start_offset_nano"+ ],+ "type": "object"+ },"StepOrderValue": {"enum": ["strict", "unordered", "ordered"],"type": "string"@@ -37217,6 +37590,94 @@"required": ["results"],"type": "object"},+ "TraceSpansAggregationQuery": {+ "additionalProperties": false,+ "properties": {+ "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": "TraceSpansAggregationQuery",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "response": {+ "$ref": "#/definitions/TraceSpansAggregationQueryResponse"+ },+ "serviceNames": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "tags": {+ "$ref": "#/definitions/QueryLogTags"+ },+ "version": {+ "description": "version of the node, used for schema migrations",+ "type": "number"+ }+ },+ "required": ["dateRange", "kind"],+ "type": "object"+ },+ "TraceSpansAggregationQueryResponse": {+ "additionalProperties": false,+ "properties": {+ "compare": {+ "description": "Result rows for the comparison period when `compareFilter.compare` is true.",+ "items": {+ "$ref": "#/definitions/AggregatedSpanRow"+ },+ "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_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "items": {+ "$ref": "#/definitions/AggregatedSpanRow"+ },+ "type": "array"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ }+ },+ "required": ["results"],+ "type": "object"+ },"TraceSpansQuery": {"additionalProperties": false,"properties": {@@ -37331,6 +37792,98 @@"required": ["results"],"type": "object"},+ "TraceSpansTreeQuery": {+ "additionalProperties": false,+ "properties": {+ "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": "TraceSpansTreeQuery",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "response": {+ "$ref": "#/definitions/TraceSpansTreeQueryResponse"+ },+ "serviceNames": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "spanName": {+ "description": "Span name to scope the matched trace set. Required because the `(trace_id, parent_span_id)` self-join is prohibitive without bounding the matched traces — at high name cardinality the query becomes unsafe to run.",+ "type": "string"+ },+ "tags": {+ "$ref": "#/definitions/QueryLogTags"+ },+ "version": {+ "description": "version of the node, used for schema migrations",+ "type": "number"+ }+ },+ "required": ["dateRange", "kind", "spanName"],+ "type": "object"+ },+ "TraceSpansTreeQueryResponse": {+ "additionalProperties": false,+ "properties": {+ "compare": {+ "description": "Result rows for the comparison period when `compareFilter.compare` is true.",+ "items": {+ "$ref": "#/definitions/SpanTreeNode"+ },+ "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_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "items": {+ "$ref": "#/definitions/SpanTreeNode"+ },+ "type": "array"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ }+ },+ "required": ["results"],+ "type": "object"+ },"TracesQuery": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 01f0ba8ef70a..85ed574bf0fe 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -106,6 +106,8 @@ export enum NodeKind {LogAttributesQuery = 'LogAttributesQuery',LogValuesQuery = 'LogValuesQuery',TraceSpansQuery = 'TraceSpansQuery',+ TraceSpansAggregationQuery = 'TraceSpansAggregationQuery',+ TraceSpansTreeQuery = 'TraceSpansTreeQuery',SessionBatchEventsQuery = 'SessionBatchEventsQuery',// Interface nodes@@ -230,6 +232,8 @@ export type AnyDataNode =| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| ExperimentFunnelsQuery| ExperimentTrendsQuery| CalendarHeatmapQuery@@ -329,6 +333,8 @@ export type QuerySchema =// Tracing| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery// AI| SuggestedQuestionsQuery@@ -387,6 +393,8 @@ export type AnyResponseType =| LogAttributesQueryResponse| LogValuesQueryResponse| TraceSpansQueryResponse+ | TraceSpansAggregationQueryResponse+ | TraceSpansTreeQueryResponse/** Tags that will be added to the Query log comment **/export interface QueryLogTags {@@ -3039,6 +3047,82 @@ export interface TraceSpansQueryResponse extends AnalyticsQueryResponseBase {export type CachedTraceSpansQueryResponse = CachedQueryResponse<TraceSpansQueryResponse>+/** One aggregated span row keyed by `(service_name, name)`. Used by the delta-table view. */+export interface AggregatedSpanRow {+ service_name: string+ name: string+ count: integer+ total_duration_nano: number+ avg_duration_nano: number+ p50_duration_nano: number+ p95_duration_nano: number+ error_count: integer+}++export interface TraceSpansAggregationQuery extends DataNode<TraceSpansAggregationQueryResponse> {+ kind: NodeKind.TraceSpansAggregationQuery+ dateRange: DateRange+ /** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */+ compareFilter?: CompareFilter+ filterGroup?: PropertyGroupFilter+ serviceNames?: string[]+}++export interface TraceSpansAggregationQueryResponse extends AnalyticsQueryResponseBase {+ results: AggregatedSpanRow[]+ /** Result rows for the comparison period when `compareFilter.compare` is true. */+ compare?: AggregatedSpanRow[]+}++export type CachedTraceSpansAggregationQueryResponse = CachedQueryResponse<TraceSpansAggregationQueryResponse>++/**+ * One node in an aggregated span call tree. The `(service_name, name)` pair identifies+ * the node; `(parent_service, parent_name)` links it to its parent. Spans without a+ * matching parent in the window get `parent_name = '<ROOT>'` so orphans surface explicitly.+ */+export interface SpanTreeNode {+ parent_service: string+ parent_name: string+ service_name: string+ name: string+ count: integer+ total_duration_nano: number+ avg_duration_nano: number+ p50_duration_nano: number+ p95_duration_nano: number+ error_count: integer+ /**+ * Average nanoseconds from the parent span's start to this span's start. Zero for+ * root spans. Used to order children left-to-right by typical start time in the+ * flame graph.+ */+ avg_start_offset_nano: number+}++export interface TraceSpansTreeQuery extends DataNode<TraceSpansTreeQueryResponse> {+ kind: NodeKind.TraceSpansTreeQuery+ dateRange: DateRange+ /**+ * Span name to scope the matched trace set. Required because the+ * `(trace_id, parent_span_id)` self-join is prohibitive without bounding the+ * matched traces — at high name cardinality the query becomes unsafe to run.+ */+ spanName: string+ /** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */+ compareFilter?: CompareFilter+ filterGroup?: PropertyGroupFilter+ serviceNames?: string[]+}++export interface TraceSpansTreeQueryResponse extends AnalyticsQueryResponseBase {+ results: SpanTreeNode[]+ /** Result rows for the comparison period when `compareFilter.compare` is true. */+ compare?: SpanTreeNode[]+}++export type CachedTraceSpansTreeQueryResponse = CachedQueryResponse<TraceSpansTreeQueryResponse>+export interface FileSystemCount {count: numberentries: FileSystemEntry[]diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsxindex 5db6a4f51778..78d04e4ae5a8 100644--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx@@ -558,6 +558,16 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {icon: IconLive,inMenu: false,},+ [NodeKind.TraceSpansAggregationQuery]: {+ name: 'Trace Spans Aggregation',+ icon: IconLive,+ inMenu: false,+ },+ [NodeKind.TraceSpansTreeQuery]: {+ name: 'Trace Spans Tree',+ 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 efa4f0e2526c..bca1e2e93aac 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -199,7 +199,14 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:| NodeKind.EXPERIMENT_DATA_WAREHOUSE_NODE):return {"product": Product.EXPERIMENTS}- case NodeKind.TRACE_QUERY | NodeKind.TRACES_QUERY | NodeKind.TRACE_NEIGHBORS_QUERY | NodeKind.TRACE_SPANS_QUERY:+ case (+ NodeKind.TRACE_QUERY+ | NodeKind.TRACES_QUERY+ | NodeKind.TRACE_NEIGHBORS_QUERY+ | NodeKind.TRACE_SPANS_QUERY+ | NodeKind.TRACE_SPANS_AGGREGATION_QUERY+ | NodeKind.TRACE_SPANS_TREE_QUERY+ ):return {"product": Product.LLM_ANALYTICS}case (NodeKind.VECTOR_SEARCH_QUERYdiff --git a/posthog/schema.py b/posthog/schema.pyindex 26aab952ce94..0648b3aa6e22 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -3516,6 +3516,8 @@ class NodeKind(StrEnum):LOG_ATTRIBUTES_QUERY = "LogAttributesQuery"LOG_VALUES_QUERY = "LogValuesQuery"TRACE_SPANS_QUERY = "TraceSpansQuery"+ TRACE_SPANS_AGGREGATION_QUERY = "TraceSpansAggregationQuery"+ TRACE_SPANS_TREE_QUERY = "TraceSpansTreeQuery"SESSION_BATCH_EVENTS_QUERY = "SessionBatchEventsQuery"DATA_TABLE_NODE = "DataTableNode"DATA_VISUALIZATION_NODE = "DataVisualizationNode"@@ -3977,7 +3979,7 @@ class QueryResponseAlternative7(BaseModel):stdout: str | None = None-class QueryResponseAlternative79(BaseModel):+class QueryResponseAlternative81(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -5239,6 +5241,20 @@ class ActorsPropertyTaxonomyResponse(BaseModel):sample_values: list[str | float | bool | int]+class AggregatedSpanRow(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ avg_duration_nano: float+ count: int+ error_count: int+ name: str+ p50_duration_nano: float+ p95_duration_nano: float+ service_name: str+ total_duration_nano: float++class AlertCondition(BaseModel):model_config = ConfigDict(extra="forbid",@@ -7679,7 +7695,7 @@ class QueryResponseAlternative29(BaseModel):status: ExternalQueryStatus-class QueryResponseAlternative85(BaseModel):+class QueryResponseAlternative87(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -8404,6 +8420,30 @@ class SpanPropertyFilter(BaseModel):value: list[str | float | bool] | str | float | bool | None = None+class SpanTreeNode(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ avg_duration_nano: float+ avg_start_offset_nano: float = Field(+ ...,+ description=(+ "Average nanoseconds from the parent span's start to this span's start."+ " Zero for root spans. Used to order children left-to-right by typical"+ " start time in the flame graph."+ ),+ )+ count: int+ error_count: int+ name: str+ p50_duration_nano: float+ p95_duration_nano: float+ parent_name: str+ parent_service: str+ service_name: str+ total_duration_nano: float++class StickinessCriteria(BaseModel):model_config = ConfigDict(extra="forbid",@@ -8698,6 +8738,36 @@ class TraceQueryResponse(BaseModel):)+class TraceSpansAggregationQueryResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ compare: list[AggregatedSpanRow] | 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_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[AggregatedSpanRow]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )++class TraceSpansQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -8728,6 +8798,36 @@ class TraceSpansQueryResponse(BaseModel):)+class TraceSpansTreeQueryResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ compare: list[SpanTreeNode] | 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_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[SpanTreeNode]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )++class TracesQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -12037,6 +12137,47 @@ class CachedTraceQueryResponse(BaseModel):)+class CachedTraceSpansAggregationQueryResponse(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[AggregatedSpanRow] | 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_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[AggregatedSpanRow]+ timezone: str+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )++class CachedTraceSpansQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -12078,6 +12219,47 @@ class CachedTraceSpansQueryResponse(BaseModel):)+class CachedTraceSpansTreeQueryResponse(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[SpanTreeNode] | 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_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[SpanTreeNode]+ timezone: str+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )++class CachedTracesQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -17239,7 +17421,67 @@ class QueryResponseAlternative78(BaseModel):)+class QueryResponseAlternative79(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ compare: list[AggregatedSpanRow] | 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_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[AggregatedSpanRow]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )++class QueryResponseAlternative80(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ compare: list[SpanTreeNode] | 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_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[SpanTreeNode]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+++class QueryResponseAlternative82(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -17268,7 +17510,7 @@ class QueryResponseAlternative80(BaseModel):)-class QueryResponseAlternative81(BaseModel):+class QueryResponseAlternative83(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -17297,7 +17539,7 @@ class QueryResponseAlternative81(BaseModel):)-class QueryResponseAlternative82(BaseModel):+class QueryResponseAlternative84(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -17323,7 +17565,7 @@ class QueryResponseAlternative82(BaseModel):)-class QueryResponseAlternative83(BaseModel):+class QueryResponseAlternative85(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -17353,7 +17595,7 @@ class QueryResponseAlternative83(BaseModel):)-class QueryResponseAlternative86(BaseModel):+class QueryResponseAlternative88(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -17379,7 +17621,7 @@ class QueryResponseAlternative86(BaseModel):)-class QueryResponseAlternative87(BaseModel):+class QueryResponseAlternative89(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -17405,7 +17647,7 @@ class QueryResponseAlternative87(BaseModel):)-class QueryResponseAlternative88(BaseModel):+class QueryResponseAlternative90(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -17431,7 +17673,7 @@ class QueryResponseAlternative88(BaseModel):)-class QueryResponseAlternative89(BaseModel):+class QueryResponseAlternative91(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -17462,7 +17704,7 @@ class QueryResponseAlternative89(BaseModel):types: list | None = None-class QueryResponseAlternative90(BaseModel):+class QueryResponseAlternative92(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -17488,7 +17730,7 @@ class QueryResponseAlternative90(BaseModel):)-class QueryResponseAlternative91(BaseModel):+class QueryResponseAlternative93(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -18634,6 +18876,8 @@ class AnyResponseType(| LogAttributesQueryResponse| LogValuesQueryResponse| TraceSpansQueryResponse+ | TraceSpansAggregationQueryResponse+ | TraceSpansTreeQueryResponse]):root: (@@ -18650,6 +18894,8 @@ class AnyResponseType(| LogAttributesQueryResponse| LogValuesQueryResponse| TraceSpansQueryResponse+ | TraceSpansAggregationQueryResponse+ | TraceSpansTreeQueryResponse)@@ -19995,6 +20241,26 @@ class TeamTaxonomyQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")+class TraceSpansAggregationQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ 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["TraceSpansAggregationQuery"] = "TraceSpansAggregationQuery"+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ response: TraceSpansAggregationQueryResponse | 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",@@ -20020,6 +20286,34 @@ class TraceSpansQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")+class TraceSpansTreeQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ 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["TraceSpansTreeQuery"] = "TraceSpansTreeQuery"+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ response: TraceSpansTreeQueryResponse | None = None+ serviceNames: list[str] | None = None+ spanName: str = Field(+ ...,+ description=(+ "Span name to scope the matched trace set. Required because the `(trace_id,"+ " parent_span_id)` self-join is prohibitive without bounding the matched"+ " traces — at high name cardinality the query becomes unsafe to run."+ ),+ )+ tags: QueryLogTags | None = None+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")++class VectorSearchQuery(BaseModel):model_config = ConfigDict(extra="forbid",@@ -21733,13 +22027,15 @@ class QueryResponseAlternative(| QueryResponseAlternative81| QueryResponseAlternative82| QueryResponseAlternative83+ | QueryResponseAlternative84| QueryResponseAlternative85- | QueryResponseAlternative86| QueryResponseAlternative87| QueryResponseAlternative88| QueryResponseAlternative89| QueryResponseAlternative90| QueryResponseAlternative91+ | QueryResponseAlternative92+ | QueryResponseAlternative93]):root: (@@ -21821,13 +22117,15 @@ class QueryResponseAlternative(| QueryResponseAlternative81| QueryResponseAlternative82| QueryResponseAlternative83+ | QueryResponseAlternative84| QueryResponseAlternative85- | QueryResponseAlternative86| QueryResponseAlternative87| QueryResponseAlternative88| QueryResponseAlternative89| QueryResponseAlternative90| QueryResponseAlternative91+ | QueryResponseAlternative92+ | QueryResponseAlternative93)@@ -22899,6 +23197,8 @@ class HogQLAutocomplete(BaseModel):| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| ExperimentFunnelsQuery| ExperimentTrendsQuery| CalendarHeatmapQuery@@ -22981,6 +23281,8 @@ class HogQLMetadata(BaseModel):| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| ExperimentFunnelsQuery| ExperimentTrendsQuery| CalendarHeatmapQuery@@ -23101,6 +23403,8 @@ class MaxInsightContext(BaseModel):| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -23217,6 +23521,8 @@ class QueryRequest(BaseModel):| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -23326,6 +23632,8 @@ class QuerySchemaRoot(| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -23405,6 +23713,8 @@ class QuerySchemaRoot(| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -23489,6 +23799,8 @@ class QueryUpgradeRequest(BaseModel):| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -23573,6 +23885,8 @@ class QueryUpgradeResponse(BaseModel):| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuery@@ -23808,6 +24122,8 @@ class VisualizationArtifactContent(BaseModel):| LogAttributesQuery| LogValuesQuery| TraceSpansQuery+ | TraceSpansAggregationQuery+ | TraceSpansTreeQuery| SuggestedQuestionsQuery| TeamTaxonomyQuery| EventTaxonomyQuerydiff --git a/products/tracing/backend/aggregation_query_runner.py b/products/tracing/backend/aggregation_query_runner.pynew file mode 100644index 000000000000..689be0e9ae84--- /dev/null+++ b/products/tracing/backend/aggregation_query_runner.py@@ -0,0 +1,415 @@+"""+Span aggregation query runners.++Two runners share a common scaffolding mixin:++- ``TraceSpansAggregationQueryRunner`` (flat): single-table ``GROUP BY (service_name,+ name)`` over a date window. One row per ``(service, name)``. Cheap enough to scan the+ full window. Used by the delta-table view.+- ``TraceSpansTreeQueryRunner`` (tree): self-join on ``(trace_id, parent_span_id)`` to+ attach parent linkage. Requires a ``spanName`` so the matched trace set is bounded —+ without that the join is prohibitive at high name cardinality. One row per+ ``(parent, child)`` edge. Used by the flame-graph view.++Both support an optional comparison window via ``compareFilter`` and run the two+windows in parallel when set.+"""++import datetime as dt+import contextvars+from concurrent.futures import ThreadPoolExecutor+from typing import TYPE_CHECKING, cast++from posthog.schema import (+ AggregatedSpanRow,+ CachedTraceSpansAggregationQueryResponse,+ CachedTraceSpansTreeQueryResponse,+ DateRange,+ HogQLFilters,+ HogQLQueryModifiers,+ IntervalType,+ PropertyGroupsMode,+ SpanPropertyFilter,+ SpanPropertyFilterType,+ SpanTreeNode,+ TraceSpansAggregationQuery,+ TraceSpansAggregationQueryResponse,+ TraceSpansTreeQuery,+ TraceSpansTreeQueryResponse,+)++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext+from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.property import property_to_expr+from posthog.hogql.query import execute_hogql_query+from posthog.hogql.timings import HogQLTimings++from posthog.clickhouse.client.connection import Workload+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner+from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompareToDateRange+from posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange+from posthog.models.filters.mixins.utils import cached_property++from .logic import translate_span_filter++if TYPE_CHECKING:+ from posthog.models import Team, User+++# Hard cap on number of rows returned per period. Keeps payloads bounded when name+# cardinality blows up (e.g. untemplated URL paths). The flame graph collapses long+# tails anyway so the lower-ranked rows aren't visible.+_ROW_LIMIT = 5000+++class _SpanAggregationMixin:+ """Shared scaffolding for the two span aggregation runners.++ Both subclasses also inherit from ``AnalyticsQueryRunner[ResponseT]`` for their+ specific response type. This mixin assumes ``self.query`` exposes the shared fields+ (``dateRange``, ``compareFilter``, ``filterGroup``, ``serviceNames``) and that+ subclasses implement the abstract hooks below.+ """++ # Declared so the mixin's bodies type-check standalone. Subclasses redeclare `query`+ # 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+ team: "Team"+ modifiers: HogQLQueryModifiers+ timings: HogQLTimings+ limit_context: LimitContext++ def _extract_filters(self) -> None:+ # Replicates the filter extraction the per-trace runner mixin does. We can't reuse+ # that mixin directly: it validates against TraceSpansQuery and wires a paginator+ # that does not apply here.+ def get_property_type(value: str | float | bool) -> str:+ try:+ float(value)+ return "float"+ except (ValueError, TypeError):+ pass+ return "str"++ self.span_filters: list[SpanPropertyFilter] = []+ self.span_attribute_filters: list[SpanPropertyFilter] = []+ self.resource_attribute_filters: list[SpanPropertyFilter] = []+ filter_group = self.query.filterGroup+ if not filter_group or not filter_group.values:+ return++ for property_group in filter_group.values:+ for prop in property_group.values:+ prop_type = getattr(prop, "type", None)+ if prop_type == SpanPropertyFilterType.SPAN_RESOURCE_ATTRIBUTE:+ self.resource_attribute_filters.append(cast(SpanPropertyFilter, prop))+ elif prop_type == SpanPropertyFilterType.SPAN:+ self.span_filters.append(cast(SpanPropertyFilter, prop))+ elif prop_type == SpanPropertyFilterType.SPAN_ATTRIBUTE:+ if isinstance(prop, SpanPropertyFilter) and prop.value:+ property_type = "str"+ if isinstance(prop.value, list):+ property_types = {get_property_type(v) for v in prop.value}+ if len(property_types) == 1:+ property_type = property_types.pop()+ else:+ property_type = get_property_type(prop.value)++ prop = prop.model_copy(deep=True)+ prop.key = f"{prop.key}__{property_type}"++ self.span_attribute_filters.append(cast(SpanPropertyFilter, prop))++ def validate_query_runner_access(self, user: "User") -> bool:+ from posthog.rbac.user_access_control import UserAccessControlError++ raise UserAccessControlError("tracing", "viewer")++ @cached_property+ def query_date_range(self) -> QueryDateRange:+ # Aggregation does not need the per-second interval autosizing the list view does.+ return QueryDateRange(+ date_range=self.query.dateRange,+ team=self.team,+ interval=IntervalType.MINUTE,+ now=dt.datetime.now(),+ )++ def _compare_query_date_range(self) -> QueryDateRange | None:+ compare_filter = self.query.compareFilter+ if not compare_filter or not compare_filter.compare:+ return None++ if compare_filter.compare_to:+ return QueryCompareToDateRange(+ date_range=self.query.dateRange,+ team=self.team,+ interval=IntervalType.MINUTE,+ now=dt.datetime.now(),+ compare_to=compare_filter.compare_to,+ )++ return QueryPreviousPeriodDateRange(+ date_range=self.query.dateRange,+ team=self.team,+ interval=IntervalType.MINUTE,+ now=dt.datetime.now(),+ )++ @cached_property+ def settings(self) -> HogQLGlobalSettings:+ return HogQLGlobalSettings(+ allow_experimental_object_type=False,+ allow_experimental_join_condition=False,+ transform_null_in=False,+ max_bytes_to_read=None,+ read_overflow_mode=None,+ )++ def to_query(self) -> ast.SelectQuery:+ # Required by the AnalyticsQueryRunner base class. We default to building the+ # primary-window query here; the comparison window goes through `_run_period`.+ return self._build_query(self.query_date_range)++ def _run_with_compare(self) -> tuple[list, list | None]:+ """Run primary window, and comparison window in parallel when configured."""+ compare_range = self._compare_query_date_range()++ if compare_range is None:+ return self._run_period(self.query_date_range), None++ # Copy contextvars to worker threads so query tags (product/feature) set by the+ # viewset propagate. ThreadPoolExecutor does not inherit contextvars by default.+ primary_ctx = contextvars.copy_context()+ compare_ctx = contextvars.copy_context()++ def run_primary() -> list:+ return primary_ctx.run(self._run_period, self.query_date_range)++ def run_compare() -> list:+ return compare_ctx.run(self._run_period, compare_range)++ with ThreadPoolExecutor(max_workers=2) as pool:+ current_future = pool.submit(run_primary)+ previous_future = pool.submit(run_compare)+ return current_future.result(), previous_future.result()++ def _run_period(self, query_date_range: QueryDateRange) -> list:+ query = self._build_query(query_date_range)+ response = execute_hogql_query(+ query_type=self.query.kind,+ query=query,+ modifiers=self.modifiers,+ team=self.team,+ workload=Workload.LOGS,+ timings=self.timings,+ limit_context=self.limit_context,+ settings=self.settings,+ filters=HogQLFilters(+ dateRange=DateRange(+ date_from=query_date_range.date_from().isoformat(),+ date_to=query_date_range.date_to().isoformat(),+ )+ ),+ )+ return [self._row_from_clickhouse(row) for row in response.results]++ def _where_without_date_range(self) -> ast.Expr:+ # The base mixin's `where()` always injects its own time_bucket clause sourced+ # from `self.query_date_range`, but for the compare period we need to inject a+ # different range. We rebuild a smaller clause here that just covers filters,+ # and let `_build_query` add the time clause inline using its parameter.+ exprs: list[ast.Expr] = [ast.Placeholder(expr=ast.Field(chain=["filters"]))]++ if self.query.serviceNames:+ exprs.append(+ parse_expr(+ "service_name IN {serviceNames}",+ placeholders={+ "serviceNames": ast.Tuple(exprs=[ast.Constant(value=str(sn)) for sn in self.query.serviceNames])+ },+ )+ )++ if self.span_filters or self.span_attribute_filters or self.resource_attribute_filters:+ for span_filter in self.span_filters:+ translate_span_filter(span_filter)+ exprs.append(property_to_expr(span_filter, team=self.team))+ if self.span_attribute_filters:+ exprs.append(property_to_expr(self.span_attribute_filters, team=self.team))+ for resource_filter in self.resource_attribute_filters:+ exprs.append(property_to_expr(resource_filter, team=self.team))++ return ast.And(exprs=exprs)++ # --- subclass hooks ---+ def _build_query(self, query_date_range: QueryDateRange) -> ast.SelectQuery:+ raise NotImplementedError++ def _row_from_clickhouse(self, row: list) -> AggregatedSpanRow | SpanTreeNode:+ raise NotImplementedError+++class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunner[TraceSpansAggregationQueryResponse]):+ query: TraceSpansAggregationQuery+ cached_response: CachedTraceSpansAggregationQueryResponse++ def __init__(self, query: TraceSpansAggregationQuery, *args, **kwargs) -> None:+ super().__init__(query, *args, **kwargs)+ self.modifiers.convertToProjectTimezone = False+ self.modifiers.propertyGroupsMode = PropertyGroupsMode.OPTIMIZED+ self._extract_filters()++ def _calculate(self) -> TraceSpansAggregationQueryResponse:+ current_rows, previous_rows = self._run_with_compare()+ return TraceSpansAggregationQueryResponse(results=current_rows, compare=previous_rows)++ def _build_query(self, query_date_range: QueryDateRange) -> ast.SelectQuery:+ # Single table scan plus hash aggregate. Cheap enough to run unscoped.+ query = parse_select(+ """+ SELECT+ service_name,+ name,+ count() AS count,+ sum(duration_nano) AS total_duration_nano,+ avg(duration_nano) AS avg_duration_nano,+ quantile(0.5)(duration_nano) AS p50_duration_nano,+ quantile(0.95)(duration_nano) AS p95_duration_nano,+ countIf(status_code = 2) AS error_count+ FROM posthog.trace_spans+ WHERE {where}+ AND toStartOfDay(time_bucket) >= toStartOfDay({date_from})+ AND toStartOfDay(time_bucket) <= toStartOfDay({date_to})+ AND timestamp >= {date_from}+ AND timestamp < {date_to}+ GROUP BY service_name, name+ ORDER BY total_duration_nano DESC+ LIMIT {limit}+ """,+ placeholders={+ "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) -> AggregatedSpanRow:+ return AggregatedSpanRow(+ service_name=row[0] or "",+ name=row[1] or "",+ count=row[2],+ total_duration_nano=float(row[3] or 0),+ avg_duration_nano=float(row[4] or 0),+ p50_duration_nano=float(row[5] or 0),+ p95_duration_nano=float(row[6] or 0),+ error_count=row[7] or 0,+ )++ def run(self, *args, **kwargs) -> TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse:+ response = super().run(*args, **kwargs)+ assert isinstance(response, TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse)+ return response+++class TraceSpansTreeQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunner[TraceSpansTreeQueryResponse]):+ query: TraceSpansTreeQuery+ cached_response: CachedTraceSpansTreeQueryResponse++ def __init__(self, query: TraceSpansTreeQuery, *args, **kwargs) -> None:+ super().__init__(query, *args, **kwargs)+ self.modifiers.convertToProjectTimezone = False+ self.modifiers.propertyGroupsMode = PropertyGroupsMode.OPTIMIZED+ self._extract_filters()++ def _calculate(self) -> TraceSpansTreeQueryResponse:+ current_rows, previous_rows = self._run_with_compare()+ return TraceSpansTreeQueryResponse(results=current_rows, compare=previous_rows)++ def _build_query(self, query_date_range: QueryDateRange) -> ast.SelectQuery:+ # The CTE has to widen the span-name filter so we can also fetch parent and+ # ancestor rows that match by trace_id but not by name; otherwise the LEFT JOIN+ # can't recover the parent.+ query = parse_select(+ """+ WITH matched_traces AS (+ SELECT DISTINCT trace_id+ FROM posthog.trace_spans+ WHERE {where}+ AND name = {span_name}+ AND toStartOfDay(time_bucket) >= toStartOfDay({date_from})+ AND toStartOfDay(time_bucket) <= toStartOfDay({date_to})+ AND timestamp >= {date_from}+ AND timestamp < {date_to}+ ),+ spans AS (+ SELECT+ span_id, parent_span_id, trace_id, service_name, name,+ duration_nano, status_code, timestamp+ FROM posthog.trace_spans+ WHERE trace_id IN (SELECT trace_id FROM matched_traces)+ AND toStartOfDay(time_bucket) >= toStartOfDay({date_from})+ AND toStartOfDay(time_bucket) <= toStartOfDay({date_to})+ AND timestamp >= {date_from}+ AND timestamp < {date_to}+ )+ SELECT+ coalesce(p.service_name, '') AS parent_service,+ if(empty(s.parent_span_id), '<ROOT>', coalesce(p.name, '<ROOT>')) AS parent_name,+ s.service_name AS service_name,+ s.name AS name,+ count() AS count,+ sum(s.duration_nano) AS total_duration_nano,+ avg(s.duration_nano) AS avg_duration_nano,+ quantile(0.5)(s.duration_nano) AS p50_duration_nano,+ quantile(0.95)(s.duration_nano) AS p95_duration_nano,+ countIf(s.status_code = 2) AS error_count,+ avg(+ if(+ empty(s.parent_span_id) OR isNull(p.timestamp),+ toFloat(0),+ toFloat(s.timestamp) - toFloat(p.timestamp)+ )+ ) AS avg_start_offset_nano+ FROM spans AS s+ LEFT JOIN spans AS p+ ON p.trace_id = s.trace_id AND p.span_id = s.parent_span_id+ GROUP BY parent_service, parent_name, service_name, name+ ORDER BY total_duration_nano DESC+ LIMIT {limit}+ """,+ placeholders={+ "where": self._where_without_date_range(),+ "span_name": ast.Constant(value=self.query.spanName),+ "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) -> SpanTreeNode:+ return SpanTreeNode(+ parent_service=row[0] or "",+ parent_name=row[1] or "<ROOT>",+ service_name=row[2] or "",+ name=row[3] or "",+ count=row[4],+ total_duration_nano=float(row[5] or 0),+ avg_duration_nano=float(row[6] or 0),+ p50_duration_nano=float(row[7] or 0),+ p95_duration_nano=float(row[8] or 0),+ error_count=row[9] or 0,+ avg_start_offset_nano=float(row[10] or 0),+ )++ def run(self, *args, **kwargs) -> TraceSpansTreeQueryResponse | CachedTraceSpansTreeQueryResponse:+ response = super().run(*args, **kwargs)+ assert isinstance(response, TraceSpansTreeQueryResponse | CachedTraceSpansTreeQueryResponse)+ return responsediff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex 0fb7faec8959..49d7bfdead92 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -13,15 +13,23 @@ from typing import TYPE_CHECKINGfrom zoneinfo import ZoneInfofrom posthog.schema import (+ CachedTraceSpansAggregationQueryResponse,CachedTraceSpansQueryResponse,+ CachedTraceSpansTreeQueryResponse,+ CompareFilter,DateRange,HogQLFilters,IntervalType,+ PropertyGroupFilter,PropertyGroupsMode,SpanPropertyFilter,SpanPropertyFilterType,+ TraceSpansAggregationQuery,+ TraceSpansAggregationQueryResponse,TraceSpansQuery,TraceSpansQueryResponse,+ TraceSpansTreeQuery,+ TraceSpansTreeQueryResponse,)from posthog.hogql import ast@@ -32,7 +40,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator-from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, QueryRunner+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode, QueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.filters.mixins.utils import cached_property@@ -73,6 +81,55 @@ _STATUS_CODE_LABEL_TO_INTS: dict[str, list[int]] = {}+def translate_span_filter(span_filter: SpanPropertyFilter) -> None:+ """Translate UI/API filter values into ClickHouse column representations, in place.++ The filter UI stores human-readable forms — hex ids, seconds for duration, label+ strings for `kind`/`status_code` — but the ClickHouse columns are base64 bytes,+ nanoseconds, and integers. Every code path that turns a `SpanPropertyFilter` into+ a WHERE clause must apply this translation before calling `property_to_expr`,+ otherwise filters like `{key: "kind", value: "Server"}` silently match zero rows.++ Idempotent — safe to call repeatedly on the same filter. Compare-mode invokes+ `_where_without_date_range()` once per window on the same `SpanPropertyFilter`+ instances; without the post-translation guards on `kind`/`status_code` the second+ pass would map the already-translated integers back to `[]` and silently drop the+ filter for the compare window.+ """+ if span_filter.key in ("trace_id", "span_id"):+ # `_normalise_to_base64` is a no-op on already-base64 values (16/8-byte ids+ # always encode to padding-suffixed strings that fail `int(_, 16)`).+ if isinstance(span_filter.value, list):+ span_filter.value = [_normalise_to_base64(str(v)) for v in span_filter.value]+ else:+ span_filter.value = _normalise_to_base64(str(span_filter.value))++ if span_filter.key == "duration":+ # Key flips to `duration_nano` after first pass, so this block is unreachable+ # on subsequent invocations.+ span_filter.key = "duration_nano"+ if isinstance(span_filter.value, list):+ span_filter.value = [+ str(decimal.Decimal(str(v)) * 1000000) for v in span_filter.value if _is_number(str(v))+ ]+ elif _is_number(str(span_filter.value)):+ span_filter.value = str(decimal.Decimal(str(span_filter.value)) * 1000000)++ if span_filter.key == "kind" and span_filter.value is not None:+ values: list = span_filter.value if isinstance(span_filter.value, list) else [span_filter.value]+ if not all(isinstance(v, int) for v in values):+ span_filter.value = [_SPAN_KIND_LABEL_TO_INT[str(v)] for v in values if str(v) in _SPAN_KIND_LABEL_TO_INT]++ if span_filter.key == "status_code" and span_filter.value is not None:+ values = span_filter.value if isinstance(span_filter.value, list) else [span_filter.value]+ if not all(isinstance(v, str) and v.isdigit() for v in values):+ expanded: list[int] = []+ for v in values:+ if str(v) in _STATUS_CODE_LABEL_TO_INTS:+ expanded.extend(_STATUS_CODE_LABEL_TO_INTS[str(v)])+ span_filter.value = [str(v) for v in expanded]++class TraceSpansQueryRunnerMixin(QueryRunner):"""Shared WHERE clause and settings for all trace span query runners."""@@ -158,39 +215,7 @@ class TraceSpansQueryRunnerMixin(QueryRunner):if self.span_filters:for span_filter in self.span_filters:- if span_filter.key in ("trace_id", "span_id"):- if isinstance(span_filter.value, list):- span_filter.value = [_normalise_to_base64(str(v)) for v in span_filter.value]- else:- span_filter.value = _normalise_to_base64(str(span_filter.value))-- if span_filter.key in ("duration"):- span_filter.key = "duration_nano"-- if isinstance(span_filter.value, list):- span_filter.value = [- str(decimal.Decimal(str(v)) * 1000000) for v in span_filter.value if _is_number(str(v))- ]- else:- if _is_number(str(span_filter.value)):- span_filter.value = str(decimal.Decimal(str(span_filter.value)) * 1000000)-- # Filter UI stores human labels for kind/status_code so the applied-filter- # chip reads naturally. Translate labels to the integer column values here.- if span_filter.key == "kind":- values = span_filter.value if isinstance(span_filter.value, list) else [str(span_filter.value)]- span_filter.value = [- _SPAN_KIND_LABEL_TO_INT[str(v)] for v in values if str(v) in _SPAN_KIND_LABEL_TO_INT- ]-- if span_filter.key == "status_code":- values = span_filter.value if isinstance(span_filter.value, list) else [str(span_filter.value)]- expanded: list[int] = []- for v in values:- if str(v) in _STATUS_CODE_LABEL_TO_INTS:- expanded.extend(_STATUS_CODE_LABEL_TO_INTS[str(v)])- span_filter.value = [str(v) for v in expanded]-+ translate_span_filter(span_filter)exprs.append(property_to_expr(span_filter, team=self.team))if self.span_attribute_filters:@@ -623,3 +648,53 @@ def run_attribute_values_query(results.append({"id": value, "name": value})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",+ date_range: DateRange,+ compare_filter: CompareFilter | None = None,+ filter_group: PropertyGroupFilter | None = None,+ service_names: list[str] | None = None,+) -> TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse:+ """Facade-friendly entry point for running a flat span aggregation query."""+ query = TraceSpansAggregationQuery(+ dateRange=date_range,+ compareFilter=compare_filter,+ filterGroup=filter_group,+ serviceNames=service_names,+ )+ runner = TraceSpansAggregationQueryRunner(query, team)+ response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert isinstance(response, TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse)+ return response+++def run_tree_query(+ *,+ team: "Team",+ date_range: DateRange,+ span_name: str,+ compare_filter: CompareFilter | None = None,+ filter_group: PropertyGroupFilter | None = None,+ service_names: list[str] | None = None,+) -> TraceSpansTreeQueryResponse | CachedTraceSpansTreeQueryResponse:+ """Facade-friendly entry point for running a span call-tree aggregation query."""+ query = TraceSpansTreeQuery(+ dateRange=date_range,+ spanName=span_name,+ compareFilter=compare_filter,+ filterGroup=filter_group,+ serviceNames=service_names,+ )+ runner = TraceSpansTreeQueryRunner(query, team)+ response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert isinstance(response, TraceSpansTreeQueryResponse | CachedTraceSpansTreeQueryResponse)+ return responsediff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex a05ecec52d49..76df4c268761 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -22,6 +22,7 @@ from rest_framework.response import Responsefrom posthog.schema import (CachedTraceSpansQueryResponse,+ CompareFilter,DateRange,ProductKey,PropertyGroupFilter,@@ -38,9 +39,11 @@ from posthog.hogql_queries.utils.time_sliced_query import time_sliced_resultsfrom ..logic import (TraceSpansQueryRunner,+ run_aggregation_query,run_attribute_names_query,run_attribute_values_query,run_service_names_query,+ run_tree_query,)from ..sparkline_query_runner import TraceSpansSparklineQueryRunner@@ -184,6 +187,78 @@ class _TracingValuesQuerySerializer(serializers.Serializer):offset = serializers.IntegerField(required=False, min_value=0, help_text="Pagination offset (default: 0).")+class _CompareFilterSerializer(serializers.Serializer):+ compare = serializers.BooleanField(+ required=False,+ default=False,+ help_text="When true, also fetch results for a comparison window and return them under `compare`.",+ )+ compare_to = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Relative date offset for the comparison window (e.g. '-1h', '-1d', '-7d'). Defaults to the immediately previous period of equal length.",+ )+++class _TracingAggregationQueryBodySerializer(serializers.Serializer):+ 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 applied to spans in both windows.",+ )+++class _TracingAggregationRequestSerializer(serializers.Serializer):+ query = _TracingAggregationQueryBodySerializer(help_text="The span aggregation query to execute.")+++class _TracingTreeQueryBodySerializer(serializers.Serializer):+ spanName = serializers.CharField(+ required=True,+ help_text=(+ "Span name to scope the matched trace set. Required because the "+ "(trace_id, parent_span_id) self-join is unsafe without bounding the matched traces."+ ),+ )+ 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="Additional property filters applied to spans in both windows.",+ )+++class _TracingTreeRequestSerializer(serializers.Serializer):+ query = _TracingTreeQueryBodySerializer(help_text="The span call-tree aggregation query to execute.")++@extend_schema(tags=["tracing"])class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):scope_object = "tracing"@@ -299,6 +374,94 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)return Response({"results": response.results}, status=status.HTTP_200_OK)+ @extend_schema(request=_TracingAggregationRequestSerializer)+ @action(detail=False, methods=["POST"], url_path="aggregate", required_scopes=["tracing:read"])+ def aggregate(self, request: Request, *args, **kwargs) -> Response:+ tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)+ query_data = request.data.get("query", {}) or {}+ 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_aggregation_query(+ team=self.team,+ date_range=date_range,+ 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=_TracingTreeRequestSerializer)+ @action(detail=False, methods=["POST"], url_path="tree", required_scopes=["tracing:read"])+ def tree(self, request: Request, *args, **kwargs) -> Response:+ tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)+ query_data = request.data.get("query", {}) or {}+ span_name = query_data.get("spanName")+ if not span_name or not isinstance(span_name, str):+ return Response(+ {"detail": "`spanName` is required for tree aggregation queries."},+ 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_tree_query(+ team=self.team,+ date_range=date_range,+ span_name=span_name,+ 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/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex f32251c6193d..49662af9becb 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -20,16 +20,15 @@ export interface _TracingDateRangeApi {date_to?: string | null}-/**- * * `latest` - latest- * `earliest` - earliest- */-export type OrderByEnumApi = (typeof OrderByEnumApi)[keyof typeof OrderByEnumApi]--export const OrderByEnumApi = {- Latest: 'latest',- Earliest: 'earliest',-} as const+export interface _CompareFilterApi {+ /** When true, also fetch results for a comparison window and return them under `compare`. */+ compare?: boolean+ /**+ * Relative date offset for the comparison window (e.g. '-1h', '-1d', '-7d'). Defaults to the immediately previous period of equal length.+ * @nullable+ */+ compare_to?: string | null+}/*** * `span` - span@@ -99,6 +98,33 @@ export interface _SpanPropertyFilterApi {value?: unknown}+export interface _TracingAggregationQueryBodyApi {+ /** 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 applied to spans in both windows. */+ filterGroup?: _SpanPropertyFilterApi[]+}++export interface _TracingAggregationRequestApi {+ /** The span aggregation query to execute. */+ query: _TracingAggregationQueryBodyApi+}++/**+ * * `latest` - latest+ * `earliest` - earliest+ */+export type OrderByEnumApi = (typeof OrderByEnumApi)[keyof typeof OrderByEnumApi]++export const OrderByEnumApi = {+ Latest: 'latest',+ Earliest: 'earliest',+} as const+export interface _TracingQueryBodyApi {/** Date range for the query. Defaults to last hour. */dateRange?: _TracingDateRangeApi@@ -135,6 +161,24 @@ export interface _TracingTraceRequestApi {dateRange?: _TracingDateRangeApi}+export interface _TracingTreeQueryBodyApi {+ /** Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces. */+ spanName: string+ /** 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[]+ /** Additional property filters applied to spans in both windows. */+ filterGroup?: _SpanPropertyFilterApi[]+}++export interface _TracingTreeRequestApi {+ /** The span call-tree aggregation query to execute. */+ query: _TracingTreeQueryBodyApi+}+export type TracingSpansAttributesRetrieveParams = {/*** Type of attributes: "span" for span attributes, "resource" for resource attributes.diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex c7550a0a3e76..bf7cfe1cce94 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -12,10 +12,29 @@ import type {TracingSpansAttributesRetrieveParams,TracingSpansServiceNamesRetrieveParams,TracingSpansValuesRetrieveParams,+ _TracingAggregationRequestApi,_TracingQueryRequestApi,_TracingTraceRequestApi,+ _TracingTreeRequestApi,} from './api.schemas'+export const getTracingSpansAggregateCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/tracing/spans/aggregate/`+}++export const tracingSpansAggregateCreate = async (+ projectId: string,+ _tracingAggregationRequestApi: _TracingAggregationRequestApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getTracingSpansAggregateCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(_tracingAggregationRequestApi),+ })+}+export const getTracingSpansAttributesRetrieveUrl = (projectId: string,params?: TracingSpansAttributesRetrieveParams@@ -128,6 +147,23 @@ export const tracingSpansTraceCreate = async (})}+export const getTracingSpansTreeCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/tracing/spans/tree/`+}++export const tracingSpansTreeCreate = async (+ projectId: string,+ _tracingTreeRequestApi: _TracingTreeRequestApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getTracingSpansTreeCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(_tracingTreeRequestApi),+ })+}+export const getTracingSpansValuesRetrieveUrl = (projectId: string, params: TracingSpansValuesRetrieveParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex f45205b2b055..652ceb120882 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -9,6 +9,96 @@*/import * as zod from 'zod'+export const tracingSpansAggregateCreateBodyQueryOneCompareFilterOneCompareDefault = false+export const tracingSpansAggregateCreateBodyQueryOneFilterGroupDefault = []++export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ 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(tracingSpansAggregateCreateBodyQueryOneCompareFilterOneCompareDefault)+ .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). 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(tracingSpansAggregateCreateBodyQueryOneFilterGroupDefault)+ .describe('Property filters applied to spans in both windows.'),+ })+ .describe('The span aggregation query to execute.'),+})+export const tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100export const tracingSpansQueryCreateBodyQueryOneRootSpansDefault = true@@ -208,3 +298,98 @@ export const TracingSpansTraceCreateBody = /* @__PURE__ */ zod.object({.optional().describe('Date range for the query. Defaults to last 24 hours.'),})++export const tracingSpansTreeCreateBodyQueryOneCompareFilterOneCompareDefault = false+export const tracingSpansTreeCreateBodyQueryOneFilterGroupDefault = []++export const TracingSpansTreeCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ spanName: zod+ .string()+ .describe(+ 'Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces.'+ ),+ 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(tracingSpansTreeCreateBodyQueryOneCompareFilterOneCompareDefault)+ .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). 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(tracingSpansTreeCreateBodyQueryOneFilterGroupDefault)+ .describe('Additional property filters applied to spans in both windows.'),+ })+ .describe('The span call-tree aggregation query to execute.'),+})diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yamlindex 606f9e5333c6..2c00aefbfc7d 100644--- a/products/tracing/mcp/tools.yaml+++ b/products/tracing/mcp/tools.yaml@@ -109,3 +109,9 @@ tools:response:include:- results+ tracing-spans-aggregate-create:+ operation: tracing_spans_aggregate_create+ enabled: false+ tracing-spans-tree-create:+ operation: tracing_spans_tree_create+ enabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 156f99b3504a..a4b7938800c8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -3571,6 +3571,17 @@ export namespace Schemas {Sandbox: 'sandbox',} as const;+ export interface AggregatedSpanRow {+ avg_duration_nano: number;+ count: number;+ error_count: number;+ name: string;+ p50_duration_nano: number;+ p95_duration_nano: number;+ service_name: string;+ total_duration_nano: number;+ }+export interface InsightsThresholdBounds {/** Alert fires when the value drops below this number. */lower?: number | null;@@ -17684,6 +17695,89 @@ export namespace Schemas {version?: number | null;}+ export interface TraceSpansAggregationQueryResponse {+ /** Result rows for the comparison period when `compareFilter.compare` is true. */+ compare?: AggregatedSpanRow[] | null;+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ 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 date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: AggregatedSpanRow[];+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;+ }++ export interface TraceSpansAggregationQuery {+ /** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */+ compareFilter?: CompareFilter | null;+ dateRange: DateRange;+ filterGroup?: PropertyGroupFilter | null;+ kind?: 'TraceSpansAggregationQuery';+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ response?: TraceSpansAggregationQueryResponse | null;+ serviceNames?: string[] | null;+ tags?: QueryLogTags | null;+ /** version of the node, used for schema migrations */+ version?: number | null;+ }++ export interface SpanTreeNode {+ avg_duration_nano: number;+ /** Average nanoseconds from the parent span's start to this span's start. Zero for root spans. Used to order children left-to-right by typical start time in the flame graph. */+ avg_start_offset_nano: number;+ count: number;+ error_count: number;+ name: string;+ p50_duration_nano: number;+ p95_duration_nano: number;+ parent_name: string;+ parent_service: string;+ service_name: string;+ total_duration_nano: number;+ }++ export interface TraceSpansTreeQueryResponse {+ /** Result rows for the comparison period when `compareFilter.compare` is true. */+ compare?: SpanTreeNode[] | null;+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ 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 date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: SpanTreeNode[];+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;+ }++ export interface TraceSpansTreeQuery {+ /** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */+ compareFilter?: CompareFilter | null;+ dateRange: DateRange;+ filterGroup?: PropertyGroupFilter | null;+ kind?: 'TraceSpansTreeQuery';+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ response?: TraceSpansTreeQueryResponse | null;+ serviceNames?: string[] | null;+ /** Span name to scope the matched trace set. Required because the `(trace_id, parent_span_id)` self-join is prohibitive without bounding the matched traces — at high name cardinality the query becomes unsafe to run. */+ spanName: string;+ tags?: QueryLogTags | null;+ /** version of the node, used for schema migrations */+ version?: number | null;+ }+export type RecordingOrder = typeof RecordingOrder[keyof typeof RecordingOrder];@@ -18024,7 +18118,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 | WebTrendsQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | TraceSpansQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | 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 | WebTrendsQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | null;tags?: QueryLogTags | null;/** Variables to be subsituted into the query */variables?: HogQLMetadataVariables;@@ -18050,7 +18144,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 | WebTrendsQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | TraceSpansQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | 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 | WebTrendsQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | RevenueExampleEventsQuery | RevenueExampleDataWarehouseTablesQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | null;/** Start position of the editor word */startPosition: number;tags?: QueryLogTags | null;@@ -30920,7 +31014,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 | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | 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 | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | 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@@ -32278,10 +32372,46 @@ export namespace Schemas {}export interface QueryResponseAlternative79 {- questions: string[];+ /** Result rows for the comparison period when `compareFilter.compare` is true. */+ compare?: AggregatedSpanRow[] | null;+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ 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 date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: AggregatedSpanRow[];+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;}export interface QueryResponseAlternative80 {+ /** Result rows for the comparison period when `compareFilter.compare` is true. */+ compare?: SpanTreeNode[] | null;+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ 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 date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: SpanTreeNode[];+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;+ }++ export interface QueryResponseAlternative81 {+ questions: string[];+ }++ export interface QueryResponseAlternative82 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;hasMore?: boolean | null;@@ -32300,7 +32430,7 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export interface QueryResponseAlternative81 {+ export interface QueryResponseAlternative83 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;hasMore?: boolean | null;@@ -32319,7 +32449,7 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export interface QueryResponseAlternative82 {+ export interface QueryResponseAlternative84 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -32335,7 +32465,7 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export interface QueryResponseAlternative83 {+ export interface QueryResponseAlternative85 {columns?: string[] | null;/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -32355,7 +32485,7 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export interface QueryResponseAlternative85 {+ export interface QueryResponseAlternative87 {/** Timestamp of the newer trace */newerTimestamp?: string | null;/** ID of the newer trace (chronologically after current) */@@ -32368,7 +32498,7 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export interface QueryResponseAlternative86 {+ export interface QueryResponseAlternative88 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -32384,7 +32514,7 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export interface QueryResponseAlternative87 {+ export interface QueryResponseAlternative89 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -32400,7 +32530,7 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export interface QueryResponseAlternative88 {+ export interface QueryResponseAlternative90 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -32416,7 +32546,7 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export interface QueryResponseAlternative89 {+ export interface QueryResponseAlternative91 {columns?: unknown[] | null;/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -32437,9 +32567,9 @@ export namespace Schemas {types?: unknown[] | null;}- export type QueryResponseAlternative90ResultsItem = { [key: string]: unknown };+ export type QueryResponseAlternative92ResultsItem = { [key: string]: unknown };- export interface QueryResponseAlternative90 {+ export interface QueryResponseAlternative92 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -32450,12 +32580,12 @@ export namespace Schemas {query_status?: QueryStatus | null;/** The date range used for the query */resolved_date_range?: ResolvedDateRangeResponse | null;- results: QueryResponseAlternative90ResultsItem[];+ results: QueryResponseAlternative92ResultsItem[];/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;}- export interface QueryResponseAlternative91 {+ export interface QueryResponseAlternative93 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;/** Generated HogQL query. */@@ -32471,18 +32601,18 @@ export namespace Schemas {timings?: QueryTiming[] | 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 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91;+ 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 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93;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 | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | 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 | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | 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 | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | 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 | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | PropertyValuesQuery;}export interface RecomputeResult {@@ -34704,6 +34834,16 @@ export namespace Schemas {is_organization_first_user: boolean;}+ export interface _CompareFilter {+ /** When true, also fetch results for a comparison window and return them under `compare`. */+ compare?: boolean;+ /**+ * Relative date offset for the comparison window (e.g. '-1h', '-1d', '-7d'). Defaults to the immediately previous period of equal length.+ * @nullable+ */+ compare_to?: string | null;+ }+export interface _DateRange {/*** Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.@@ -35174,6 +35314,22 @@ export namespace Schemas {date_to?: string | null;}+ export interface _TracingAggregationQueryBody {+ /** 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 applied to spans in both windows. */+ filterGroup?: _SpanPropertyFilter[];+ }++ export interface _TracingAggregationRequest {+ /** The span aggregation query to execute. */+ query: _TracingAggregationQueryBody;+ }+export interface _TracingQueryBody {/** Date range for the query. Defaults to last hour. */dateRange?: _TracingDateRange;@@ -35210,6 +35366,24 @@ export namespace Schemas {dateRange?: _TracingDateRange;}+ export interface _TracingTreeQueryBody {+ /** Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces. */+ spanName: string;+ /** 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[];+ /** Additional property filters applied to spans in both windows. */+ filterGroup?: _SpanPropertyFilter[];+ }++ export interface _TracingTreeRequest {+ /** The span call-tree aggregation query to execute. */+ query: _TracingTreeQueryBody;+ }+export type EnvironmentsAlertsListParams = {/*** Number of results to return per page.