: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): show the sessions and users behind the current span query (#101094)
Jimmy Zhu93f58a2dd182
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 00ac8e84f82f..fe93df560ba8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6496,6 +6496,10 @@ snapshots:hash: v1.k794b7964.f7b919b2c420a09ce82ea731390a821c0ec23fea52a26cb7b73c279ff906e2be.kYxfbLWv0vgLI4RPXovyFzobM6K04qFePwZ61e2wkEkproducts-tracing-operationstable--loading--light:hash: v1.k794b7964.04bcc55cb9522d72f548084a92d35c0aba20ff4995949bd8b2ee8686f96cb6ac.P_KhZ-T4DKSiE8XyxMJSgUEUR9bDfDvgYnGqSOiR860+ products-tracing-operationstable--with-impact-columns--dark:+ hash: v1.k794b7964.58421fb9485687230fc55051bb13eeefff6fec4dbc8cc0eeb9a9a9f3f39a30cd.RKEFDA_TPq6C7rBaWvs1_loggCz5bgkCHWNiGQWxX0c+ products-tracing-operationstable--with-impact-columns--light:+ hash: v1.k794b7964.eac04f11bc22c27252d415d04b4a1aa49fd3b8efcfc52ffee28a7e6b6e318417.A4sjcvRfFZFLstF9ShgxDiEyFTQSKg_n9y-x7DdIZpcproducts-tracing-virtualizedspanlist--default--dark:hash: v1.k794b7964.d6cf5ccbc379f67404b237b878878ce7e60512d45869c05c24dfab7784335406.zEh7cw_wZ10BGEuJkOUdjqS8SiWt7386-Cuz4Qc0Lesproducts-tracing-virtualizedspanlist--default--light:@@ -11064,6 +11068,22 @@ snapshots:hash: v1.k794b7964.d4169f92563f1a61588ba823f6be7392267558bfbb86124b6e53ec9b18056418.acrrts8TAMCVepFdVIC0S1wZjdtoI-atFC1n-9B9Qwkscenes-app-tasks--unified-navigation--light:hash: v1.k794b7964.e0a6374da2da7262d08d1992bea3898259837679f5676f4330400d27559ac5d2.0GaInhE5K4q2-DGSz6KrZX6vsXX_WN_S8oNY3a1_ZzQ+ scenes-app-tracing-tracingimpactcounts--no-coverage--dark:+ hash: v1.k794b7964.fcfa5be29c5721d0db9fa21ecab20f16c04a4074c9af7fb3a58311900e168a48.449yuARgMYf4b4FJpXH8evt5uiuySFxQx1sco2E2Qs0+ scenes-app-tracing-tracingimpactcounts--no-coverage--light:+ hash: v1.k794b7964.dd17052cb0d5b98b9e6a3752b5cbb0905fd329b9216ddff2c333d8c6c16a2089.D4HCAG9P4JqVSFTokHJqc5w-d0ddr9SphSTLnD3e8OE+ scenes-app-tracing-tracingimpactcounts--partial-coverage--dark:+ hash: v1.k794b7964.bec2b97c41b6f47c056824bb4524c070062dad3f0cdcac7fcc0094e3b5380b7e.E3aa53rQZlsU9zHYhxEYGNCJB_ncztNdBHJLbWX27vk+ scenes-app-tracing-tracingimpactcounts--partial-coverage--light:+ hash: v1.k794b7964.ee37e4228b8c9516e040a9796831b21eb6f83bd35c71b343e9c241d89ddbce36.JJPhc_20VE8KjiCgemsQrG2cxkjKngTAsQP8kryb_As+ scenes-app-tracing-tracingimpactcounts--sessions-and-users--dark:+ hash: v1.k794b7964.741d151cb96e4d19030c71227eeca31b151ab671f263ef2fb9995b83619bef03.6TqiMPoftIpD7HW6lFctmg2tw7yjiSAJQ4HUZPZnFIg+ scenes-app-tracing-tracingimpactcounts--sessions-and-users--light:+ hash: v1.k794b7964.3ec41e5ef8fb64630308fa7e879fc4c51b4f50146a265d085a5eb5f9e1e58519.EpQTIi4Cqs1vB4nwIR63hJnGl273DZuESpnxayLQHIs+ scenes-app-tracing-tracingimpactcounts--sessions-only--dark:+ hash: v1.k794b7964.b8c44f66626ff2d35a9a566c58337683e9ade9433d135be7f8bb4b17e338aa09.xkwHBWc90Tu3C_N2E-Vtw47FBYj2EOePlemtN4qmwDQ+ scenes-app-tracing-tracingimpactcounts--sessions-only--light:+ hash: v1.k794b7964.1df982f4a9a5e13533ba18e16809fc68a44c64764aaf3713a8a7e98ab55e9b9b.kL4oa8rGztR7a71LeNRcpjpBpVYvrVTNmouBb4sRErEscenes-app-user-interviews-invite-preview-modal--emailable--dark:hash: v1.k794b7964.72aefcbed7109d9a1e05f4240c269ce0fa8c6d744f174720aa6fb3cc09d6f624.uCLx-0pStvTD_U6yriY685FeR9zupKQb1RVQL1xcExAscenes-app-user-interviews-invite-preview-modal--emailable--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 5340727da028..add0c617039a 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2950,6 +2950,7 @@ const api = {compareFilter?: { compare?: boolean; compare_to?: string | null }limit?: numberoffset?: number+ includeImpact?: boolean},signal?: AbortSignal): Promise<{diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex fe2dfa07e017..3fc946e74001 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -525,6 +525,7 @@ export const FEATURE_FLAGS = {TOOLBAR_PAID_HEATMAPS: 'toolbar-paid-heatmaps', // owner: #team-web-analyticsTRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)TRACING_FACET_RAIL: 'tracing-facet-rail', // owner: #team-apm — gates the facet rail (faceted filter sidebar) in tracing+ TRACING_IMPACT_STRIP: 'tracing-impact-strip', // owner: #team-apm — gates the sessions/users impact strip and the Operations table's impact columnsTRACING_LATENCY_HEATMAP: 'tracing-latency-heatmap', // owner: #team-apm — gates the latency-over-time heatmap chart in tracingTRACING_METRICS_TAB: 'tracing-metrics-tab', // owner: #team-apm — gates the Metrics tab (metrics correlated via exemplars) in the trace drawerTRACING_OPERATIONS_VIEW: 'tracing-operations-view', // owner: #team-apm — gates the Operations (per-operation aggregate) tab in tracingdiff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.tsindex 4810c006a094..e509a01d7dd6 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts@@ -327,6 +327,7 @@ export interface dataNodeLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| nullresponseError: string | nullresponseErrorObject: Record<string, any> | null@@ -425,6 +426,7 @@ export interface dataNodeLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefined,payload?: {@@ -448,6 +450,7 @@ export interface dataNodeLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefinedpayload?: {@@ -501,6 +504,7 @@ export interface dataNodeLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,payload?: any) => {@@ -518,6 +522,7 @@ export interface dataNodeLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| nullpayload?: any}@@ -544,6 +549,7 @@ export interface dataNodeLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,payload?: any) => {@@ -561,6 +567,7 @@ export interface dataNodeLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| nullpayload?: any}@@ -750,6 +757,7 @@ export interface dataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => DataNode | nullcanLoadNewData: (newQuery: DataNode<Record<string, any>> | null, isShowingCachedResults: boolean) => boolean@@ -769,6 +777,7 @@ export interface dataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,responseError: string | null,dataLoading: boolean,@@ -792,6 +801,7 @@ export interface dataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => booleandataLimit: (@@ -809,6 +819,7 @@ export interface dataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => number | nullbackToSourceQuery: (query: DataNode<Record<string, any>>) => InsightVizNode | null@@ -828,6 +839,7 @@ export interface dataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => string | nullnextAllowedRefresh: (@@ -846,6 +858,7 @@ export interface dataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => string | nullgetInsightRefreshButtonDisabledReason: (@@ -867,6 +880,7 @@ export interface dataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => QueryTiming[] | nullnumberOfRows: (@@ -884,6 +898,7 @@ export interface dataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => number | nullhasActiveFilters: (query: DataNode<Record<string, any>>) => boolean@@ -904,6 +919,7 @@ export interface dataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,responseErrorObject: Record<string, any> | null,queryScanResult: QueryScanPollResult | nulldiff --git a/frontend/src/queries/nodes/DataTable/dataTableLogic.ts b/frontend/src/queries/nodes/DataTable/dataTableLogic.tsindex 7da2acbaf5f9..19897246c5dd 100644--- a/frontend/src/queries/nodes/DataTable/dataTableLogic.ts+++ b/frontend/src/queries/nodes/DataTable/dataTableLogic.ts@@ -50,6 +50,7 @@ import type {TraceSpansAttributeBreakdownQueryResponse,TraceSpansQueryResponse,} from '../../schema/schema-general'+import type { TraceSpansTreeQueryResponse } from '../../schema/schema-general'import { getColumnsForQuery, removeExpressionComment } from './utils'export interface DataTableLogicProps {@@ -87,6 +88,7 @@ export interface dataTableLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // dataNodeLogicresponseError: string | null // dataNodeLogicresponseLoading: boolean // dataNodeLogic@@ -151,6 +153,7 @@ export interface dataTableLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => string[] | nulldataTableRows: (@@ -170,6 +173,7 @@ export interface dataTableLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,columnsInResponse: string[] | null,arg: any,diff --git a/frontend/src/queries/nodes/DataVisualization/Components/seriesBreakdownLogic.ts b/frontend/src/queries/nodes/DataVisualization/Components/seriesBreakdownLogic.tsindex 0faed171f84c..35ae5e06c707 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/seriesBreakdownLogic.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/seriesBreakdownLogic.ts@@ -19,6 +19,7 @@ import type {TraceSpansAttributeBreakdownQueryResponse,TraceSpansQueryResponse,} from '../../../schema/schema-general'+import type { TraceSpansTreeQueryResponse } from '../../../schema/schema-general'import { AxisSeries, AxisSeriesSettings, SelectedYAxis, dataVisualizationLogic } from '../dataVisualizationLogic'import type { Column } from '../dataVisualizationLogic'import { humanizeEventColumnValue } from '../eventColumnLabels'@@ -122,6 +123,7 @@ export interface seriesBreakdownLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // dataVisualizationLogicselectedXAxis: string | null // dataVisualizationLogicselectedYAxis: (SelectedYAxis | null)[] | null // dataVisualizationLogic@@ -155,6 +157,7 @@ export interface seriesBreakdownLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null}deleteSeriesBreakdown: () => {}@@ -182,6 +185,7 @@ export interface seriesBreakdownLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,columns: Column[]) => string[]@@ -204,6 +208,7 @@ export interface seriesBreakdownLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,columns: Column[],chartSettings: ChartSettings,diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.tsindex c0b328f7d5ba..fe01ca0358a6 100644--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts@@ -58,6 +58,7 @@ import type {TraceSpansAttributeBreakdownQueryResponse,TraceSpansQueryResponse,} from '../../schema/schema-general'+import type { TraceSpansTreeQueryResponse } from '../../schema/schema-general'import { dataNodeLogic } from '../DataNode/dataNodeLogic'import { QueryFeature, getQueryFeatures } from '../DataTable/queryFeatures'import { getAutoBoxPlotSettings } from './Components/Charts/sqlBoxPlotAdapter'@@ -642,6 +643,7 @@ export interface dataVisualizationLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // dataNodeLogicresponseError: string | null // dataNodeLogicresponseLoading: boolean // dataNodeLogic@@ -835,6 +837,7 @@ export interface dataVisualizationLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => Column[]numericalColumns: (columns: Column[]) => Column[]@@ -862,6 +865,7 @@ export interface dataVisualizationLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,columns: Column[],chartSettings: ChartSettings,@@ -883,6 +887,7 @@ export interface dataVisualizationLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,columns: Column[]) => AxisSeries<string> | null@@ -902,6 +907,7 @@ export interface dataVisualizationLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,columns: Column[]) => AxisSeries<any>[]@@ -921,6 +927,7 @@ export interface dataVisualizationLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,chartSettings: ChartSettings) => TableDataCell<any>[][]@@ -955,6 +962,7 @@ export interface dataVisualizationLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => ChartDisplayTypeisTableVisualization: (effectiveVisualizationType: ChartDisplayType) => booleandiff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 773249d272fd..b2505d5bb909 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -1408,8 +1408,21 @@"service_name": {"type": "string"},+ "sessions": {+ "$ref": "#/definitions/integer",+ "description": "Set only when the query asked for `includeImpact`. `sessions` and `users` are uniq() estimates; the two span counts are exact."+ },+ "spans_with_distinct_id": {+ "$ref": "#/definitions/integer"+ },+ "spans_with_session_id": {+ "$ref": "#/definitions/integer"+ },"total_duration_nano": {"type": "number"+ },+ "users": {+ "$ref": "#/definitions/integer"}},"required": [@@ -53513,6 +53526,10 @@"filterGroup": {"$ref": "#/definitions/PropertyGroupFilter"},+ "includeImpact": {+ "description": "Also aggregate sessions and people per operation. Off by default: it reads the attribute maps.",+ "type": "boolean"+ },"kind": {"const": "TraceSpansAggregationQuery","type": "string"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 09a0ac179357..cfceedf11605 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -4978,6 +4978,11 @@ export interface AggregatedSpanRow {p99_duration_nano: numberp999_duration_nano: numbererror_count: integer+ /** Set only when the query asked for `includeImpact`. `sessions` and `users` are uniq() estimates; the two span counts are exact. */+ sessions?: integer+ users?: integer+ spans_with_session_id?: integer+ spans_with_distinct_id?: integer}export interface TraceSpansAggregationQuery extends DataNode<TraceSpansAggregationQueryResponse> {@@ -4987,6 +4992,8 @@ export interface TraceSpansAggregationQuery extends DataNode<TraceSpansAggregaticompareFilter?: CompareFilterfilterGroup?: PropertyGroupFilterserviceNames?: string[]+ /** Also aggregate sessions and people per operation. Off by default: it reads the attribute maps. */+ includeImpact?: boolean}export interface TraceSpansAggregationQueryResponse extends AnalyticsQueryResponseBase {diff --git a/frontend/src/scenes/cohorts/cohortCountWarningLogic.ts b/frontend/src/scenes/cohorts/cohortCountWarningLogic.tsindex 2907a18a3875..0ebf37c56303 100644--- a/frontend/src/scenes/cohorts/cohortCountWarningLogic.ts+++ b/frontend/src/scenes/cohorts/cohortCountWarningLogic.ts@@ -18,6 +18,7 @@ import type {TraceSpansAttributeBreakdownQueryResponse,TraceSpansQueryResponse,} from '../../queries/schema/schema-general'+import type { TraceSpansTreeQueryResponse } from '../../queries/schema/schema-general'export type CohortCountWarningLogicProps = {cohort: CohortType@@ -41,6 +42,7 @@ export interface cohortCountWarningLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // dataNodeLogicshouldShowCountWarning: boolean}@@ -64,6 +66,7 @@ export interface cohortCountWarningLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,query: DataTableNode) => booleandiff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsxindex 4962fc4daf23..4c97fcbf4621 100644--- a/frontend/src/scenes/insights/insightDataLogic.tsx+++ b/frontend/src/scenes/insights/insightDataLogic.tsx@@ -139,6 +139,7 @@ export interface insightDataLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // dataNodeLogicinsightLoadingTimeSeconds: number // dataNodeLogicinsightPollResponse: Record<string, QueryStatus | null> | null // dataNodeLogic@@ -205,6 +206,7 @@ export interface insightDataLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefined,payload?:@@ -236,6 +238,7 @@ export interface insightDataLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefined} // dataNodeLogic@@ -489,6 +492,7 @@ export interface insightDataLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => Record<string, any>hogQL: (insightData: Record<string, any>, query: Node<Record<string, any>> | null) => string | nulldiff --git a/frontend/src/scenes/insights/insightDataTimingLogic.ts b/frontend/src/scenes/insights/insightDataTimingLogic.tsindex a585f6d606ce..39b2d264c516 100644--- a/frontend/src/scenes/insights/insightDataTimingLogic.ts+++ b/frontend/src/scenes/insights/insightDataTimingLogic.ts@@ -23,6 +23,7 @@ import type {TraceSpansAttributeBreakdownQueryResponse,TraceSpansQueryResponse,} from '../../queries/schema/schema-general'+import type { TraceSpansTreeQueryResponse } from '../../queries/schema/schema-general'import { keyForInsightLogicProps } from './sharedUtils'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -42,6 +43,7 @@ export interface insightDataTimingLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // dataNodeLogiccurrentTeamId: number | null // teamLogicqueryStartTimes: Record<string, number>@@ -84,6 +86,7 @@ export interface insightDataTimingLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefined,payload?:@@ -115,6 +118,7 @@ export interface insightDataTimingLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefined} // dataNodeLogicdiff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 4ab4c2418308..fe058842d447 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -334,6 +334,7 @@ export interface insightVizDataLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefined,payload?:@@ -365,6 +366,7 @@ export interface insightVizDataLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefined} // insightDataLogicdiff --git a/posthog/schema.py b/posthog/schema.pyindex 56124ddcb51c..a2a52e01afd5 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -3431,7 +3431,17 @@ class AggregatedSpanRow(BaseModel):p999_duration_nano: floatp99_duration_nano: floatservice_name: str+ sessions: int | None = Field(+ default=None,+ description=(+ "Set only when the query asked for `includeImpact`. `sessions` and `users`"+ " are uniq() estimates; the two span counts are exact."+ ),+ )+ spans_with_distinct_id: int | None = None+ spans_with_session_id: int | None = Nonetotal_duration_nano: float+ users: int | None = Noneclass AlertCondition(BaseModel):@@ -29510,6 +29520,10 @@ class TraceSpansAggregationQuery(BaseModel):)dateRange: DateRangefilterGroup: PropertyGroupFilter | None = None+ includeImpact: bool | None = Field(+ default=None,+ description=("Also aggregate sessions and people per operation. Off by default: it reads the attribute maps."),+ )kind: Literal["TraceSpansAggregationQuery"] = "TraceSpansAggregationQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")response: TraceSpansAggregationQueryResponse | None = Nonediff --git a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.tsindex 612946464c45..e67e12eb4155 100644--- a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts+++ b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts@@ -32,6 +32,7 @@ import type {TraceSpansAttributeBreakdownQueryResponse,TraceSpansQueryResponse,} from '../../../frontend/src/queries/schema/schema-general'+import type { TraceSpansTreeQueryResponse } from '../../../frontend/src/queries/schema/schema-general'import { aiObservabilitySessionLogic } from './aiObservabilitySessionLogic'import { SessionTurn, extractSessionTurns } from './extractSessionTurns'import { llmAnalyticsSummarizationBatchCheckCreate, llmAnalyticsSummarizationCreate } from './generated/api'@@ -126,6 +127,7 @@ export interface aiObservabilitySessionDataLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // dataNodeLogicresponseError: string | null // dataNodeLogicresponseLoading: boolean // dataNodeLogic@@ -250,6 +252,7 @@ export interface aiObservabilitySessionDataLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => LLMTrace[]sessionTurns: (traces: LLMTrace[], fullTraces: Record<string, LLMTrace>) => SessionTurn[]diff --git a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.tsindex 9cdd05f66f4a..449e7c3bd71b 100644--- a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts+++ b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts@@ -32,6 +32,7 @@ import type {TraceSpansAttributeBreakdownQueryResponse,TraceSpansQueryResponse,} from '../../../frontend/src/queries/schema/schema-general'+import type { TraceSpansTreeQueryResponse } from '../../../frontend/src/queries/schema/schema-general'import { type TraceGitMetadata, aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'import { captureNormalizationFailure, normalizeMessages } from './messageNormalization'@@ -322,6 +323,7 @@ export interface aiObservabilityTraceDataLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // dataNodeLogicresponseError: string | null // dataNodeLogicresponseLoading: boolean // dataNodeLogic@@ -388,6 +390,7 @@ export interface aiObservabilityTraceDataLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => LLMTrace | undefinedshowableEvents: (trace: LLMTrace | undefined) => LLMTraceEvent[]diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex a6f692bbf4a5..5313700db3ff 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -397,6 +397,7 @@ export interface accountsLogicActions {| import('~/queries/schema').TraceSpansAggregationQueryResponse| import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse| import('~/queries/schema').TraceSpansQueryResponse+ | import('~/queries/schema').TraceSpansTreeQueryResponse| undefined,payload?:| {@@ -428,6 +429,7 @@ export interface accountsLogicActions {| import('~/queries/schema').TraceSpansAggregationQueryResponse| import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse| import('~/queries/schema').TraceSpansQueryResponse+ | import('~/queries/schema').TraceSpansTreeQueryResponse| undefined} // dataNodeLogiclistLoadNextData: () => any // dataNodeLogicdiff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.tsindex eafe5134b871..07939790c485 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts@@ -32,6 +32,7 @@ import type {TraceSpansAttributeBreakdownQueryResponse,TraceSpansQueryResponse,} from '../../../../../frontend/src/queries/schema/schema-general'+import type { TraceSpansTreeQueryResponse } from '../../../../../frontend/src/queries/schema/schema-general'import { ACCOUNTS_METRICS_DATA_NODE_KEY } from '../../constants'import { isNumericDisplayType } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'import { AccountColumnGroup, AccountColumnOption, accountsColumnConfigLogic } from './accountsColumnConfigLogic'@@ -306,6 +307,7 @@ export interface accountsOverviewTilesLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // dataNodeLogicaccountsResponseLoading: boolean // dataNodeLogiceditorVisible: boolean@@ -393,6 +395,7 @@ export interface accountsOverviewTilesLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null,reconciledTiles: AccountsOverviewTile[]) => Record<string, number | null>diff --git a/products/error_tracking/frontend/logics/issuesDataNodeLogic.tsx b/products/error_tracking/frontend/logics/issuesDataNodeLogic.tsxindex 96c9e09efeb7..53d30b1029a0 100644--- a/products/error_tracking/frontend/logics/issuesDataNodeLogic.tsx+++ b/products/error_tracking/frontend/logics/issuesDataNodeLogic.tsx@@ -64,6 +64,7 @@ export interface issuesDataNodeLogicValues {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null // nodeLogicresponseLoading: boolean // nodeLogicresults: ErrorTrackingIssue[]@@ -168,6 +169,7 @@ export interface issuesDataNodeLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefined,payload?:@@ -199,6 +201,7 @@ export interface issuesDataNodeLogicActions {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null| undefined} // nodeLogic@@ -258,6 +261,7 @@ export interface issuesDataNodeLogicMeta {| TraceSpansAggregationQueryResponse| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse+ | TraceSpansTreeQueryResponse| null) => ErrorTrackingIssue[]}diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.tsindex 0c2743932c17..597e5369cc86 100644--- a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.ts+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.ts@@ -85,6 +85,7 @@ export interface chartPreviewsLogicActions {| import('~/queries/schema').TraceSpansAggregationQueryResponse| import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse| import('~/queries/schema').TraceSpansQueryResponse+ | import('~/queries/schema').TraceSpansTreeQueryResponse| undefined,payload?:| {@@ -116,6 +117,7 @@ export interface chartPreviewsLogicActions {| import('~/queries/schema').TraceSpansAggregationQueryResponse| import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse| import('~/queries/schema').TraceSpansQueryResponse+ | import('~/queries/schema').TraceSpansTreeQueryResponse| undefined} // insightVizDataLogicsetInsightData: (diff --git a/products/product_analytics/frontend/insights/funnels/FunnelCorrelation/funnelCorrelationUsageLogic.ts b/products/product_analytics/frontend/insights/funnels/FunnelCorrelation/funnelCorrelationUsageLogic.tsindex 9521b2d48ed9..785e2ff57328 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelCorrelation/funnelCorrelationUsageLogic.ts+++ b/products/product_analytics/frontend/insights/funnels/FunnelCorrelation/funnelCorrelationUsageLogic.ts@@ -129,6 +129,7 @@ export interface funnelCorrelationUsageLogicActions {| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse| null+ | import('~/queries/schema').TraceSpansTreeQueryResponse| undefined,payload?:| {@@ -160,6 +161,7 @@ export interface funnelCorrelationUsageLogicActions {| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse| null+ | import('~/queries/schema').TraceSpansTreeQueryResponse| undefined} // insightVizDataLogic}diff --git a/products/product_analytics/frontend/insights/retention/retentionPeopleLogic.ts b/products/product_analytics/frontend/insights/retention/retentionPeopleLogic.tsindex 36900e3d6807..f122aeb0b1d0 100644--- a/products/product_analytics/frontend/insights/retention/retentionPeopleLogic.ts+++ b/products/product_analytics/frontend/insights/retention/retentionPeopleLogic.ts@@ -76,6 +76,7 @@ export interface retentionPeopleLogicActions {| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse| null+ | import('~/queries/schema').TraceSpansTreeQueryResponse| undefined,payload?:| {@@ -107,6 +108,7 @@ export interface retentionPeopleLogicActions {| TraceSpansAttributeBreakdownQueryResponse| TraceSpansQueryResponse| null+ | import('~/queries/schema').TraceSpansTreeQueryResponse| undefined} // insightVizDataLogicclearPeople: () => {diff --git a/products/tracing/backend/aggregation_query_runner.py b/products/tracing/backend/aggregation_query_runner.pyindex 933892e6886c..5dff181ef568 100644--- a/products/tracing/backend/aggregation_query_runner.py+++ b/products/tracing/backend/aggregation_query_runner.py@@ -56,6 +56,8 @@ from posthog.models.filters.mixins.utils import cached_property# _ROW_LIMIT lives in logic.py so the presentation layer can reach it through the# facade-allowed `logic` module; imported here (and re-exported) for the sibling runners.from .logic import _ROW_LIMIT, TIME_BUCKET_DATE_RANGE_WHERE, translate_span_filter, with_span_attribute_type_suffix+from .models import TracingIdentityAttributeKeys+from .span_identity import identity_value_exprif TYPE_CHECKING:from posthog.models import Team, User@@ -241,6 +243,7 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunn*args,limit: int | None = None,offset: int = 0,+ identity_keys: TracingIdentityAttributeKeys | None = None,**kwargs,) -> None:super().__init__(query, *args, **kwargs)@@ -249,6 +252,7 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunnself._extract_filters()self._limit = _ROW_LIMIT if limit is None else max(1, min(limit, _ROW_LIMIT))self._offset = max(0, offset)+ self._identity_keys = identity_keysdef get_cache_payload(self) -> dict:# Runner arguments, not query fields, so the base payload cannot see them.@@ -260,6 +264,27 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunndef _build_query(self, query_date_range: QueryDateRange) -> ast.SelectQuery:# Single table scan plus hash aggregate. Cheap enough to run unscoped.+ placeholders: dict[str, ast.Expr] = {+ "where": self._where_without_date_range(),+ "limit": ast.Constant(value=self._limit),+ "offset": ast.Constant(value=self._offset),+ **query_date_range.to_placeholders(),+ }+ # Appended rather than always present, because reading the attribute maps is the+ # expensive part of this query and only the Operations columns need it. uniq() is+ # HyperLogLog-based and skips NULLs. `_row_from_clickhouse` reads these by position.+ impact_columns = ""+ if self.query.includeImpact:+ if self._identity_keys is None:+ raise ValueError("includeImpact requires identity_keys")+ placeholders["session_value"] = identity_value_expr(self._identity_keys.session)+ placeholders["person_value"] = identity_value_expr(self._identity_keys.distinct_id)+ impact_columns = """,+ uniq({session_value}) AS sessions,+ uniq({person_value}) AS users,+ count({session_value}) AS spans_with_session_id,+ count({person_value}) AS spans_with_distinct_id"""+query = parse_select("""SELECT@@ -269,7 +294,9 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunnsum(duration_nano) AS total_duration_nano,avg(duration_nano) AS avg_duration_nano,quantiles(0.5, 0.95, 0.99, 0.999)(duration_nano) AS duration_quantiles,- countIf(status_code = 2) AS error_count+ countIf(status_code = 2) AS error_count"""+ + impact_columns+ + """FROM posthog.trace_spansWHERE {where}AND """@@ -282,18 +309,14 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunnLIMIT {limit}OFFSET {offset}""",- placeholders={- "where": self._where_without_date_range(),- "limit": ast.Constant(value=self._limit),- "offset": ast.Constant(value=self._offset),- **query_date_range.to_placeholders(),- },+ placeholders=placeholders,)assert isinstance(query, ast.SelectQuery)return querydef _row_from_clickhouse(self, row: list) -> AggregatedSpanRow:p50, p95, p99, p999 = row[5] or (0.0, 0.0, 0.0, 0.0)+ with_impact = self.query.includeImpactreturn AggregatedSpanRow(service_name=row[0] or "",name=row[1] or "",@@ -305,6 +328,10 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunnp99_duration_nano=float(p99 or 0),p999_duration_nano=float(p999 or 0),error_count=row[6] or 0,+ sessions=row[7] if with_impact else None,+ users=row[8] if with_impact else None,+ spans_with_session_id=row[9] if with_impact else None,+ spans_with_distinct_id=row[10] if with_impact else None,)def run(self, *args, **kwargs) -> TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse:diff --git a/products/tracing/backend/attribute_breakdown_query_runner.py b/products/tracing/backend/attribute_breakdown_query_runner.pyindex 5717872a33f8..20d86f707f02 100644--- a/products/tracing/backend/attribute_breakdown_query_runner.py+++ b/products/tracing/backend/attribute_breakdown_query_runner.py@@ -21,6 +21,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.tracing.backend.aggregation_query_runner import _ROW_LIMIT, _SpanAggregationMixinfrom products.tracing.backend.logic import TIME_BUCKET_DATE_RANGE_WHERE+from products.tracing.backend.span_identity import str_attr_fieldif TYPE_CHECKING:from posthog.models import Team@@ -97,11 +98,8 @@ class TraceSpansAttributeBreakdownQueryRunner(# resource_attributes' property group matches any key as-is.breakdown_field = ast.Field(chain=["resource_attributes", self.query.breakdownKey])else:- # Span attribute keys carry a type suffix in the physical map (attributes_map_str);- # the property-group resolver only rewrites suffixed keys to map access — a bare key- # falls through to a JSON read, which is illegal on the Map column. Every value is- # present in the __str map (the float/datetime maps are derived from it).- breakdown_field = ast.Field(chain=["attributes", f"{self.query.breakdownKey}__str"])+ # Every value is present in the __str map (the float/datetime maps are derived from it).+ breakdown_field = str_attr_field(self.query.breakdownKey)order_column = _ORDER_COLUMNS[self.query.orderBy or TraceSpanBreakdownOrderBy.COUNT]where: ast.Expr = self._where_without_date_range()diff --git a/products/tracing/backend/count_query_runner.py b/products/tracing/backend/count_query_runner.pyindex 790c74f3ff50..f43b76804010 100644--- a/products/tracing/backend/count_query_runner.py+++ b/products/tracing/backend/count_query_runner.py@@ -11,19 +11,17 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings-from posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.query import execute_hogql_query+from posthog.hogql.parser import parse_select-from posthog.clickhouse.client.connection import Workloadfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode-from products.tracing.backend.logic import TraceSpansQueryRunnerMixin+from products.tracing.backend.logic import TraceSpansScalarQueryRunnerMixin, fail_fast_scalar_settingsif TYPE_CHECKING:from posthog.models import Team-class TraceSpansCountQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[TraceSpansQueryResponse]):+class TraceSpansCountQueryRunner(TraceSpansScalarQueryRunnerMixin, AnalyticsQueryRunner[TraceSpansQueryResponse]):"""Returns a scalar count of trace spans matching the given filters.Cheap pre-flight before query-apm-spans: lets a caller size the result set before@@ -35,50 +33,21 @@ class TraceSpansCountQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunne@cached_propertydef settings(self) -> HogQLGlobalSettings:- # A count should fail fast rather than scan unbounded data — matches the caps the- # logs count runner uses against the same kind of table.- return HogQLGlobalSettings(- max_execution_time=30,- max_bytes_to_read=10_000_000_000,- read_overflow_mode="throw",- )+ return fail_fast_scalar_settings()def _calculate(self) -> TraceSpansQueryResponse:- response = execute_hogql_query(- query_type="TraceSpansQuery",- query=self.to_query(),- modifiers=self.modifiers,- team=self.team,- workload=Workload.LOGS,- timings=self.timings,- filters=self.query_date_range.to_hogql_filters(),- settings=self.settings,- )- count = response.results[0][0] if response.results else 0- trace_count = response.results[0][1] if response.results else 0+ results = self.execute()+ count = results[0][0] if results else 0+ trace_count = results[0][1] if results else 0return TraceSpansQueryResponse(results={"count": count, "traceCount": trace_count})def to_query(self) -> ast.SelectQuery:- # where() bounds the window by time_bucket (day precision); add explicit half-open- # per-row timestamp bounds so the count matches the requested window exactly.- where_with_timestamp = ast.And(- exprs=[- self.where(),- parse_expr(- "timestamp >= {date_from} AND timestamp < {date_to}",- placeholders={- "date_from": ast.Constant(value=self.query_date_range.date_from()),- "date_to": ast.Constant(value=self.query_date_range.date_to()),- },- ),- ]- )# count() is every matching span (the "Spans" view's row count). The trace count must match the- # "Traces" view, which selects traces by root-span match (rootSpans defaults True → root_only in- # logic.py), so restrict the distinct-trace count to matching root spans — not any matching span.+ # "Traces" view, which selects traces by root-span match (rootSpans defaults True -> root_only in+ # logic.py), so restrict the distinct-trace count to matching root spans, not any matching span.query = parse_select("SELECT count(), uniqExactIf(trace_id, is_root_span = 1) FROM posthog.trace_spans WHERE {where}",- placeholders={"where": where_with_timestamp},+ placeholders={"where": self.where_with_exact_timestamps()},)assert isinstance(query, ast.SelectQuery)return querydiff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.pyindex 645be878abcb..eecb6849d71c 100644--- a/products/tracing/backend/facade/api.py+++ b/products/tracing/backend/facade/api.py@@ -41,6 +41,7 @@ from products.tracing.backend.count_query_runner import run_count_query as _run_from products.tracing.backend.duration_histogram_query_runner import (run_duration_histogram_query as _run_duration_histogram_query,)+from products.tracing.backend.impact_query_runner import run_impact_query as _run_impact_queryfrom products.tracing.backend.latency_heatmap_query_runner import (run_latency_heatmap_query as _run_latency_heatmap_query,)@@ -81,6 +82,24 @@ def run_count_query()+def run_impact_query(+ *,+ team: "Team",+ date_range: DateRange,+ service_names: list[str] | None = None,+ status_codes: list[int] | None = None,+ filter_group: PropertyGroupFilter | None = None,+) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:+ """Run the sessions/people aggregates for the spans matching the given filters."""+ return _run_impact_query(+ team=team,+ date_range=date_range,+ service_names=service_names,+ status_codes=status_codes,+ filter_group=filter_group,+ )++def run_attribute_breakdown_query(*,team: "Team",diff --git a/products/tracing/backend/impact_query_runner.py b/products/tracing/backend/impact_query_runner.pynew file mode 100644index 000000000000..4364e5cca605--- /dev/null+++ b/products/tracing/backend/impact_query_runner.py@@ -0,0 +1,137 @@+from functools import cached_property+from typing import TYPE_CHECKING++from posthog.schema import (+ CachedTraceSpansQueryResponse,+ DateRange,+ PropertyGroupFilter,+ TraceSpansQuery,+ TraceSpansQueryResponse,+)++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.parser import parse_select++from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode++from products.tracing.backend.logic import TraceSpansScalarQueryRunnerMixin, fail_fast_scalar_settings+from products.tracing.backend.models import TracingIdentityAttributeKeys, resolved_tracing_identity_attribute_keys+from products.tracing.backend.span_identity import identity_value_expr++if TYPE_CHECKING:+ from posthog.models import Team++TOP_IDENTITY_VALUES = 5+++def _top_values(entries: list[tuple] | None) -> list[dict]:+ # topK(..., 'counts') rows are (value, count, error) tuples; the error margin is popover noise.+ return [{"value": value, "count": int(count)} for value, count, _error in entries or []]+++class TraceSpansImpactQueryRunner(TraceSpansScalarQueryRunnerMixin, AnalyticsQueryRunner[TraceSpansQueryResponse]):+ """Counts the unique sessions and people behind the spans matching the given filters.++ Its own scan rather than an addition to the count query: the count serves every tracing+ user on every filter change, while these aggregates decompress the two attribute-map+ columns over the whole window and only the impact strip needs them.+ """++ query: TraceSpansQuery+ cached_response: CachedTraceSpansQueryResponse++ def __init__(self, query: TraceSpansQuery, *args, identity_keys: TracingIdentityAttributeKeys, **kwargs) -> None:+ super().__init__(query, *args, **kwargs)+ self._identity_keys = identity_keys++ def get_cache_payload(self) -> dict:+ # The counts are resolved through the team's configured identity keys, which live in+ # Postgres rather than in the query. Without them in the payload, editing the tracing+ # config would keep serving counts computed under the superseded keys.+ return {+ **super().get_cache_payload(),+ "tracing_session_keys": self._identity_keys.session,+ "tracing_distinct_id_keys": self._identity_keys.distinct_id,+ }++ @cached_property+ def settings(self) -> HogQLGlobalSettings:+ # Unlike the bare count, this decompresses the attribute maps over a mostly identical+ # window on every filter tweak, hence the uncompressed block cache.+ return fail_fast_scalar_settings(use_uncompressed_cache=True)++ def _calculate(self) -> TraceSpansQueryResponse:+ results = self.execute()+ (+ total,+ spans_with_session_id,+ sessions,+ spans_with_distinct_id,+ users,+ top_sessions,+ top_users,+ ) = results[0] if results else (0, 0, 0, 0, 0, [], [])+ return TraceSpansQueryResponse(+ results={+ "total": total,+ "spansWithSessionId": spans_with_session_id,+ "sessions": sessions,+ "spansWithDistinctId": spans_with_distinct_id,+ "users": users,+ "topSessions": _top_values(top_sessions),+ "topUsers": _top_values(top_users),+ }+ )++ def to_query(self) -> ast.SelectQuery:+ # uniq()/topK() are HyperLogLog-based: ~1-2% off an exact count(DISTINCT), much cheaper,+ # and NULL-skipping, so spans carrying no identity need no predicate.+ query = parse_select(+ """+ SELECT+ count() AS total,+ count(session_value) AS spans_with_session_id,+ uniq(session_value) AS sessions,+ count(person_value) AS spans_with_distinct_id,+ uniq(person_value) AS users,+ topK({top_n}, 3, 'counts')(session_value) AS top_sessions,+ topK({top_n}, 3, 'counts')(person_value) AS top_users+ FROM (+ SELECT {session_value} AS session_value, {person_value} AS person_value+ FROM posthog.trace_spans+ WHERE {where}+ )+ """,+ placeholders={+ "session_value": identity_value_expr(self._identity_keys.session),+ "person_value": identity_value_expr(self._identity_keys.distinct_id),+ "where": self.where_with_exact_timestamps(),+ "top_n": ast.Constant(value=TOP_IDENTITY_VALUES),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return query+++def run_impact_query(+ *,+ team: "Team",+ date_range: DateRange,+ service_names: list[str] | None = None,+ status_codes: list[int] | None = None,+ filter_group: PropertyGroupFilter | None = None,+) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:+ """Facade-friendly entry point for running a span impact query."""+ query = TraceSpansQuery(+ dateRange=date_range,+ serviceNames=service_names,+ statusCodes=status_codes,+ filterGroup=filter_group,+ )+ runner = TraceSpansImpactQueryRunner(query, team, identity_keys=resolved_tracing_identity_attribute_keys(team))+ # Cached, unlike the count beside it: the strip re-mounts and reloads whenever the user+ # leaves the traces view or turns compare on.+ response = runner.run(ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)+ assert isinstance(response, TraceSpansQueryResponse | CachedTraceSpansQueryResponse)+ return responsediff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex 20b645aea351..c2c3d127be07 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -391,6 +391,63 @@ class TraceSpansQueryRunnerMixin(QueryRunner):)+def fail_fast_scalar_settings(*, use_uncompressed_cache: bool = False) -> HogQLGlobalSettings:+ """Caps for the single-row aggregates beside the span list: fail fast rather than scan+ unbounded data, so an over-wide window fails instead of holding a ClickHouse thread the list+ query needs. A runner that repeatedly decompresses the attribute maps over near-identical+ windows opts into the uncompressed block cache, guarded to its own read cap."""+ max_bytes_to_read = 10_000_000_000+ return HogQLGlobalSettings(+ max_execution_time=30,+ max_bytes_to_read=max_bytes_to_read,+ read_overflow_mode="throw",+ use_uncompressed_cache=use_uncompressed_cache or None,+ merge_tree_max_rows_to_use_cache=50_000_000 if use_uncompressed_cache else None,+ merge_tree_max_bytes_to_use_cache=max_bytes_to_read if use_uncompressed_cache else None,+ )+++class TraceSpansScalarQueryRunnerMixin(TraceSpansQueryRunnerMixin):+ """Scaffolding for the single-row aggregates that run beside the span list.++ Subclasses provide `to_query()`, their own `settings` (the aggregates differ in what they+ read, so they differ in what they should cache), and turn the single result row into a+ response.+ """++ def where_with_exact_timestamps(self) -> ast.Expr:+ """`where()` plus per-row timestamp bounds.++ `where()` bounds the window by time_bucket, at day precision. These aggregates have to+ match the requested range exactly, so they add the half-open bounds.+ """+ return ast.And(+ exprs=[+ self.where(),+ parse_expr(+ "timestamp >= {date_from} AND timestamp < {date_to}",+ placeholders={+ "date_from": ast.Constant(value=self.query_date_range.date_from()),+ "date_to": ast.Constant(value=self.query_date_range.date_to()),+ },+ ),+ ]+ )++ def execute(self) -> list:+ response = execute_hogql_query(+ query_type="TraceSpansQuery",+ query=self.to_query(),+ modifiers=self.modifiers,+ team=self.team,+ workload=Workload.LOGS,+ timings=self.timings,+ filters=self.query_date_range.to_hogql_filters(),+ settings=self.settings,+ )+ return response.results++class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[TraceSpansQueryResponse]):query: TraceSpansQuerycached_response: CachedTraceSpansQueryResponse@@ -1082,18 +1139,30 @@ def run_aggregation_query(service_names: list[str] | None = None,limit: int | None = None,offset: int = 0,+ include_impact: bool = False,) -> TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse:"""Facade-friendly entry point for running a flat span aggregation query."""# The runners import `translate_span_filter` from this module, so a module-level import here is circular.from .aggregation_query_runner import TraceSpansAggregationQueryRunner # noqa: PLC0415+ # Resolved here rather than in the runner: with `compareFilter` the runner builds each window+ # on its own thread, where a Django read would open a second connection.+ from .models import resolved_tracing_identity_attribute_keys # noqa: PLC0415 — circular at module level+query = TraceSpansAggregationQuery(dateRange=date_range,compareFilter=compare_filter,filterGroup=filter_group,serviceNames=service_names,+ includeImpact=include_impact,+ )+ runner = TraceSpansAggregationQueryRunner(+ query,+ team,+ limit=limit,+ offset=offset,+ identity_keys=resolved_tracing_identity_attribute_keys(team) if include_impact else None,)- runner = TraceSpansAggregationQueryRunner(query, team, limit=limit, offset=offset)response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)assert isinstance(response, TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse)return responsediff --git a/products/tracing/backend/models.py b/products/tracing/backend/models.pyindex 0f26f8c420d5..28d3c52fd75f 100644--- a/products/tracing/backend/models.py+++ b/products/tracing/backend/models.py@@ -1,16 +1,21 @@"""Django models for tracing."""import logging+from typing import TYPE_CHECKINGfrom django.contrib.postgres.fields import ArrayFieldfrom django.db import modelsfrom django.db.models import Value+from posthog.dataclasses import frozenfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.team.extensions import register_team_extension_signalfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModelfrom posthog.utils import generate_short_id+if TYPE_CHECKING:+ from posthog.models import Team+logger = logging.getLogger(__name__)# Define your models here@@ -42,6 +47,61 @@ def default_tracing_session_id_attribute_keys() -> list[str]:return list(DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS)+# Same list as DISTINCT_ID_KEYS in products/logs/frontend/utils.tsx, which the span attribute+# table resolves against. Copied rather than imported so tracing takes no dependency on Logs;+# keep them in sync, or the counts stop covering the spans the UI links.+DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS = [+ "distinct.id",+ "distinct_id",+ "distinctId",+ "distinctID",+ "posthogDistinctId",+ "posthogDistinctID",+ "posthog_distinct_id",+ "posthog.distinct.id",+ "posthog.distinct_id",+]++# The session-ID counterpart. Some pipelines emit `posthogSessionId` though no SDK sends it.+SESSION_ID_ATTRIBUTE_KEY_CONVENTIONS = [+ "session.id",+ "session_id",+ "sessionId",+ "sessionID",+ "$session_id",+ "posthogSessionId",+ "posthogSessionID",+ "posthog_session_id",+ "posthog.session.id",+ "posthog.session_id",+]+++@frozen+class TracingIdentityAttributeKeys:+ """The attribute keys that link a span to a session and to a person."""++ session: list[str]+ distinct_id: list[str]+++def resolved_tracing_identity_attribute_keys(team: "Team") -> TracingIdentityAttributeKeys:+ """Each list is the team's configured keys, or the default when unconfigured, followed by the+ built-in conventions the UI links regardless of config. Deduped, configured keys first. Both+ come from one config read, because every caller needs both."""+ config = TeamTracingConfig.objects.filter(team=team).first()+ session_keys = (+ config.tracing_session_id_attribute_keys if config else None+ ) or DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS+ distinct_id_keys = (+ config.tracing_distinct_id_attribute_keys if config else None+ ) or DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS+ return TracingIdentityAttributeKeys(+ session=list(dict.fromkeys([*session_keys, *SESSION_ID_ATTRIBUTE_KEY_CONVENTIONS])),+ distinct_id=list(dict.fromkeys([*distinct_id_keys, *DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS])),+ )++class TeamTracingConfig(models.Model):# Plain `models.Model` (not `TeamScopedRootMixin`) — span emission and ingestion are# per-environment, and so is this config. Inheriting the root-mixin would rewritediff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex a87629064ac0..b3660af56721 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -12,10 +12,11 @@ No business logic here - that belongs in logic.py via the facade.import jsonimport base64+from collections.abc import Callablefrom django.db import models-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import extend_schema, extend_schema_fieldfrom pydantic import ValidationErrorfrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action@@ -52,6 +53,7 @@ from ..facade.api import (run_attribute_breakdown_query,run_count_query,run_duration_histogram_query,+ run_impact_query,run_latency_heatmap_query,run_symbol_stats_query,)@@ -135,6 +137,57 @@ class _SpanPropertyFilterSerializer(serializers.Serializer):)+# The UI sends the nested group its filter editor produces, while MCP sends a flat list that+# `_normalize_filter_group` wraps into the same shape. A contract naming only the flat list+# makes every UI caller cast its way past the generated type.+_SPAN_FILTER_GROUP_SCHEMA = {+ "oneOf": [+ {+ "type": "array",+ "items": {"$ref": "#/components/schemas/_SpanPropertyFilter"},+ "description": "A flat list of filters, combined with AND.",+ },+ {+ "type": "object",+ "description": "A nested group of filter groups, as the UI filter editor builds it.",+ "properties": {+ "type": {"type": "string", "enum": ["AND", "OR"], "description": "How the inner groups combine."},+ "values": {+ "type": "array",+ "description": "The inner filter groups.",+ "items": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "enum": ["AND", "OR"],+ "description": "How the filters in this group combine.",+ },+ "values": {+ "type": "array",+ "items": {"$ref": "#/components/schemas/_SpanPropertyFilter"},+ "description": "The property filters in this group.",+ },+ },+ "required": ["type", "values"],+ },+ },+ },+ "required": ["type", "values"],+ },+ ]+}+++@extend_schema_field(_SPAN_FILTER_GROUP_SCHEMA)+class _SpanFilterGroupField(serializers.JSONField):+ """Documents both filter shapes the span actions accept.++ These body serializers only feed the OpenAPI spec, so the runtime field stays permissive and+ the decorator carries the contract.+ """++class _TracingQueryBodySerializer(serializers.Serializer):dateRange = _TracingDateRangeSerializer(required=False,@@ -438,6 +491,14 @@ class _TracingAggregationQueryBodySerializer(serializers.Serializer):"through results beyond the first page."),)+ includeImpact = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Also return the sessions and people behind each operation. Off by default because it reads the span "+ "and resource attribute maps, which the rest of the aggregation never touches."+ ),+ )class _TracingAggregationRequestSerializer(serializers.Serializer):@@ -455,6 +516,34 @@ class _AggregatedSpanRowSerializer(serializers.Serializer):p99_duration_nano = serializers.FloatField(help_text="99th percentile span duration in nanoseconds.")p999_duration_nano = serializers.FloatField(help_text="99.9th percentile span duration in nanoseconds.")error_count = serializers.IntegerField(help_text="Spans with OTel status code Error (status_code = 2).")+ sessions = serializers.IntegerField(+ allow_null=True,+ help_text=(+ "Estimated unique session IDs across this group's spans (HyperLogLog, about 1-2% error). "+ "Null unless the query set `includeImpact`."+ ),+ )+ users = serializers.IntegerField(+ allow_null=True,+ help_text=(+ "Estimated unique person distinct IDs across this group's spans (HyperLogLog, about 1-2% error). "+ "Null unless the query set `includeImpact`."+ ),+ )+ spans_with_session_id = serializers.IntegerField(+ allow_null=True,+ help_text=(+ "How many of this group's spans carry a session ID under the team's configured or conventional "+ "attribute keys. Null unless the query set `includeImpact`."+ ),+ )+ spans_with_distinct_id = serializers.IntegerField(+ allow_null=True,+ help_text=(+ "How many of this group's spans carry a person distinct ID under the team's configured or conventional "+ "attribute keys. Null unless the query set `includeImpact`."+ ),+ )class _TracingAggregationResponseSerializer(serializers.Serializer):@@ -610,11 +699,9 @@ class _TracingCountBodySerializer(serializers.Serializer):required=False,help_text="Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.",)- filterGroup = serializers.ListField(- child=_SpanPropertyFilterSerializer(),+ filterGroup = _SpanFilterGroupField(required=False,- default=[],- help_text="Property filters for the count.",+ help_text="Property filters for the count. Either a flat list of filters or a nested filter group.",)@@ -629,6 +716,49 @@ class _TracingCountResponseSerializer(serializers.Serializer):)+class _TracingImpactRequestSerializer(serializers.Serializer):+ query = _TracingCountBodySerializer(+ help_text="The impact query to execute. Takes the same filters as the count query."+ )+++class _TracingImpactTopValueSerializer(serializers.Serializer):+ value = serializers.CharField(help_text="The session ID or person distinct ID.")+ count = serializers.IntegerField(+ help_text="Approximate number of matching spans that carry this value (topK estimate)."+ )+++class _TracingImpactResponseSerializer(serializers.Serializer):+ total = serializers.IntegerField(help_text="Number of spans matching the filters.")+ spansWithSessionId = serializers.IntegerField(+ help_text=(+ "How many of the matching spans carry a session ID under the team's configured or conventional "+ "attribute keys."+ )+ )+ sessions = serializers.IntegerField(+ help_text="Estimated number of unique session IDs across the matching spans (HyperLogLog, about 1-2% error)."+ )+ spansWithDistinctId = serializers.IntegerField(+ help_text=(+ "How many of the matching spans carry a person distinct ID under the team's configured or conventional "+ "attribute keys."+ )+ )+ users = serializers.IntegerField(+ help_text="Estimated number of unique distinct IDs across the matching spans (HyperLogLog, about 1-2% error)."+ )+ topSessions = _TracingImpactTopValueSerializer(+ many=True,+ help_text="Top session IDs on the matching spans, ordered by span count descending (topK, at most 5).",+ )+ topUsers = _TracingImpactTopValueSerializer(+ many=True,+ help_text="Top person distinct IDs on the matching spans, ordered by span count descending (topK, at most 5).",+ )++# Upper bound on symbols per request; each becomes a multiIf branch in the generated query._MAX_SYMBOLS = 1000@@ -757,6 +887,21 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)return filter_groupreturn {"type": "AND", "values": []}+ @staticmethod+ def _query_body(data: object) -> dict:+ """The `query` object every span action reads its filters from, given a parsed body.++ `request.data` is whatever JSON the client sent, so without this a string or an array+ reaches the `query_data.get(...)` calls in each action and raises `AttributeError`,+ which turns a malformed request into a 500.+ """+ if not isinstance(data, dict):+ raise ParseError("Request body must be an object.")+ query_data = data.get("query") or {}+ if not isinstance(query_data, dict):+ raise ParseError("`query` must be an object.")+ return query_data+@staticmethoddef _parse_positive_int(value: object, default: int, *, minimum: int) -> int:"""Coerce an untrusted JSON value to an int no smaller than `minimum`, falling back to `default`."""@@ -821,7 +966,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)@action(detail=False, methods=["POST"], required_scopes=["tracing:read"])def query(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)- query_data = request.data.get("query", {})+ query_data = self._query_body(request.data)after_cursor = query_data.get("after", None)date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)@@ -933,11 +1078,21 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)status=status.HTTP_200_OK,)- @extend_schema(request=_TracingCountRequestSerializer, responses={200: _TracingCountResponseSerializer})- @action(detail=False, methods=["POST"], required_scopes=["tracing:read"])- def count(self, request: Request, *args, **kwargs) -> Response:+ def _run_scalar_span_query(+ self,+ request: Request,+ runner: Callable[..., TraceSpansQueryResponse | CachedTraceSpansQueryResponse],+ *,+ event_name: str,+ ) -> Response:+ """Run one of the single-row span aggregates that sit beside the list, over the shared+ `_TracingCountBodySerializer` filters.++ These run on every filter change, so an over-wide window returns an actionable 400+ rather than an opaque 500.+ """tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)- query_data = request.data.get("query", {})+ query_data = self._query_body(request.data)date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)filter_group = (@@ -947,7 +1102,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet))try:- response = run_count_query(+ response = runner(team=self.team,date_range=date_range,service_names=query_data.get("serviceNames", None),@@ -955,37 +1110,43 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)filter_group=filter_group,)except CHQueryErrorTooManyBytes:- # The count is a bounded pre-flight; when it would scan past the byte cap we- # return an actionable 400 instead of surfacing an opaque 500 to the caller.return Response({"detail": (- "This count scans too much data to run as a pre-flight. Narrow the date "- "range or add serviceNames, statusCodes, or filterGroup filters, then retry."+ "This query scans too much data. Narrow the date range or add serviceNames, "+ "statusCodes, or filterGroup filters, then retry.")},status=status.HTTP_400_BAD_REQUEST,)- report_user_action(- request.user,- "tracing count queried",+ self._report_usage(+ request,+ event_name,{"has_filter_group": bool(query_data.get("filterGroup")),"service_names_count": len(query_data.get("serviceNames") or []),"status_codes_count": len(query_data.get("statusCodes") or []),},- team=self.team,- request=request,)return Response(response.results, status=status.HTTP_200_OK)+ @extend_schema(request=_TracingCountRequestSerializer, responses={200: _TracingCountResponseSerializer})+ @action(detail=False, methods=["POST"], required_scopes=["tracing:read"])+ def count(self, request: Request, *args, **kwargs) -> Response:+ return self._run_scalar_span_query(request, run_count_query, event_name="tracing count queried")++ @extend_schema(request=_TracingImpactRequestSerializer, responses={200: _TracingImpactResponseSerializer})+ @action(detail=False, methods=["POST"], required_scopes=["tracing:read"])+ def impact(self, request: Request, *args, **kwargs) -> Response:+ return self._run_scalar_span_query(request, run_impact_query, event_name="tracing impact queried")+@extend_schema(request=_SymbolStatsRequestSerializer, responses={200: _SymbolStatsResponseSerializer})@action(detail=False, methods=["POST"], url_path="symbol-stats", required_scopes=["tracing:read"])def symbol_stats(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)- query_data = request.data.get("query", {}) or {}+ query_data = self._query_body(request.data)file_path = query_data.get("filePath")if not file_path or not isinstance(file_path, str):@@ -1058,7 +1219,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)@action(detail=False, methods=["POST"], required_scopes=["tracing:read"])def sparkline(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)- query_data = request.data.get("query", {})+ query_data = self._query_body(request.data)date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)try:@@ -1088,7 +1249,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)@action(detail=False, methods=["POST"], url_path="duration-histogram", required_scopes=["tracing:read"])def duration_histogram(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)- query_data = request.data.get("query", {})+ query_data = self._query_body(request.data)date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)try:@@ -1131,7 +1292,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)@action(detail=False, methods=["POST"], url_path="latency-heatmap", required_scopes=["tracing:read"])def latency_heatmap(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)- query_data = request.data.get("query", {}) or {}+ query_data = self._query_body(request.data)date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)try:@@ -1158,7 +1319,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)@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 {}+ query_data = self._query_body(request.data)date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)try:@@ -1187,6 +1348,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)service_names=query_data.get("serviceNames", None),limit=min(limit + 1, _ROW_LIMIT),offset=offset,+ include_impact=bool(query_data.get("includeImpact")),)results = list(response.results)@@ -1207,6 +1369,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)"has_compare": bool(query_data.get("compareFilter")),"has_filter_group": bool(query_data.get("filterGroup")),"service_names_count": len(query_data.get("serviceNames") or []),+ "include_impact": bool(query_data.get("includeImpact")),},)@@ -1224,7 +1387,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)@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 {}+ query_data = self._query_body(request.data)span_name = query_data.get("spanName")if not span_name or not isinstance(span_name, str):return Response(@@ -1277,7 +1440,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)@action(detail=False, methods=["POST"], url_path="attribute-breakdown", required_scopes=["tracing:read"])def attribute_breakdown(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)- query_data = request.data.get("query", {}) or {}+ query_data = self._query_body(request.data)breakdown_key = query_data.get("breakdownKey")if not breakdown_key or not isinstance(breakdown_key, str):diff --git a/products/tracing/backend/span_identity.py b/products/tracing/backend/span_identity.pynew file mode 100644index 000000000000..eaff80813e8f--- /dev/null+++ b/products/tracing/backend/span_identity.py@@ -0,0 +1,35 @@+"""Reading span attributes out of the physical attribute maps.++Shared by the impact query runner and the operations aggregation, so the strip's counts and the+table's columns come from the same expression.+"""++from posthog.hogql import ast+++def str_attr_field(key: str) -> ast.Field:+ """A span attribute read, with the physical map's type suffix.++ Span attributes live in the typed str map; the property-group resolver rewrites a+ `__str`-suffixed key into a Map read. A bare key falls through to an illegal JSON read.+ """+ return ast.Field(chain=["attributes", f"{key}__str"])+++def identity_value_expr(attribute_keys: list[str]) -> ast.Expr:+ """First non-empty value across the candidate keys, or NULL when a span carries none.++ Span attributes are checked before resource attributes for each key. That is the precedence+ `getSessionIdWithKey` applies in products/logs/frontend/utils.tsx, which the span attribute+ table and the trace drawer header resolve through, so the counts cover the spans the UI+ already renders as replay and person links.++ `resource_attributes` matches any key as-is. A missing key reads as '', which `nullIf` scrubs+ to NULL so the aggregates skip spans that carry no identity.+ """+ args: list[ast.Expr] = []+ for attribute_key in attribute_keys:+ resource_read: ast.Expr = ast.Field(chain=["resource_attributes", attribute_key])+ for read in (str_attr_field(attribute_key), resource_read):+ args.append(ast.Call(name="nullIf", args=[read, ast.Constant(value="")]))+ return ast.Call(name="coalesce", args=args)diff --git a/products/tracing/backend/symbol_stats_query_runner.py b/products/tracing/backend/symbol_stats_query_runner.pyindex 4057a9f2fee5..c842c34999e3 100644--- a/products/tracing/backend/symbol_stats_query_runner.py+++ b/products/tracing/backend/symbol_stats_query_runner.py@@ -50,6 +50,7 @@ from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPrfrom posthog.models.filters.mixins.utils import cached_propertyfrom products.tracing.backend.logic import TIME_BUCKET_DATE_RANGE_WHERE+from products.tracing.backend.span_identity import str_attr_fieldif TYPE_CHECKING:from posthog.models import Team@@ -72,20 +73,14 @@ _BUSY_KEY = "busy_ns"_MAX_RESULT_ROWS = 5000-def _str_attr_field(key: str) -> ast.Field:- # Span attributes live in the typed str map; the property-group resolver rewrites a- # `__str`-suffixed key into a Map read. A bare key falls through to an illegal JSON read.- return ast.Field(chain=["attributes", f"{key}__str"])--def _first_nonempty_str_attr(keys: list[str]) -> ast.Expr:# Map access returns '' for a missing key (not NULL), so coalesce() can't merge generations.# Fold right with if(notEmpty(...)) instead, taking the first key that actually carries a value.- expr: ast.Expr = _str_attr_field(keys[-1])+ expr: ast.Expr = str_attr_field(keys[-1])for key in reversed(keys[:-1]):expr = ast.Call(name="if",- args=[ast.Call(name="notEmpty", args=[_str_attr_field(key)]), _str_attr_field(key), expr],+ args=[ast.Call(name="notEmpty", args=[str_attr_field(key)]), str_attr_field(key), expr],)return expr@@ -256,7 +251,7 @@ class TraceSpansSymbolStatsQueryRunner(AnalyticsQueryRunner[TraceSpansSymbolStat# `line` and percentiles are computed at that granularity (never composed across buckets).bucket_key = _range_key_expr(self.query.symbols) if self.query.symbols else ast.Field(chain=["raw_line"])- busy_field = _str_attr_field(_BUSY_KEY)+ busy_field = str_attr_field(_BUSY_KEY)query = parse_select("""SELECT@@ -314,7 +309,7 @@ class TraceSpansSymbolStatsQueryRunner(AnalyticsQueryRunner[TraceSpansSymbolStat# Derive presence from the parsed float, not `!= ''`: a missing Map key resolves# inconsistently under OPTIMIZED property groups, but toFloatOrZero('') is reliably 0."has_busy_expr": parse_expr(- "toFloatOrZero({busy}) > 0", placeholders={"busy": _str_attr_field(_BUSY_KEY)}+ "toFloatOrZero({busy}) > 0", placeholders={"busy": str_attr_field(_BUSY_KEY)}),"current_start": ast.Constant(value=current_start),"inner_where": inner_where,diff --git a/products/tracing/backend/tests/test_impact_query_runner.py b/products/tracing/backend/tests/test_impact_query_runner.pynew file mode 100644index 000000000000..af0725f7e0c5--- /dev/null+++ b/products/tracing/backend/tests/test_impact_query_runner.py@@ -0,0 +1,161 @@+import datetime as dt++from posthog.schema import DateRange, TraceSpansQuery++from posthog.clickhouse.client import sync_execute++from products.tracing.backend.impact_query_runner import TraceSpansImpactQueryRunner, run_impact_query+from products.tracing.backend.logic import run_aggregation_query+from products.tracing.backend.models import TeamTracingConfig, TracingIdentityAttributeKeys+from products.tracing.backend.tests.test_keyset_pagination import DATE_FROM, DATE_TO, _b64, _TraceSpansTestBase++# (service, span attributes, resource attributes). Span-attribute keys carry the ingestion MV's+# `__str` suffix; resource-attribute keys do not.+SPANS = [+ ("checkout", {"sessionId__str": "sess-a", "posthogDistinctId__str": "user-1"}, {}),+ ("checkout", {"sessionId__str": "sess-a", "posthogDistinctId__str": "user-1"}, {}),+ ("checkout", {"sessionId__str": "sess-b", "posthogDistinctId__str": "user-2"}, {}),+ ("checkout", {}, {"sessionId": "sess-c", "posthogDistinctId": "user-3"}),+ ("checkout", {"sessionId__str": "sess-d"}, {"sessionId": "sess-ignored"}),+ ("checkout", {"my.session.key__str": "sess-custom"}, {}),+ ("worker", {}, {}),+ ("worker", {}, {}),+]++TOTAL_SPANS = len(SPANS)+SPANS_WITH_SESSION = 5+SPANS_WITH_DISTINCT_ID = 4+UNIQUE_SESSIONS = 4+UNIQUE_USERS = 3+++def _map_literal(entries: dict[str, str]) -> str:+ if not entries:+ return "map()"+ pairs = ", ".join(f"'{key}', '{value}'" for key, value in entries.items())+ return f"map({pairs})"+++class _ImpactTestBase(_TraceSpansTestBase):+ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ cls._recreate_trace_spans_tables()++ base = dt.datetime(2026, 6, 2, 8, 0, 0)+ ts_str = base.strftime("%Y-%m-%d %H:%M:%S.%f")+ end_str = (base + dt.timedelta(milliseconds=100)).strftime("%Y-%m-%d %H:%M:%S.%f")+ rows: list[str] = []+ for i, (service, attributes, resource_attributes) in enumerate(SPANS):+ trace_id = _b64(i.to_bytes(16, "big"))+ span_id = _b64((2000 + i).to_bytes(8, "big"))+ rows.append(+ f"('019e8770-0000-0000-0000-{i:012d}', {cls.team.id}, '{trace_id}', '{span_id}', '', "+ f"'POST /checkout', 2, '{ts_str}', '{end_str}', '{ts_str}', 0, '{service}', "+ f"{_map_literal(attributes)}, {_map_literal(resource_attributes)})"+ )+ sync_execute(+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "+ "timestamp, end_time, observed_timestamp, status_code, service_name, attributes_map_str, "+ "resource_attributes) VALUES " + ",".join(rows)+ )++ def _impact(self, **kwargs) -> dict:+ response = run_impact_query(+ team=self.team,+ date_range=DateRange(date_from=DATE_FROM, date_to=DATE_TO),+ **kwargs,+ )+ assert isinstance(response.results, dict)+ return response.results+++class TestTraceSpansImpact(_ImpactTestBase):+ def test_impact_counts(self):+ impact = self._impact()+ self.assertEqual(+ {key: impact[key] for key in ("total", "spansWithSessionId", "spansWithDistinctId", "sessions", "users")},+ {+ "total": TOTAL_SPANS,+ "spansWithSessionId": SPANS_WITH_SESSION,+ "spansWithDistinctId": SPANS_WITH_DISTINCT_ID,+ "sessions": UNIQUE_SESSIONS,+ "users": UNIQUE_USERS,+ },+ )++ def test_span_attribute_wins_over_resource_attribute(self):+ values = {entry["value"] for entry in self._impact()["topSessions"]}+ self.assertIn("sess-d", values)+ self.assertNotIn("sess-ignored", values)++ def test_top_sessions_ordered_by_span_count(self):+ top_sessions = self._impact()["topSessions"]+ self.assertEqual(top_sessions[0]["value"], "sess-a")+ self.assertEqual(top_sessions[0]["count"], 2)++ def test_filters_narrow_the_counts(self):+ impact = self._impact(service_names=["worker"])+ self.assertEqual(impact["total"], 2)+ self.assertEqual(impact["sessions"], 0)+ self.assertEqual(impact["topSessions"], [])++ def test_unconfigured_key_reads_as_no_identity(self):+ self.assertNotIn("sess-custom", {entry["value"] for entry in self._impact()["topSessions"]})++ def test_cache_key_covers_the_configured_identity_keys(self):+ # The keys come from Postgres, not the query, so nothing else in the cache payload moves+ # when a team edits them. Without them a config change keeps serving the old counts.+ def cache_key(session_keys: list[str]) -> str:+ runner = TraceSpansImpactQueryRunner(+ TraceSpansQuery(dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO)),+ self.team,+ identity_keys=TracingIdentityAttributeKeys(session=session_keys, distinct_id=["posthogDistinctId"]),+ )+ return runner.get_cache_key()++ self.assertNotEqual(cache_key(["sessionId"]), cache_key(["my.session.key"]))++ def test_configured_keys_are_read(self):+ TeamTracingConfig.objects.update_or_create(+ team=self.team, defaults={"tracing_session_id_attribute_keys": ["my.session.key"]}+ )++ impact = self._impact()+ self.assertEqual(impact["sessions"], UNIQUE_SESSIONS + 1)+ self.assertEqual(impact["spansWithSessionId"], SPANS_WITH_SESSION + 1)+ self.assertIn("sess-a", {entry["value"] for entry in impact["topSessions"]})+++class TestOperationsImpactColumns(_ImpactTestBase):+ def _rows(self, include_impact: bool) -> dict:+ response = run_aggregation_query(+ team=self.team,+ date_range=DateRange(date_from=DATE_FROM, date_to=DATE_TO),+ include_impact=include_impact,+ )+ return {row.service_name: row for row in response.results}++ def test_impact_columns(self):+ # The runner unpacks these rows positionally.+ rows = self._rows(include_impact=True)+ checkout = rows["checkout"]+ self.assertEqual(+ (checkout.sessions, checkout.users, checkout.spans_with_session_id, checkout.spans_with_distinct_id),+ (UNIQUE_SESSIONS, UNIQUE_USERS, SPANS_WITH_SESSION, SPANS_WITH_DISTINCT_ID),+ )+ self.assertEqual(rows["worker"].sessions, 0)++ def test_impact_columns_absent_by_default(self):+ # None rather than 0 is what proves the default path never read the attribute maps.+ row = self._rows(include_impact=False)["checkout"]+ self.assertIsNone(row.sessions)+ self.assertIsNone(row.users)+ self.assertIsNone(row.spans_with_session_id)+ self.assertIsNone(row.spans_with_distinct_id)++ def test_durations_survive_the_extra_columns(self):+ with_impact = self._rows(include_impact=True)["checkout"]+ without_impact = self._rows(include_impact=False)["checkout"]+ self.assertEqual(with_impact.count, without_impact.count)+ self.assertEqual(with_impact.p95_duration_nano, without_impact.p95_duration_nano)diff --git a/products/tracing/backend/tests/test_span_endpoint_errors.py b/products/tracing/backend/tests/test_span_endpoint_errors.pyindex 963b896656d9..31977617a7c5 100644--- a/products/tracing/backend/tests/test_span_endpoint_errors.py+++ b/products/tracing/backend/tests/test_span_endpoint_errors.py@@ -4,10 +4,11 @@ from unittest.mock import patchfrom django.test import SimpleTestCasefrom parameterized import parameterized+from rest_framework.exceptions import ParseErrorfrom posthog.errors import CHQueryErrorTooManyBytes-from products.tracing.backend.presentation.views import _serialize_compare_rows+from products.tracing.backend.presentation.views import SpansViewSet, _serialize_compare_rowsclass _FakeRow:@@ -35,6 +36,30 @@ class TestSerializeCompareRows(SimpleTestCase):self.assertEqual(_serialize_compare_rows([_FakeRow(1), _FakeRow(2)]), [{"value": 1}, {"value": 2}])+class TestQueryBody(SimpleTestCase):+ @parameterized.expand(+ [+ ("array_body", ["x"]),+ ("string_body", "x"),+ ("array_query", {"query": ["x"]}),+ ("string_query", {"query": "x"}),+ ]+ )+ def test_rejects_non_object(self, _name, data):+ with self.assertRaises(ParseError):+ SpansViewSet._query_body(data)++ @parameterized.expand(+ [+ ("missing", {}, {}),+ ("null", {"query": None}, {}),+ ("object", {"query": {"serviceNames": ["web"]}}, {"serviceNames": ["web"]}),+ ]+ )+ def test_reads_the_query(self, _name, data, expected):+ self.assertEqual(SpansViewSet._query_body(data), expected)++class TestSpanCountErrorHandling(APIBaseTest):def test_count_over_byte_cap_returns_400_not_500(self):# The count is a bounded pre-flight; exceeding ClickHouse's byte cap must surface as an@@ -51,6 +76,16 @@ class TestSpanCountErrorHandling(APIBaseTest):self.assertEqual(response.status_code, 400, response.content)self.assertIn("narrow", response.json()["detail"].lower())+ def test_count_rejects_a_non_object_query(self):+ # The body reaches the field reads unvalidated, so a non-object query used to raise an+ # AttributeError and surface as a 500.+ response = self.client.post(+ f"/api/projects/{self.team.id}/tracing/spans/count/",+ {"query": ["x"]},+ format="json",+ )+ self.assertEqual(response.status_code, 400, response.content)+def test_aggregate_rejects_malformed_compare_filter(self):# A compareFilter that fails validation must 400, not be swallowed into a 200 with# compare: null — otherwise a requested comparison silently disappears.diff --git a/products/tracing/frontend/OperationsTable.stories.tsx b/products/tracing/frontend/OperationsTable.stories.tsxindex 7199a8381f0b..287e7dfc73b7 100644--- a/products/tracing/frontend/OperationsTable.stories.tsx+++ b/products/tracing/frontend/OperationsTable.stories.tsx@@ -65,6 +65,31 @@ export const Default: Story = {args: { rows: ROWS, loading: false, windowMs: 3_600_000 },}+/** The third operation is a background worker with no identity, so its cells stay empty. */+export const WithImpactColumns: Story = {+ args: {+ rows: [+ {+ ...ROWS[0],+ sessions: 214_882,+ users: 96_204,+ spans_with_session_id: 1_280_100,+ spans_with_distinct_id: 1_190_400,+ },+ {+ ...ROWS[1],+ sessions: 4102,+ users: 3980,+ spans_with_session_id: 24_500,+ spans_with_distinct_id: 24_500,+ },+ ROWS[2],+ ] as AggregatedSpanRow[],+ loading: false,+ windowMs: 3_600_000,+ },+}+export const Empty: Story = {args: { rows: [], loading: false, windowMs: 3_600_000 },}diff --git a/products/tracing/frontend/OperationsTable.tsx b/products/tracing/frontend/OperationsTable.tsxindex afcc5f1a7bb8..8029cbe9c77e 100644--- a/products/tracing/frontend/OperationsTable.tsx+++ b/products/tracing/frontend/OperationsTable.tsx@@ -4,6 +4,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'import { AggregatedSpanRow } from '~/queries/schema/schema-general'+import { formatIdentityCoverage } from './identityCoverage'import { formatDuration } from './TraceWaterfallView'import { VirtualizedTable, VirtualizedTableColumn } from './VirtualizedTable'@@ -37,7 +38,54 @@ const durationCell =(pick: (row: AggregatedSpanRow) => number) =>(row: AggregatedSpanRow): JSX.Element => <span className="font-mono">{formatDuration(pick(row))}</span>-function buildColumns(windowMs: number): VirtualizedTableColumn<AggregatedSpanRow>[] {+const impactCell =+ (pick: (row: AggregatedSpanRow) => number | undefined, covered: (row: AggregatedSpanRow) => number | undefined) =>+ (row: AggregatedSpanRow): JSX.Element => {+ const value = pick(row)+ if (value == null) {+ return <span className="text-muted">—</span>+ }+ // An operation whose spans mostly carry no ID has a count covering a fraction of its+ // traffic, so the cell says which fraction. A `title` rather than a Tooltip: this renders+ // per row of a virtualized table, and the text is a plain sentence.+ const coverage = formatIdentityCoverage(covered(row), row.count)+ return (+ <span title={`Estimated from ${coverage} of this operation's spans, the ones carrying the ID.`}>+ {humanFriendlyNumber(value)}+ </span>+ )+ }++function buildColumns(windowMs: number, showImpact: boolean): VirtualizedTableColumn<AggregatedSpanRow>[] {+ const impactColumns: VirtualizedTableColumn<AggregatedSpanRow>[] = showImpact+ ? [+ {+ key: 'sessions',+ title: 'Sessions',+ width: 90,+ align: 'right',+ tooltip: 'Estimated unique sessions behind this operation, over the spans carrying a session ID.',+ sorter: (a, b) => (a.sessions ?? 0) - (b.sessions ?? 0),+ render: impactCell(+ (row) => row.sessions,+ (row) => row.spans_with_session_id+ ),+ },+ {+ key: 'users',+ title: 'Users',+ width: 90,+ align: 'right',+ tooltip: 'Estimated unique people behind this operation, over the spans carrying a distinct ID.',+ sorter: (a, b) => (a.users ?? 0) - (b.users ?? 0),+ render: impactCell(+ (row) => row.users,+ (row) => row.spans_with_distinct_id+ ),+ },+ ]+ : []+return [{key: 'service_name',@@ -90,6 +138,7 @@ function buildColumns(windowMs: number): VirtualizedTableColumn<AggregatedSpanRo</span>),},+ ...impactColumns,{key: 'p50',title: 'p50',@@ -144,11 +193,19 @@ export interface OperationsTableProps {loading: boolean/** Resolved aggregation window (ms) — turns span counts into a request rate. */windowMs: number+ /** Show the Sessions and Users columns. Must match the `includeImpact` the rows were fetched with. */+ showImpact?: booleanonRowClick?: (row: AggregatedSpanRow) => void}-export function OperationsTable({ rows, loading, windowMs, onRowClick }: OperationsTableProps): JSX.Element {- const columns = useMemo(() => buildColumns(windowMs), [windowMs])+export function OperationsTable({+ rows,+ loading,+ windowMs,+ showImpact = false,+ onRowClick,+}: OperationsTableProps): JSX.Element {+ const columns = useMemo(() => buildColumns(windowMs, showImpact), [windowMs, showImpact])return (<VirtualizedTable<AggregatedSpanRow>// pinned: identifies stored column widths — renaming resets everyone's widthsdiff --git a/products/tracing/frontend/TracingDisplayBar.tsx b/products/tracing/frontend/TracingDisplayBar.tsxindex 4b5796598cc5..4e411936d4b3 100644--- a/products/tracing/frontend/TracingDisplayBar.tsx+++ b/products/tracing/frontend/TracingDisplayBar.tsx@@ -3,11 +3,13 @@ import { useActions, useValues } from 'kea'import { IconChevronLeft, IconChevronRight, IconList, IconListTree, IconStack } from '@posthog/icons'import { LemonButton, LemonSegmentedButton, type LemonSegmentedButtonOption } from '@posthog/lemon-ui'+import { FlaggedFeature } from 'lib/components/FlaggedFeature'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { humanFriendlyNumber } from 'lib/utils/numbers'import { CompareMenuButton } from './components/Comparison/CompareMenuButton'+import { TracingImpactStrip } from './components/TracingImpactStrip'import { tracingConfigLogic } from './tracingConfigLogic'import { tracingSceneLogic, type TracingDisplayMode } from './tracingSceneLogic'@@ -27,7 +29,10 @@ export function TracingDisplayBar(): JSX.Element {const facetRailEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_FACET_RAIL]const inTracesView = displayMode !== 'operations'- const showCount = inTracesView && !compareActive && totalMatchingFilters > 0+ // The Operations view carries its own counts in table columns, and a comparison covers two+ // windows while both indicators describe one.+ const showsSingleWindowCounts = inTracesView && !compareActive+ const showCount = showsSingleWindowCounts && totalMatchingFilters > 0// data-attrs keep the names from the two controls this one replaced, for analytics continuity.const displayModeOptions: LemonSegmentedButtonOption<TracingDisplayMode>[] = [@@ -88,6 +93,12 @@ export function TracingDisplayBar(): JSX.Element {matching filters</span>)}+ {/* Gated here so the strip's logic (and its query) only mount when the flag is on. */}+ {showsSingleWindowCounts && (+ <FlaggedFeature flag={FEATURE_FLAGS.TRACING_IMPACT_STRIP}>+ <TracingImpactStrip />+ </FlaggedFeature>+ )}</div>{inTracesView && (<div className="flex items-center gap-1.5 flex-wrap">diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex b494f27d18bc..f3131814f842 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -130,6 +130,7 @@ function TracingSceneContents(): JSX.Element {const operationsViewEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_OPERATIONS_VIEW]const facetRailEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_FACET_RAIL]const heatmapEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_LATENCY_HEATMAP]+ const impactStripEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_IMPACT_STRIP]// Resolved aggregation window (ms) — turns span counts into a request rate.// Use sparklineWindowMs which correctly resolves relative date strings (e.g. '-1h').@@ -240,6 +241,7 @@ function TracingSceneContents(): JSX.Element {rows={aggregation.current}loading={aggregationLoading}windowMs={operationsWindowMs}+ showImpact={impactStripEnabled}onRowClick={(row) =>router.actions.push(urls.tracingOperation(row.service_name, row.name, filters.dateRange)diff --git a/products/tracing/frontend/components/TracingImpactCounts.stories.tsx b/products/tracing/frontend/components/TracingImpactCounts.stories.tsxnew file mode 100644index 000000000000..cf5fa112d899--- /dev/null+++ b/products/tracing/frontend/components/TracingImpactCounts.stories.tsx@@ -0,0 +1,53 @@+import type { Meta, StoryObj } from '@storybook/react'++import type { _TracingImpactResponseApi } from 'products/tracing/frontend/generated/api.schemas'++import { TracingImpactCounts } from './TracingImpactCounts'++const meta: Meta<typeof TracingImpactCounts> = {+ title: 'Scenes-App/Tracing/TracingImpactCounts',+ component: TracingImpactCounts,+ parameters: { layout: 'padded', viewMode: 'story' },+}+export default meta++type Story = StoryObj<typeof TracingImpactCounts>++function makeImpact(overrides: Partial<_TracingImpactResponseApi> = {}): _TracingImpactResponseApi {+ return {+ total: 12400,+ spansWithSessionId: 11800,+ sessions: 214,+ spansWithDistinctId: 9600,+ users: 96,+ topSessions: [+ { value: '01936d3a-5983-7e70-b287-2f21ab1a70c1', count: 3200 },+ { value: '01936d3a-72aa-7c3e-8f10-4a5f0d9be2d4', count: 1900 },+ { value: '01936d3a-9c41-7b52-a6e3-1d8c27f4e0b9', count: 450 },+ ],+ topUsers: [+ { value: '[email protected]', count: 4100 },+ { value: '[email protected]', count: 2600 },+ ],+ ...overrides,+ }+}++export const SessionsAndUsers: Story = {+ args: { impact: makeImpact() },+}++/** Spans that carry a session ID but were never linked to a person. */+export const SessionsOnly: Story = {+ args: { impact: makeImpact({ spansWithDistinctId: 0, users: 0 }) },+}++/** Partial instrumentation: the tooltip is what tells the reader the count covers a slice. */+export const PartialCoverage: Story = {+ args: { impact: makeImpact({ spansWithSessionId: 380, sessions: 12, spansWithDistinctId: 0, users: 0 }) },+}++/** Server-only spans with no identity attributes at all. */+export const NoCoverage: Story = {+ args: { impact: makeImpact({ spansWithSessionId: 0, sessions: 0, spansWithDistinctId: 0, users: 0 }) },+}diff --git a/products/tracing/frontend/components/TracingImpactCounts.tsx b/products/tracing/frontend/components/TracingImpactCounts.tsxnew file mode 100644index 000000000000..043c8d0c6602--- /dev/null+++ b/products/tracing/frontend/components/TracingImpactCounts.tsx@@ -0,0 +1,138 @@+import { LemonButton, LemonDropdown, Tooltip } from '@posthog/lemon-ui'++import ViewRecordingButton, {+ RecordingPlayerType,+ ViewRecordingButtonVariant,+} from 'lib/components/ViewRecordingButton/ViewRecordingButton'+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'++import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'+import type {+ _TracingImpactResponseApi,+ _TracingImpactTopValueApi,+} from 'products/tracing/frontend/generated/api.schemas'++import { formatIdentityCoverage } from '../identityCoverage'++export interface TracingImpactCountsProps {+ impact: _TracingImpactResponseApi+}++/** The coverage figure is load-bearing: 214 sessions over 3% of the spans is not 214 sessions. */+export function TracingImpactCounts({ impact }: TracingImpactCountsProps): JSX.Element | null {+ if (impact.total === 0) {+ return null+ }++ if (impact.spansWithSessionId === 0 && impact.spansWithDistinctId === 0) {+ return (+ <Tooltip title="No spans in this view carry a session ID or a person distinct ID. Add one to your span attributes to see the sessions and people behind them.">+ <span className="text-muted text-xs" data-attr="tracing-impact-no-coverage">+ No session or user IDs+ </span>+ </Tooltip>+ )+ }++ return (+ <span className="flex items-center gap-1 text-muted text-xs" data-attr="tracing-impact-counts">+ <ImpactCount+ count={impact.sessions}+ coveredSpans={impact.spansWithSessionId}+ totalSpans={impact.total}+ noun="sessions"+ caption="Estimated unique session IDs, by span count."+ coverageNoun="a session ID"+ entries={impact.topSessions ?? []}+ dataAttr="tracing-impact-sessions"+ renderValue={(value) => (+ <ViewRecordingButton+ sessionId={value}+ openPlayerIn={RecordingPlayerType.Modal}+ label={value}+ variant={ViewRecordingButtonVariant.Link}+ checkRecordingExists+ data-attr="tracing-impact-top-session"+ />+ )}+ />+ <ImpactCount+ count={impact.users}+ coveredSpans={impact.spansWithDistinctId}+ totalSpans={impact.total}+ noun="users"+ caption="Estimated unique people, by span count."+ coverageNoun="a distinct ID"+ entries={impact.topUsers ?? []}+ dataAttr="tracing-impact-users"+ renderValue={(value) => (+ <span onClick={(e) => e.stopPropagation()}>+ <PersonDisplay person={{ distinct_id: value }} noEllipsis inline />+ </span>+ )}+ />+ </span>+ )+}++interface ImpactCountProps {+ count: number+ coveredSpans: number+ totalSpans: number+ noun: string+ caption: string+ coverageNoun: string+ entries: _TracingImpactTopValueApi[]+ dataAttr: string+ renderValue: (value: string) => JSX.Element+}++/** One count, with the coverage it was estimated over and a popover of the values behind it. */+function ImpactCount({+ count,+ coveredSpans,+ totalSpans,+ noun,+ caption,+ coverageNoun,+ entries,+ dataAttr,+ renderValue,+}: ImpactCountProps): JSX.Element | null {+ if (coveredSpans === 0) {+ return null+ }++ const fullCaption = `${caption} ${formatIdentityCoverage(+ coveredSpans,+ totalSpans+ )} of the matching spans carry ${coverageNoun}.`++ return (+ <LemonDropdown+ placement="bottom-start"+ closeOnClickInside={false}+ overlay={+ <div className="flex flex-col gap-1 p-1 max-w-160">+ <span className="text-muted text-xs">{fullCaption}</span>+ {entries.map(({ value, count: spanCount }) => (+ <div key={value} className="flex items-center justify-between gap-4 text-xs">+ <span className="font-mono truncate">{renderValue(value)}</span>+ <span className="text-muted whitespace-nowrap">+ <span>{humanFriendlyLargeNumber(spanCount)}</span> spans+ </span>+ </div>+ ))}+ </div>+ }+ >+ <LemonButton size="xsmall" data-attr={dataAttr} tooltip={fullCaption}>+ <span className="text-muted text-xs font-normal">+ {/* The changing number gets its own element: a bare changing text node beside+ siblings breaks under in-page translation. */}+ <span>{humanFriendlyLargeNumber(count)}</span> {noun}+ </span>+ </LemonButton>+ </LemonDropdown>+ )+}diff --git a/products/tracing/frontend/components/TracingImpactStrip.tsx b/products/tracing/frontend/components/TracingImpactStrip.tsxnew file mode 100644index 000000000000..4b31779fd097--- /dev/null+++ b/products/tracing/frontend/components/TracingImpactStrip.tsx@@ -0,0 +1,15 @@+import { useValues } from 'kea'++import { tracingImpactLogic } from '../tracingImpactLogic'+import { TracingImpactCounts } from './TracingImpactCounts'++/** Mounting this mounts the logic and runs the query, so the caller gates it on the flag. */+export function TracingImpactStrip(): JSX.Element | null {+ const { impact } = useValues(tracingImpactLogic)++ if (!impact) {+ return null+ }++ return <TracingImpactCounts impact={impact} />+}diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex 3fb20bdd881b..35333c9c864d 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -159,6 +159,8 @@ export interface _TracingAggregationQueryBodyApi {* @minimum 0*/offset?: number+ /** Also return the sessions and people behind each operation. Off by default because it reads the span and resource attribute maps, which the rest of the aggregation never touches. */+ includeImpact?: boolean}export interface _TracingAggregationRequestApi {@@ -187,6 +189,26 @@ export interface _AggregatedSpanRowApi {p999_duration_nano: number/** Spans with OTel status code Error (status_code = 2). */error_count: number+ /**+ * Estimated unique session IDs across this group's spans (HyperLogLog, about 1-2% error). Null unless the query set `includeImpact`.+ * @nullable+ */+ sessions: number | null+ /**+ * Estimated unique person distinct IDs across this group's spans (HyperLogLog, about 1-2% error). Null unless the query set `includeImpact`.+ * @nullable+ */+ users: number | null+ /**+ * How many of this group's spans carry a session ID under the team's configured or conventional attribute keys. Null unless the query set `includeImpact`.+ * @nullable+ */+ spans_with_session_id: number | null+ /**+ * How many of this group's spans carry a person distinct ID under the team's configured or conventional attribute keys. Null unless the query set `includeImpact`.+ * @nullable+ */+ spans_with_distinct_id: number | null}export interface _TracingAggregationResponseApi {@@ -309,6 +331,23 @@ export interface _TracingAttributesResponseApi {count: number}+/**+ * Property filters for the count. Either a flat list of filters or a nested filter group.+ */+export type _TracingCountBodyApiFilterGroup =+ | _SpanPropertyFilterApi[]+ | {+ /** How the inner groups combine. */+ type: 'AND' | 'OR'+ /** The inner filter groups. */+ values: {+ /** How the filters in this group combine. */+ type: 'AND' | 'OR'+ /** The property filters in this group. */+ values: _SpanPropertyFilterApi[]+ }[]+ }+export interface _TracingCountBodyApi {/** Date range for the count. Defaults to last hour. */dateRange?: _TracingDateRangeApi@@ -316,8 +355,8 @@ export interface _TracingCountBodyApi {serviceNames?: string[]/** Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans. */statusCodes?: number[]- /** Property filters for the count. */- filterGroup?: _SpanPropertyFilterApi[]+ /** Property filters for the count. Either a flat list of filters or a nested filter group. */+ filterGroup?: _TracingCountBodyApiFilterGroup}export interface _TracingCountRequestApi {@@ -355,6 +394,35 @@ export interface _HasSpansResponseApi {hasSpans: boolean}+export interface _TracingImpactRequestApi {+ /** The impact query to execute. Takes the same filters as the count query. */+ query: _TracingCountBodyApi+}++export interface _TracingImpactTopValueApi {+ /** The session ID or person distinct ID. */+ value: string+ /** Approximate number of matching spans that carry this value (topK estimate). */+ count: number+}++export interface _TracingImpactResponseApi {+ /** Number of spans matching the filters. */+ total: number+ /** How many of the matching spans carry a session ID under the team's configured or conventional attribute keys. */+ spansWithSessionId: number+ /** Estimated number of unique session IDs across the matching spans (HyperLogLog, about 1-2% error). */+ sessions: number+ /** How many of the matching spans carry a person distinct ID under the team's configured or conventional attribute keys. */+ spansWithDistinctId: number+ /** Estimated number of unique distinct IDs across the matching spans (HyperLogLog, about 1-2% error). */+ users: number+ /** Top session IDs on the matching spans, ordered by span count descending (topK, at most 5). */+ topSessions: _TracingImpactTopValueApi[]+ /** Top person distinct IDs on the matching spans, ordered by span count descending (topK, at most 5). */+ topUsers: _TracingImpactTopValueApi[]+}+export interface _TracingLatencyHeatmapRequestApi {/** The latency-heatmap query to execute. */query: _TracingDurationHistogramQueryBodyApidiff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex 618fd6e4b2d9..f8877ac669a4 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -29,6 +29,8 @@ import type {_TracingCountRequestApi,_TracingCountResponseApi,_TracingDurationHistogramRequestApi,+ _TracingImpactRequestApi,+ _TracingImpactResponseApi,_TracingLatencyHeatmapRequestApi,_TracingLatencyHeatmapResponseApi,_TracingQueryRequestApi,@@ -211,6 +213,23 @@ export const tracingSpansHasSpansRetrieve = async (})}+export const getTracingSpansImpactCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tracing/spans/impact/`+}++export const tracingSpansImpactCreate = async (+ projectId: string,+ _tracingImpactRequestApi: _TracingImpactRequestApi,+ options?: RequestInit+): Promise<_TracingImpactResponseApi> => {+ return apiMutator<_TracingImpactResponseApi>(getTracingSpansImpactCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(_tracingImpactRequestApi),+ })+}+export const getTracingSpansLatencyHeatmapCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/tracing/spans/latency-heatmap/`}diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex cc1b58e9bab2..c9b6dc472857 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -50,6 +50,8 @@ export const tracingSpansAggregateCreateBodyQueryOneLimitMax = 5000export const tracingSpansAggregateCreateBodyQueryOneOffsetMin = 0+export const tracingSpansAggregateCreateBodyQueryOneIncludeImpactDefault = false+export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({query: zod.object({@@ -152,6 +154,12 @@ export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({.describe('Row offset for pagination. Combine with `limit` and the `next_offset` returned in the response to page through results beyond the first page.'),+ includeImpact: zod+ .boolean()+ .default(tracingSpansAggregateCreateBodyQueryOneIncludeImpactDefault)+ .describe(+ 'Also return the sessions and people behind each operation. Off by default because it reads the span and resource attribute maps, which the rest of the aggregation never touches.'+ ),}).describe('The span aggregation query to execute.'),})@@ -283,8 +291,6 @@ export const TracingSpansAttributeBreakdownCreateBody = /* @__PURE__ */ zod.obje.describe('The attribute breakdown query to execute.'),})-export const tracingSpansCountCreateBodyQueryOneFilterGroupDefault = []-export const TracingSpansCountCreateBody = /* @__PURE__ */ zod.object({query: zod.object({@@ -311,54 +317,120 @@ export const TracingSpansCountCreateBody = /* @__PURE__ */ zod.object({'Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.'),filterGroup: zod- .array(- zod.object({- key: zod- .string()- .describe(- 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'- ),- type: zod- .enum(['span', 'span_attribute', 'span_resource_attribute'])- .describe(- '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'- )- .describe(- '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'- ),- operator: zod- .enum([- 'exact',- 'is_not',- 'icontains',- 'not_icontains',- 'starts_with',- 'not_starts_with',- 'ends_with',- 'not_ends_with',- '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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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(tracingSpansCountCreateBodyQueryOneFilterGroupDefault)- .describe('Property filters for the count.'),+ .union([+ zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'+ ),+ type: zod+ .enum(['span', 'span_attribute', 'span_resource_attribute'])+ .describe(+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'starts_with',+ 'not_starts_with',+ 'ends_with',+ 'not_ends_with',+ '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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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.'+ ),+ })+ )+ .describe('A flat list of filters, combined with AND.'),+ zod+ .object({+ type: zod.enum(['AND', 'OR']).describe('How the inner groups combine.'),+ values: zod+ .array(+ zod.object({+ type: zod+ .enum(['AND', 'OR'])+ .describe('How the filters in this group combine.'),+ values: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'+ ),+ type: zod+ .enum(['span', 'span_attribute', 'span_resource_attribute'])+ .describe(+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'starts_with',+ 'not_starts_with',+ 'ends_with',+ 'not_ends_with',+ '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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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.'+ ),+ })+ )+ .describe('The property filters in this group.'),+ })+ )+ .describe('The inner filter groups.'),+ })+ .describe('A nested group of filter groups, as the UI filter editor builds it.'),+ ])+ .optional()+ .describe('Property filters for the count. Either a flat list of filters or a nested filter group.'),}).describe('The span count query to execute.'),})@@ -450,6 +522,150 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec.describe('The duration-histogram query to execute.'),})+export const TracingSpansImpactCreateBody = /* @__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 count. Defaults to last hour.'),+ serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),+ statusCodes: zod+ .array(zod.number())+ .optional()+ .describe(+ 'Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.'+ ),+ filterGroup: zod+ .union([+ zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'+ ),+ type: zod+ .enum(['span', 'span_attribute', 'span_resource_attribute'])+ .describe(+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'starts_with',+ 'not_starts_with',+ 'ends_with',+ 'not_ends_with',+ '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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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.'+ ),+ })+ )+ .describe('A flat list of filters, combined with AND.'),+ zod+ .object({+ type: zod.enum(['AND', 'OR']).describe('How the inner groups combine.'),+ values: zod+ .array(+ zod.object({+ type: zod+ .enum(['AND', 'OR'])+ .describe('How the filters in this group combine.'),+ values: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'+ ),+ type: zod+ .enum(['span', 'span_attribute', 'span_resource_attribute'])+ .describe(+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'starts_with',+ 'not_starts_with',+ 'ends_with',+ 'not_ends_with',+ '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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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.'+ ),+ })+ )+ .describe('The property filters in this group.'),+ })+ )+ .describe('The inner filter groups.'),+ })+ .describe('A nested group of filter groups, as the UI filter editor builds it.'),+ ])+ .optional()+ .describe('Property filters for the count. Either a flat list of filters or a nested filter group.'),+ })+ .describe('The impact query to execute. Takes the same filters as the count query.'),+})+export const tracingSpansLatencyHeatmapCreateBodyQueryOneFilterGroupDefault = []export const tracingSpansLatencyHeatmapCreateBodyQueryOneRootSpansDefault = truediff --git a/products/tracing/frontend/identityCoverage.test.ts b/products/tracing/frontend/identityCoverage.test.tsnew file mode 100644index 000000000000..5d002d9af64d--- /dev/null+++ b/products/tracing/frontend/identityCoverage.test.ts@@ -0,0 +1,17 @@+import { formatIdentityCoverage } from './identityCoverage'++describe('formatIdentityCoverage', () => {+ // A reading of 0% or 100% would say the count covers nothing, or all of it, when neither+ // is true.+ it.each([+ ['no covered spans', 0, 1000, '0%'],+ ['no spans at all', 0, 0, '0%'],+ ['a partly covered set', 400, 1000, '40%'],+ ['a sliver that would round to zero', 1, 1000, '<1%'],+ ['a share that would round up to full coverage', 995, 1000, '>99%'],+ ['almost every span', 999, 1000, '>99%'],+ ['every span', 1000, 1000, '100%'],+ ])('reports %s', (_name, covered, total, expected) => {+ expect(formatIdentityCoverage(covered, total)).toBe(expected)+ })+})diff --git a/products/tracing/frontend/identityCoverage.ts b/products/tracing/frontend/identityCoverage.tsnew file mode 100644index 000000000000..63587deea7e8--- /dev/null+++ b/products/tracing/frontend/identityCoverage.ts@@ -0,0 +1,19 @@+import { percentage } from 'lib/utils/numbers'++/**+ * The share of `total` spans that carry the ID. A partly covered set never reads as a flat+ * 0% or 100%, because either would say the count beside it covers nothing or everything.+ */+export function formatIdentityCoverage(covered: number | undefined, total: number): string {+ if (!covered || !total) {+ return '0%'+ }+ const fraction = covered / total+ if (fraction < 0.005) {+ return '<1%'+ }+ if (fraction >= 0.995 && fraction < 1) {+ return '>99%'+ }+ return percentage(fraction, 0)+}diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 2c52d0820227..fa9d8b93ed22 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -52,6 +52,7 @@ import {type TracingFilters,type TracingOrderBy,TRACING_SCENE_VIEWER_ID,+ dataScopeKey,tracingFiltersLogic,} from './tracingFiltersLogic'import type { OverlayWindow, TimeComparison, TracingOrderDirection, TracingViewMode } from './tracingFiltersLogic'@@ -1086,6 +1087,9 @@ export const tracingDataLogic = kea<tracingDataLogicType>([// The Operations table sorts/filters the full result set client-side, so// request the endpoint's hard cap rather than its small default page.limit: OPERATIONS_AGGREGATION_LIMIT,+ // Only the Operations table renders the Sessions and Users columns, and+ // the aggregates read attribute maps the rest of the query never touches.+ includeImpact: fullRange && !!values.featureFlags[FEATURE_FLAGS.TRACING_IMPACT_STRIP],},controller.signal)@@ -1107,12 +1111,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([// filters) AND the view mode — but not on sort or compare. Skip the re-fetch (and// its spinner overlay) only when a sort/compare toggle re-runs the query without// changing scope or view mode.- const scopeKey = JSON.stringify([- values.utcDateRange,- values.filters.serviceNames,- values.queryFilterGroup,- values.filters.viewMode,- ])+ const scopeKey = JSON.stringify([dataScopeKey(values), values.filters.viewMode])if (scopeKey === cache.sparklineScope) {return values.rawSparklineData}@@ -1146,11 +1145,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([// response, and the label selects which to show. So a Traces/Spans (or sort/compare)// toggle that re-runs the query must not re-hit the endpoint; only the data scope// (date range, services, filters) changes the result. Skip the fetch when unchanged.- const scopeKey = JSON.stringify([- values.utcDateRange,- values.filters.serviceNames,- values.queryFilterGroup,- ])+ const scopeKey = dataScopeKey(values)if (scopeKey === cache.matchingCountsScope) {return values.matchingCounts}@@ -1182,12 +1177,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([// Same scope semantics as the sparkline: the heatmap depends on the data scope// and the view mode (root spans vs every span), but not on sort or compare.// Skip the re-fetch when a sort toggle re-runs the query without changing scope.- const scopeKey = JSON.stringify([- values.utcDateRange,- values.filters.serviceNames,- values.queryFilterGroup,- values.filters.viewMode,- ])+ const scopeKey = JSON.stringify([dataScopeKey(values), values.filters.viewMode])if (scopeKey === cache.latencyHeatmapScope) {return values.rawLatencyHeatmap}diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.tsindex 12d67eb7552f..90b4d0a6b276 100644--- a/products/tracing/frontend/tracingFiltersLogic.ts+++ b/products/tracing/frontend/tracingFiltersLogic.ts@@ -140,6 +140,17 @@ export interface TracingFilters {// outside a BindLogic still resolve to the scene's instance during the keyed migration.export const TRACING_SCENE_VIEWER_ID = 'default'+/** What a span query is scoped to. Loaders key their skip-the-refetch guard on this, so a sort or+ * compare toggle re-runs the query without re-hitting the endpoint. Add a new filter dimension+ * here, or a guard will read a changed filter as unchanged. */+export function dataScopeKey(values: {+ utcDateRange: unknown+ filters: { serviceNames: string[] }+ queryFilterGroup: unknown+}): string {+ return JSON.stringify([values.utcDateRange, values.filters.serviceNames, values.queryFilterGroup])+}+export interface TracingFiltersLogicProps {id: string// Filters enforced by the embedding surface (e.g. a person profile traces tab pins adiff --git a/products/tracing/frontend/tracingImpactLogic.test.ts b/products/tracing/frontend/tracingImpactLogic.test.tsnew file mode 100644index 000000000000..e60f066b57c4--- /dev/null+++ b/products/tracing/frontend/tracingImpactLogic.test.ts@@ -0,0 +1,184 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { initKeaTests } from '~/test/init'+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'++import { tracingSpansImpactCreate } from 'products/tracing/frontend/generated/api'+import type { _TracingImpactResponseApi } from 'products/tracing/frontend/generated/api.schemas'++import { tracingDataLogic } from './tracingDataLogic'+import { tracingFiltersLogic } from './tracingFiltersLogic'+import { tracingImpactLogic } from './tracingImpactLogic'++jest.mock('products/tracing/frontend/generated/api', () => ({+ __esModule: true,+ tracingSpansImpactCreate: jest.fn(),+}))++const mockImpact = tracingSpansImpactCreate as jest.MockedFunction<typeof tracingSpansImpactCreate>++const ID = 'test-viewer'++const IMPACT: _TracingImpactResponseApi = {+ total: 1000,+ spansWithSessionId: 400,+ sessions: 214,+ spansWithDistinctId: 300,+ users: 96,+ topSessions: [{ value: 'sess-a', count: 40 }],+ topUsers: [{ value: 'user-1', count: 30 }],+}++// What heatmapBrushToFilters produces for the heatmap's slow tail: a duration range, in ms.+const durationFilterGroup: UniversalFiltersGroup = {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: PropertyFilterType.Span,+ key: 'duration',+ operator: PropertyOperator.GreaterThanOrEqual,+ value: 500,+ },+ {+ type: PropertyFilterType.Span,+ key: 'duration',+ operator: PropertyOperator.LessThan,+ value: 1000,+ },+ ] as UniversalFiltersGroup['values'],+ },+ ],+}++describe('tracingImpactLogic', () => {+ let logic: ReturnType<typeof tracingImpactLogic.build>+ let filtersLogic: ReturnType<typeof tracingFiltersLogic.build>+ let dataLogic: ReturnType<typeof tracingDataLogic.build>++ const requestBody = (): any => mockImpact.mock.calls[mockImpact.mock.calls.length - 1][1].query++ beforeEach(() => {+ initKeaTests()+ jest.clearAllMocks()+ mockImpact.mockResolvedValue(IMPACT)+ filtersLogic = tracingFiltersLogic({ id: ID })+ filtersLogic.mount()+ dataLogic = tracingDataLogic({ id: ID })+ dataLogic.mount()+ logic = tracingImpactLogic({ id: ID })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ dataLogic.unmount()+ filtersLogic.unmount()+ })++ it('loads the counts on mount', async () => {+ await expectLogic(logic).toDispatchActions(['loadImpactSuccess']).toMatchValues({ impact: IMPACT })+ })++ it('waits for the team before requesting the counts', async () => {+ // Flags and the team both load asynchronously. A request built before the team lands asks+ // for /api/projects/null/, fails, and leaves the strip empty until the next filter change.+ logic.unmount()+ teamLogic.actions.loadCurrentTeamSuccess(null)+ jest.clearAllMocks()+ logic = tracingImpactLogic({ id: ID })+ logic.mount()++ await expectLogic(logic).toFinishAllListeners()+ expect(mockImpact).not.toHaveBeenCalled()++ await expectLogic(logic, () => {+ teamLogic.actions.loadCurrentTeamSuccess(MOCK_DEFAULT_TEAM)+ }).toDispatchActions(['loadImpactSuccess'])++ expect(mockImpact).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), expect.anything(), expect.anything())+ })++ it('scopes the request to the viewer filters', async () => {+ filtersLogic.actions.setServiceNames(['checkout'])+ filtersLogic.actions.setFilterGroup(durationFilterGroup)++ await expectLogic(logic, () => {+ dataLogic.actions.runQuery()+ }).toDispatchActions(['loadImpactSuccess'])++ // A brushed latency selection reaches the strip as these duration filters.+ expect(requestBody().serviceNames).toEqual(['checkout'])+ expect(requestBody().filterGroup).toEqual(durationFilterGroup)+ })++ it('refreshes when the filters change', async () => {+ await expectLogic(logic).toDispatchActions(['loadImpactSuccess'])++ await expectLogic(logic, () => {+ filtersLogic.actions.setServiceNames(['checkout'])+ dataLogic.actions.runQuery()+ }).toDispatchActions(['loadImpact', 'loadImpactSuccess'])++ expect(mockImpact).toHaveBeenCalledTimes(2)+ })++ it('does not re-query when the filters are unchanged', async () => {+ await expectLogic(logic).toDispatchActions(['loadImpactSuccess'])++ dataLogic.actions.runQuery()+ await expectLogic(logic).toNotHaveDispatchedActions(['loadImpact'])++ expect(mockImpact).toHaveBeenCalledTimes(1)+ })++ it('re-queries the same filters on an explicit refresh', async () => {+ await expectLogic(logic).toDispatchActions(['loadImpactSuccess'])++ await expectLogic(logic, () => {+ dataLogic.actions.refreshQuery()+ }).toDispatchActions(['loadImpact', 'loadImpactSuccess'])++ expect(mockImpact).toHaveBeenCalledTimes(2)+ })++ it('drops the previous counts while reloading', async () => {+ await expectLogic(logic).toDispatchActions(['loadImpactSuccess']).toMatchValues({ impact: IMPACT })++ await expectLogic(logic, () => {+ filtersLogic.actions.setServiceNames(['checkout'])+ dataLogic.actions.runQuery()+ })+ .toDispatchActions(['loadImpact'])+ .toMatchValues({ impact: null })+ })++ it('renders nothing rather than an error when the request fails', async () => {+ mockImpact.mockRejectedValue(new Error('boom'))++ await expectLogic(logic, () => {+ filtersLogic.actions.setServiceNames(['checkout'])+ dataLogic.actions.runQuery()+ })+ .toDispatchActions(['loadImpactSuccess'])+ .toMatchValues({ impact: null })+ })++ it('retries after a failure rather than treating the filters as done', async () => {+ mockImpact.mockRejectedValue(new Error('boom'))+ await expectLogic(logic).toDispatchActions(['loadImpactSuccess']).toMatchValues({ impact: null })++ mockImpact.mockResolvedValue(IMPACT)+ await expectLogic(logic, () => {+ dataLogic.actions.runQuery()+ })+ .toDispatchActions(['loadImpactSuccess'])+ .toMatchValues({ impact: IMPACT })+ })+})diff --git a/products/tracing/frontend/tracingImpactLogic.ts b/products/tracing/frontend/tracingImpactLogic.tsnew file mode 100644index 000000000000..244a91643d9c--- /dev/null+++ b/products/tracing/frontend/tracingImpactLogic.ts@@ -0,0 +1,174 @@+import { MakeLogicType, connect, kea, key, listeners, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import { teamLogic } from 'scenes/teamLogic'++import { UniversalFiltersGroup } from '~/types'++import { tracingSpansImpactCreate } from 'products/tracing/frontend/generated/api'+import type {+ _TracingCountBodyApi,+ _TracingCountBodyApiFilterGroup,+ _TracingImpactResponseApi,+} from 'products/tracing/frontend/generated/api.schemas'++import { tracingDataLogic } from './tracingDataLogic'+import { TRACING_SCENE_VIEWER_ID, dataScopeKey, type TracingFilters, tracingFiltersLogic } from './tracingFiltersLogic'++export interface TracingImpactLogicProps {+ id: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface tracingImpactLogicValues {+ currentTeamId: number | null // teamLogic+ filters: TracingFilters // tracingFiltersLogic+ queryFilterGroup: UniversalFiltersGroup // tracingFiltersLogic+ utcDateRange: {+ date_from: string | null | undefined+ date_to: string+ } // tracingFiltersLogic+ impact: _TracingImpactResponseApi | null+ impactLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface tracingImpactLogicActions {+ refreshQuery: () => {+ value: true+ } // tracingDataLogic+ runQuery: () => {+ value: true+ } // tracingDataLogic+ loadImpact: (_: any) => any+ loadImpactFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadImpactSuccess: (+ impact: _TracingImpactResponseApi | null,+ payload?: any+ ) => {+ impact: _TracingImpactResponseApi | null+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface tracingImpactLogicMeta {+ key: string+}++export type tracingImpactLogicType = MakeLogicType<+ tracingImpactLogicValues,+ tracingImpactLogicActions,+ TracingImpactLogicProps,+ tracingImpactLogicMeta+>++export const tracingImpactLogic = kea<tracingImpactLogicType>([+ props({ id: TRACING_SCENE_VIEWER_ID } as TracingImpactLogicProps),+ key(({ id }) => id),+ path((key) => ['products', 'tracing', 'frontend', 'tracingImpactLogic', key]),+ connect(({ id }: TracingImpactLogicProps) => ({+ values: [+ tracingFiltersLogic({ id }),+ ['utcDateRange', 'queryFilterGroup', 'filters'],+ teamLogic,+ ['currentTeamId'],+ ],+ actions: [tracingDataLogic({ id }), ['runQuery', 'refreshQuery']],+ })),+ loaders(({ cache, values }) => ({+ impact: [+ null as _TracingImpactResponseApi | null,+ {+ loadImpact: async (_, breakpoint) => {+ // Team loading can outlast this logic's mount, and a request built without an+ // ID asks for /api/projects/null/. The currentTeamId subscription below runs+ // the load once the ID lands.+ const currentTeamId = values.currentTeamId+ if (currentTeamId === null) {+ return null+ }+ // Read up front so the recorded scope is the one the response covers, and+ // claimed so a runQuery arriving mid-flight starts no second scan.+ const scopeKey = dataScopeKey(values)+ cache.inFlightScope = scopeKey+ await breakpoint(300)+ const query: _TracingCountBodyApi = {+ dateRange: values.utcDateRange,+ serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,+ // The editor's group holds any universal filter, while the endpoint reads+ // only the span ones, so the narrowing is asserted rather than checked.+ filterGroup: values.queryFilterGroup as _TracingCountBodyApiFilterGroup,+ }+ // Re-adding the key aborts the superseded request. A hidden tab must not.+ const controller = new AbortController()+ cache.disposables.add(() => () => controller.abort(), 'impactRequest', {+ pauseOnPageHidden: false,+ })+ let response: _TracingImpactResponseApi | null = null+ try {+ response = await tracingSpansImpactCreate(+ String(currentTeamId),+ { query },+ { signal: controller.signal }+ )+ } catch {+ // Passive decoration, so a failure shows nothing rather than a toast.+ }+ breakpoint()+ cache.inFlightScope = undefined+ // Only on success, so a failure retries instead of being cached as done.+ if (response) {+ cache.impactScope = scopeKey+ }+ return response+ },+ },+ ],+ })),+ reducers({+ impact: {+ // So the previous query's counts never render beside the new query's results.+ loadImpact: () => null,+ },+ }),+ listeners(({ actions, values, cache }) => ({+ // A latency-heatmap brush reaches the strip here: it lands as filters, then re-queries.+ runQuery: () => {+ const scopeKey = dataScopeKey(values)+ if (scopeKey === cache.impactScope || scopeKey === cache.inFlightScope) {+ return+ }+ actions.loadImpact(null)+ },+ // Loads here rather than relying on tracingDataLogic's runQuery, whose listener could+ // reach the guard first.+ refreshQuery: () => {+ cache.impactScope = undefined+ cache.inFlightScope = undefined+ actions.loadImpact(null)+ },+ })),+ // Stands in for an afterMount load: the data logic usually fires its initial runQuery before+ // this logic exists, so the strip starts its own. Keyed on the team ID so a team that arrives+ // late still gets a load, rather than leaving the strip empty until the next filter change.+ subscriptions(({ actions, values, cache }) => ({+ currentTeamId: (currentTeamId: number | null) => {+ if (currentTeamId === null) {+ return+ }+ const scopeKey = dataScopeKey(values)+ if (scopeKey === cache.impactScope || scopeKey === cache.inFlightScope) {+ return+ }+ actions.loadImpact(null)+ },+ })),+])diff --git a/products/tracing/frontend/tracingSceneLogic.test.ts b/products/tracing/frontend/tracingSceneLogic.test.tsindex 9ee0aac01cc4..83efa555bbaf 100644--- a/products/tracing/frontend/tracingSceneLogic.test.ts+++ b/products/tracing/frontend/tracingSceneLogic.test.ts@@ -7,6 +7,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { initKeaTests } from '~/test/init'+import { tracingDataLogic } from './tracingDataLogic'import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from './tracingFiltersLogic'import { tracingSceneLogic } from './tracingSceneLogic'@@ -107,6 +108,25 @@ describe('tracingSceneLogic', () => {expect(router.values.searchParams.view).toBe('operations')})+ it('refetches the Operations aggregation when the impact flag resolves late', () => {+ // Flags load asynchronously, so rows can arrive while the flag is still off. Without the+ // refetch the Sessions and Users columns render over rows that carry no impact fields.+ enableOperationsView()+ mountAt({ view: 'operations' })+ tracingDataLogic({ id: TRACING_SCENE_VIEWER_ID }).actions.fetchAggregationSuccess({+ current: [{ service_name: 'web', name: 'GET /', count: 1 }],+ previous: null,+ } as any)+ const aggregate = jest.spyOn(api.tracing, 'aggregate')++ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.TRACING_OPERATIONS_VIEW]: true,+ [FEATURE_FLAGS.TRACING_IMPACT_STRIP]: true,+ })++ expect(aggregate).toHaveBeenCalledWith(expect.objectContaining({ includeImpact: true }), expect.anything())+ })+it('resets the operations tab to traces when the flag is disabled mid-session', () => {enableOperationsView()mountAt({ view: 'operations' })diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex 93afc1955b2b..7882844a1df6 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -108,6 +108,13 @@ export interface tracingSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingSceneLogicActions {+ setFeatureFlags: (+ flags: string[],+ variants: Record<string, boolean | string>+ ) => {+ flags: string[]+ variants: Record<string, boolean | string>+ } // featureFlagLogicapplyHeatmapBrush: (selection: import('./heatmapBrush').HeatmapBrushSelection) => {selection: import('./heatmapBrush').HeatmapBrushSelection} // tracingDataLogic@@ -335,6 +342,8 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([],tracingViewerLogic({ id: TRACING_SCENE_VIEWER_ID }),['openTrace', 'selectSpan', 'closeTrace', 'openCompareFlame', 'closeCompareFlame'],+ featureFlagLogic,+ ['setFeatureFlags'],],})),@@ -410,6 +419,20 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([actions.fetchAggregation({ fullRange: true })}},+ // Flags resolve asynchronously, so one that arrives after the Operations fetch would show+ // the Sessions and Users columns over rows fetched without them. Mirrors the heatmap's+ // late-flag refetch in tracingDataLogic.+ setFeatureFlags: () => {+ if (+ values.activeTracingTab === 'operations' &&+ values.featureFlags[FEATURE_FLAGS.TRACING_IMPACT_STRIP] &&+ values.aggregation.current.length > 0 &&+ values.aggregation.current[0].sessions == null &&+ !values.aggregationLoading+ ) {+ actions.fetchAggregation({ fullRange: true })+ }+ },setActiveTracingTab: ({ tab }) => {if (tab === 'operations') {actions.fetchAggregation({ fullRange: true })diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yamlindex ec10aa87df10..f090b8c05f55 100644--- a/products/tracing/mcp/tools.yaml+++ b/products/tracing/mcp/tools.yaml@@ -230,6 +230,9 @@ tools:tracing-spans-has-spans-retrieve:operation: tracing_spans_has_spans_retrieveenabled: false+ tracing-spans-impact-create:+ operation: tracing_spans_impact_create+ enabled: falsetracing-spans-symbol-stats-create:operation: tracing_spans_symbol_stats_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4686f21af890..f3c438745bdf 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9809,7 +9809,12 @@ export namespace Schemas {p999_duration_nano: number;p99_duration_nano: number;service_name: string;+ /** Set only when the query asked for `includeImpact`. `sessions` and `users` are uniq() estimates; the two span counts are exact. */+ sessions?: number | null;+ spans_with_distinct_id?: number | null;+ spans_with_session_id?: number | null;total_duration_nano: number;+ users?: number | null;}/**@@ -50716,6 +50721,8 @@ export namespace Schemas {compareFilter?: CompareFilter | null;dateRange: DateRange;filterGroup?: PropertyGroupFilter | null;+ /** Also aggregate sessions and people per operation. Off by default: it reads the attribute maps. */+ includeImpact?: boolean | null;kind?: 'TraceSpansAggregationQuery';/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;@@ -99263,6 +99270,26 @@ export namespace Schemas {p999_duration_nano: number;/** Spans with OTel status code Error (status_code = 2). */error_count: number;+ /**+ * Estimated unique session IDs across this group's spans (HyperLogLog, about 1-2% error). Null unless the query set `includeImpact`.+ * @nullable+ */+ sessions: number | null;+ /**+ * Estimated unique person distinct IDs across this group's spans (HyperLogLog, about 1-2% error). Null unless the query set `includeImpact`.+ * @nullable+ */+ users: number | null;+ /**+ * How many of this group's spans carry a session ID under the team's configured or conventional attribute keys. Null unless the query set `includeImpact`.+ * @nullable+ */+ spans_with_session_id: number | null;+ /**+ * How many of this group's spans carry a person distinct ID under the team's configured or conventional attribute keys. Null unless the query set `includeImpact`.+ * @nullable+ */+ spans_with_distinct_id: number | null;}export interface _CompareFilter {@@ -101021,6 +101048,8 @@ export namespace Schemas {* @minimum 0*/offset?: number;+ /** Also return the sessions and people behind each operation. Off by default because it reads the span and resource attribute maps, which the rest of the aggregation never touches. */+ includeImpact?: boolean;}export interface _TracingAggregationRequest {@@ -101137,6 +101166,21 @@ export namespace Schemas {count: number;}+ /**+ * Property filters for the count. Either a flat list of filters or a nested filter group.+ */+ export type _TracingCountBodyFilterGroup = _SpanPropertyFilter[] | {+ /** How the inner groups combine. */+ type: 'AND' | 'OR';+ /** The inner filter groups. */+ values: ({+ /** How the filters in this group combine. */+ type: 'AND' | 'OR';+ /** The property filters in this group. */+ values: _SpanPropertyFilter[];+ })[];+ };+export interface _TracingCountBody {/** Date range for the count. Defaults to last hour. */dateRange?: _TracingDateRange;@@ -101144,8 +101188,8 @@ export namespace Schemas {serviceNames?: string[];/** Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans. */statusCodes?: number[];- /** Property filters for the count. */- filterGroup?: _SpanPropertyFilter[];+ /** Property filters for the count. Either a flat list of filters or a nested filter group. */+ filterGroup?: _TracingCountBodyFilterGroup;}export interface _TracingCountRequest {@@ -101178,6 +101222,35 @@ export namespace Schemas {query: _TracingDurationHistogramQueryBody;}+ export interface _TracingImpactRequest {+ /** The impact query to execute. Takes the same filters as the count query. */+ query: _TracingCountBody;+ }++ export interface _TracingImpactTopValue {+ /** The session ID or person distinct ID. */+ value: string;+ /** Approximate number of matching spans that carry this value (topK estimate). */+ count: number;+ }++ export interface _TracingImpactResponse {+ /** Number of spans matching the filters. */+ total: number;+ /** How many of the matching spans carry a session ID under the team's configured or conventional attribute keys. */+ spansWithSessionId: number;+ /** Estimated number of unique session IDs across the matching spans (HyperLogLog, about 1-2% error). */+ sessions: number;+ /** How many of the matching spans carry a person distinct ID under the team's configured or conventional attribute keys. */+ spansWithDistinctId: number;+ /** Estimated number of unique distinct IDs across the matching spans (HyperLogLog, about 1-2% error). */+ users: number;+ /** Top session IDs on the matching spans, ordered by span count descending (topK, at most 5). */+ topSessions: _TracingImpactTopValue[];+ /** Top person distinct IDs on the matching spans, ordered by span count descending (topK, at most 5). */+ topUsers: _TracingImpactTopValue[];+ }+export interface _TracingLatencyHeatmapCell {/** ISO 8601 UTC start of the time bucket. */time: string;diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.tsindex c0218412d046..3cc0cd131347 100644--- a/services/mcp/src/generated/tracing/api.ts+++ b/services/mcp/src/generated/tracing/api.ts@@ -22,6 +22,8 @@ export const tracingSpansAggregateCreateBodyQueryOneLimitMax = 5000export const tracingSpansAggregateCreateBodyQueryOneOffsetMin = 0+export const tracingSpansAggregateCreateBodyQueryOneIncludeImpactDefault = false+export const TracingSpansAggregateCreateBody = () => zod.object({query: zod.object({@@ -124,6 +126,12 @@ export const TracingSpansAggregateCreateBody = () => zod.object({.describe('Row offset for pagination. Combine with `limit` and the `next_offset` returned in the response to page through results beyond the first page.'),+ includeImpact: zod+ .boolean()+ .default(tracingSpansAggregateCreateBodyQueryOneIncludeImpactDefault)+ .describe(+ 'Also return the sessions and people behind each operation. Off by default because it reads the span and resource attribute maps, which the rest of the aggregation never touches.'+ ),}).describe('The span aggregation query to execute.'),})@@ -312,8 +320,6 @@ export const TracingSpansCountCreateParams = () => zod.object({),})-export const tracingSpansCountCreateBodyQueryOneFilterGroupDefault = []-export const TracingSpansCountCreateBody = () => zod.object({query: zod.object({@@ -340,54 +346,120 @@ export const TracingSpansCountCreateBody = () => zod.object({'Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.'),filterGroup: zod- .array(- zod.object({- key: zod- .string()- .describe(- 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'- ),- type: zod- .enum(['span', 'span_attribute', 'span_resource_attribute'])- .describe(- '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'- )- .describe(- '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'- ),- operator: zod- .enum([- 'exact',- 'is_not',- 'icontains',- 'not_icontains',- 'starts_with',- 'not_starts_with',- 'ends_with',- 'not_ends_with',- '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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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(tracingSpansCountCreateBodyQueryOneFilterGroupDefault)- .describe('Property filters for the count.'),+ .union([+ zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'+ ),+ type: zod+ .enum(['span', 'span_attribute', 'span_resource_attribute'])+ .describe(+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'starts_with',+ 'not_starts_with',+ 'ends_with',+ 'not_ends_with',+ '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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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.'+ ),+ })+ )+ .describe('A flat list of filters, combined with AND.'),+ zod+ .object({+ type: zod.enum(['AND', 'OR']).describe('How the inner groups combine.'),+ values: zod+ .array(+ zod.object({+ type: zod+ .enum(['AND', 'OR'])+ .describe('How the filters in this group combine.'),+ values: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'+ ),+ type: zod+ .enum(['span', 'span_attribute', 'span_resource_attribute'])+ .describe(+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'starts_with',+ 'not_starts_with',+ 'ends_with',+ 'not_ends_with',+ '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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\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.'+ ),+ })+ )+ .describe('The property filters in this group.'),+ })+ )+ .describe('The inner filter groups.'),+ })+ .describe('A nested group of filter groups, as the UI filter editor builds it.'),+ ])+ .optional()+ .describe('Property filters for the count. Either a flat list of filters or a nested filter group.'),}).describe('The span count query to execute.'),})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.jsonindex d6da1b745f88..51988f17bd9a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json@@ -97,6 +97,11 @@},"type": "array"},+ "includeImpact": {+ "default": false,+ "description": "Also return the sessions and people behind each operation. Off by default because it reads the span and resource attribute maps, which the rest of the aggregation never touches.",+ "type": "boolean"+ },"limit": {"description": "Max rows to return, ordered by total_duration_nano DESC. Defaults to 100; hard max 5000. Keep this small to bound the response size — a high value on high-cardinality span names (e.g. untemplated URL paths) returns a very large payload. Prefer narrowing with `serviceNames`/`filterGroup` over raising the limit.","maximum": 5000,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-count.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-count.jsonindex d7766a0772a5..73419456774f 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-count.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-count.json@@ -33,47 +33,124 @@"type": "object"},"filterGroup": {- "default": [],- "description": "Property filters for the count.",- "items": {- "properties": {- "key": {- "description": "Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").",- "type": "string"- },- "operator": {- "description": "Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `starts_with` - starts_with\n* `not_starts_with` - not_starts_with\n* `ends_with` - ends_with\n* `not_ends_with` - not_ends_with\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_set` - is_set\n* `is_not_set` - is_not_set",- "enum": [- "exact",- "is_not",- "icontains",- "not_icontains",- "starts_with",- "not_starts_with",- "ends_with",- "not_ends_with",- "regex",- "not_regex",- "gt",- "lt",- "is_set",- "is_not_set"- ],- "type": "string"- },- "type": {- "description": "\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute",- "enum": ["span", "span_attribute", "span_resource_attribute"],- "type": "string"+ "anyOf": [+ {+ "description": "A flat list of filters, combined with AND.",+ "items": {+ "properties": {+ "key": {+ "description": "Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").",+ "type": "string"+ },+ "operator": {+ "description": "Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `starts_with` - starts_with\n* `not_starts_with` - not_starts_with\n* `ends_with` - ends_with\n* `not_ends_with` - not_ends_with\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_set` - is_set\n* `is_not_set` - is_not_set",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "lt",+ "is_set",+ "is_not_set"+ ],+ "type": "string"+ },+ "type": {+ "description": "\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute",+ "enum": ["span", "span_attribute", "span_resource_attribute"],+ "type": "string"+ },+ "value": {+ "description": "Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators."+ }+ },+ "required": ["key", "type", "operator"],+ "type": "object"},- "value": {- "description": "Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators."- }+ "type": "array"},- "required": ["key", "type", "operator"],- "type": "object"- },- "type": "array"+ {+ "description": "A nested group of filter groups, as the UI filter editor builds it.",+ "properties": {+ "type": {+ "description": "How the inner groups combine.",+ "enum": ["AND", "OR"],+ "type": "string"+ },+ "values": {+ "description": "The inner filter groups.",+ "items": {+ "properties": {+ "type": {+ "description": "How the filters in this group combine.",+ "enum": ["AND", "OR"],+ "type": "string"+ },+ "values": {+ "description": "The property filters in this group.",+ "items": {+ "properties": {+ "key": {+ "description": "Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").",+ "type": "string"+ },+ "operator": {+ "description": "Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `starts_with` - starts_with\n* `not_starts_with` - not_starts_with\n* `ends_with` - ends_with\n* `not_ends_with` - not_ends_with\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_set` - is_set\n* `is_not_set` - is_not_set",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "lt",+ "is_set",+ "is_not_set"+ ],+ "type": "string"+ },+ "type": {+ "description": "\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute",+ "enum": [+ "span",+ "span_attribute",+ "span_resource_attribute"+ ],+ "type": "string"+ },+ "value": {+ "description": "Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators."+ }+ },+ "required": ["key", "type", "operator"],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": ["type", "values"],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": ["type", "values"],+ "type": "object"+ }+ ],+ "description": "Property filters for the count. Either a flat list of filters or a nested filter group."},"serviceNames": {"description": "Filter by service names.",